diff --git a/packages/battery_plus/example/linux/.gitignore b/packages/battery_plus/example/linux/.gitignore new file mode 100644 index 0000000000..d3896c9844 --- /dev/null +++ b/packages/battery_plus/example/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/packages/battery_plus/example/linux/CMakeLists.txt b/packages/battery_plus/example/linux/CMakeLists.txt new file mode 100644 index 0000000000..386893d7de --- /dev/null +++ b/packages/battery_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.batteryexample.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/battery_plus/example/linux/flutter/CMakeLists.txt b/packages/battery_plus/example/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000000..4f48a7ced5 --- /dev/null +++ b/packages/battery_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/battery_plus/example/linux/flutter/generated_plugin_registrant.cc b/packages/battery_plus/example/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000000..d38195aa04 --- /dev/null +++ b/packages/battery_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/battery_plus/example/linux/flutter/generated_plugin_registrant.h b/packages/battery_plus/example/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000000..9bf7478940 --- /dev/null +++ b/packages/battery_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/battery_plus/example/linux/flutter/generated_plugins.cmake b/packages/battery_plus/example/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000000..51436ae8c9 --- /dev/null +++ b/packages/battery_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/battery_plus/example/linux/main.cc b/packages/battery_plus/example/linux/main.cc new file mode 100644 index 0000000000..058e6178fe --- /dev/null +++ b/packages/battery_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/battery_plus/example/linux/my_application.cc b/packages/battery_plus/example/linux/my_application.cc new file mode 100644 index 0000000000..f28ca30940 --- /dev/null +++ b/packages/battery_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/battery_plus/example/linux/my_application.h b/packages/battery_plus/example/linux/my_application.h new file mode 100644 index 0000000000..72271d5e41 --- /dev/null +++ b/packages/battery_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_ diff --git a/packages/battery_plus/lib/battery_plus.dart b/packages/battery_plus/lib/battery_plus.dart index c269863d25..5fdd8e8ec2 100644 --- a/packages/battery_plus/lib/battery_plus.dart +++ b/packages/battery_plus/lib/battery_plus.dart @@ -3,8 +3,12 @@ // found in the LICENSE file. import 'dart:async'; +import 'dart:io' show Platform; +import 'package:flutter/foundation.dart' show kIsWeb; import 'package:battery_plus_platform_interface/battery_plus_platform_interface.dart'; +import 'package:battery_plus_platform_interface/src/method_channel_battery_plus.dart'; +import 'package:battery_plus_linux/battery_plus_linux.dart'; // Export enums from the platform_interface so plugin users can use them directly. export 'package:battery_plus_platform_interface/battery_plus_platform_interface.dart' @@ -29,7 +33,24 @@ class Battery { static Battery _singleton; - static BatteryPlatform get _platform => BatteryPlatform.instance; + static bool _manualDartRegistrationNeeded = true; + + static BatteryPlatform get _platform { + // 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. + if (_manualDartRegistrationNeeded) { + // Only do the initial registration if it hasn't already been overridden + // with a non-default instance. + if (!kIsWeb && BatteryPlatform.instance is MethodChannelBattery) { + if (Platform.isLinux) { + BatteryPlatform.instance = BatteryLinux(); + } + } + _manualDartRegistrationNeeded = false; + } + return BatteryPlatform.instance; + } /// get battery level Future get batteryLevel { diff --git a/packages/battery_plus/pubspec.yaml b/packages/battery_plus/pubspec.yaml index ca6a3b9b02..be75dbe14d 100644 --- a/packages/battery_plus/pubspec.yaml +++ b/packages/battery_plus/pubspec.yaml @@ -12,6 +12,8 @@ flutter: pluginClass: BatteryPlugin ios: pluginClass: FLTBatteryPlugin + linux: + default_package: battery_plus_linux macos: default_package: battery_plus_macos web: @@ -24,6 +26,7 @@ dependencies: sdk: flutter meta: ^1.0.5 battery_plus_platform_interface: ^0.1.0 + battery_plus_linux: ^0.1.0 battery_plus_macos: ^0.1.0 battery_plus_web: ^0.1.0 battery_plus_windows: ^0.1.0 diff --git a/packages/battery_plus_linux/.gitignore b/packages/battery_plus_linux/.gitignore new file mode 100644 index 0000000000..1985397a2c --- /dev/null +++ b/packages/battery_plus_linux/.gitignore @@ -0,0 +1,74 @@ +# 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/ +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +build/ + +# Android related +**/android/**/gradle-wrapper.jar +**/android/.gradle +**/android/captures/ +**/android/gradlew +**/android/gradlew.bat +**/android/local.properties +**/android/**/GeneratedPluginRegistrant.java + +# iOS/XCode related +**/ios/**/*.mode1v3 +**/ios/**/*.mode2v3 +**/ios/**/*.moved-aside +**/ios/**/*.pbxuser +**/ios/**/*.perspectivev3 +**/ios/**/*sync/ +**/ios/**/.sconsign.dblite +**/ios/**/.tags* +**/ios/**/.vagrant/ +**/ios/**/DerivedData/ +**/ios/**/Icon? +**/ios/**/Pods/ +**/ios/**/.symlinks/ +**/ios/**/profile +**/ios/**/xcuserdata +**/ios/.generated/ +**/ios/Flutter/App.framework +**/ios/Flutter/Flutter.framework +**/ios/Flutter/Flutter.podspec +**/ios/Flutter/Generated.xcconfig +**/ios/Flutter/app.flx +**/ios/Flutter/app.zip +**/ios/Flutter/flutter_assets/ +**/ios/Flutter/flutter_export_environment.sh +**/ios/ServiceDefinitions.json +**/ios/Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!**/ios/**/default.mode1v3 +!**/ios/**/default.mode2v3 +!**/ios/**/default.pbxuser +!**/ios/**/default.perspectivev3 diff --git a/packages/battery_plus_linux/.metadata b/packages/battery_plus_linux/.metadata new file mode 100644 index 0000000000..6b9d686e29 --- /dev/null +++ b/packages/battery_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/battery_plus_linux/CHANGELOG.md b/packages/battery_plus_linux/CHANGELOG.md new file mode 100644 index 0000000000..f1742b3610 --- /dev/null +++ b/packages/battery_plus_linux/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.1.0 + +- Initial Linux support. diff --git a/packages/battery_plus_linux/LICENSE b/packages/battery_plus_linux/LICENSE new file mode 100644 index 0000000000..0c91662b3f --- /dev/null +++ b/packages/battery_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/battery_plus_linux/README.md b/packages/battery_plus_linux/README.md new file mode 100644 index 0000000000..91445b0845 --- /dev/null +++ b/packages/battery_plus_linux/README.md @@ -0,0 +1,12 @@ +# Battery Plus Linux + +[![Flutter Community: battery_plus_linux](https://fluttercommunity.dev/_github/header/battery_plus_linux)](https://github.com/fluttercommunity/community) + +[![pub package](https://img.shields.io/pub/v/battery_plus_linux.svg)](https://pub.dev/packages/battery_plus_linux) + +The Linux implementation of [`battery_plus`](https://pub.dev/packages/battery_plus). + +## Usage + +This package is already included as part of the `battery_plus` package dependency, and will +be included when using `battery_plus` as normal. diff --git a/packages/battery_plus_linux/analysis_options.yaml b/packages/battery_plus_linux/analysis_options.yaml new file mode 100644 index 0000000000..486705dbf2 --- /dev/null +++ b/packages/battery_plus_linux/analysis_options.yaml @@ -0,0 +1 @@ +include: package:pedantic/analysis_options.1.9.0.yaml diff --git a/packages/battery_plus_linux/lib/battery_plus_linux.dart b/packages/battery_plus_linux/lib/battery_plus_linux.dart new file mode 100644 index 0000000000..1bc47fe890 --- /dev/null +++ b/packages/battery_plus_linux/lib/battery_plus_linux.dart @@ -0,0 +1,4 @@ +/// The Linux implementation of `battery_plus`. +library battery_plus_linux; + +export 'src/battery_linux.dart'; diff --git a/packages/battery_plus_linux/lib/src/battery_linux.dart b/packages/battery_plus_linux/lib/src/battery_linux.dart new file mode 100644 index 0000000000..44733ce0f1 --- /dev/null +++ b/packages/battery_plus_linux/lib/src/battery_linux.dart @@ -0,0 +1,68 @@ +import 'dart:async'; + +import 'package:battery_plus_platform_interface/battery_plus_platform_interface.dart'; +import 'package:meta/meta.dart'; + +import 'upower_device.dart'; + +// ### TODO: introduce an 'unknown' battery state for workstations? +// https://github.com/fluttercommunity/plus_plugins/issues/61 +extension _ToBatteryState on UPowerBatteryState { + BatteryState toBatteryState() { + switch (this) { + case UPowerBatteryState.charging: + return BatteryState.charging; + case UPowerBatteryState.discharging: + return BatteryState.discharging; + default: + return BatteryState.full; + } + } +} + +@visibleForTesting +typedef UPowerDeviceFactory = UPowerDevice Function(); + +/// The Linux implementation of BatteryPlatform. +class BatteryLinux extends BatteryPlatform { + /// Returns the current battery level in percent. + @override + Future get batteryLevel { + final device = createDevice(); + return device + .getPercentage() + .then((value) => value.round()) + .whenComplete(() => device.dispose()); + } + + /// Fires whenever the battery state changes. + @override + Stream get onBatteryStateChanged { + _stateController ??= StreamController( + onListen: _startListenState, + onCancel: _stopListenState, + ); + return _stateController.stream.asBroadcastStream(); + } + + UPowerDevice _stateDevice; + StreamController _stateController; + + @visibleForTesting + UPowerDeviceFactory createDevice = () => UPowerDevice.display(); + + void _addState(UPowerBatteryState value) { + _stateController.add(value.toBatteryState()); + } + + void _startListenState() { + _stateDevice ??= createDevice(); + _stateDevice.getState().then((value) => _addState(value)); + _stateDevice.subscribeStateChanged().listen((value) => _addState(value)); + } + + void _stopListenState() { + _stateDevice?.dispose(); + _stateDevice = null; + } +} diff --git a/packages/battery_plus_linux/lib/src/upower_device.dart b/packages/battery_plus_linux/lib/src/upower_device.dart new file mode 100644 index 0000000000..53032f3b68 --- /dev/null +++ b/packages/battery_plus_linux/lib/src/upower_device.dart @@ -0,0 +1,57 @@ +import 'package:dbus/dbus.dart'; + +const _kInterface = 'org.freedesktop.UPower'; +const _kDeviceAddress = 'org.freedesktop.UPower.Device'; +const _kDisplayDevicePath = '/org/freedesktop/UPower/devices/DisplayDevice'; + +enum UPowerBatteryState { + unknown, + charging, + discharging, + empty, + fullyCharged, + pendingCharge, + pendingDischarge +} + +extension UPowerBatteryStateInt on int { + UPowerBatteryState toBatteryState() => UPowerBatteryState.values[this]; +} + +typedef UPowerBatteryStateCallback = void Function(UPowerBatteryState state); + +class UPowerDevice extends DBusRemoteObject { + UPowerDevice._({DBusClient client, DBusObjectPath path}) + : super(client, _kInterface, path); + + factory UPowerDevice.display([DBusClient client]) { + return UPowerDevice._( + client: client ?? DBusClient.system(), + path: DBusObjectPath(_kDisplayDevicePath), + ); + } + + void dispose() => client?.close(); + + Future getPercentage() { + return getProperty(_kDeviceAddress, 'Percentage') + .then((value) => (value as DBusDouble).value) + .catchError((error) => print(error)) + .then((value) => value ?? 0.0); + } + + Future getState() { + return getProperty(_kDeviceAddress, 'State') + .then((value) => (value as DBusUint32).value.toBatteryState()) + .catchError((error) => print(error)) + .then((value) => value ?? UPowerBatteryState.unknown); + } + + Stream subscribeStateChanged() { + return subscribePropertiesChanged() + .where((event) => event.changedProperties.containsKey('State')) + .map((event) => (event.changedProperties['State'] as DBusUint32) + .value + .toBatteryState()); + } +} diff --git a/packages/battery_plus_linux/pubspec.yaml b/packages/battery_plus_linux/pubspec.yaml new file mode 100644 index 0000000000..2cd258db19 --- /dev/null +++ b/packages/battery_plus_linux/pubspec.yaml @@ -0,0 +1,29 @@ +name: battery_plus_linux +description: Linux implementation of the battery_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: + battery_plus_platform_interface: ^0.1.0 + dbus: ^0.1.0 + flutter: + sdk: flutter + meta: ^1.2.3 + +dev_dependencies: + flutter_test: + sdk: flutter + mockito: ^4.1.2 + pedantic: ^1.9.2 + +flutter: + plugin: + platforms: + linux: + dartPluginClass: BatteryLinux + pluginClass: none diff --git a/packages/battery_plus_linux/test/battery_plus_linux_test.dart b/packages/battery_plus_linux/test/battery_plus_linux_test.dart new file mode 100644 index 0000000000..3a2221588d --- /dev/null +++ b/packages/battery_plus_linux/test/battery_plus_linux_test.dart @@ -0,0 +1,35 @@ +import 'package:battery_plus_linux/src/battery_linux.dart'; +import 'package:battery_plus_linux/src/upower_device.dart'; +import 'package:battery_plus_platform_interface/battery_plus_platform_interface.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; + +class MockDevice extends Mock implements UPowerDevice {} + +void main() { + test('battery level', () async { + final battery = BatteryLinux(); + battery.createDevice = () { + final device = MockDevice(); + when(device.getPercentage()).thenAnswer((_) => Future.value(56.78)); + return device; + }; + expect(battery.batteryLevel, completion(equals(57))); + }); + + test('battery state changes', () { + final battery = BatteryLinux(); + battery.createDevice = () { + final device = MockDevice(); + when(device.getState()).thenAnswer((_) { + return Future.value(UPowerBatteryState.charging); + }); + when(device.subscribeStateChanged()).thenAnswer((_) { + return Stream.value(UPowerBatteryState.fullyCharged); + }); + return device; + }; + expect(battery.onBatteryStateChanged, + emitsInOrder([BatteryState.charging, BatteryState.full])); + }); +}