From e29cc169f967d45db7ff7b39710579de2ccf4396 Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Sat, 20 Apr 2024 22:23:50 +0800 Subject: [PATCH 01/22] feat(screen-brightness-platform-interface): added method for changing system brightness --- .idea/modules/app/android.app.iml | 96 ------------------- .../lib/constant/method_name.dart | 1 + .../lib/method_channel_screen_brightness.dart | 30 +++++- .../screen_brightness_platform_interface.dart | 11 +++ 4 files changed, 41 insertions(+), 97 deletions(-) delete mode 100644 .idea/modules/app/android.app.iml diff --git a/.idea/modules/app/android.app.iml b/.idea/modules/app/android.app.iml deleted file mode 100644 index f04075b..0000000 --- a/.idea/modules/app/android.app.iml +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/screen_brightness_platform_interface/lib/constant/method_name.dart b/screen_brightness_platform_interface/lib/constant/method_name.dart index c4a5f3d..d004638 100644 --- a/screen_brightness_platform_interface/lib/constant/method_name.dart +++ b/screen_brightness_platform_interface/lib/constant/method_name.dart @@ -1,4 +1,5 @@ const methodNameGetSystemScreenBrightness = 'getSystemScreenBrightness'; +const methodNameSetSystemScreenBrightness = 'setSystemScreenBrightness'; const methodNameGetScreenBrightness = 'getScreenBrightness'; const methodNameSetScreenBrightness = 'setScreenBrightness'; const methodNameResetScreenBrightness = 'resetScreenBrightness'; diff --git a/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart b/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart index e2251cf..b1171d0 100644 --- a/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart +++ b/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart @@ -79,6 +79,34 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { return currentBrightness; } + /// Set system brightness with double value. + /// + /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will + /// be throw. + /// + /// This method is useful for user to change system brightness. + /// + /// When [_channel.invokeMethod] fails to set system brightness, it throws + /// [PlatformException] with code and message: + /// + /// Code: -1, Message: Unable to change system brightness + /// Failed to set system brightness + /// + /// Code: -2, Message: Unexpected error on null brightness + /// Cannot read parameter from method channel map, or parameter is null + /// + /// (Android only) Code: -10, Message: Unexpected error on activity binding + /// Unexpected error when getting activity, activity may be null + @override + Future setSystemScreenBrightness(double brightness) async { + if (!brightness.isInRange(minBrightness, maxBrightness)) { + throw RangeError.range(brightness, minBrightness, maxBrightness); + } + + await pluginMethodChannel.invokeMethod( + methodNameSetSystemScreenBrightness, {"brightness": brightness}); + } + /// Set screen brightness with double value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will @@ -86,7 +114,7 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { /// /// This method is useful for user to change screen brightness. /// - /// When [_channel.invokeMethod] fails to get current brightness, it throws + /// When [_channel.invokeMethod] fails to set current brightness, it throws /// [PlatformException] with code and message: /// /// Code: -1, Message: Unable to change screen brightness diff --git a/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart b/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart index e5feee7..3a4a293 100644 --- a/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart +++ b/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart @@ -53,6 +53,17 @@ abstract class ScreenBrightnessPlatform extends PlatformInterface { throw UnimplementedError('current brightness has not been implemented.'); } + /// Set system brightness with double value. + /// + /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will + /// be throw. + /// + /// This method is useful for user to change system brightness. + Future setSystemScreenBrightness(double brightness) async { + throw UnimplementedError( + 'setSystemScreenBrightness(brightness) has not been implemented.'); + } + /// Set screen brightness with double value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will From c4e170273d46cdea6070537ea2a99779a4b51e34 Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Sun, 28 Apr 2024 12:15:02 +0800 Subject: [PATCH 02/22] feat(screen-brightness-android): added change system brightness --- screen_brightness/lib/screen_brightness.dart | 22 +++ screen_brightness/pubspec.yaml | 22 +-- .../test/screen_brightness_test.dart | 8 +- .../ScreenBrightnessAndroidPlugin.kt | 55 ++++++++ .../android/app/src/main/AndroidManifest.xml | 6 +- .../example/lib/main.dart | 129 +++++++++++------- .../example/pubspec.lock | 7 +- .../example/pubspec.yaml | 6 +- screen_brightness_android/pubspec.yaml | 6 +- 9 files changed, 190 insertions(+), 71 deletions(-) diff --git a/screen_brightness/lib/screen_brightness.dart b/screen_brightness/lib/screen_brightness.dart index 3130106..402f6ca 100644 --- a/screen_brightness/lib/screen_brightness.dart +++ b/screen_brightness/lib/screen_brightness.dart @@ -67,6 +67,28 @@ class ScreenBrightness { /// (Android) Settings.System.SCREEN_BRIGHTNESS Future get current => _platform.current; + /// Set system brightness with double value. + /// + /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will + /// be throw. + /// + /// This method is useful for user to change system brightness. + /// + /// When [_channel.invokeMethod] fails to set system brightness, it throws + /// [PlatformException] with code and message: + /// + /// Code: -1, Message: Unable to change system brightness + /// Failed to set system brightness + /// + /// Code: -2, Message: Unexpected error on null brightness + /// Cannot read parameter from method channel map, or parameter is null + /// + /// (Android only) Code: -10, Message: Unexpected error on activity binding + /// Unexpected error when getting activity, activity may be null + @override + Future setSystemScreenBrightness(double brightness) => + _platform.setSystemScreenBrightness(brightness); + /// Set screen brightness with double value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will diff --git a/screen_brightness/pubspec.yaml b/screen_brightness/pubspec.yaml index d3f90ca..6c070fc 100644 --- a/screen_brightness/pubspec.yaml +++ b/screen_brightness/pubspec.yaml @@ -30,17 +30,17 @@ dev_dependencies: plugin_platform_interface: ">=2.0.0 <3.0.0" async: ">=2.0.0 <3.0.0" -#dependency_overrides: -# screen_brightness_platform_interface: -# path: ../screen_brightness_platform_interface/ -# screen_brightness_android: -# path: ../screen_brightness_android -# screen_brightness_ios: -# path: ../screen_brightness_ios -# screen_brightness_macos: -# path: ../screen_brightness_macos -# screen_brightness_windows: -# path: ../screen_brightness_windows +dependency_overrides: + screen_brightness_platform_interface: + path: ../screen_brightness_platform_interface/ + screen_brightness_android: + path: ../screen_brightness_android + screen_brightness_ios: + path: ../screen_brightness_ios + screen_brightness_macos: + path: ../screen_brightness_macos + screen_brightness_windows: + path: ../screen_brightness_windows # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/screen_brightness/test/screen_brightness_test.dart b/screen_brightness/test/screen_brightness_test.dart index 70eb4d6..33eaa24 100644 --- a/screen_brightness/test/screen_brightness_test.dart +++ b/screen_brightness/test/screen_brightness_test.dart @@ -13,6 +13,7 @@ late StreamController controller; class MockScreenBrightnessPlatform with MockPlatformInterfaceMixin implements ScreenBrightnessPlatform { + double _systemBrightness = systemBrightness; double _currentBrightness = systemBrightness; double? _changedBrightness; @@ -20,11 +21,16 @@ class MockScreenBrightnessPlatform bool _isAnimate = true; @override - Future get system => Future.value(systemBrightness); + Future get system => Future.value(_systemBrightness); @override Future get current => Future.value(_currentBrightness); + @override + Future setSystemScreenBrightness(double brightness) async { + _systemBrightness = brightness; + } + @override Future setScreenBrightness(double brightness, {bool animated = true}) async { diff --git a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt index d5963f6..2a8ec80 100644 --- a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt +++ b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt @@ -1,10 +1,15 @@ package com.aaassseee.screen_brightness_android import android.app.Activity +import android.app.Instrumentation.ActivityResult import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Build import android.os.PowerManager import android.provider.Settings import android.view.WindowManager +import androidx.core.app.ActivityCompat.startActivityForResult import com.aaassseee.screen_brightness_android.stream_handler.CurrentBrightnessChangeStreamHandler import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.activity.ActivityAware @@ -13,6 +18,7 @@ import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import io.flutter.plugin.common.PluginRegistry import java.lang.reflect.Field import kotlin.math.sign import kotlin.properties.Delegates @@ -104,6 +110,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { when (call.method) { "getSystemScreenBrightness" -> handleGetSystemBrightnessMethodCall(result) + "setSystemScreenBrightness" -> handleSetSystemBrightnessMethodCall(call, result) "getScreenBrightness" -> handleGetScreenBrightnessMethodCall(result) "setScreenBrightness" -> handleSetScreenBrightnessMethodCall(call, result) "resetScreenBrightness" -> handleResetScreenBrightnessMethodCall(result) @@ -123,10 +130,58 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity ) / maximumBrightness } + private fun setSystemBrightness(context: Context, brightness: Float): Boolean { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (!Settings.System.canWrite(context)) { + Intent( + Settings.ACTION_MANAGE_WRITE_SETTINGS, + Uri.parse("package:${context.packageName}") + ).let { + it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(it) + } + return false + } + } + + return Settings.System.putInt( + context.contentResolver, + Settings.System.SCREEN_BRIGHTNESS, + (maximumBrightness * brightness).toInt() + ) + } + private fun handleGetSystemBrightnessMethodCall(result: MethodChannel.Result) { result.success(systemBrightness) } + private fun handleSetSystemBrightnessMethodCall( + call: MethodCall, + result: MethodChannel.Result + ) { + val activity = activity + if (activity == null) { + result.error("-10", "Unexpected error on activity binding", null) + return + } + + val brightness: Float? = (call.argument("brightness") as? Double)?.toFloat() + if (brightness == null) { + result.error("-2", "Unexpected error on null brightness", null) + return + } + + val isSet = setSystemBrightness(activity.applicationContext, brightness) + if (!isSet) { + result.error("-1", "Unable to change system brightness", null) + return + } + + systemBrightness = brightness + result.success(null) + } + + private fun handleGetScreenBrightnessMethodCall(result: MethodChannel.Result) { val activity = activity if (activity == null) { diff --git a/screen_brightness_android/example/android/app/src/main/AndroidManifest.xml b/screen_brightness_android/example/android/app/src/main/AndroidManifest.xml index 76fa812..aac30a4 100644 --- a/screen_brightness_android/example/android/app/src/main/AndroidManifest.xml +++ b/screen_brightness_android/example/android/app/src/main/AndroidManifest.xml @@ -1,5 +1,7 @@ - + + + diff --git a/screen_brightness_android/example/lib/main.dart b/screen_brightness_android/example/lib/main.dart index 7305d76..b2e4854 100644 --- a/screen_brightness_android/example/lib/main.dart +++ b/screen_brightness_android/example/lib/main.dart @@ -123,6 +123,16 @@ class ControllerPage extends StatefulWidget { } class _ControllerPageState extends State { + Future setSystemBrightness(double brightness) async { + try { + await ScreenBrightnessPlatform.instance + .setSystemScreenBrightness(brightness); + } catch (e) { + debugPrint(e.toString()); + throw 'Failed to set brightness'; + } + } + Future setBrightness(double brightness) async { try { await ScreenBrightnessPlatform.instance.setScreenBrightness(brightness); @@ -147,53 +157,78 @@ class _ControllerPageState extends State { appBar: AppBar( title: const Text('Controller'), ), - body: Center( - child: FutureBuilder( - future: ScreenBrightnessPlatform.instance.current, - builder: (context, snapshot) { - double currentBrightness = 0; - if (snapshot.hasData) { - currentBrightness = snapshot.data!; - } - - return StreamBuilder( - stream: - ScreenBrightnessPlatform.instance.onCurrentBrightnessChanged, - builder: (context, snapshot) { - double changedBrightness = currentBrightness; - if (snapshot.hasData) { - changedBrightness = snapshot.data!; - } - - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - FutureBuilder( - future: ScreenBrightnessPlatform.instance.hasChanged, - builder: (context, snapshot) { - return Text( - 'Brightness has changed via plugin: ${snapshot.data}'); - }, - ), - Text('Current brightness: $changedBrightness'), - Slider.adaptive( - value: changedBrightness, - onChanged: (value) { - setBrightness(value); - }, - ), - ElevatedButton( - onPressed: () { - resetBrightness(); - }, - child: const Text('reset brightness'), - ), - ], - ); - }, - ); - }, - ), + body: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + FutureBuilder( + future: ScreenBrightnessPlatform.instance.system, + builder: (context, snapshot) { + double systemBrightness = 0; + if (snapshot.hasData) { + systemBrightness = snapshot.data!; + } + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('System brightness: $systemBrightness'), + Slider.adaptive( + value: systemBrightness, + onChanged: (value) { + setSystemBrightness(value); + }, + ), + ], + ); + }, + ), + FutureBuilder( + future: ScreenBrightnessPlatform.instance.current, + builder: (context, snapshot) { + double currentBrightness = 0; + if (snapshot.hasData) { + currentBrightness = snapshot.data!; + } + + return StreamBuilder( + stream: ScreenBrightnessPlatform + .instance.onCurrentBrightnessChanged, + builder: (context, snapshot) { + double changedBrightness = currentBrightness; + if (snapshot.hasData) { + changedBrightness = snapshot.data!; + } + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + FutureBuilder( + future: ScreenBrightnessPlatform.instance.hasChanged, + builder: (context, snapshot) { + return Text( + 'Brightness has changed via plugin: ${snapshot.data}'); + }, + ), + Text('Current brightness: $changedBrightness'), + Slider.adaptive( + value: changedBrightness, + onChanged: (value) { + setBrightness(value); + }, + ), + ElevatedButton( + onPressed: () { + resetBrightness(); + }, + child: const Text('reset brightness'), + ), + ], + ); + }, + ); + }, + ), + ], ), ); } diff --git a/screen_brightness_android/example/pubspec.lock b/screen_brightness_android/example/pubspec.lock index 333cf6a..77c5158 100644 --- a/screen_brightness_android/example/pubspec.lock +++ b/screen_brightness_android/example/pubspec.lock @@ -149,10 +149,9 @@ packages: screen_brightness_platform_interface: dependency: "direct main" description: - name: screen_brightness_platform_interface - sha256: "9f3ebf7f22d5487e7676fe9ddaf3fc55b6ff8057707cf6dc0121c7dfda346a16" - url: "https://pub.dev" - source: hosted + path: "../../screen_brightness_platform_interface" + relative: true + source: path version: "1.0.1" sky_engine: dependency: transitive diff --git a/screen_brightness_android/example/pubspec.yaml b/screen_brightness_android/example/pubspec.yaml index 80820cc..b1b4594 100644 --- a/screen_brightness_android/example/pubspec.yaml +++ b/screen_brightness_android/example/pubspec.yaml @@ -26,9 +26,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -#dependency_overrides: -# screen_brightness_platform_interface: -# path: ../../screen_brightness_platform_interface/ +dependency_overrides: + screen_brightness_platform_interface: + path: ../../screen_brightness_platform_interface/ # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/screen_brightness_android/pubspec.yaml b/screen_brightness_android/pubspec.yaml index f65dcda..ff5b3af 100644 --- a/screen_brightness_android/pubspec.yaml +++ b/screen_brightness_android/pubspec.yaml @@ -24,9 +24,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -#dependency_overrides: -# screen_brightness_platform_interface: -# path: ../screen_brightness_platform_interface/ +dependency_overrides: + screen_brightness_platform_interface: + path: ../screen_brightness_platform_interface/ flutter: plugin: From f82ad0c74d1f0eecd6dcb509d8719729e75d8eca Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Wed, 1 May 2024 23:11:56 +0800 Subject: [PATCH 03/22] refactor!: renamed screen brightness to application screen brightness --- screen_brightness/lib/screen_brightness.dart | 122 +++--- .../test/screen_brightness_test.dart | 11 +- .../ScreenBrightnessAndroidPlugin.kt | 2 +- .../example/lib/main.dart | 25 +- screen_brightness_ios/example/lib/main.dart | 27 +- .../SwiftScreenBrightnessIosPlugin.swift | 2 +- screen_brightness_macos/example/lib/main.dart | 27 +- .../Classes/ScreenBrightnessMacosPlugin.swift | 2 +- .../lib/constant/method_name.dart | 12 +- .../lib/constant/plugin_channel.dart | 13 +- .../lib/method_channel_screen_brightness.dart | 133 ++++--- .../screen_brightness_platform_interface.dart | 95 ++--- ...en_brightness_platform_interface_test.dart | 170 +++++--- .../example/lib/main.dart | 27 +- .../screen_brightness_windows.iml | 375 ++++++++++++++++++ .../src/screen_brightness_windows_plugin.cpp | 2 +- 16 files changed, 763 insertions(+), 282 deletions(-) diff --git a/screen_brightness/lib/screen_brightness.dart b/screen_brightness/lib/screen_brightness.dart index 402f6ca..19863de 100644 --- a/screen_brightness/lib/screen_brightness.dart +++ b/screen_brightness/lib/screen_brightness.dart @@ -25,59 +25,62 @@ class ScreenBrightness { return ScreenBrightnessPlatform.instance; } - /// Returns system screen brightness which is set when application is started. + /// Returns system screen brightness. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This parameter is useful for user to get screen brightness value after - /// calling [resetScreenBrightness] + /// This parameter is useful for user to get system screen brightness value + /// after calling [setSystemScreenBrightness] + /// + /// This parameter is useful for user to get system screen brightness value + /// after calling [resetApplicationScreenBrightness] /// /// Platform difference: - /// (macOS): return initial brightness + /// (macOS)(Windows): return initial brightness /// - /// When [_channel.invokeMethod] fails to get current brightness, it throws - /// [PlatformException] with code and message: + /// When [_channel.invokeMethod] fails to get system screen brightness, it + /// throws [PlatformException] with code and message: /// - /// Code: -9, Message: Brightness value returns null + /// Code: -9, Message: value returns null Future get system => _platform.system; - /// Returns current screen brightness which is current screen brightness value. + /// Returns application screen brightness value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This parameter is useful for user to get screen brightness value after - /// calling [setScreenBrightness] + /// This parameter is useful for user to get application screen brightness + /// value after calling [setApplicationScreenBrightness] /// - /// Calling this method after calling [resetScreenBrightness] may return wrong + /// Calling this method after calling [resetApplicationScreenBrightness] may return wrong /// value in iOS because UIScreen.main.brightness returns old brightness value /// - /// When [_channel.invokeMethod] fails to get current brightness, it throws - /// [PlatformException] with code and message: + /// When [_channel.invokeMethod] fails to get application screen brightness, + /// it throws [PlatformException] with code and message: /// - /// Code: -9, Message: Brightness value returns null + /// Code: -9, Message: value returns null /// /// (Android only) Code: -10, Message: Unexpected error on activity binding /// Unexpected error when getting activity, activity may be null /// /// (Android only) (macOS only) Code: -11, Message: Could not found system - /// setting screen brightness value + /// screen brightness value /// Unexpected error when getting brightness from Setting using /// (Android) Settings.System.SCREEN_BRIGHTNESS - Future get current => _platform.current; + Future get application => _platform.application; - /// Set system brightness with double value. + /// Set system screen brightness with double value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This method is useful for user to change system brightness. + /// This method is useful for user to change system screen brightness. /// - /// When [_channel.invokeMethod] fails to set system brightness, it throws - /// [PlatformException] with code and message: + /// When [_channel.invokeMethod] fails to set system screen brightness, it + /// throws [PlatformException] with code and message: /// - /// Code: -1, Message: Unable to change system brightness + /// Code: -1, Message: Unable to change system screen brightness /// Failed to set system brightness /// /// Code: -2, Message: Unexpected error on null brightness @@ -85,21 +88,20 @@ class ScreenBrightness { /// /// (Android only) Code: -10, Message: Unexpected error on activity binding /// Unexpected error when getting activity, activity may be null - @override Future setSystemScreenBrightness(double brightness) => _platform.setSystemScreenBrightness(brightness); - /// Set screen brightness with double value. + /// Set application screen brightness with double value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This method is useful for user to change screen brightness. + /// This method is useful for user to change application screen brightness. /// - /// When [_channel.invokeMethod] fails to get current brightness, it throws - /// [PlatformException] with code and message: + /// When [_channel.invokeMethod] fails to set application screen brightness, + /// it throws [PlatformException] with code and message: /// - /// Code: -1, Message: Unable to change screen brightness + /// Code: -1, Message: Unable to change application screen brightness /// Failed to set brightness /// /// Code: -2, Message: Unexpected error on null brightness @@ -107,45 +109,50 @@ class ScreenBrightness { /// /// (Android only) Code: -10, Message: Unexpected error on activity binding /// Unexpected error when getting activity, activity may be null - Future setScreenBrightness(double brightness) => - _platform.setScreenBrightness(brightness); + Future setApplicationScreenBrightness(double brightness) => + _platform.setApplicationScreenBrightness(brightness); - /// Reset screen brightness with (Android)-1 or (iOS)system brightness value. + /// Reset application screen brightness with (Android) -1 or (iOS)system + /// brightness value. /// - /// This method is useful for user to reset screen brightness when user leave - /// the page which has change the brightness value. + /// This method is useful for user to reset application screen brightness + /// when user leave the page which has change the application screen + /// brightness value. /// - /// When [_channel.invokeMethod] fails to get current brightness, it throws - /// [PlatformException] with code and message: + /// When [_channel.invokeMethod] fails to get application screen brightness, + /// it throws [PlatformException] with code and message: /// - /// Code: -1, Message: Unable to change screen brightness - /// Failed to reset brightness + /// Code: -1, Message: Unable to reset application screen brightness + /// Failed to reset application screen brightness /// /// Code: -2, Message: Unexpected error on null brightness /// System brightness in plugin is null /// /// (Android only) Code: -10, Message: Unexpected error on activity binding /// Unexpected error when getting activity, activity may be null - Future resetScreenBrightness() => _platform.resetScreenBrightness(); + Future resetApplicationScreenBrightness() => + _platform.resetApplicationScreenBrightness(); - /// Returns stream with screen brightness changes including - /// [ScreenBrightness.setScreenBrightness], - /// [ScreenBrightness.resetScreenBrightness], system control center or system + /// Returns stream with application screen brightness changes including + /// [ScreenBrightness.setApplicationScreenBrightness], + /// [ScreenBrightness.resetApplicationScreenBrightness], system control center or system /// setting. /// /// This stream is useful for user to listen to brightness changes. - Stream get onCurrentBrightnessChanged => - _platform.onCurrentBrightnessChanged; + Stream get onApplicationBrightnessChanged => + _platform.onApplicationBrightnessChanged; - /// Returns boolean to identify brightness has changed with this plugin. + /// Returns boolean to identify application screen brightness has changed by + /// this plugin. /// /// e.g - /// [ScreenBrightness.setScreenBrightness] will make this true - /// [ScreenBrightness.resetScreenBrightness] will make this false - Future get hasChanged => _platform.hasChanged; + /// [ScreenBrightness.setApplicationScreenBrightness] will make this true + /// [ScreenBrightness.resetApplicationScreenBrightness] will make this false + Future get hasApplicationScreenBrightnessChanged => + _platform.hasApplicationScreenBrightnessChanged; - /// Returns boolean to identify will auto reset when application lifecycle - /// changed. + /// Returns boolean to identify will auto reset to system brightness when + /// application lifecycle changed. /// /// This parameter is useful for user to determinate current state of auto reset. /// @@ -153,29 +160,30 @@ class ScreenBrightness { /// having reset method. Future get isAutoReset => _platform.isAutoReset; - /// Returns boolean for disable auto reset when application lifecycle changed + /// Set auto reset when application lifecycle changed /// - /// This method is useful for user change weather this plugin should auto reset - /// brightness when application lifecycle changed. + /// This method is useful for user change whether this plugin should auto reset + /// to system brightness when application lifecycle changed. /// /// (iOS only) implemented in iOS only because only iOS native side does not /// having reset method. Future setAutoReset(bool isAutoReset) => _platform.setAutoReset(isAutoReset); - /// Returns boolean to identify will animate brightness transition + /// Returns boolean to identify will animate when application screen brightness + /// changed. /// - /// This parameter is useful for user to determinate will there be animate - /// transition. + /// This parameter is useful for user to determinate will there be animation + /// transition when application screen brightness changed. /// /// (iOS only) implemented in iOS only because only iOS native side does not /// having reset method. Future get isAnimate => _platform.isAnimate; - /// Set animate when brightness transition + /// Set will animate when application screen brightness changed. /// - /// This method is useful for user change weather this plugin should animate - /// when brightness transition + /// This method is useful for user change whether this plugin should animate + /// when application screen brightness changed. /// /// (iOS only) implemented in iOS only because only iOS native side does not /// having reset method. diff --git a/screen_brightness/test/screen_brightness_test.dart b/screen_brightness/test/screen_brightness_test.dart index 33eaa24..7571350 100644 --- a/screen_brightness/test/screen_brightness_test.dart +++ b/screen_brightness/test/screen_brightness_test.dart @@ -24,7 +24,7 @@ class MockScreenBrightnessPlatform Future get system => Future.value(_systemBrightness); @override - Future get current => Future.value(_currentBrightness); + Future get application => Future.value(_currentBrightness); @override Future setSystemScreenBrightness(double brightness) async { @@ -32,23 +32,24 @@ class MockScreenBrightnessPlatform } @override - Future setScreenBrightness(double brightness, + Future setApplicationScreenBrightness(double brightness, {bool animated = true}) async { _currentBrightness = brightness; _changedBrightness = brightness; } @override - Future resetScreenBrightness() async { + Future resetApplicationScreenBrightness() async { _currentBrightness = systemBrightness; _changedBrightness = null; } @override - Stream get onCurrentBrightnessChanged => controller.stream; + Stream get onApplicationBrightnessChanged => controller.stream; @override - Future get hasChanged async => _changedBrightness != null; + Future get hasApplicationScreenBrightnessChanged async => + _changedBrightness != null; @override Future get isAutoReset async => _isAutoReset; diff --git a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt index 2a8ec80..44facae 100644 --- a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt +++ b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt @@ -80,7 +80,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity currentBrightnessChangeEventChannel = EventChannel( flutterPluginBinding.binaryMessenger, - "github.com/aaassseee/screen_brightness/change" + "github.com/aaassseee/screen_brightness/application_brightness_change" ) try { diff --git a/screen_brightness_android/example/lib/main.dart b/screen_brightness_android/example/lib/main.dart index b2e4854..406b9f7 100644 --- a/screen_brightness_android/example/lib/main.dart +++ b/screen_brightness_android/example/lib/main.dart @@ -70,7 +70,7 @@ class HomePage extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ FutureBuilder( - future: ScreenBrightnessPlatform.instance.current, + future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { double currentBrightness = 0; if (snapshot.hasData) { @@ -79,7 +79,7 @@ class HomePage extends StatelessWidget { return StreamBuilder( stream: ScreenBrightnessPlatform - .instance.onCurrentBrightnessChanged, + .instance.onApplicationBrightnessChanged, builder: (context, snapshot) { double changedBrightness = currentBrightness; if (snapshot.hasData) { @@ -135,7 +135,8 @@ class _ControllerPageState extends State { Future setBrightness(double brightness) async { try { - await ScreenBrightnessPlatform.instance.setScreenBrightness(brightness); + await ScreenBrightnessPlatform.instance + .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); throw 'Failed to set brightness'; @@ -144,7 +145,8 @@ class _ControllerPageState extends State { Future resetBrightness() async { try { - await ScreenBrightnessPlatform.instance.resetScreenBrightness(); + await ScreenBrightnessPlatform.instance + .resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); throw 'Failed to reset brightness'; @@ -183,7 +185,7 @@ class _ControllerPageState extends State { }, ), FutureBuilder( - future: ScreenBrightnessPlatform.instance.current, + future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { double currentBrightness = 0; if (snapshot.hasData) { @@ -192,7 +194,7 @@ class _ControllerPageState extends State { return StreamBuilder( stream: ScreenBrightnessPlatform - .instance.onCurrentBrightnessChanged, + .instance.onApplicationBrightnessChanged, builder: (context, snapshot) { double changedBrightness = currentBrightness; if (snapshot.hasData) { @@ -203,7 +205,8 @@ class _ControllerPageState extends State { mainAxisSize: MainAxisSize.min, children: [ FutureBuilder( - future: ScreenBrightnessPlatform.instance.hasChanged, + future: ScreenBrightnessPlatform + .instance.hasApplicationScreenBrightnessChanged, builder: (context, snapshot) { return Text( 'Brightness has changed via plugin: ${snapshot.data}'); @@ -259,25 +262,25 @@ class _RouteAwarePageState extends State with RouteAware { @override void didPush() { super.didPush(); - ScreenBrightnessPlatform.instance.setScreenBrightness(0.7); + ScreenBrightnessPlatform.instance.setApplicationScreenBrightness(0.7); } @override void didPushNext() { super.didPushNext(); - ScreenBrightnessPlatform.instance.resetScreenBrightness(); + ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness(); } @override void didPop() { super.didPop(); - ScreenBrightnessPlatform.instance.resetScreenBrightness(); + ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness(); } @override void didPopNext() { super.didPopNext(); - ScreenBrightnessPlatform.instance.setScreenBrightness(0.7); + ScreenBrightnessPlatform.instance.setApplicationScreenBrightness(0.7); } @override diff --git a/screen_brightness_ios/example/lib/main.dart b/screen_brightness_ios/example/lib/main.dart index 7305d76..0a79f7b 100644 --- a/screen_brightness_ios/example/lib/main.dart +++ b/screen_brightness_ios/example/lib/main.dart @@ -70,7 +70,7 @@ class HomePage extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ FutureBuilder( - future: ScreenBrightnessPlatform.instance.current, + future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { double currentBrightness = 0; if (snapshot.hasData) { @@ -79,7 +79,7 @@ class HomePage extends StatelessWidget { return StreamBuilder( stream: ScreenBrightnessPlatform - .instance.onCurrentBrightnessChanged, + .instance.onApplicationBrightnessChanged, builder: (context, snapshot) { double changedBrightness = currentBrightness; if (snapshot.hasData) { @@ -125,7 +125,8 @@ class ControllerPage extends StatefulWidget { class _ControllerPageState extends State { Future setBrightness(double brightness) async { try { - await ScreenBrightnessPlatform.instance.setScreenBrightness(brightness); + await ScreenBrightnessPlatform.instance + .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); throw 'Failed to set brightness'; @@ -134,7 +135,8 @@ class _ControllerPageState extends State { Future resetBrightness() async { try { - await ScreenBrightnessPlatform.instance.resetScreenBrightness(); + await ScreenBrightnessPlatform.instance + .resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); throw 'Failed to reset brightness'; @@ -149,7 +151,7 @@ class _ControllerPageState extends State { ), body: Center( child: FutureBuilder( - future: ScreenBrightnessPlatform.instance.current, + future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { double currentBrightness = 0; if (snapshot.hasData) { @@ -157,8 +159,8 @@ class _ControllerPageState extends State { } return StreamBuilder( - stream: - ScreenBrightnessPlatform.instance.onCurrentBrightnessChanged, + stream: ScreenBrightnessPlatform + .instance.onApplicationBrightnessChanged, builder: (context, snapshot) { double changedBrightness = currentBrightness; if (snapshot.hasData) { @@ -169,7 +171,8 @@ class _ControllerPageState extends State { mainAxisSize: MainAxisSize.min, children: [ FutureBuilder( - future: ScreenBrightnessPlatform.instance.hasChanged, + future: ScreenBrightnessPlatform + .instance.hasApplicationScreenBrightnessChanged, builder: (context, snapshot) { return Text( 'Brightness has changed via plugin: ${snapshot.data}'); @@ -224,25 +227,25 @@ class _RouteAwarePageState extends State with RouteAware { @override void didPush() { super.didPush(); - ScreenBrightnessPlatform.instance.setScreenBrightness(0.7); + ScreenBrightnessPlatform.instance.setApplicationScreenBrightness(0.7); } @override void didPushNext() { super.didPushNext(); - ScreenBrightnessPlatform.instance.resetScreenBrightness(); + ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness(); } @override void didPop() { super.didPop(); - ScreenBrightnessPlatform.instance.resetScreenBrightness(); + ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness(); } @override void didPopNext() { super.didPopNext(); - ScreenBrightnessPlatform.instance.setScreenBrightness(0.7); + ScreenBrightnessPlatform.instance.setApplicationScreenBrightness(0.7); } @override diff --git a/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift b/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift index 4cdb66c..63144d2 100644 --- a/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift +++ b/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift @@ -24,7 +24,7 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp instance.methodChannel = FlutterMethodChannel(name: "github.com/aaassseee/screen_brightness", binaryMessenger: registrar.messenger()) registrar.addMethodCallDelegate(instance, channel: instance.methodChannel!) - instance.currentBrightnessChangeEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/change", binaryMessenger: registrar.messenger()) + instance.currentBrightnessChangeEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_change", binaryMessenger: registrar.messenger()) instance.currentBrightnessChangeEventChannel!.setStreamHandler(instance.currentBrightnessChangeStreamHandler) registrar.addApplicationDelegate(instance) diff --git a/screen_brightness_macos/example/lib/main.dart b/screen_brightness_macos/example/lib/main.dart index 7305d76..0a79f7b 100644 --- a/screen_brightness_macos/example/lib/main.dart +++ b/screen_brightness_macos/example/lib/main.dart @@ -70,7 +70,7 @@ class HomePage extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ FutureBuilder( - future: ScreenBrightnessPlatform.instance.current, + future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { double currentBrightness = 0; if (snapshot.hasData) { @@ -79,7 +79,7 @@ class HomePage extends StatelessWidget { return StreamBuilder( stream: ScreenBrightnessPlatform - .instance.onCurrentBrightnessChanged, + .instance.onApplicationBrightnessChanged, builder: (context, snapshot) { double changedBrightness = currentBrightness; if (snapshot.hasData) { @@ -125,7 +125,8 @@ class ControllerPage extends StatefulWidget { class _ControllerPageState extends State { Future setBrightness(double brightness) async { try { - await ScreenBrightnessPlatform.instance.setScreenBrightness(brightness); + await ScreenBrightnessPlatform.instance + .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); throw 'Failed to set brightness'; @@ -134,7 +135,8 @@ class _ControllerPageState extends State { Future resetBrightness() async { try { - await ScreenBrightnessPlatform.instance.resetScreenBrightness(); + await ScreenBrightnessPlatform.instance + .resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); throw 'Failed to reset brightness'; @@ -149,7 +151,7 @@ class _ControllerPageState extends State { ), body: Center( child: FutureBuilder( - future: ScreenBrightnessPlatform.instance.current, + future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { double currentBrightness = 0; if (snapshot.hasData) { @@ -157,8 +159,8 @@ class _ControllerPageState extends State { } return StreamBuilder( - stream: - ScreenBrightnessPlatform.instance.onCurrentBrightnessChanged, + stream: ScreenBrightnessPlatform + .instance.onApplicationBrightnessChanged, builder: (context, snapshot) { double changedBrightness = currentBrightness; if (snapshot.hasData) { @@ -169,7 +171,8 @@ class _ControllerPageState extends State { mainAxisSize: MainAxisSize.min, children: [ FutureBuilder( - future: ScreenBrightnessPlatform.instance.hasChanged, + future: ScreenBrightnessPlatform + .instance.hasApplicationScreenBrightnessChanged, builder: (context, snapshot) { return Text( 'Brightness has changed via plugin: ${snapshot.data}'); @@ -224,25 +227,25 @@ class _RouteAwarePageState extends State with RouteAware { @override void didPush() { super.didPush(); - ScreenBrightnessPlatform.instance.setScreenBrightness(0.7); + ScreenBrightnessPlatform.instance.setApplicationScreenBrightness(0.7); } @override void didPushNext() { super.didPushNext(); - ScreenBrightnessPlatform.instance.resetScreenBrightness(); + ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness(); } @override void didPop() { super.didPop(); - ScreenBrightnessPlatform.instance.resetScreenBrightness(); + ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness(); } @override void didPopNext() { super.didPopNext(); - ScreenBrightnessPlatform.instance.setScreenBrightness(0.7); + ScreenBrightnessPlatform.instance.setApplicationScreenBrightness(0.7); } @override diff --git a/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift b/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift index 3b8f67d..f08946e 100644 --- a/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift +++ b/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift @@ -24,7 +24,7 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { instance.methodChannel = FlutterMethodChannel(name: "github.com/aaassseee/screen_brightness", binaryMessenger: registrar.messenger) registrar.addMethodCallDelegate(instance, channel: instance.methodChannel!) - instance.currentBrightnessChangeEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/change", binaryMessenger: registrar.messenger) + instance.currentBrightnessChangeEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_change", binaryMessenger: registrar.messenger) instance.currentBrightnessChangeEventChannel!.setStreamHandler(instance.currentBrightnessChangeStreamHandler) } diff --git a/screen_brightness_platform_interface/lib/constant/method_name.dart b/screen_brightness_platform_interface/lib/constant/method_name.dart index d004638..d153a41 100644 --- a/screen_brightness_platform_interface/lib/constant/method_name.dart +++ b/screen_brightness_platform_interface/lib/constant/method_name.dart @@ -1,10 +1,14 @@ const methodNameGetSystemScreenBrightness = 'getSystemScreenBrightness'; const methodNameSetSystemScreenBrightness = 'setSystemScreenBrightness'; -const methodNameGetScreenBrightness = 'getScreenBrightness'; -const methodNameSetScreenBrightness = 'setScreenBrightness'; -const methodNameResetScreenBrightness = 'resetScreenBrightness'; +const methodNameGetApplicationScreenBrightness = + 'getApplicationScreenBrightness'; +const methodNameSetApplicationScreenBrightness = + 'setApplicationScreenBrightness'; +const methodNameResetApplicationScreenBrightness = + 'resetApplicationScreenBrightness'; -const methodNameHasChanged = 'hasChanged'; +const methodNameHasApplicationScreenBrightnessChanged = + 'hasApplicationScreenBrightnessChanged'; const methodNameIsAutoReset = 'isAutoReset'; const methodNameSetAutoReset = 'setAutoReset'; diff --git a/screen_brightness_platform_interface/lib/constant/plugin_channel.dart b/screen_brightness_platform_interface/lib/constant/plugin_channel.dart index 09d76aa..a6e97ba 100644 --- a/screen_brightness_platform_interface/lib/constant/plugin_channel.dart +++ b/screen_brightness_platform_interface/lib/constant/plugin_channel.dart @@ -3,7 +3,12 @@ import 'package:flutter/services.dart'; const pluginMethodChannelName = 'github.com/aaassseee/screen_brightness'; const pluginMethodChannel = MethodChannel(pluginMethodChannelName); -const pluginEventChannelCurrentBrightnessChangeName = - 'github.com/aaassseee/screen_brightness/change'; -const pluginEventChannelCurrentBrightnessChange = - EventChannel(pluginEventChannelCurrentBrightnessChangeName); +const pluginEventChannelApplicationBrightnessChangedName = + 'github.com/aaassseee/screen_brightness/application_brightness_change'; +const pluginEventChannelApplicationBrightnessChanged = + EventChannel(pluginEventChannelApplicationBrightnessChangedName); + +const pluginEventChannelSystemBrightnessChangedName = + 'github.com/aaassseee/screen_brightness/system_brightness_changed'; +const pluginEventChannelSystemBrightnessChanged = + EventChannel(pluginEventChannelSystemBrightnessChangedName); diff --git a/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart b/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart index b1171d0..0e18bc9 100644 --- a/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart +++ b/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart @@ -8,22 +8,26 @@ import 'constant/plugin_channel.dart'; /// Implementation of screen brightness platform interface class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { - /// Private stream which is listened to event channel for preventing - Stream? _onCurrentBrightnessChanged; + /// Private stream which is listened to event channel for preventing creating + /// new stream + Stream? _onApplicationBrightnessChanged; - /// Returns system screen brightness which is set when application is started. + /// Returns system screen brightness. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This parameter is useful for user to get screen brightness value after - /// calling [resetScreenBrightness] + /// This parameter is useful for user to get system screen brightness value + /// after calling [setSystemScreenBrightness] + /// + /// This parameter is useful for user to get system screen brightness value + /// after calling [resetApplicationScreenBrightness] /// /// Platform difference: - /// (macOS): return initial brightness + /// (macOS)(Windows): return initial brightness /// - /// When [_channel.invokeMethod] fails to get current brightness, it throws - /// [PlatformException] with code and message: + /// When [_channel.invokeMethod] fails to get system screen brightness, it + /// throws [PlatformException] with code and message: /// /// Code: -9, Message: value returns null @override @@ -41,19 +45,19 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { return systemBrightness; } - /// Returns current screen brightness which is current screen brightness value. + /// Returns application screen brightness value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This parameter is useful for user to get screen brightness value after - /// calling [setScreenBrightness] + /// This parameter is useful for user to get application screen brightness + /// value after calling [setApplicationScreenBrightness] /// - /// Calling this method after calling [resetScreenBrightness] may return wrong + /// Calling this method after calling [resetApplicationScreenBrightness] may return wrong /// value in iOS because UIScreen.main.brightness returns old brightness value /// - /// When [_channel.invokeMethod] fails to get current brightness, it throws - /// [PlatformException] with code and message: + /// When [_channel.invokeMethod] fails to get application screen brightness, + /// it throws [PlatformException] with code and message: /// /// Code: -9, Message: value returns null /// @@ -61,13 +65,13 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { /// Unexpected error when getting activity, activity may be null /// /// (Android only) (macOS only) Code: -11, Message: Could not found system - /// setting screen brightness value + /// screen brightness value /// Unexpected error when getting brightness from Setting using /// (Android) Settings.System.SCREEN_BRIGHTNESS @override - Future get current async { + Future get application async { final currentBrightness = await pluginMethodChannel - .invokeMethod(methodNameGetScreenBrightness); + .invokeMethod(methodNameGetApplicationScreenBrightness); if (currentBrightness == null) { throw PlatformException(code: "-9", message: "value returns null"); } @@ -79,17 +83,17 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { return currentBrightness; } - /// Set system brightness with double value. + /// Set system screen brightness with double value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This method is useful for user to change system brightness. + /// This method is useful for user to change system screen brightness. /// - /// When [_channel.invokeMethod] fails to set system brightness, it throws - /// [PlatformException] with code and message: + /// When [_channel.invokeMethod] fails to set system screen brightness, it + /// throws [PlatformException] with code and message: /// - /// Code: -1, Message: Unable to change system brightness + /// Code: -1, Message: Unable to change system screen brightness /// Failed to set system brightness /// /// Code: -2, Message: Unexpected error on null brightness @@ -107,17 +111,17 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { methodNameSetSystemScreenBrightness, {"brightness": brightness}); } - /// Set screen brightness with double value. + /// Set application screen brightness with double value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This method is useful for user to change screen brightness. + /// This method is useful for user to change application screen brightness. /// - /// When [_channel.invokeMethod] fails to set current brightness, it throws - /// [PlatformException] with code and message: + /// When [_channel.invokeMethod] fails to set application screen brightness, + /// it throws [PlatformException] with code and message: /// - /// Code: -1, Message: Unable to change screen brightness + /// Code: -1, Message: Unable to change application screen brightness /// Failed to set brightness /// /// Code: -2, Message: Unexpected error on null brightness @@ -126,25 +130,27 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { /// (Android only) Code: -10, Message: Unexpected error on activity binding /// Unexpected error when getting activity, activity may be null @override - Future setScreenBrightness(double brightness) async { + Future setApplicationScreenBrightness(double brightness) async { if (!brightness.isInRange(minBrightness, maxBrightness)) { throw RangeError.range(brightness, minBrightness, maxBrightness); } await pluginMethodChannel.invokeMethod( - methodNameSetScreenBrightness, {"brightness": brightness}); + methodNameSetApplicationScreenBrightness, {"brightness": brightness}); } - /// Reset screen brightness with (Android)-1 or (iOS)system brightness value. + /// Reset application screen brightness with (Android) -1 or (iOS)system + /// brightness value. /// - /// This method is useful for user to reset screen brightness when user leave - /// the page which has change the brightness value. + /// This method is useful for user to reset application screen brightness + /// when user leave the page which has change the application screen + /// brightness value. /// - /// When [_channel.invokeMethod] fails to get current brightness, it throws - /// [PlatformException] with code and message: + /// When [_channel.invokeMethod] fails to get application screen brightness, + /// it throws [PlatformException] with code and message: /// - /// Code: -1, Message: Unable to change screen brightness - /// Failed to reset brightness + /// Code: -1, Message: Unable to reset application screen brightness + /// Failed to reset application screen brightness /// /// Code: -2, Message: Unexpected error on null brightness /// System brightness in plugin is null @@ -152,37 +158,41 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { /// (Android only) Code: -10, Message: Unexpected error on activity binding /// Unexpected error when getting activity, activity may be null @override - Future resetScreenBrightness() async { - await pluginMethodChannel.invokeMethod(methodNameResetScreenBrightness); + Future resetApplicationScreenBrightness() async { + await pluginMethodChannel + .invokeMethod(methodNameResetApplicationScreenBrightness); } - /// Returns stream with screen brightness changes including - /// [ScreenBrightness.setScreenBrightness], - /// [ScreenBrightness.resetScreenBrightness], system control center or system + /// Returns stream with application screen brightness changes including + /// [ScreenBrightness.setApplicationScreenBrightness], + /// [ScreenBrightness.resetApplicationScreenBrightness], system control center or system /// setting. /// /// This stream is useful for user to listen to brightness changes. @override - Stream get onCurrentBrightnessChanged { - _onCurrentBrightnessChanged ??= pluginEventChannelCurrentBrightnessChange - .receiveBroadcastStream() - .cast(); - return _onCurrentBrightnessChanged!; + Stream get onApplicationBrightnessChanged { + _onApplicationBrightnessChanged ??= + pluginEventChannelApplicationBrightnessChanged + .receiveBroadcastStream() + .cast(); + return _onApplicationBrightnessChanged!; } - /// Returns boolean to identify brightness has changed with this plugin. + /// Returns boolean to identify application screen brightness has changed by + /// this plugin. /// /// e.g - /// [ScreenBrightness.setScreenBrightness] will make this true - /// [ScreenBrightness.resetScreenBrightness] will make this false + /// [ScreenBrightness.setApplicationScreenBrightness] will make this true + /// [ScreenBrightness.resetApplicationScreenBrightness] will make this false @override - Future get hasChanged async { - return await pluginMethodChannel.invokeMethod(methodNameHasChanged) ?? + Future get hasApplicationScreenBrightnessChanged async { + return await pluginMethodChannel.invokeMethod( + methodNameHasApplicationScreenBrightnessChanged) ?? false; } - /// Returns boolean to identify will auto reset when application lifecycle - /// changed. + /// Returns boolean to identify will auto reset to system brightness when + /// application lifecycle changed. /// /// This parameter is useful for user to determinate current state of auto reset. /// @@ -197,8 +207,8 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { /// Set auto reset when application lifecycle changed /// - /// This method is useful for user change weather this plugin should auto reset - /// brightness when application lifecycle changed. + /// This method is useful for user change whether this plugin should auto reset + /// to system brightness when application lifecycle changed. /// /// (iOS only) implemented in iOS only because only iOS native side does not /// having reset method. @@ -208,10 +218,11 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { .invokeMethod(methodNameSetAutoReset, {"isAutoReset": isAutoReset}); } - /// Returns boolean to identify will animate brightness transition + /// Returns boolean to identify will animate when application screen brightness + /// changed. /// - /// This parameter is useful for user to determinate will there be animate - /// transition. + /// This parameter is useful for user to determinate will there be animation + /// transition when application screen brightness changed. /// /// (iOS only) implemented in iOS only because only iOS native side does not /// having reset method. @@ -221,10 +232,10 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { true; } - /// Set animate when brightness transition + /// Set will animate when application screen brightness changed. /// - /// This method is useful for user change weather this plugin should animate - /// when brightness transition + /// This method is useful for user change whether this plugin should animate + /// when application screen brightness changed. /// /// (iOS only) implemented in iOS only because only iOS native side does not /// having reset method. diff --git a/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart b/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart index 3a4a293..33ffce6 100644 --- a/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart +++ b/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart @@ -31,114 +31,115 @@ abstract class ScreenBrightnessPlatform extends PlatformInterface { _instance = instance; } - /// Returns system screen brightness which is set when application is started. + /// Returns system screen brightness. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This parameter is useful for user to get screen brightness value after - /// calling [resetScreenBrightness] + /// This parameter is useful for user to get system screen brightness value + /// after calling [setSystemScreenBrightness] + /// + /// This parameter is useful for user to get system screen brightness value + /// after calling [resetApplicationScreenBrightness] Future get system async { throw UnimplementedError('system brightness has not been implemented.'); } - /// Returns current screen brightness which is current screen brightness value. + /// Returns application screen brightness value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This parameter is useful for user to get screen brightness value after - /// calling [setScreenBrightness] - Future get current async { - throw UnimplementedError('current brightness has not been implemented.'); + /// This parameter is useful for user to get application screen brightness + /// value after calling [setApplicationScreenBrightness] + Future get application async { + throw UnimplementedError( + 'application brightness has not been implemented.'); } - /// Set system brightness with double value. + /// Set system screen brightness with double value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This method is useful for user to change system brightness. + /// This method is useful for user to change system screen brightness. Future setSystemScreenBrightness(double brightness) async { throw UnimplementedError( 'setSystemScreenBrightness(brightness) has not been implemented.'); } - /// Set screen brightness with double value. + /// Set application screen brightness with double value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This method is useful for user to change screen brightness. - Future setScreenBrightness(double brightness) async { + /// This method is useful for user to change application screen brightness. + Future setApplicationScreenBrightness(double brightness) async { throw UnimplementedError( - 'setScreenBrightness(brightness) has not been implemented.'); + 'setApplicationScreenBrightness(brightness) has not been implemented.'); } - /// Reset screen brightness with (Android)-1 or (iOS)system brightness value. + /// Reset application screen brightness with (Android) -1 or (iOS)system + /// brightness value. /// - /// This method is useful for user to reset screen brightness when user leave - /// the page which has change the brightness value. - Future resetScreenBrightness() async { + /// This method is useful for user to reset application screen brightness + /// when user leave the page which has change the brightness value. + Future resetApplicationScreenBrightness() async { throw UnimplementedError( - 'resetScreenBrightness() has not been implemented.'); + 'resetApplicationScreenBrightness() has not been implemented.'); } - /// Returns stream with screen brightness changes including - /// [ScreenBrightness.setScreenBrightness], - /// [ScreenBrightness.resetScreenBrightness], system control center or system + /// Returns stream with application screen brightness changes including + /// [ScreenBrightness.setApplicationScreenBrightness], + /// [ScreenBrightness.resetApplicationScreenBrightness], system control center or system /// setting. /// /// This stream is useful for user to listen to brightness changes. - Stream get onCurrentBrightnessChanged { + Stream get onApplicationBrightnessChanged { throw UnimplementedError( - 'onCurrentBrightnessChanged has not been implemented.'); + 'onApplicationBrightnessChanged has not been implemented.'); } - /// Returns boolean to identify brightness has changed with this plugin. + /// Returns boolean to identify application screen brightness has changed by + /// this plugin. /// /// e.g - /// [ScreenBrightness.setScreenBrightness] will make this true - /// [ScreenBrightness.resetScreenBrightness] will make this false - Future get hasChanged { - throw UnimplementedError('hasChanged has not been implemented.'); + /// [ScreenBrightness.setApplicationScreenBrightness] will make this true + /// [ScreenBrightness.resetApplicationScreenBrightness] will make this false + Future get hasApplicationScreenBrightnessChanged { + throw UnimplementedError( + 'hasApplicationScreenBrightnessChanged has not been implemented.'); } - /// Returns boolean to identify will auto reset when application lifecycle - /// changed. + /// Returns boolean to identify will auto reset to system brightness when + /// application lifecycle changed. /// /// This parameter is useful for user to determinate current state of auto reset. - /// - /// (iOS only) implemented in iOS only because only iOS native side does not - /// having reset method. Future get isAutoReset async { - throw UnimplementedError( - 'isAutoResetWithLifecycleChange has not been implemented.'); + throw UnimplementedError('isAutoReset has not been implemented.'); } /// Set auto reset when application lifecycle changed /// - /// This method is useful for user change weather this plugin should auto reset - /// brightness when application lifecycle changed. - /// - /// (iOS only) implemented in iOS only because only iOS native side does not - /// having reset method. + /// This method is useful for user change whether this plugin should auto reset + /// to system brightness when application lifecycle changed. Future setAutoReset(bool isAutoReset) async { throw UnimplementedError('setAutoReset has not been implemented.'); } - /// Returns boolean to identify will animate brightness transition + /// Returns boolean to identify will animate when application screen brightness + /// change. /// - /// This parameter is useful for user to determinate will there be animate - /// transition. + /// This parameter is useful for user to determinate will there be animation + /// transition when application screen brightness changed. Future get isAnimate async { throw UnimplementedError('isAnimate has not been implemented.'); } - /// Set animate when brightness transition + /// Set will animate when application screen brightness changed. /// - /// This method is useful for user change weather this plugin should animate - /// when brightness transition + /// This method is useful for user change whether this plugin should animate + /// when application screen brightness changed. Future setAnimate(bool isAnimate) async { throw UnimplementedError('setAnimate has not been implemented.'); } diff --git a/screen_brightness_platform_interface/test/screen_brightness_platform_interface_test.dart b/screen_brightness_platform_interface/test/screen_brightness_platform_interface_test.dart index 723918e..90fe712 100644 --- a/screen_brightness_platform_interface/test/screen_brightness_platform_interface_test.dart +++ b/screen_brightness_platform_interface/test/screen_brightness_platform_interface_test.dart @@ -27,10 +27,11 @@ void main() { group('plugin test', () { double? systemBrightness; - double? changedBrightness; + double? applicationBrightness; bool isAutoReset = true; - const pluginEventChannelCurrentBrightnessChange = - MethodChannel(pluginEventChannelCurrentBrightnessChangeName); + bool isAnimate = true; + const pluginEventChannelApplicationBrightnessChanged = + MethodChannel(pluginEventChannelApplicationBrightnessChangedName); late MethodChannelScreenBrightness methodChannelScreenBrightness; setUp(() { @@ -43,19 +44,22 @@ void main() { case methodNameGetSystemScreenBrightness: return systemBrightness; - case methodNameGetScreenBrightness: - return changedBrightness ?? systemBrightness; + case methodNameSetSystemScreenBrightness: + systemBrightness = call.arguments['brightness']; - case methodNameSetScreenBrightness: - changedBrightness = call.arguments['brightness']; + case methodNameGetApplicationScreenBrightness: + return applicationBrightness ?? systemBrightness; + + case methodNameSetApplicationScreenBrightness: + applicationBrightness = call.arguments['brightness']; return null; - case methodNameResetScreenBrightness: - changedBrightness = null; + case methodNameResetApplicationScreenBrightness: + applicationBrightness = null; return null; - case methodNameHasChanged: - return changedBrightness != null; + case methodNameHasApplicationScreenBrightnessChanged: + return applicationBrightness != null; case methodNameIsAutoReset: return isAutoReset; @@ -63,21 +67,27 @@ void main() { case methodNameSetAutoReset: isAutoReset = call.arguments['isAutoReset']; return null; + + case methodNameIsAnimate: + return isAnimate; + + case methodNameSetAnimate: + isAnimate = call.arguments['isAnimate']; } return null; }); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(pluginEventChannelCurrentBrightnessChange, - (call) async { + .setMockMethodCallHandler( + pluginEventChannelApplicationBrightnessChanged, (call) async { switch (call.method) { case 'listen': await TestDefaultBinaryMessengerBinding .instance.defaultBinaryMessenger .handlePlatformMessage( - pluginEventChannelCurrentBrightnessChange.name, - pluginEventChannelCurrentBrightnessChange.codec + pluginEventChannelApplicationBrightnessChanged.name, + pluginEventChannelApplicationBrightnessChanged.codec .encodeSuccessEnvelope(0.2.toDouble()), (_) {}, ); @@ -97,7 +107,7 @@ void main() { .setMockMethodCallHandler(pluginMethodChannel, null); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler( - pluginEventChannelCurrentBrightnessChange, null); + pluginEventChannelApplicationBrightnessChanged, null); }); test('get platform instance', () { @@ -126,32 +136,51 @@ void main() { throwsA(isA())); }); - test('get screen brightness', () async { - expect(await methodChannelScreenBrightness.current, systemBrightness); + test('set system screen brightness', () async { + const targetBrightness = 0.1; + await methodChannelScreenBrightness + .setSystemScreenBrightness(targetBrightness); + expect(await methodChannelScreenBrightness.system, targetBrightness); + }); + + test('set system screen brightness with invalid number', () async { + Object? error; + try { + await methodChannelScreenBrightness.setSystemScreenBrightness(2); + } catch (e) { + error = e; + } + + expect(error, isA()); + }); + + test('get application screen brightness', () async { + expect(await methodChannelScreenBrightness.application, systemBrightness); }); - test('get screen brightness with null', () async { + test('get application screen brightness with null', () async { systemBrightness = null; - expect(() async => methodChannelScreenBrightness.current, + expect(() async => methodChannelScreenBrightness.application, throwsA(isA())); }); - test('get screen brightness with invalid number', () async { - changedBrightness = -1; - expect(() async => methodChannelScreenBrightness.current, + test('get application screen brightness with invalid number', () async { + applicationBrightness = -1; + expect(() async => methodChannelScreenBrightness.application, throwsA(isA())); }); - test('set screen brightness', () async { + test('set application screen brightness', () async { const targetBrightness = 0.1; - await methodChannelScreenBrightness.setScreenBrightness(targetBrightness); - expect(await methodChannelScreenBrightness.current, targetBrightness); + await methodChannelScreenBrightness + .setApplicationScreenBrightness(targetBrightness); + expect(await methodChannelScreenBrightness.application, targetBrightness); }); - test('set screen brightness with invalid number', () async { + test('set application screen brightness with invalid number', () async { Object? error; try { - await methodChannelScreenBrightness.setScreenBrightness(2); + await methodChannelScreenBrightness.setApplicationScreenBrightness(2); } catch (e) { error = e; } @@ -159,31 +188,40 @@ void main() { expect(error, isA()); }); - test('reset screen brightness', () async { - await methodChannelScreenBrightness.resetScreenBrightness(); + test('reset application screen brightness', () async { + await methodChannelScreenBrightness.resetApplicationScreenBrightness(); expect(await methodChannelScreenBrightness.system, systemBrightness); }); - test('on screen brightness changed', () async { - final result = - await methodChannelScreenBrightness.onCurrentBrightnessChanged.first; + test('on application screen brightness changed', () async { + final result = await methodChannelScreenBrightness + .onApplicationBrightnessChanged.first; expect(result, 0.2); }); - test('on screen brightness changed', () async { - final result = - await methodChannelScreenBrightness.onCurrentBrightnessChanged.first; + test('on application screen brightness changed', () async { + final result = await methodChannelScreenBrightness + .onApplicationBrightnessChanged.first; expect(result, 0.2); }); - test('has changed', () async { - expect(await methodChannelScreenBrightness.hasChanged, false); + test('has application screen brightness changed', () async { + expect( + await methodChannelScreenBrightness + .hasApplicationScreenBrightnessChanged, + false); - await methodChannelScreenBrightness.setScreenBrightness(0.1); - expect(await methodChannelScreenBrightness.hasChanged, true); + await methodChannelScreenBrightness.setApplicationScreenBrightness(0.1); + expect( + await methodChannelScreenBrightness + .hasApplicationScreenBrightnessChanged, + true); - await methodChannelScreenBrightness.resetScreenBrightness(); - expect(await methodChannelScreenBrightness.hasChanged, false); + await methodChannelScreenBrightness.resetApplicationScreenBrightness(); + expect( + await methodChannelScreenBrightness + .hasApplicationScreenBrightnessChanged, + false); }); test('is auto reset', () async { @@ -195,6 +233,16 @@ void main() { await methodChannelScreenBrightness.setAutoReset(true); expect(await methodChannelScreenBrightness.isAutoReset, true); }); + + test('is animate', () async { + expect(await methodChannelScreenBrightness.isAnimate, true); + + await methodChannelScreenBrightness.setAnimate(false); + expect(await methodChannelScreenBrightness.isAnimate, false); + + await methodChannelScreenBrightness.setAnimate(true); + expect(await methodChannelScreenBrightness.isAnimate, true); + }); }); group('mock unimplemented platform interface test', () { @@ -204,25 +252,33 @@ void main() { expect(() => platform.system, throwsUnimplementedError); }); - test('unimplemented current brightness', () { - expect(() => platform.current, throwsUnimplementedError); + test('unimplemented set system screen brightness', () { + expect(() => platform.setSystemScreenBrightness(0.2), + throwsUnimplementedError); }); - test('unimplemented set screen brightness', () { - expect(() => platform.setScreenBrightness(0.2), throwsUnimplementedError); + test('unimplemented application current brightness', () { + expect(() => platform.application, throwsUnimplementedError); }); - test('unimplemented reset screen brightness', () { - expect(() => platform.resetScreenBrightness(), throwsUnimplementedError); + test('unimplemented set application screen brightness', () { + expect(() => platform.setApplicationScreenBrightness(0.2), + throwsUnimplementedError); }); - test('unimplemented onCurrentBrightnessChanged stream', () { - expect( - () => platform.onCurrentBrightnessChanged, throwsUnimplementedError); + test('unimplemented reset application screen brightness', () { + expect(() => platform.resetApplicationScreenBrightness(), + throwsUnimplementedError); + }); + + test('unimplemented onApplicationBrightnessChanged stream', () { + expect(() => platform.onApplicationBrightnessChanged, + throwsUnimplementedError); }); - test('unimplemented has changed', () { - expect(() => platform.hasChanged, throwsUnimplementedError); + test('unimplemented has application screen brightness changed', () { + expect(() => platform.hasApplicationScreenBrightnessChanged, + throwsUnimplementedError); }); test('unimplemented is auto reset', () { @@ -232,5 +288,13 @@ void main() { test('unimplemented set auto reset', () { expect(() => platform.setAutoReset(true), throwsUnimplementedError); }); + + test('unimplemented is animate', () { + expect(() => platform.isAnimate, throwsUnimplementedError); + }); + + test('unimplemented set animate', () { + expect(() => platform.setAnimate(true), throwsUnimplementedError); + }); }); } diff --git a/screen_brightness_windows/example/lib/main.dart b/screen_brightness_windows/example/lib/main.dart index 7305d76..0a79f7b 100644 --- a/screen_brightness_windows/example/lib/main.dart +++ b/screen_brightness_windows/example/lib/main.dart @@ -70,7 +70,7 @@ class HomePage extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ FutureBuilder( - future: ScreenBrightnessPlatform.instance.current, + future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { double currentBrightness = 0; if (snapshot.hasData) { @@ -79,7 +79,7 @@ class HomePage extends StatelessWidget { return StreamBuilder( stream: ScreenBrightnessPlatform - .instance.onCurrentBrightnessChanged, + .instance.onApplicationBrightnessChanged, builder: (context, snapshot) { double changedBrightness = currentBrightness; if (snapshot.hasData) { @@ -125,7 +125,8 @@ class ControllerPage extends StatefulWidget { class _ControllerPageState extends State { Future setBrightness(double brightness) async { try { - await ScreenBrightnessPlatform.instance.setScreenBrightness(brightness); + await ScreenBrightnessPlatform.instance + .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); throw 'Failed to set brightness'; @@ -134,7 +135,8 @@ class _ControllerPageState extends State { Future resetBrightness() async { try { - await ScreenBrightnessPlatform.instance.resetScreenBrightness(); + await ScreenBrightnessPlatform.instance + .resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); throw 'Failed to reset brightness'; @@ -149,7 +151,7 @@ class _ControllerPageState extends State { ), body: Center( child: FutureBuilder( - future: ScreenBrightnessPlatform.instance.current, + future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { double currentBrightness = 0; if (snapshot.hasData) { @@ -157,8 +159,8 @@ class _ControllerPageState extends State { } return StreamBuilder( - stream: - ScreenBrightnessPlatform.instance.onCurrentBrightnessChanged, + stream: ScreenBrightnessPlatform + .instance.onApplicationBrightnessChanged, builder: (context, snapshot) { double changedBrightness = currentBrightness; if (snapshot.hasData) { @@ -169,7 +171,8 @@ class _ControllerPageState extends State { mainAxisSize: MainAxisSize.min, children: [ FutureBuilder( - future: ScreenBrightnessPlatform.instance.hasChanged, + future: ScreenBrightnessPlatform + .instance.hasApplicationScreenBrightnessChanged, builder: (context, snapshot) { return Text( 'Brightness has changed via plugin: ${snapshot.data}'); @@ -224,25 +227,25 @@ class _RouteAwarePageState extends State with RouteAware { @override void didPush() { super.didPush(); - ScreenBrightnessPlatform.instance.setScreenBrightness(0.7); + ScreenBrightnessPlatform.instance.setApplicationScreenBrightness(0.7); } @override void didPushNext() { super.didPushNext(); - ScreenBrightnessPlatform.instance.resetScreenBrightness(); + ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness(); } @override void didPop() { super.didPop(); - ScreenBrightnessPlatform.instance.resetScreenBrightness(); + ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness(); } @override void didPopNext() { super.didPopNext(); - ScreenBrightnessPlatform.instance.setScreenBrightness(0.7); + ScreenBrightnessPlatform.instance.setApplicationScreenBrightness(0.7); } @override diff --git a/screen_brightness_windows/screen_brightness_windows.iml b/screen_brightness_windows/screen_brightness_windows.iml index e2656b4..e545c25 100644 --- a/screen_brightness_windows/screen_brightness_windows.iml +++ b/screen_brightness_windows/screen_brightness_windows.iml @@ -12,6 +12,381 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp b/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp index 968b43b..1239aa1 100644 --- a/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp +++ b/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp @@ -60,7 +60,7 @@ namespace screen_brightness const auto current_brightness_change_event_channel = std::make_unique>( - registrar->messenger(), "github.com/aaassseee/screen_brightness/change", + registrar->messenger(), "github.com/aaassseee/screen_brightness/application_brightness_change", &flutter::StandardMethodCodec::GetInstance()); plugin->current_brightness_change_stream_handler_ = new CurrentBrightnessChangeStreamHandler(); From a28f1d70bb5679c4fb70f1f5f10db1556a5220db Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Thu, 2 May 2024 00:10:49 +0800 Subject: [PATCH 04/22] refactor!(screen-brightness): renamed screen brightness to application screen brightness --- screen_brightness/example/lib/main.dart | 63 ++++++++++--------- screen_brightness/lib/screen_brightness.dart | 42 ++++++------- .../test/screen_brightness_test.dart | 42 +++++++------ .../lib/method_channel_screen_brightness.dart | 56 ++++++++--------- .../screen_brightness_platform_interface.dart | 18 +++--- 5 files changed, 116 insertions(+), 105 deletions(-) diff --git a/screen_brightness/example/lib/main.dart b/screen_brightness/example/lib/main.dart index 4a4e4fc..a21ef64 100644 --- a/screen_brightness/example/lib/main.dart +++ b/screen_brightness/example/lib/main.dart @@ -70,22 +70,24 @@ class HomePage extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ FutureBuilder( - future: ScreenBrightness.instance.current, + future: ScreenBrightness.instance.application, builder: (context, snapshot) { - double currentBrightness = 0; + double applicationBrightness = 0; if (snapshot.hasData) { - currentBrightness = snapshot.data!; + applicationBrightness = snapshot.data!; } return StreamBuilder( - stream: ScreenBrightness.instance.onCurrentBrightnessChanged, + stream: + ScreenBrightness.instance.onApplicationBrightnessChanged, builder: (context, snapshot) { - double changedBrightness = currentBrightness; + double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { - changedBrightness = snapshot.data!; + changedApplicationBrightness = snapshot.data!; } - return Text('current brightness $changedBrightness'); + return Text( + 'Application screen brightness $changedApplicationBrightness'); }, ); }, @@ -122,21 +124,22 @@ class ControllerPage extends StatefulWidget { } class _ControllerPageState extends State { - Future setBrightness(double brightness) async { + Future setApplicationScreenBrightness(double brightness) async { try { - await ScreenBrightness.instance.setScreenBrightness(brightness); + await ScreenBrightness.instance + .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set brightness'; + throw 'Failed to set application screen brightness'; } } - Future resetBrightness() async { + Future resetApplicationScreenBrightness() async { try { - await ScreenBrightness.instance.resetScreenBrightness(); + await ScreenBrightness.instance.resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); - throw 'Failed to reset brightness'; + throw 'Failed to reset application screen brightness'; } } @@ -148,41 +151,43 @@ class _ControllerPageState extends State { ), body: Center( child: FutureBuilder( - future: ScreenBrightness.instance.current, + future: ScreenBrightness.instance.application, builder: (context, snapshot) { - double currentBrightness = 0; + double applicationBrightness = 0; if (snapshot.hasData) { - currentBrightness = snapshot.data!; + applicationBrightness = snapshot.data!; } return StreamBuilder( - stream: ScreenBrightness.instance.onCurrentBrightnessChanged, + stream: ScreenBrightness.instance.onApplicationBrightnessChanged, builder: (context, snapshot) { - double changedBrightness = currentBrightness; + double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { - changedBrightness = snapshot.data!; + changedApplicationBrightness = snapshot.data!; } return Column( mainAxisSize: MainAxisSize.min, children: [ FutureBuilder( - future: ScreenBrightness.instance.hasChanged, + future: ScreenBrightness + .instance.hasApplicationScreenBrightnessChanged, builder: (context, snapshot) { return Text( - 'Brightness has changed via plugin: ${snapshot.data}'); + 'Application brightness has changed via plugin: ${snapshot.data}'); }, ), - Text('Current brightness: $changedBrightness'), + Text( + 'Application screen brightness: $changedApplicationBrightness'), Slider.adaptive( - value: changedBrightness, + value: changedApplicationBrightness, onChanged: (value) { - setBrightness(value); + setApplicationScreenBrightness(value); }, ), ElevatedButton( onPressed: () { - resetBrightness(); + resetApplicationScreenBrightness(); }, child: const Text('reset brightness'), ), @@ -222,25 +227,25 @@ class _RouteAwarePageState extends State with RouteAware { @override void didPush() { super.didPush(); - ScreenBrightness.instance.setScreenBrightness(0.7); + ScreenBrightness.instance.setApplicationScreenBrightness(0.7); } @override void didPushNext() { super.didPushNext(); - ScreenBrightness.instance.resetScreenBrightness(); + ScreenBrightness.instance.resetApplicationScreenBrightness(); } @override void didPop() { super.didPop(); - ScreenBrightness.instance.resetScreenBrightness(); + ScreenBrightness.instance.resetApplicationScreenBrightness(); } @override void didPopNext() { super.didPopNext(); - ScreenBrightness.instance.setScreenBrightness(0.7); + ScreenBrightness.instance.setApplicationScreenBrightness(0.7); } @override diff --git a/screen_brightness/lib/screen_brightness.dart b/screen_brightness/lib/screen_brightness.dart index 19863de..34b3384 100644 --- a/screen_brightness/lib/screen_brightness.dart +++ b/screen_brightness/lib/screen_brightness.dart @@ -45,6 +45,27 @@ class ScreenBrightness { /// Code: -9, Message: value returns null Future get system => _platform.system; + /// Set system screen brightness with double value. + /// + /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will + /// be throw. + /// + /// This method is useful for user to change system screen brightness. + /// + /// When [_channel.invokeMethod] fails to set system screen brightness, it + /// throws [PlatformException] with code and message: + /// + /// Code: -1, Message: Unable to change system screen brightness + /// Failed to set system brightness + /// + /// Code: -2, Message: Unexpected error on null brightness + /// Cannot read parameter from method channel map, or parameter is null + /// + /// (Android only) Code: -10, Message: Unexpected error on activity binding + /// Unexpected error when getting activity, activity may be null + Future setSystemScreenBrightness(double brightness) => + _platform.setSystemScreenBrightness(brightness); + /// Returns application screen brightness value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will @@ -70,27 +91,6 @@ class ScreenBrightness { /// (Android) Settings.System.SCREEN_BRIGHTNESS Future get application => _platform.application; - /// Set system screen brightness with double value. - /// - /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will - /// be throw. - /// - /// This method is useful for user to change system screen brightness. - /// - /// When [_channel.invokeMethod] fails to set system screen brightness, it - /// throws [PlatformException] with code and message: - /// - /// Code: -1, Message: Unable to change system screen brightness - /// Failed to set system brightness - /// - /// Code: -2, Message: Unexpected error on null brightness - /// Cannot read parameter from method channel map, or parameter is null - /// - /// (Android only) Code: -10, Message: Unexpected error on activity binding - /// Unexpected error when getting activity, activity may be null - Future setSystemScreenBrightness(double brightness) => - _platform.setSystemScreenBrightness(brightness); - /// Set application screen brightness with double value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will diff --git a/screen_brightness/test/screen_brightness_test.dart b/screen_brightness/test/screen_brightness_test.dart index 7571350..fb63c7f 100644 --- a/screen_brightness/test/screen_brightness_test.dart +++ b/screen_brightness/test/screen_brightness_test.dart @@ -82,22 +82,28 @@ void main() { expect(await screenBrightness.system, systemBrightness); }); - test('get screen brightness', () async { - expect(await screenBrightness.current, systemBrightness); + test('set system screen brightness with valid number', () async { + const targetBrightness = 0.1; + await screenBrightness.setSystemScreenBrightness(targetBrightness); + expect(await screenBrightness.system, targetBrightness); + }); + + test('get application screen brightness', () async { + expect(await screenBrightness.application, systemBrightness); }); - test('set screen brightness with valid number', () async { + test('set application screen brightness with valid number', () async { const targetBrightness = 0.1; - await screenBrightness.setScreenBrightness(targetBrightness); - expect(await screenBrightness.current, targetBrightness); + await screenBrightness.setApplicationScreenBrightness(targetBrightness); + expect(await screenBrightness.application, targetBrightness); }); - test('reset screen brightness', () async { - await screenBrightness.resetScreenBrightness(); - expect(await screenBrightness.current, systemBrightness); + test('reset application screen brightness', () async { + await screenBrightness.resetApplicationScreenBrightness(); + expect(await screenBrightness.application, systemBrightness); }); - group('on screen brightness changed stream', () { + group('on application screen brightness changed stream', () { setUp(() { controller = StreamController(); }); @@ -108,7 +114,7 @@ void main() { test('receive values', () async { final queue = - StreamQueue(screenBrightness.onCurrentBrightnessChanged); + StreamQueue(screenBrightness.onApplicationBrightnessChanged); controller.add(0.2); expect(await queue.next, 0.2); @@ -124,17 +130,17 @@ void main() { }); }); - test('has changed', () async { - expect(await screenBrightness.hasChanged, false); + test('has application screen brightness changed', () async { + expect(await screenBrightness.hasApplicationScreenBrightnessChanged, false); - await screenBrightness.setScreenBrightness(0.1); - expect(await screenBrightness.hasChanged, true); + await screenBrightness.setApplicationScreenBrightness(0.1); + expect(await screenBrightness.hasApplicationScreenBrightnessChanged, true); - await screenBrightness.setScreenBrightness(systemBrightness); - expect(await screenBrightness.hasChanged, true); + await screenBrightness.setApplicationScreenBrightness(systemBrightness); + expect(await screenBrightness.hasApplicationScreenBrightnessChanged, true); - await screenBrightness.resetScreenBrightness(); - expect(await screenBrightness.hasChanged, false); + await screenBrightness.resetApplicationScreenBrightness(); + expect(await screenBrightness.hasApplicationScreenBrightnessChanged, false); }); test('is auto reset', () async { diff --git a/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart b/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart index 0e18bc9..8f92d86 100644 --- a/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart +++ b/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart @@ -45,6 +45,34 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { return systemBrightness; } + /// Set system screen brightness with double value. + /// + /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will + /// be throw. + /// + /// This method is useful for user to change system screen brightness. + /// + /// When [_channel.invokeMethod] fails to set system screen brightness, it + /// throws [PlatformException] with code and message: + /// + /// Code: -1, Message: Unable to change system screen brightness + /// Failed to set system brightness + /// + /// Code: -2, Message: Unexpected error on null brightness + /// Cannot read parameter from method channel map, or parameter is null + /// + /// (Android only) Code: -10, Message: Unexpected error on activity binding + /// Unexpected error when getting activity, activity may be null + @override + Future setSystemScreenBrightness(double brightness) async { + if (!brightness.isInRange(minBrightness, maxBrightness)) { + throw RangeError.range(brightness, minBrightness, maxBrightness); + } + + await pluginMethodChannel.invokeMethod( + methodNameSetSystemScreenBrightness, {"brightness": brightness}); + } + /// Returns application screen brightness value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will @@ -83,34 +111,6 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { return currentBrightness; } - /// Set system screen brightness with double value. - /// - /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will - /// be throw. - /// - /// This method is useful for user to change system screen brightness. - /// - /// When [_channel.invokeMethod] fails to set system screen brightness, it - /// throws [PlatformException] with code and message: - /// - /// Code: -1, Message: Unable to change system screen brightness - /// Failed to set system brightness - /// - /// Code: -2, Message: Unexpected error on null brightness - /// Cannot read parameter from method channel map, or parameter is null - /// - /// (Android only) Code: -10, Message: Unexpected error on activity binding - /// Unexpected error when getting activity, activity may be null - @override - Future setSystemScreenBrightness(double brightness) async { - if (!brightness.isInRange(minBrightness, maxBrightness)) { - throw RangeError.range(brightness, minBrightness, maxBrightness); - } - - await pluginMethodChannel.invokeMethod( - methodNameSetSystemScreenBrightness, {"brightness": brightness}); - } - /// Set application screen brightness with double value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will diff --git a/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart b/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart index 33ffce6..7b1afd8 100644 --- a/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart +++ b/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart @@ -45,27 +45,27 @@ abstract class ScreenBrightnessPlatform extends PlatformInterface { throw UnimplementedError('system brightness has not been implemented.'); } - /// Returns application screen brightness value. + /// Set system screen brightness with double value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This parameter is useful for user to get application screen brightness - /// value after calling [setApplicationScreenBrightness] - Future get application async { + /// This method is useful for user to change system screen brightness. + Future setSystemScreenBrightness(double brightness) async { throw UnimplementedError( - 'application brightness has not been implemented.'); + 'setSystemScreenBrightness(brightness) has not been implemented.'); } - /// Set system screen brightness with double value. + /// Returns application screen brightness value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will /// be throw. /// - /// This method is useful for user to change system screen brightness. - Future setSystemScreenBrightness(double brightness) async { + /// This parameter is useful for user to get application screen brightness + /// value after calling [setApplicationScreenBrightness] + Future get application async { throw UnimplementedError( - 'setSystemScreenBrightness(brightness) has not been implemented.'); + 'application brightness has not been implemented.'); } /// Set application screen brightness with double value. From 456d2f01eb3d465e10301f37888897e0036febde Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Tue, 21 May 2024 01:04:58 +0800 Subject: [PATCH 05/22] feat!: added set system brightness --- screen_brightness/example/lib/main.dart | 141 ++++++++++------ .../ScreenBrightnessAndroidPlugin.kt | 81 +++++----- ...ionScreenBrightnessChangeStreamHandler.kt} | 2 +- .../example/lib/main.dart | 40 ++--- screen_brightness_ios/example/lib/main.dart | 151 +++++++++++------- screen_brightness_ios/example/pubspec.lock | 7 +- screen_brightness_ios/example/pubspec.yaml | 6 +- ...ScreenBrightnessChangeStreamHandler.swift} | 6 +- .../SwiftScreenBrightnessIosPlugin.swift | 129 +++++++++------ screen_brightness_ios/pubspec.yaml | 6 +- screen_brightness_macos/example/lib/main.dart | 151 +++++++++++------- screen_brightness_macos/example/pubspec.lock | 9 +- screen_brightness_macos/example/pubspec.yaml | 6 +- .../Classes/ScreenBrightnessMacosPlugin.swift | 123 ++++++++------ ...ScreenBrightnessChangeStreamHandler.swift} | 6 +- screen_brightness_macos/pubspec.yaml | 6 +- .../example/lib/main.dart | 151 +++++++++++------- .../example/pubspec.lock | 7 +- .../example/pubspec.yaml | 6 +- .../windows/CMakeLists.txt | 4 +- .../screen_brightness_windows_plugin.h | 36 +++-- .../src/screen_brightness_windows_plugin.cpp | 138 ++++++++++------ 22 files changed, 721 insertions(+), 491 deletions(-) rename screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/{CurrentBrightnessChangeStreamHandler.kt => ApplicationScreenBrightnessChangeStreamHandler.kt} (96%) rename screen_brightness_ios/ios/Classes/StreamHandler/{CurrentBrightnessChangeStreamHandler.swift => ApplicationScreenBrightnessChangeStreamHandler.swift} (51%) rename screen_brightness_macos/macos/Classes/StreamHandler/{CurrentBrightnessChangeStreamHandler.swift => ApplicationScreenBrightnessChangeStreamHandler.swift} (50%) diff --git a/screen_brightness/example/lib/main.dart b/screen_brightness/example/lib/main.dart index a21ef64..3438404 100644 --- a/screen_brightness/example/lib/main.dart +++ b/screen_brightness/example/lib/main.dart @@ -87,7 +87,7 @@ class HomePage extends StatelessWidget { } return Text( - 'Application screen brightness $changedApplicationBrightness'); + 'Application brightness $changedApplicationBrightness'); }, ); }, @@ -124,22 +124,31 @@ class ControllerPage extends StatefulWidget { } class _ControllerPageState extends State { - Future setApplicationScreenBrightness(double brightness) async { + Future setSystemBrightness(double brightness) async { + try { + await ScreenBrightness.instance.setSystemScreenBrightness(brightness); + } catch (e) { + debugPrint(e.toString()); + throw 'Failed to set system brightness'; + } + } + + Future setApplicationBrightness(double brightness) async { try { await ScreenBrightness.instance .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set application screen brightness'; + throw 'Failed to set application brightness'; } } - Future resetApplicationScreenBrightness() async { + Future resetApplicationBrightness() async { try { await ScreenBrightness.instance.resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); - throw 'Failed to reset application screen brightness'; + throw 'Failed to reset application brightness'; } } @@ -149,54 +158,80 @@ class _ControllerPageState extends State { appBar: AppBar( title: const Text('Controller'), ), - body: Center( - child: FutureBuilder( - future: ScreenBrightness.instance.application, - builder: (context, snapshot) { - double applicationBrightness = 0; - if (snapshot.hasData) { - applicationBrightness = snapshot.data!; - } - - return StreamBuilder( - stream: ScreenBrightness.instance.onApplicationBrightnessChanged, - builder: (context, snapshot) { - double changedApplicationBrightness = applicationBrightness; - if (snapshot.hasData) { - changedApplicationBrightness = snapshot.data!; - } - - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - FutureBuilder( - future: ScreenBrightness - .instance.hasApplicationScreenBrightnessChanged, - builder: (context, snapshot) { - return Text( - 'Application brightness has changed via plugin: ${snapshot.data}'); - }, - ), - Text( - 'Application screen brightness: $changedApplicationBrightness'), - Slider.adaptive( - value: changedApplicationBrightness, - onChanged: (value) { - setApplicationScreenBrightness(value); - }, - ), - ElevatedButton( - onPressed: () { - resetApplicationScreenBrightness(); - }, - child: const Text('reset brightness'), - ), - ], - ); - }, - ); - }, - ), + body: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + FutureBuilder( + future: ScreenBrightness.instance.system, + builder: (context, snapshot) { + double systemBrightness = 0; + if (snapshot.hasData) { + systemBrightness = snapshot.data!; + } + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('System brightness: $systemBrightness'), + Slider.adaptive( + value: systemBrightness, + onChanged: (value) { + setSystemBrightness(value); + }, + ), + ], + ); + }, + ), + FutureBuilder( + future: ScreenBrightness.instance.application, + builder: (context, snapshot) { + double applicationBrightness = 0; + if (snapshot.hasData) { + applicationBrightness = snapshot.data!; + } + + return StreamBuilder( + stream: + ScreenBrightness.instance.onApplicationBrightnessChanged, + builder: (context, snapshot) { + double changedApplicationBrightness = applicationBrightness; + if (snapshot.hasData) { + changedApplicationBrightness = snapshot.data!; + } + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + FutureBuilder( + future: ScreenBrightness + .instance.hasApplicationScreenBrightnessChanged, + builder: (context, snapshot) { + return Text( + 'Application brightness has changed via plugin: ${snapshot.data}'); + }, + ), + Text( + 'Application brightness: $changedApplicationBrightness'), + Slider.adaptive( + value: changedApplicationBrightness, + onChanged: (value) { + setApplicationBrightness(value); + }, + ), + ElevatedButton( + onPressed: () { + resetApplicationBrightness(); + }, + child: const Text('reset brightness'), + ), + ], + ); + }, + ); + }, + ), + ], ), ); } diff --git a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt index 44facae..811ec41 100644 --- a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt +++ b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt @@ -1,7 +1,6 @@ package com.aaassseee.screen_brightness_android import android.app.Activity -import android.app.Instrumentation.ActivityResult import android.content.Context import android.content.Intent import android.net.Uri @@ -9,8 +8,7 @@ import android.os.Build import android.os.PowerManager import android.provider.Settings import android.view.WindowManager -import androidx.core.app.ActivityCompat.startActivityForResult -import com.aaassseee.screen_brightness_android.stream_handler.CurrentBrightnessChangeStreamHandler +import com.aaassseee.screen_brightness_android.stream_handler.ApplicationScreenBrightnessChangeStreamHandler import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.activity.ActivityAware import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding @@ -18,7 +16,6 @@ import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler -import io.flutter.plugin.common.PluginRegistry import java.lang.reflect.Field import kotlin.math.sign import kotlin.properties.Delegates @@ -35,9 +32,9 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity */ private lateinit var methodChannel: MethodChannel - private lateinit var currentBrightnessChangeEventChannel: EventChannel + private lateinit var applicationScreenBrightnessChangedEventChannel: EventChannel - private var currentBrightnessChangeStreamHandler: CurrentBrightnessChangeStreamHandler? = null + private var applicationScreenBrightnessChangeStreamHandler: ApplicationScreenBrightnessChangeStreamHandler? = null private var activity: Activity? = null @@ -46,7 +43,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity * * This value refer to the brightness value between 0 and 1 when the application initialized. */ - private var systemBrightness by Delegates.notNull() + private var systemScreenBrightness by Delegates.notNull() /** * The value which will be init when this plugin is attached to the Flutter engine @@ -56,15 +53,15 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity * By system default the value should be 255.0f, however it vary in some OS, e.g. Miui. * Should not be changed in the future */ - private var maximumBrightness by Delegates.notNull() + private var maximumScreenBrightness by Delegates.notNull() /** - * The value which will be set when user called [handleSetScreenBrightnessMethodCall] - * or [handleResetScreenBrightnessMethodCall] + * The value which will be set when user called [handleSetApplicationScreenBrightnessMethodCall] + * or [handleResetApplicationScreenBrightnessMethodCall] * - * This value refer to the brightness value between 0 and 1 when user called [handleSetScreenBrightnessMethodCall]. + * This value refer to the brightness value between 0 and 1 when user called [handleSetApplicationScreenBrightnessMethodCall]. */ - private var changedBrightness: Float? = null + private var applicationScreenBrightness: Float? = null private var isAutoReset: Boolean = true @@ -78,14 +75,14 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity methodChannel.setMethodCallHandler(this) - currentBrightnessChangeEventChannel = EventChannel( + applicationScreenBrightnessChangedEventChannel = EventChannel( flutterPluginBinding.binaryMessenger, "github.com/aaassseee/screen_brightness/application_brightness_change" ) try { - maximumBrightness = getScreenMaximumBrightness(flutterPluginBinding.applicationContext) - systemBrightness = getSystemBrightness(flutterPluginBinding.applicationContext) + maximumScreenBrightness = getScreenMaximumBrightness(flutterPluginBinding.applicationContext) + systemScreenBrightness = getSystemBrightness(flutterPluginBinding.applicationContext) } catch (e: Settings.SettingNotFoundException) { e.printStackTrace() } @@ -94,27 +91,27 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity override fun onAttachedToActivity(binding: ActivityPluginBinding) { activity = binding.activity - currentBrightnessChangeStreamHandler = - CurrentBrightnessChangeStreamHandler( + applicationScreenBrightnessChangeStreamHandler = + ApplicationScreenBrightnessChangeStreamHandler( binding.activity, onListenStart = null, onChange = { eventSink -> - systemBrightness = getSystemBrightness(binding.activity) - if (changedBrightness == null) { - eventSink.success(systemBrightness) + systemScreenBrightness = getSystemBrightness(binding.activity) + if (applicationScreenBrightness == null) { + eventSink.success(systemScreenBrightness) } }) - currentBrightnessChangeEventChannel.setStreamHandler(currentBrightnessChangeStreamHandler) + applicationScreenBrightnessChangedEventChannel.setStreamHandler(applicationScreenBrightnessChangeStreamHandler) } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { when (call.method) { "getSystemScreenBrightness" -> handleGetSystemBrightnessMethodCall(result) "setSystemScreenBrightness" -> handleSetSystemBrightnessMethodCall(call, result) - "getScreenBrightness" -> handleGetScreenBrightnessMethodCall(result) - "setScreenBrightness" -> handleSetScreenBrightnessMethodCall(call, result) - "resetScreenBrightness" -> handleResetScreenBrightnessMethodCall(result) - "hasChanged" -> handleHasChangedMethodCall(result) + "getApplicationScreenBrightness" -> handleGetApplicationScreenBrightnessMethodCall(result) + "setApplicationScreenBrightness" -> handleSetApplicationScreenBrightnessMethodCall(call, result) + "resetApplicationScreenBrightness" -> handleResetApplicationScreenBrightnessMethodCall(result) + "hasApplicationScreenBrightnessChanged" -> handleHasApplicationScreenBrightnessChangedMethodCall(result) "isAutoReset" -> handleIsAutoResetMethodCall(result) "setAutoReset" -> handleSetAutoResetMethodCall(call, result) "isAnimate" -> handleIsAnimateMethodCall(result) @@ -127,7 +124,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity return Settings.System.getInt( context.contentResolver, Settings.System.SCREEN_BRIGHTNESS - ) / maximumBrightness + ) / maximumScreenBrightness } private fun setSystemBrightness(context: Context, brightness: Float): Boolean { @@ -147,12 +144,12 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity return Settings.System.putInt( context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, - (maximumBrightness * brightness).toInt() + (maximumScreenBrightness * brightness).toInt() ) } private fun handleGetSystemBrightnessMethodCall(result: MethodChannel.Result) { - result.success(systemBrightness) + result.success(systemScreenBrightness) } private fun handleSetSystemBrightnessMethodCall( @@ -177,12 +174,12 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity return } - systemBrightness = brightness + systemScreenBrightness = brightness result.success(null) } - private fun handleGetScreenBrightnessMethodCall(result: MethodChannel.Result) { + private fun handleGetApplicationScreenBrightnessMethodCall(result: MethodChannel.Result) { val activity = activity if (activity == null) { result.error("-10", "Unexpected error on activity binding", null) @@ -241,7 +238,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity } } - private fun handleSetScreenBrightnessMethodCall( + private fun handleSetApplicationScreenBrightnessMethodCall( call: MethodCall, result: MethodChannel.Result ) { @@ -263,12 +260,12 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity return } - changedBrightness = brightness + applicationScreenBrightness = brightness handleCurrentBrightnessChanged(brightness) result.success(null) } - private fun handleResetScreenBrightnessMethodCall(result: MethodChannel.Result) { + private fun handleResetApplicationScreenBrightnessMethodCall(result: MethodChannel.Result) { val activity = activity if (activity == null) { result.error("-10", "Unexpected error on activity binding", null) @@ -282,17 +279,17 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity return } - changedBrightness = null - handleCurrentBrightnessChanged(systemBrightness) + applicationScreenBrightness = null + handleCurrentBrightnessChanged(systemScreenBrightness) result.success(null) } private fun handleCurrentBrightnessChanged(currentBrightness: Float) { - currentBrightnessChangeStreamHandler?.addCurrentBrightnessToEventSink(currentBrightness.toDouble()) + applicationScreenBrightnessChangeStreamHandler?.addCurrentBrightnessToEventSink(currentBrightness.toDouble()) } - private fun handleHasChangedMethodCall(result: MethodChannel.Result) { - result.success(changedBrightness != null) + private fun handleHasApplicationScreenBrightnessChangedMethodCall(result: MethodChannel.Result) { + result.success(applicationScreenBrightness != null) } private fun handleIsAutoResetMethodCall(result: MethodChannel.Result) { @@ -335,13 +332,13 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity override fun onDetachedFromActivity() { activity = null - currentBrightnessChangeEventChannel.setStreamHandler(null) - currentBrightnessChangeStreamHandler = null + applicationScreenBrightnessChangedEventChannel.setStreamHandler(null) + applicationScreenBrightnessChangeStreamHandler = null } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { methodChannel.setMethodCallHandler(null) - currentBrightnessChangeEventChannel.setStreamHandler(null) - currentBrightnessChangeStreamHandler = null + applicationScreenBrightnessChangedEventChannel.setStreamHandler(null) + applicationScreenBrightnessChangeStreamHandler = null } } diff --git a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/CurrentBrightnessChangeStreamHandler.kt b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ApplicationScreenBrightnessChangeStreamHandler.kt similarity index 96% rename from screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/CurrentBrightnessChangeStreamHandler.kt rename to screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ApplicationScreenBrightnessChangeStreamHandler.kt index 48cbe99..0d9a176 100644 --- a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/CurrentBrightnessChangeStreamHandler.kt +++ b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ApplicationScreenBrightnessChangeStreamHandler.kt @@ -7,7 +7,7 @@ import android.os.Looper import android.provider.Settings import io.flutter.plugin.common.EventChannel -class CurrentBrightnessChangeStreamHandler( +class ApplicationScreenBrightnessChangeStreamHandler( private val context: Context, val onListenStart: ((eventSink: EventChannel.EventSink) -> Unit)?, val onChange: ((eventSink: EventChannel.EventSink) -> Unit) diff --git a/screen_brightness_android/example/lib/main.dart b/screen_brightness_android/example/lib/main.dart index 406b9f7..ad2f90c 100644 --- a/screen_brightness_android/example/lib/main.dart +++ b/screen_brightness_android/example/lib/main.dart @@ -72,21 +72,22 @@ class HomePage extends StatelessWidget { FutureBuilder( future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { - double currentBrightness = 0; + double applicationBrightness = 0; if (snapshot.hasData) { - currentBrightness = snapshot.data!; + applicationBrightness = snapshot.data!; } return StreamBuilder( stream: ScreenBrightnessPlatform .instance.onApplicationBrightnessChanged, builder: (context, snapshot) { - double changedBrightness = currentBrightness; + double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { - changedBrightness = snapshot.data!; + changedApplicationBrightness = snapshot.data!; } - return Text('current brightness $changedBrightness'); + return Text( + 'Application brightness $changedApplicationBrightness'); }, ); }, @@ -129,27 +130,27 @@ class _ControllerPageState extends State { .setSystemScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set brightness'; + throw 'Failed to set system brightness'; } } - Future setBrightness(double brightness) async { + Future setApplicationBrightness(double brightness) async { try { await ScreenBrightnessPlatform.instance .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set brightness'; + throw 'Failed to set application brightness'; } } - Future resetBrightness() async { + Future resetApplicationBrightness() async { try { await ScreenBrightnessPlatform.instance .resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); - throw 'Failed to reset brightness'; + throw 'Failed to reset application brightness'; } } @@ -187,18 +188,18 @@ class _ControllerPageState extends State { FutureBuilder( future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { - double currentBrightness = 0; + double applicationBrightness = 0; if (snapshot.hasData) { - currentBrightness = snapshot.data!; + applicationBrightness = snapshot.data!; } return StreamBuilder( stream: ScreenBrightnessPlatform .instance.onApplicationBrightnessChanged, builder: (context, snapshot) { - double changedBrightness = currentBrightness; + double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { - changedBrightness = snapshot.data!; + changedApplicationBrightness = snapshot.data!; } return Column( @@ -209,19 +210,20 @@ class _ControllerPageState extends State { .instance.hasApplicationScreenBrightnessChanged, builder: (context, snapshot) { return Text( - 'Brightness has changed via plugin: ${snapshot.data}'); + 'Application brightness has changed via plugin: ${snapshot.data}'); }, ), - Text('Current brightness: $changedBrightness'), + Text( + 'Application brightness: $changedApplicationBrightness'), Slider.adaptive( - value: changedBrightness, + value: changedApplicationBrightness, onChanged: (value) { - setBrightness(value); + setApplicationBrightness(value); }, ), ElevatedButton( onPressed: () { - resetBrightness(); + resetApplicationBrightness(); }, child: const Text('reset brightness'), ), diff --git a/screen_brightness_ios/example/lib/main.dart b/screen_brightness_ios/example/lib/main.dart index 0a79f7b..ad2f90c 100644 --- a/screen_brightness_ios/example/lib/main.dart +++ b/screen_brightness_ios/example/lib/main.dart @@ -72,21 +72,22 @@ class HomePage extends StatelessWidget { FutureBuilder( future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { - double currentBrightness = 0; + double applicationBrightness = 0; if (snapshot.hasData) { - currentBrightness = snapshot.data!; + applicationBrightness = snapshot.data!; } return StreamBuilder( stream: ScreenBrightnessPlatform .instance.onApplicationBrightnessChanged, builder: (context, snapshot) { - double changedBrightness = currentBrightness; + double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { - changedBrightness = snapshot.data!; + changedApplicationBrightness = snapshot.data!; } - return Text('current brightness $changedBrightness'); + return Text( + 'Application brightness $changedApplicationBrightness'); }, ); }, @@ -123,23 +124,33 @@ class ControllerPage extends StatefulWidget { } class _ControllerPageState extends State { - Future setBrightness(double brightness) async { + Future setSystemBrightness(double brightness) async { + try { + await ScreenBrightnessPlatform.instance + .setSystemScreenBrightness(brightness); + } catch (e) { + debugPrint(e.toString()); + throw 'Failed to set system brightness'; + } + } + + Future setApplicationBrightness(double brightness) async { try { await ScreenBrightnessPlatform.instance .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set brightness'; + throw 'Failed to set application brightness'; } } - Future resetBrightness() async { + Future resetApplicationBrightness() async { try { await ScreenBrightnessPlatform.instance .resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); - throw 'Failed to reset brightness'; + throw 'Failed to reset application brightness'; } } @@ -149,54 +160,80 @@ class _ControllerPageState extends State { appBar: AppBar( title: const Text('Controller'), ), - body: Center( - child: FutureBuilder( - future: ScreenBrightnessPlatform.instance.application, - builder: (context, snapshot) { - double currentBrightness = 0; - if (snapshot.hasData) { - currentBrightness = snapshot.data!; - } - - return StreamBuilder( - stream: ScreenBrightnessPlatform - .instance.onApplicationBrightnessChanged, - builder: (context, snapshot) { - double changedBrightness = currentBrightness; - if (snapshot.hasData) { - changedBrightness = snapshot.data!; - } - - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - FutureBuilder( - future: ScreenBrightnessPlatform - .instance.hasApplicationScreenBrightnessChanged, - builder: (context, snapshot) { - return Text( - 'Brightness has changed via plugin: ${snapshot.data}'); - }, - ), - Text('Current brightness: $changedBrightness'), - Slider.adaptive( - value: changedBrightness, - onChanged: (value) { - setBrightness(value); - }, - ), - ElevatedButton( - onPressed: () { - resetBrightness(); - }, - child: const Text('reset brightness'), - ), - ], - ); - }, - ); - }, - ), + body: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + FutureBuilder( + future: ScreenBrightnessPlatform.instance.system, + builder: (context, snapshot) { + double systemBrightness = 0; + if (snapshot.hasData) { + systemBrightness = snapshot.data!; + } + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('System brightness: $systemBrightness'), + Slider.adaptive( + value: systemBrightness, + onChanged: (value) { + setSystemBrightness(value); + }, + ), + ], + ); + }, + ), + FutureBuilder( + future: ScreenBrightnessPlatform.instance.application, + builder: (context, snapshot) { + double applicationBrightness = 0; + if (snapshot.hasData) { + applicationBrightness = snapshot.data!; + } + + return StreamBuilder( + stream: ScreenBrightnessPlatform + .instance.onApplicationBrightnessChanged, + builder: (context, snapshot) { + double changedApplicationBrightness = applicationBrightness; + if (snapshot.hasData) { + changedApplicationBrightness = snapshot.data!; + } + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + FutureBuilder( + future: ScreenBrightnessPlatform + .instance.hasApplicationScreenBrightnessChanged, + builder: (context, snapshot) { + return Text( + 'Application brightness has changed via plugin: ${snapshot.data}'); + }, + ), + Text( + 'Application brightness: $changedApplicationBrightness'), + Slider.adaptive( + value: changedApplicationBrightness, + onChanged: (value) { + setApplicationBrightness(value); + }, + ), + ElevatedButton( + onPressed: () { + resetApplicationBrightness(); + }, + child: const Text('reset brightness'), + ), + ], + ); + }, + ); + }, + ), + ], ), ); } diff --git a/screen_brightness_ios/example/pubspec.lock b/screen_brightness_ios/example/pubspec.lock index 5687a23..82624e4 100644 --- a/screen_brightness_ios/example/pubspec.lock +++ b/screen_brightness_ios/example/pubspec.lock @@ -149,10 +149,9 @@ packages: screen_brightness_platform_interface: dependency: "direct main" description: - name: screen_brightness_platform_interface - sha256: "9f3ebf7f22d5487e7676fe9ddaf3fc55b6ff8057707cf6dc0121c7dfda346a16" - url: "https://pub.dev" - source: hosted + path: "../../screen_brightness_platform_interface" + relative: true + source: path version: "1.0.1" sky_engine: dependency: transitive diff --git a/screen_brightness_ios/example/pubspec.yaml b/screen_brightness_ios/example/pubspec.yaml index f7f41b0..53dd631 100644 --- a/screen_brightness_ios/example/pubspec.yaml +++ b/screen_brightness_ios/example/pubspec.yaml @@ -26,9 +26,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -#dependency_overrides: -# screen_brightness_platform_interface: -# path: ../../screen_brightness_platform_interface/ +dependency_overrides: + screen_brightness_platform_interface: + path: ../../screen_brightness_platform_interface/ # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/screen_brightness_ios/ios/Classes/StreamHandler/CurrentBrightnessChangeStreamHandler.swift b/screen_brightness_ios/ios/Classes/StreamHandler/ApplicationScreenBrightnessChangeStreamHandler.swift similarity index 51% rename from screen_brightness_ios/ios/Classes/StreamHandler/CurrentBrightnessChangeStreamHandler.swift rename to screen_brightness_ios/ios/Classes/StreamHandler/ApplicationScreenBrightnessChangeStreamHandler.swift index 2648e08..231737a 100644 --- a/screen_brightness_ios/ios/Classes/StreamHandler/CurrentBrightnessChangeStreamHandler.swift +++ b/screen_brightness_ios/ios/Classes/StreamHandler/ApplicationScreenBrightnessChangeStreamHandler.swift @@ -9,12 +9,12 @@ import Foundation import Flutter import UIKit -public class CurrentBrightnessChangeStreamHandler: BaseStreamHandler { - public func addCurrentBrightnessToEventSink(_ currentBrightness: CGFloat) { +public class ApplicationScreenBrightnessChangeStreamHandler: BaseStreamHandler { + public func addApplicationScreenBrightnessToEventSink(_ applicationScreenBrightness: CGFloat) { guard let eventSink = eventSink else { return } - eventSink(Double(currentBrightness)) + eventSink(Double(applicationScreenBrightness)) } } diff --git a/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift b/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift index 63144d2..e5f3ce6 100644 --- a/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift +++ b/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift @@ -4,11 +4,11 @@ import UIKit public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApplicationLifeCycleDelegate { var methodChannel: FlutterMethodChannel? - var currentBrightnessChangeEventChannel: FlutterEventChannel? - let currentBrightnessChangeStreamHandler: CurrentBrightnessChangeStreamHandler = CurrentBrightnessChangeStreamHandler() + var applicationScreenBrightnessChangedEventChannel: FlutterEventChannel? + let applicationScreenBrightnessChangeStreamHandler: ApplicationScreenBrightnessChangeStreamHandler = ApplicationScreenBrightnessChangeStreamHandler() - var systemBrightness: CGFloat? - var changedBrightness: CGFloat? + var systemScreenBrightness: CGFloat? + var applicationScreenBrightness: CGFloat? var isAutoReset: Bool = true var isAnimate: Bool = true @@ -24,37 +24,41 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp instance.methodChannel = FlutterMethodChannel(name: "github.com/aaassseee/screen_brightness", binaryMessenger: registrar.messenger()) registrar.addMethodCallDelegate(instance, channel: instance.methodChannel!) - instance.currentBrightnessChangeEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_change", binaryMessenger: registrar.messenger()) - instance.currentBrightnessChangeEventChannel!.setStreamHandler(instance.currentBrightnessChangeStreamHandler) + instance.applicationScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_change", binaryMessenger: registrar.messenger()) + instance.applicationScreenBrightnessChangedEventChannel!.setStreamHandler(instance.applicationScreenBrightnessChangeStreamHandler) registrar.addApplicationDelegate(instance) } override init() { super.init() - systemBrightness = UIScreen.main.brightness + systemScreenBrightness = UIScreen.main.brightness } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "getSystemScreenBrightness": - handleGetSystemBrightnessMethodCall(result: result) + handleGetSystemScreenBrightnessMethodCall(result: result) break; - - case "getScreenBrightness": - handleGetScreenBrightnessMethodCall(result: result) + + case "setSystemScreenBrightness": + handleSetSystemScreenBrightnessMethodCall(call, result: result) + break; + + case "getApplicationScreenBrightness": + handleGetApplicationScreenBrightnessMethodCall(result: result) break; - case "setScreenBrightness": - handleSetScreenBrightnessMethodCall(call: call, result: result) + case "setApplicationScreenBrightness": + handleSetApplicationScreenBrightnessMethodCall(call: call, result: result) break; - case "resetScreenBrightness": - handleResetScreenBrightnessMethodCall(result: result) + case "resetApplicationScreenBrightness": + handleResetApplicationScreenBrightnessMethodCall(result: result) break; - case "hasChanged": - handleHasChangedMethodCall(result: result) + case "hasApplicationScreenBrightnessChanged": + handleHasApplicationScreenBrightnessChangedMethodCall(result: result) break; case "isAutoReset": @@ -74,7 +78,7 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp break; } } - + public func setScreenBrightness(targetBrightness: CGFloat, animated: Bool, duration: TimeInterval = 1.0) { taskQueue.cancelAllOperations() if !animated { @@ -106,48 +110,69 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp return blockOperation }), waitUntilFinished: false) } - - private func handleGetSystemBrightnessMethodCall(result: FlutterResult) { - result(systemBrightness) + + private func handleGetSystemScreenBrightnessMethodCall(result: FlutterResult) { + guard let systemScreenBrightness = systemScreenBrightness else { + result(FlutterError.init(code: "-11", message: "Could not found system screen brightness value", details: nil)) + return + } + + result(systemScreenBrightness) } - - private func handleGetScreenBrightnessMethodCall(result: FlutterResult) { + + private func handleSetSystemScreenBrightnessMethodCall(call: FlutterMethodCall, result: FlutterResult) { + guard let parameters = call.arguments as? Dictionary, let brightness = parameters["brightness"] as? NSNumber else { + result(FlutterError.init(code: "-2", message: "Unexpected error on null brightness", details: nil)) + return + } + + let _systemScreenBrightness = CGFloat(brightness.doubleValue) + setScreenBrightness(targetBrightness: _systemScreenBrightness, animated: isAnimate) + + systemScreenBrightness = _systemScreenBrightness + if (applicationScreenBrightness == nil) { + handleApplicationScreenBrightnessChanged(systemScreenBrightness) + } + result(nil) + } + + private func handleGetApplicationScreenBrightnessMethodCall(result: FlutterResult) { result(UIScreen.main.brightness) } - private func handleSetScreenBrightnessMethodCall(call: FlutterMethodCall, result: FlutterResult) { + private func handleSetApplicationScreenBrightnessMethodCall(call: FlutterMethodCall, result: FlutterResult) { guard let parameters = call.arguments as? Dictionary, let brightness = parameters["brightness"] as? NSNumber else { result(FlutterError.init(code: "-2", message: "Unexpected error on null brightness", details: nil)) return } - let _changedBrightness = CGFloat(brightness.doubleValue) - setScreenBrightness(targetBrightness: _changedBrightness, animated: isAnimate) + let _applicationScreenBrightness = CGFloat(brightness.doubleValue) + setScreenBrightness(targetBrightness: _applicationScreenBrightness, animated: isAnimate) - changedBrightness = _changedBrightness - handleCurrentBrightnessChanged(_changedBrightness) + applicationScreenBrightness = _applicationScreenBrightness + handleApplicationScreenBrightnessChanged(_applicationScreenBrightness) result(nil) } - private func handleResetScreenBrightnessMethodCall(result: FlutterResult) { - guard let initialBrightness = systemBrightness else { + private func handleResetApplicationScreenBrightnessMethodCall(result: FlutterResult) { + guard let systemScreenBrightness = systemScreenBrightness else { result(FlutterError.init(code: "-2", message: "Unexpected error on null brightness", details: nil)) return } - setScreenBrightness(targetBrightness: initialBrightness, animated: isAnimate) + setScreenBrightness(targetBrightness: systemScreenBrightness, animated: isAnimate) - changedBrightness = nil - handleCurrentBrightnessChanged(initialBrightness) + applicationScreenBrightness = nil + handleApplicationScreenBrightnessChanged(systemScreenBrightness) result(nil) } - - private func handleHasChangedMethodCall(result: FlutterResult) { - result(changedBrightness != nil) + + private func handleApplicationScreenBrightnessChanged(_ applicationScreenBrightness: CGFloat) { + applicationScreenBrightnessChangeStreamHandler.addApplicationScreenBrightnessToEventSink(applicationScreenBrightness) } - - private func handleCurrentBrightnessChanged(_ currentBrightness: CGFloat) { - currentBrightnessChangeStreamHandler.addCurrentBrightnessToEventSink(currentBrightness) + + private func handleHasApplicationScreenBrightnessChangedMethodCall(result: FlutterResult) { + result(applicationScreenBrightness != nil) } private func handleIsAutoResetMethodCall(result: FlutterResult) { @@ -178,31 +203,31 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp result(nil) } - @objc private func onSystemBrightnessChanged(notification: Notification) { + @objc private func onSystemScreenBrightnessChanged(notification: Notification) { guard let screenObject = notification.object, let brightness = (screenObject as AnyObject).brightness else { return } - systemBrightness = brightness - if (changedBrightness == nil) { - handleCurrentBrightnessChanged(brightness) + systemScreenBrightness = brightness + if (applicationScreenBrightness == nil) { + handleApplicationScreenBrightnessChanged(brightness) } } func onApplicationPause() { - guard let initialBrightness = systemBrightness else { + guard let systemScreenBrightness = systemScreenBrightness else { return } - setScreenBrightness(targetBrightness: initialBrightness, animated: isAnimate, duration: 0.5) + setScreenBrightness(targetBrightness: systemScreenBrightness, animated: isAnimate, duration: 0.5) } func onApplicationResume() { - guard let changedBrightness = changedBrightness else { + guard let applicationScreenBrightness = applicationScreenBrightness else { return } - setScreenBrightness(targetBrightness: changedBrightness, animated: isAnimate, duration: 0.5) + setScreenBrightness(targetBrightness: applicationScreenBrightness, animated: isAnimate, duration: 0.5) } public func applicationWillResignActive(_ application: UIApplication) { @@ -211,7 +236,7 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp } onApplicationPause() - NotificationCenter.default.addObserver(self, selector: #selector(onSystemBrightnessChanged), name: UIScreen.brightnessDidChangeNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(onSystemScreenBrightnessChanged), name: UIScreen.brightnessDidChangeNotification, object: nil) } public func applicationDidBecomeActive(_ application: UIApplication) { @@ -220,9 +245,9 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp } NotificationCenter.default.removeObserver(self, name: UIScreen.brightnessDidChangeNotification, object: nil) - systemBrightness = UIScreen.main.brightness - if (changedBrightness == nil) { - handleCurrentBrightnessChanged(systemBrightness!) + systemScreenBrightness = UIScreen.main.brightness + if (applicationScreenBrightness == nil) { + handleApplicationScreenBrightnessChanged(systemScreenBrightness!) } onApplicationResume() @@ -237,6 +262,6 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp NotificationCenter.default.removeObserver(self) methodChannel?.setMethodCallHandler(nil) - currentBrightnessChangeEventChannel?.setStreamHandler(nil) + applicationScreenBrightnessChangedEventChannel?.setStreamHandler(nil) } } diff --git a/screen_brightness_ios/pubspec.yaml b/screen_brightness_ios/pubspec.yaml index 5670cf3..d361fae 100644 --- a/screen_brightness_ios/pubspec.yaml +++ b/screen_brightness_ios/pubspec.yaml @@ -24,9 +24,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -#dependency_overrides: -# screen_brightness_platform_interface: -# path: ../screen_brightness_platform_interface/ +dependency_overrides: + screen_brightness_platform_interface: + path: ../screen_brightness_platform_interface/ flutter: plugin: diff --git a/screen_brightness_macos/example/lib/main.dart b/screen_brightness_macos/example/lib/main.dart index 0a79f7b..ad2f90c 100644 --- a/screen_brightness_macos/example/lib/main.dart +++ b/screen_brightness_macos/example/lib/main.dart @@ -72,21 +72,22 @@ class HomePage extends StatelessWidget { FutureBuilder( future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { - double currentBrightness = 0; + double applicationBrightness = 0; if (snapshot.hasData) { - currentBrightness = snapshot.data!; + applicationBrightness = snapshot.data!; } return StreamBuilder( stream: ScreenBrightnessPlatform .instance.onApplicationBrightnessChanged, builder: (context, snapshot) { - double changedBrightness = currentBrightness; + double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { - changedBrightness = snapshot.data!; + changedApplicationBrightness = snapshot.data!; } - return Text('current brightness $changedBrightness'); + return Text( + 'Application brightness $changedApplicationBrightness'); }, ); }, @@ -123,23 +124,33 @@ class ControllerPage extends StatefulWidget { } class _ControllerPageState extends State { - Future setBrightness(double brightness) async { + Future setSystemBrightness(double brightness) async { + try { + await ScreenBrightnessPlatform.instance + .setSystemScreenBrightness(brightness); + } catch (e) { + debugPrint(e.toString()); + throw 'Failed to set system brightness'; + } + } + + Future setApplicationBrightness(double brightness) async { try { await ScreenBrightnessPlatform.instance .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set brightness'; + throw 'Failed to set application brightness'; } } - Future resetBrightness() async { + Future resetApplicationBrightness() async { try { await ScreenBrightnessPlatform.instance .resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); - throw 'Failed to reset brightness'; + throw 'Failed to reset application brightness'; } } @@ -149,54 +160,80 @@ class _ControllerPageState extends State { appBar: AppBar( title: const Text('Controller'), ), - body: Center( - child: FutureBuilder( - future: ScreenBrightnessPlatform.instance.application, - builder: (context, snapshot) { - double currentBrightness = 0; - if (snapshot.hasData) { - currentBrightness = snapshot.data!; - } - - return StreamBuilder( - stream: ScreenBrightnessPlatform - .instance.onApplicationBrightnessChanged, - builder: (context, snapshot) { - double changedBrightness = currentBrightness; - if (snapshot.hasData) { - changedBrightness = snapshot.data!; - } - - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - FutureBuilder( - future: ScreenBrightnessPlatform - .instance.hasApplicationScreenBrightnessChanged, - builder: (context, snapshot) { - return Text( - 'Brightness has changed via plugin: ${snapshot.data}'); - }, - ), - Text('Current brightness: $changedBrightness'), - Slider.adaptive( - value: changedBrightness, - onChanged: (value) { - setBrightness(value); - }, - ), - ElevatedButton( - onPressed: () { - resetBrightness(); - }, - child: const Text('reset brightness'), - ), - ], - ); - }, - ); - }, - ), + body: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + FutureBuilder( + future: ScreenBrightnessPlatform.instance.system, + builder: (context, snapshot) { + double systemBrightness = 0; + if (snapshot.hasData) { + systemBrightness = snapshot.data!; + } + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('System brightness: $systemBrightness'), + Slider.adaptive( + value: systemBrightness, + onChanged: (value) { + setSystemBrightness(value); + }, + ), + ], + ); + }, + ), + FutureBuilder( + future: ScreenBrightnessPlatform.instance.application, + builder: (context, snapshot) { + double applicationBrightness = 0; + if (snapshot.hasData) { + applicationBrightness = snapshot.data!; + } + + return StreamBuilder( + stream: ScreenBrightnessPlatform + .instance.onApplicationBrightnessChanged, + builder: (context, snapshot) { + double changedApplicationBrightness = applicationBrightness; + if (snapshot.hasData) { + changedApplicationBrightness = snapshot.data!; + } + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + FutureBuilder( + future: ScreenBrightnessPlatform + .instance.hasApplicationScreenBrightnessChanged, + builder: (context, snapshot) { + return Text( + 'Application brightness has changed via plugin: ${snapshot.data}'); + }, + ), + Text( + 'Application brightness: $changedApplicationBrightness'), + Slider.adaptive( + value: changedApplicationBrightness, + onChanged: (value) { + setApplicationBrightness(value); + }, + ), + ElevatedButton( + onPressed: () { + resetApplicationBrightness(); + }, + child: const Text('reset brightness'), + ), + ], + ); + }, + ); + }, + ), + ], ), ); } diff --git a/screen_brightness_macos/example/pubspec.lock b/screen_brightness_macos/example/pubspec.lock index 1a7654e..208daf4 100644 --- a/screen_brightness_macos/example/pubspec.lock +++ b/screen_brightness_macos/example/pubspec.lock @@ -149,10 +149,9 @@ packages: screen_brightness_platform_interface: dependency: "direct main" description: - name: screen_brightness_platform_interface - sha256: "9f3ebf7f22d5487e7676fe9ddaf3fc55b6ff8057707cf6dc0121c7dfda346a16" - url: "https://pub.dev" - source: hosted + path: "../../screen_brightness_platform_interface" + relative: true + source: path version: "1.0.1" sky_engine: dependency: transitive @@ -225,4 +224,4 @@ packages: version: "13.0.0" sdks: dart: ">=3.2.0-0 <4.0.0" - flutter: ">=3.0.0" + flutter: ">=2.0.0" diff --git a/screen_brightness_macos/example/pubspec.yaml b/screen_brightness_macos/example/pubspec.yaml index 1e830d7..e26b260 100644 --- a/screen_brightness_macos/example/pubspec.yaml +++ b/screen_brightness_macos/example/pubspec.yaml @@ -26,9 +26,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -#dependency_overrides: -# screen_brightness_platform_interface: -# path: ../../screen_brightness_platform_interface/ +dependency_overrides: + screen_brightness_platform_interface: + path: ../../screen_brightness_platform_interface/ # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift b/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift index f08946e..944fc42 100644 --- a/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift +++ b/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift @@ -8,11 +8,11 @@ enum ScreenBrightnessError: Error { public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { var methodChannel: FlutterMethodChannel? - var currentBrightnessChangeEventChannel: FlutterEventChannel? - let currentBrightnessChangeStreamHandler: CurrentBrightnessChangeStreamHandler = CurrentBrightnessChangeStreamHandler() + var applicationScreenBrightnessChangeEventChannel: FlutterEventChannel? + let applicationScreenBrightnessChangeStreamHandler: ApplicationScreenBrightnessChangeStreamHandler = ApplicationScreenBrightnessChangeStreamHandler() - var systemBrightness: Float? - var changedBrightness: Float? + var systemScreenBrightness: Float? + var applicationScreenBrightness: Float? var isAutoReset: Bool = true var isAnimate: Bool = true @@ -24,13 +24,13 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { instance.methodChannel = FlutterMethodChannel(name: "github.com/aaassseee/screen_brightness", binaryMessenger: registrar.messenger) registrar.addMethodCallDelegate(instance, channel: instance.methodChannel!) - instance.currentBrightnessChangeEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_change", binaryMessenger: registrar.messenger) - instance.currentBrightnessChangeEventChannel!.setStreamHandler(instance.currentBrightnessChangeStreamHandler) + instance.applicationScreenBrightnessChangeEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_change", binaryMessenger: registrar.messenger) + instance.applicationScreenBrightnessChangeEventChannel!.setStreamHandler(instance.applicationScreenBrightnessChangeStreamHandler) } override init() { super.init() - systemBrightness = try? getScreenBrightness() + systemScreenBrightness = try? getScreenBrightness() NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: NSApplication.willResignActiveNotification, object: nil) @@ -44,21 +44,25 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { case "getSystemScreenBrightness": handleGetSystemBrightnessMethodCall(result: result) break; - - case "getScreenBrightness": - handleGetScreenBrightnessMethodCall(result: result) + + case "setSystemScreenBrightness": + handleSetSystemScreenBrightnessMethodCall(call, result: result) + break; + + case "getApplicationScreenBrightness": + handleGetApplicationScreenBrightnessMethodCall(result: result) break; - case "setScreenBrightness": - handleSetScreenBrightnessMethodCall(call: call, result: result) + case "setApplicationScreenBrightness": + handleSetApplicationScreenBrightnessMethodCall(call: call, result: result) break; - case "resetScreenBrightness": - handleResetScreenBrightnessMethodCall(result: result) + case "resetApplicationScreenBrightness": + handleResetApplicationScreenBrightnessMethodCall(result: result) break; - case "hasChanged": - handleHasChangedMethodCall(result: result) + case "hasApplicationScreenBrightnessChanged": + handleHasApplicationScreenBrightnessChangedMethodCall(result: result) break; case "isAutoReset": @@ -123,65 +127,84 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { } private func handleGetSystemBrightnessMethodCall(result: FlutterResult) { - guard let systemBrightness = systemBrightness else { - result(FlutterError.init(code: "-11", message: "Could not found system setting screen brightness value", details: nil)) + guard let systemScreenBrightness = systemScreenBrightness else { + result(FlutterError.init(code: "-11", message: "Could not found system screen brightness value", details: nil)) return } - result(systemBrightness) + result(systemScreenBrightness) + } + + private func handleSetSystemScreenBrightnessMethodCall(call: FlutterMethodCall, result: FlutterResult) { + guard let parameters = call.arguments as? Dictionary, let brightness = parameters["brightness"] as? NSNumber else { + result(FlutterError.init(code: "-2", message: "Unexpected error on null brightness", details: nil)) + return + } + + let _systemScreenBrightness = Float(brightness.doubleValue) + + do { + try setScreenBrightness(targetBrightness: _systemScreenBrightness) + } catch { + result(FlutterError.init(code: "-1", message: "Unable to change system screen brightness", details: nil)) + } + + systemScreenBrightness = _systemScreenBrightness + handleApplicationScreenBrightnessChanged(_systemScreenBrightness) + result(nil) } - private func handleGetScreenBrightnessMethodCall(result: FlutterResult) { + private func handleGetApplicationScreenBrightnessMethodCall(result: FlutterResult) { do { - let brightness = try getScreenBrightness() - result(brightness) + let _applicationBrightness = try getScreenBrightness() + result(_applicationBrightness) } catch { result(FlutterError.init(code: "-2", message: "Unexpected error on null brightness", details: nil)) } } - private func handleSetScreenBrightnessMethodCall(call: FlutterMethodCall, result: FlutterResult) { + private func handleSetApplicationScreenBrightnessMethodCall(call: FlutterMethodCall, result: FlutterResult) { guard let parameters = call.arguments as? Dictionary, let brightness = parameters["brightness"] as? NSNumber else { result(FlutterError.init(code: "-2", message: "Unexpected error on null brightness", details: nil)) return } - let _changedBrightness = Float(brightness.doubleValue) + let _applicationBrightness = Float(brightness.doubleValue) do { - try setScreenBrightness(targetBrightness: _changedBrightness) + try setScreenBrightness(targetBrightness: _applicationBrightness) } catch { - result(FlutterError.init(code: "-1", message: "Unable to change screen brightness", details: nil)) + result(FlutterError.init(code: "-1", message: "Unable to change application screen brightness", details: nil)) } - changedBrightness = _changedBrightness - handleCurrentBrightnessChanged(_changedBrightness) + applicationScreenBrightness = _applicationBrightness + handleApplicationScreenBrightnessChanged(_applicationBrightness) result(nil) } - private func handleResetScreenBrightnessMethodCall(result: FlutterResult) { - guard let initialBrightness = systemBrightness else { + private func handleResetApplicationScreenBrightnessMethodCall(result: FlutterResult) { + guard let systemScreenBrightness = systemScreenBrightness else { result(FlutterError.init(code: "-2", message: "Unexpected error on null brightness", details: nil)) return } do { - try setScreenBrightness(targetBrightness: initialBrightness) + try setScreenBrightness(targetBrightness: systemScreenBrightness) } catch { result(FlutterError.init(code: "-1", message: "Unable to change screen brightness", details: nil)) } - changedBrightness = nil - handleCurrentBrightnessChanged(initialBrightness) + applicationScreenBrightness = nil + handleApplicationScreenBrightnessChanged(systemScreenBrightness) result(nil) } - private func handleCurrentBrightnessChanged(_ currentBrightness: Float) { - currentBrightnessChangeStreamHandler.addCurrentBrightnessToEventSink(currentBrightness) + private func handleApplicationScreenBrightnessChanged(_ applicationScreenBrightness: Float) { + applicationScreenBrightnessChangeStreamHandler.addApplicationScreenBrightnessToEventSink(applicationScreenBrightness) } - private func handleHasChangedMethodCall(result: FlutterResult) { - result(changedBrightness != nil) + private func handleHasApplicationScreenBrightnessChangedMethodCall(result: FlutterResult) { + result(applicationScreenBrightness != nil) } private func handleIsAutoResetMethodCall(result: FlutterResult) { @@ -213,30 +236,30 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { } @objc private func getSystemBrightness(_: Timer) { - guard let _systemBrightness = try? getScreenBrightness(), systemBrightness != _systemBrightness else { + guard let brightness = try? getScreenBrightness(), systemScreenBrightness != brightness else { return } - systemBrightness = _systemBrightness - if (changedBrightness == nil) { - handleCurrentBrightnessChanged(_systemBrightness) + systemScreenBrightness = brightness + if (applicationScreenBrightness == nil) { + handleApplicationScreenBrightnessChanged(brightness) } } func onApplicationPause() { - guard let initialBrightness = systemBrightness else { + guard let systemScreenBrightness = systemScreenBrightness else { return } - try! setScreenBrightness(targetBrightness: initialBrightness) + try! setScreenBrightness(targetBrightness: systemScreenBrightness) } func onApplicationResume() { - guard let changedBrightness = changedBrightness else { + guard let applicationScreenBrightness = applicationScreenBrightness else { return } - try! setScreenBrightness(targetBrightness: changedBrightness) + try! setScreenBrightness(targetBrightness: applicationScreenBrightness) } @objc public func applicationWillResignActive(notification: Notification) { @@ -256,10 +279,10 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { brightnessPollingTimer?.invalidate() brightnessPollingTimer = nil - if let _systemBrightness = try? getScreenBrightness() { - systemBrightness = _systemBrightness - if (changedBrightness == nil) { - handleCurrentBrightnessChanged(systemBrightness!) + if let _systemScreenBrightness = try? getScreenBrightness() { + systemScreenBrightness = _systemScreenBrightness + if (applicationScreenBrightness == nil) { + handleApplicationScreenBrightnessChanged(systemScreenBrightness!) } } @@ -278,6 +301,6 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { NotificationCenter.default.removeObserver(self) methodChannel?.setMethodCallHandler(nil) - currentBrightnessChangeEventChannel?.setStreamHandler(nil) + applicationScreenBrightnessChangeEventChannel?.setStreamHandler(nil) } } diff --git a/screen_brightness_macos/macos/Classes/StreamHandler/CurrentBrightnessChangeStreamHandler.swift b/screen_brightness_macos/macos/Classes/StreamHandler/ApplicationScreenBrightnessChangeStreamHandler.swift similarity index 50% rename from screen_brightness_macos/macos/Classes/StreamHandler/CurrentBrightnessChangeStreamHandler.swift rename to screen_brightness_macos/macos/Classes/StreamHandler/ApplicationScreenBrightnessChangeStreamHandler.swift index 406598c..a418891 100644 --- a/screen_brightness_macos/macos/Classes/StreamHandler/CurrentBrightnessChangeStreamHandler.swift +++ b/screen_brightness_macos/macos/Classes/StreamHandler/ApplicationScreenBrightnessChangeStreamHandler.swift @@ -8,12 +8,12 @@ import Cocoa import FlutterMacOS -public class CurrentBrightnessChangeStreamHandler: BaseStreamHandler { - public func addCurrentBrightnessToEventSink(_ currentBrightness: Float) { +public class ApplicationScreenBrightnessChangeStreamHandler: BaseStreamHandler { + public func addApplicationScreenBrightnessToEventSink(_ applicationScreenBrightness: Float) { guard let eventSink = eventSink else { return } - eventSink(Double(currentBrightness)) + eventSink(Double(applicationScreenBrightness)) } } diff --git a/screen_brightness_macos/pubspec.yaml b/screen_brightness_macos/pubspec.yaml index 6701f2b..02722c1 100644 --- a/screen_brightness_macos/pubspec.yaml +++ b/screen_brightness_macos/pubspec.yaml @@ -24,9 +24,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -#dependency_overrides: -# screen_brightness_platform_interface: -# path: ../screen_brightness_platform_interface/ +dependency_overrides: + screen_brightness_platform_interface: + path: ../screen_brightness_platform_interface/ flutter: plugin: diff --git a/screen_brightness_windows/example/lib/main.dart b/screen_brightness_windows/example/lib/main.dart index 0a79f7b..ad2f90c 100644 --- a/screen_brightness_windows/example/lib/main.dart +++ b/screen_brightness_windows/example/lib/main.dart @@ -72,21 +72,22 @@ class HomePage extends StatelessWidget { FutureBuilder( future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { - double currentBrightness = 0; + double applicationBrightness = 0; if (snapshot.hasData) { - currentBrightness = snapshot.data!; + applicationBrightness = snapshot.data!; } return StreamBuilder( stream: ScreenBrightnessPlatform .instance.onApplicationBrightnessChanged, builder: (context, snapshot) { - double changedBrightness = currentBrightness; + double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { - changedBrightness = snapshot.data!; + changedApplicationBrightness = snapshot.data!; } - return Text('current brightness $changedBrightness'); + return Text( + 'Application brightness $changedApplicationBrightness'); }, ); }, @@ -123,23 +124,33 @@ class ControllerPage extends StatefulWidget { } class _ControllerPageState extends State { - Future setBrightness(double brightness) async { + Future setSystemBrightness(double brightness) async { + try { + await ScreenBrightnessPlatform.instance + .setSystemScreenBrightness(brightness); + } catch (e) { + debugPrint(e.toString()); + throw 'Failed to set system brightness'; + } + } + + Future setApplicationBrightness(double brightness) async { try { await ScreenBrightnessPlatform.instance .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set brightness'; + throw 'Failed to set application brightness'; } } - Future resetBrightness() async { + Future resetApplicationBrightness() async { try { await ScreenBrightnessPlatform.instance .resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); - throw 'Failed to reset brightness'; + throw 'Failed to reset application brightness'; } } @@ -149,54 +160,80 @@ class _ControllerPageState extends State { appBar: AppBar( title: const Text('Controller'), ), - body: Center( - child: FutureBuilder( - future: ScreenBrightnessPlatform.instance.application, - builder: (context, snapshot) { - double currentBrightness = 0; - if (snapshot.hasData) { - currentBrightness = snapshot.data!; - } - - return StreamBuilder( - stream: ScreenBrightnessPlatform - .instance.onApplicationBrightnessChanged, - builder: (context, snapshot) { - double changedBrightness = currentBrightness; - if (snapshot.hasData) { - changedBrightness = snapshot.data!; - } - - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - FutureBuilder( - future: ScreenBrightnessPlatform - .instance.hasApplicationScreenBrightnessChanged, - builder: (context, snapshot) { - return Text( - 'Brightness has changed via plugin: ${snapshot.data}'); - }, - ), - Text('Current brightness: $changedBrightness'), - Slider.adaptive( - value: changedBrightness, - onChanged: (value) { - setBrightness(value); - }, - ), - ElevatedButton( - onPressed: () { - resetBrightness(); - }, - child: const Text('reset brightness'), - ), - ], - ); - }, - ); - }, - ), + body: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + FutureBuilder( + future: ScreenBrightnessPlatform.instance.system, + builder: (context, snapshot) { + double systemBrightness = 0; + if (snapshot.hasData) { + systemBrightness = snapshot.data!; + } + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('System brightness: $systemBrightness'), + Slider.adaptive( + value: systemBrightness, + onChanged: (value) { + setSystemBrightness(value); + }, + ), + ], + ); + }, + ), + FutureBuilder( + future: ScreenBrightnessPlatform.instance.application, + builder: (context, snapshot) { + double applicationBrightness = 0; + if (snapshot.hasData) { + applicationBrightness = snapshot.data!; + } + + return StreamBuilder( + stream: ScreenBrightnessPlatform + .instance.onApplicationBrightnessChanged, + builder: (context, snapshot) { + double changedApplicationBrightness = applicationBrightness; + if (snapshot.hasData) { + changedApplicationBrightness = snapshot.data!; + } + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + FutureBuilder( + future: ScreenBrightnessPlatform + .instance.hasApplicationScreenBrightnessChanged, + builder: (context, snapshot) { + return Text( + 'Application brightness has changed via plugin: ${snapshot.data}'); + }, + ), + Text( + 'Application brightness: $changedApplicationBrightness'), + Slider.adaptive( + value: changedApplicationBrightness, + onChanged: (value) { + setApplicationBrightness(value); + }, + ), + ElevatedButton( + onPressed: () { + resetApplicationBrightness(); + }, + child: const Text('reset brightness'), + ), + ], + ); + }, + ); + }, + ), + ], ), ); } diff --git a/screen_brightness_windows/example/pubspec.lock b/screen_brightness_windows/example/pubspec.lock index f913719..1af82f9 100644 --- a/screen_brightness_windows/example/pubspec.lock +++ b/screen_brightness_windows/example/pubspec.lock @@ -142,10 +142,9 @@ packages: screen_brightness_platform_interface: dependency: "direct main" description: - name: screen_brightness_platform_interface - sha256: "9f3ebf7f22d5487e7676fe9ddaf3fc55b6ff8057707cf6dc0121c7dfda346a16" - url: "https://pub.dev" - source: hosted + path: "../../screen_brightness_platform_interface" + relative: true + source: path version: "1.0.1" screen_brightness_windows: dependency: "direct main" diff --git a/screen_brightness_windows/example/pubspec.yaml b/screen_brightness_windows/example/pubspec.yaml index d677ec2..6dfdf59 100644 --- a/screen_brightness_windows/example/pubspec.yaml +++ b/screen_brightness_windows/example/pubspec.yaml @@ -27,9 +27,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -#dependency_overrides: -# screen_brightness_platform_interface: -# path: ../../screen_brightness_platform_interface/ +dependency_overrides: + screen_brightness_platform_interface: + path: ../../screen_brightness_platform_interface/ # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/screen_brightness_windows/windows/CMakeLists.txt b/screen_brightness_windows/windows/CMakeLists.txt index a8f71ec..1241565 100644 --- a/screen_brightness_windows/windows/CMakeLists.txt +++ b/screen_brightness_windows/windows/CMakeLists.txt @@ -10,8 +10,8 @@ add_library(${PLUGIN_NAME} SHARED "include/screen_brightness_windows/screen_brightness_windows_plugin.h" "src/screen_brightness_windows_plugin.cpp" "include/screen_brightness_windows/base_stream_handler.h" - "include/screen_brightness_windows/current_brightness_change_stream_handler.h" - "src/current_brightness_change_stream_handler.cpp" + "include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h" + "src/application_screen_brightness_change_stream_handler.cpp" ) apply_standard_settings(${PLUGIN_NAME}) set_target_properties(${PLUGIN_NAME} PROPERTIES diff --git a/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_windows_plugin.h b/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_windows_plugin.h index 0b905af..62783ec 100644 --- a/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_windows_plugin.h +++ b/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_windows_plugin.h @@ -3,7 +3,7 @@ #include -#include "../include/screen_brightness_windows/current_brightness_change_stream_handler.h" +#include "../include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h" #include @@ -41,21 +41,21 @@ namespace screen_brightness HWND window_handler_ = nullptr; - long system_brightness_ = -1; + long system_screen_brightness_ = -1; - long minimum_brightness_ = -1; + long minimum_screen_brightness_ = -1; - long maximum_brightness_ = -1; + long maximum_screen_brightness_ = -1; - long current_brightness_ = -1; + long application_screen_brightness_ = -1; - long changed_brightness_ = -1; + long changed_screen_brightness_ = -1; bool is_auto_reset_ = true; bool is_animate_ = true; - CurrentBrightnessChangeStreamHandler* current_brightness_change_stream_handler_ = nullptr; + ApplicationScreenBrightnessChangeStreamHandler* application_screen_brightness_change_stream_handler_ = nullptr; int window_proc_id_ = -1; @@ -63,27 +63,31 @@ namespace screen_brightness void HandleMethodCall(const flutter::MethodCall& method_call, std::unique_ptr> result); - void GetBrightness(long& minimum_brightness, long& brightness, long& maximum_brightness); + void GetScreenBrightness(long& minimum_screen_brightness, long& screen_brightness, long& maximum_screen_brightness); - void SetBrightness(long brightness); + void SetScreenBrightness(long screen_brightness); - [[nodiscard]] double GetBrightnessPercentage(long brightness) const; + [[nodiscard]] double GetScreenBrightnessPercentage(long screen_brightness) const; - [[nodiscard]] long GetBrightnessValueByPercentage(double percentage) const; + [[nodiscard]] long GetScreenBrightnessValueByPercentage(double percentage) const; - void HandleGetSystemBrightnessMethodCall(std::unique_ptr> result) const; + void HandleGetSystemScreenBrightnessMethodCall(std::unique_ptr> result) const; - void HandleGetScreenBrightnessMethodCall(std::unique_ptr> result); + void HandleSetSystemScreenBrightnessMethodCall( + const flutter::MethodCall& call, + std::unique_ptr> result); + + void HandleGetApplicationScreenBrightnessMethodCall(std::unique_ptr> result); - void HandleSetScreenBrightnessMethodCall( + void HandleSetApplicationScreenBrightnessMethodCall( const flutter::MethodCall& call, std::unique_ptr> result); - void HandleResetScreenBrightnessMethodCall(std::unique_ptr> result); + void HandleResetApplicationScreenBrightnessMethodCall(std::unique_ptr> result); void HandleCurrentBrightnessChanged(long brightness); - void HandleHasChangedMethodCall(std::unique_ptr> result) const; + void HandleHasApplicationScreenBrightnessChangedMethodCall(std::unique_ptr> result) const; void HandleIsAutoResetMethodCall(std::unique_ptr> result); diff --git a/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp b/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp index 1239aa1..a1ab0b8 100644 --- a/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp +++ b/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp @@ -23,7 +23,7 @@ namespace screen_brightness window_handler_ = registrar->GetView()->GetNativeWindow(); try { - GetBrightness(minimum_brightness_, system_brightness_, maximum_brightness_); + GetScreenBrightness(minimum_screen_brightness_, system_screen_brightness_, maximum_screen_brightness_); } catch (const std::exception& exception) { @@ -58,18 +58,18 @@ namespace screen_brightness plugin_pointer->HandleMethodCall(call, std::move(result)); }); - const auto current_brightness_change_event_channel = + const auto application_screen_brightness_change_event_channel = std::make_unique>( registrar->messenger(), "github.com/aaassseee/screen_brightness/application_brightness_change", &flutter::StandardMethodCodec::GetInstance()); - plugin->current_brightness_change_stream_handler_ = new CurrentBrightnessChangeStreamHandler(); + plugin->application_screen_brightness_change_stream_handler_ = new ApplicationScreenBrightnessChangeStreamHandler(); std::unique_ptr> - current_brightness_change_stream_handler_unique_pointer + application_screen_brightness_change_stream_handler_unique_pointer { - static_cast*>(plugin->current_brightness_change_stream_handler_) + static_cast*>(plugin->application_screen_brightness_change_stream_handler_) }; - current_brightness_change_event_channel->SetStreamHandler(std::move(current_brightness_change_stream_handler_unique_pointer)); + application_screen_brightness_change_event_channel->SetStreamHandler(std::move(application_screen_brightness_change_stream_handler_unique_pointer)); registrar->AddPlugin(std::move(plugin)); } @@ -80,31 +80,37 @@ namespace screen_brightness { if (method_call.method_name() == "getSystemScreenBrightness") { - HandleGetScreenBrightnessMethodCall(std::move(result)); + HandleGetSystemScreenBrightnessMethodCall(std::move(result)); return; } - if (method_call.method_name() == "getScreenBrightness") + if (method_call.method_name() == "setSystemScreenBrightness") { - HandleGetScreenBrightnessMethodCall(std::move(result)); + HandleSetSystemScreenBrightnessMethodCall(method_call, std::move(result)); return; } - if (method_call.method_name() == "setScreenBrightness") + if (method_call.method_name() == "getApplicationScreenBrightness") { - HandleSetScreenBrightnessMethodCall(method_call, std::move(result)); + HandleGetApplicationScreenBrightnessMethodCall(std::move(result)); return; } - if (method_call.method_name() == "resetScreenBrightness") + if (method_call.method_name() == "setApplicationScreenBrightness") { - HandleResetScreenBrightnessMethodCall(std::move(result)); + HandleSetApplicationScreenBrightnessMethodCall(method_call, std::move(result)); return; } - if (method_call.method_name() == "hasChanged") + if (method_call.method_name() == "resetApplicationScreenBrightness") { - HandleHasChangedMethodCall(std::move(result)); + HandleResetApplicationScreenBrightnessMethodCall(std::move(result)); + return; + } + + if (method_call.method_name() == "hasApplicationScreenBrightnessChanged") + { + HandleHasApplicationScreenBrightnessChangedMethodCall(std::move(result)); return; } @@ -135,11 +141,11 @@ namespace screen_brightness result->NotImplemented(); } - void ScreenBrightnessWindowsPlugin::GetBrightness(long& minimum_brightness, long& brightness, long& maximum_brightness) + void ScreenBrightnessWindowsPlugin::GetScreenBrightness(long& minimum_screen_brightness, long& screen_brightness, long& maximum_screen_brightness) { DWORD physical_monitor_array_size = 0; HMONITOR monitor_handler = MonitorFromWindow(window_handler_, MONITOR_DEFAULTTOPRIMARY); - DWORD minimum = 0, current = 0, maximum = 0; + DWORD minimum_screen_brightness_ = 0, screen_brightness_ = 0, maximum_screen_brightness_ = 0; if (!GetNumberOfPhysicalMonitorsFromHMONITOR(monitor_handler, &physical_monitor_array_size)) { @@ -158,21 +164,21 @@ namespace screen_brightness throw std::exception("Problem getting physical monitors"); } - if (!GetMonitorBrightness(physical_monitor->hPhysicalMonitor, &minimum, ¤t, &maximum)) + if (!GetMonitorBrightness(physical_monitor->hPhysicalMonitor, &minimum_screen_brightness_, &screen_brightness_, &maximum_screen_brightness_)) { throw std::exception("Problem getting monitor brightness"); } - minimum_brightness = minimum; - brightness = current; - maximum_brightness = maximum; + minimum_screen_brightness = minimum_screen_brightness_; + screen_brightness = screen_brightness_; + maximum_screen_brightness = maximum_screen_brightness_; DestroyPhysicalMonitors(physical_monitor_array_size, physical_monitor); free(physical_monitor); } - void ScreenBrightnessWindowsPlugin::SetBrightness(const long brightness) + void ScreenBrightnessWindowsPlugin::SetScreenBrightness(const long screen_brightness) { DWORD physical_monitor_array_size = 0; HMONITOR monitor_handler = MonitorFromWindow(window_handler_, MONITOR_DEFAULTTOPRIMARY); @@ -194,7 +200,7 @@ namespace screen_brightness throw std::exception("Problem getting physical monitors"); } - if (!SetMonitorBrightness(physical_monitor->hPhysicalMonitor, brightness)) + if (!SetMonitorBrightness(physical_monitor->hPhysicalMonitor, screen_brightness)) { throw std::exception("Problem setting monitor brightness"); } @@ -204,27 +210,57 @@ namespace screen_brightness free(physical_monitor); } - double ScreenBrightnessWindowsPlugin::GetBrightnessPercentage(const long brightness) const + double ScreenBrightnessWindowsPlugin::GetScreenBrightnessPercentage(const long screen_brightness) const { - if (brightness < 0) + if (screen_brightness < 0) { return 0; } - return static_cast(brightness - minimum_brightness_) / (maximum_brightness_ - minimum_brightness_); + return static_cast(screen_brightness - minimum_screen_brightness_) / (maximum_screen_brightness_ - minimum_screen_brightness_); } - long ScreenBrightnessWindowsPlugin::GetBrightnessValueByPercentage(const double percentage) const + long ScreenBrightnessWindowsPlugin::GetScreenBrightnessValueByPercentage(const double percentage) const { - return static_cast((percentage * (maximum_brightness_ - minimum_brightness_)) + minimum_brightness_); + return static_cast((percentage * (maximum_screen_brightness_ - minimum_screen_brightness_)) + minimum_screen_brightness_); } - void ScreenBrightnessWindowsPlugin::HandleGetSystemBrightnessMethodCall(const std::unique_ptr> result) const + void ScreenBrightnessWindowsPlugin::HandleGetSystemScreenBrightnessMethodCall(const std::unique_ptr> result) const { - result->Success(GetBrightnessPercentage(system_brightness_)); + result->Success(GetScreenBrightnessPercentage(system_screen_brightness_)); + } + + void ScreenBrightnessWindowsPlugin::HandleSetSystemScreenBrightnessMethodCall(const flutter::MethodCall& call, std::unique_ptr> result) + { + if (window_handler_ == nullptr) + { + result->Error("-10", "Unexpected error on window handler"); + return; + } + + const flutter::EncodableMap& args = std::get(*call.arguments()); + const double brightness = std::get(args.at(flutter::EncodableValue("brightness"))); + if (std::isnan(brightness)) + { + result->Error("-2", "Unexpected error on null brightness"); + return; + } + + const long changed_brightness = GetScreenBrightnessValueByPercentage(brightness); + try + { + SetScreenBrightness(changed_brightness); + changed_screen_brightness_ = changed_brightness; + HandleCurrentBrightnessChanged(changed_brightness); + result->Success(nullptr); + } + catch (const std::exception& exception) + { + result->Error("-1", "Unable to change screen brightness.", exception.what()); + } } - void ScreenBrightnessWindowsPlugin::HandleGetScreenBrightnessMethodCall(const std::unique_ptr> result) + void ScreenBrightnessWindowsPlugin::HandleGetApplicationScreenBrightnessMethodCall(const std::unique_ptr> result) { if (window_handler_ == nullptr) { @@ -234,8 +270,8 @@ namespace screen_brightness try { - GetBrightness(minimum_brightness_, current_brightness_, maximum_brightness_); - result->Success(GetBrightnessPercentage(current_brightness_)); + GetScreenBrightness(minimum_screen_brightness_, application_screen_brightness_, maximum_screen_brightness_); + result->Success(GetScreenBrightnessPercentage(application_screen_brightness_)); } catch (const std::exception& exception) { @@ -243,7 +279,7 @@ namespace screen_brightness } } - void ScreenBrightnessWindowsPlugin::HandleSetScreenBrightnessMethodCall(const flutter::MethodCall& call, const std::unique_ptr> result) + void ScreenBrightnessWindowsPlugin::HandleSetApplicationScreenBrightnessMethodCall(const flutter::MethodCall& call, const std::unique_ptr> result) { if (window_handler_ == nullptr) { @@ -259,11 +295,11 @@ namespace screen_brightness return; } - const long changed_brightness = GetBrightnessValueByPercentage(brightness); + const long changed_brightness = GetScreenBrightnessValueByPercentage(brightness); try { - SetBrightness(changed_brightness); - changed_brightness_ = changed_brightness; + SetScreenBrightness(changed_brightness); + changed_screen_brightness_ = changed_brightness; HandleCurrentBrightnessChanged(changed_brightness); result->Success(nullptr); } @@ -273,7 +309,7 @@ namespace screen_brightness } } - void ScreenBrightnessWindowsPlugin::HandleResetScreenBrightnessMethodCall(std::unique_ptr> result) + void ScreenBrightnessWindowsPlugin::HandleResetApplicationScreenBrightnessMethodCall(std::unique_ptr> result) { if (window_handler_ == nullptr) { @@ -283,9 +319,9 @@ namespace screen_brightness try { - SetBrightness(system_brightness_); - changed_brightness_ = -1; - HandleCurrentBrightnessChanged(system_brightness_); + SetScreenBrightness(system_screen_brightness_); + changed_screen_brightness_ = -1; + HandleCurrentBrightnessChanged(system_screen_brightness_); result->Success(nullptr); } catch (const std::exception& exception) @@ -296,15 +332,15 @@ namespace screen_brightness void ScreenBrightnessWindowsPlugin::HandleCurrentBrightnessChanged(const long brightness) { - if (current_brightness_change_stream_handler_ == nullptr) + if (application_screen_brightness_change_stream_handler_ == nullptr) { return; } try { - const double brightness_percentage = GetBrightnessPercentage(brightness); - current_brightness_change_stream_handler_->AddCurrentBrightnessToEventSink(brightness_percentage); + const double brightness_percentage = GetScreenBrightnessPercentage(brightness); + application_screen_brightness_change_stream_handler_->AddApplicationScreenBrightnessToEventSink(brightness_percentage); } catch (const std::exception& exception) { @@ -312,9 +348,9 @@ namespace screen_brightness } } - void ScreenBrightnessWindowsPlugin::HandleHasChangedMethodCall(const std::unique_ptr> result) const + void ScreenBrightnessWindowsPlugin::HandleHasApplicationScreenBrightnessChangedMethodCall(const std::unique_ptr> result) const { - result->Success(changed_brightness_ != -1); + result->Success(changed_screen_brightness_ != -1); } void ScreenBrightnessWindowsPlugin::HandleIsAutoResetMethodCall(const std::unique_ptr> result) @@ -347,7 +383,7 @@ namespace screen_brightness std::optional ScreenBrightnessWindowsPlugin::HandleWindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - if (changed_brightness_ == -1 || !is_auto_reset_) + if (changed_screen_brightness_ == -1 || !is_auto_reset_) { return std::nullopt; } @@ -358,23 +394,23 @@ namespace screen_brightness switch (wParam) { case SIZE_MINIMIZED: - SetBrightness(system_brightness_); + SetScreenBrightness(system_screen_brightness_); break; case SIZE_MAXIMIZED: case SIZE_RESTORED: - SetBrightness(changed_brightness_); + SetScreenBrightness(changed_screen_brightness_); break; } break; case WM_DESTROY: - SetBrightness(system_brightness_); + SetScreenBrightness(system_screen_brightness_); break; case WM_ACTIVATEAPP: bool is_activate = bool(wParam); - SetBrightness(is_activate ? changed_brightness_ : system_brightness_); + SetScreenBrightness(is_activate ? changed_screen_brightness_ : system_screen_brightness_); break; } From 2dba835f846a2441d913adfd3400579704b87401 Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Tue, 21 May 2024 01:06:42 +0800 Subject: [PATCH 06/22] refactor(screen-brightness-windows): renamed current_brightness_change_stream_handler to application_screen_brightness_change_stream_handler --- ...tion_screen_brightness_change_stream_handler.h | 15 +++++++++++++++ .../current_brightness_change_stream_handler.h | 15 --------------- ...on_screen_brightness_change_stream_handler.cpp | 13 +++++++++++++ .../current_brightness_change_stream_handler.cpp | 13 ------------- 4 files changed, 28 insertions(+), 28 deletions(-) create mode 100644 screen_brightness_windows/windows/include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h delete mode 100644 screen_brightness_windows/windows/include/screen_brightness_windows/current_brightness_change_stream_handler.h create mode 100644 screen_brightness_windows/windows/src/application_screen_brightness_change_stream_handler.cpp delete mode 100644 screen_brightness_windows/windows/src/current_brightness_change_stream_handler.cpp diff --git a/screen_brightness_windows/windows/include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h b/screen_brightness_windows/windows/include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h new file mode 100644 index 0000000..a05b6c0 --- /dev/null +++ b/screen_brightness_windows/windows/include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h @@ -0,0 +1,15 @@ +#ifndef FLUTTER_PLUGIN_SCREEN_BRIGHTNESS_WINDOWS_PLUGIN_APPLICATION_SCREEN_BRIGHTNESS_CHNAGE_STREAM_HANDLER_H +#define FLUTTER_PLUGIN_SCREEN_BRIGHTNESS_WINDOWS_PLUGIN_APPLICATION_SCREEN_BRIGHTNESS_CHNAGE_STREAM_HANDLER_H + +#include "base_stream_handler.h" + +namespace screen_brightness +{ + class ApplicationScreenBrightnessChangeStreamHandler final : public BaseStreamHandler + { + public: + void AddApplicationScreenBrightnessToEventSink(double applicationScreenBrightness) const; + }; +} + +#endif \ No newline at end of file diff --git a/screen_brightness_windows/windows/include/screen_brightness_windows/current_brightness_change_stream_handler.h b/screen_brightness_windows/windows/include/screen_brightness_windows/current_brightness_change_stream_handler.h deleted file mode 100644 index a25a05f..0000000 --- a/screen_brightness_windows/windows/include/screen_brightness_windows/current_brightness_change_stream_handler.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef FLUTTER_PLUGIN_SCREEN_BRIGHTNESS_WINDOWS_PLUGIN_CURRENT_BRIGHTNESS_CHNAGE_STREAM_HANDLER_H -#define FLUTTER_PLUGIN_SCREEN_BRIGHTNESS_WINDOWS_PLUGIN_CURRENT_BRIGHTNESS_CHNAGE_STREAM_HANDLER_H - -#include "base_stream_handler.h" - -namespace screen_brightness -{ - class CurrentBrightnessChangeStreamHandler final : public BaseStreamHandler - { - public: - void AddCurrentBrightnessToEventSink(double brightness) const; - }; -} - -#endif \ No newline at end of file diff --git a/screen_brightness_windows/windows/src/application_screen_brightness_change_stream_handler.cpp b/screen_brightness_windows/windows/src/application_screen_brightness_change_stream_handler.cpp new file mode 100644 index 0000000..22fb9df --- /dev/null +++ b/screen_brightness_windows/windows/src/application_screen_brightness_change_stream_handler.cpp @@ -0,0 +1,13 @@ +#include "../include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h" + +namespace screen_brightness +{ + void ApplicationScreenBrightnessChangeStreamHandler::AddApplicationScreenBrightnessToEventSink(double applicationScreenBrightness) const + { + if (sink_ == nullptr) { + return; + } + + sink_->Success(applicationScreenBrightness); + } +} \ No newline at end of file diff --git a/screen_brightness_windows/windows/src/current_brightness_change_stream_handler.cpp b/screen_brightness_windows/windows/src/current_brightness_change_stream_handler.cpp deleted file mode 100644 index 43f497d..0000000 --- a/screen_brightness_windows/windows/src/current_brightness_change_stream_handler.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include "../include/screen_brightness_windows/current_brightness_change_stream_handler.h" - -namespace screen_brightness -{ - void CurrentBrightnessChangeStreamHandler::AddCurrentBrightnessToEventSink(double brightness) const - { - if (sink_ == nullptr) { - return; - } - - sink_->Success(brightness); - } -} \ No newline at end of file From 73ba980a5b8355ce0d163f8ab7871f86bbf83f7a Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Wed, 22 May 2024 16:27:42 +0800 Subject: [PATCH 07/22] fix: macOS and iOS plugin code error --- screen_brightness/screen_brightness.iml | 3 ++ .../ios/Runner.xcodeproj/project.pbxproj | 4 ++ .../example/ios/Runner/PrivacyInfo.xcprivacy | 48 +++++++++++++++++++ .../SwiftScreenBrightnessIosPlugin.swift | 4 +- screen_brightness_macos/example/macos/Podfile | 2 +- .../macos/Runner.xcodeproj/project.pbxproj | 11 +++-- .../xcshareddata/xcschemes/Runner.xcscheme | 2 +- .../Classes/ScreenBrightnessMacosPlugin.swift | 2 +- 8 files changed, 66 insertions(+), 10 deletions(-) create mode 100644 screen_brightness_ios/example/ios/Runner/PrivacyInfo.xcprivacy diff --git a/screen_brightness/screen_brightness.iml b/screen_brightness/screen_brightness.iml index cae077b..9ac4bca 100644 --- a/screen_brightness/screen_brightness.iml +++ b/screen_brightness/screen_brightness.iml @@ -18,6 +18,9 @@ + + + diff --git a/screen_brightness_ios/example/ios/Runner.xcodeproj/project.pbxproj b/screen_brightness_ios/example/ios/Runner.xcodeproj/project.pbxproj index 2733934..dbf31b8 100644 --- a/screen_brightness_ios/example/ios/Runner.xcodeproj/project.pbxproj +++ b/screen_brightness_ios/example/ios/Runner.xcodeproj/project.pbxproj @@ -14,6 +14,7 @@ 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; + A199036A2BDA0E5500E205D8 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = A19903692BDA08C300E205D8 /* PrivacyInfo.xcprivacy */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -47,6 +48,7 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A19903692BDA08C300E205D8 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -110,6 +112,7 @@ 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + A19903692BDA08C300E205D8 /* PrivacyInfo.xcprivacy */, ); path = Runner; sourceTree = ""; @@ -190,6 +193,7 @@ 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + A199036A2BDA0E5500E205D8 /* PrivacyInfo.xcprivacy in Resources */, 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/screen_brightness_ios/example/ios/Runner/PrivacyInfo.xcprivacy b/screen_brightness_ios/example/ios/Runner/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..f0d24cc --- /dev/null +++ b/screen_brightness_ios/example/ios/Runner/PrivacyInfo.xcprivacy @@ -0,0 +1,48 @@ + + + + + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + DDA9.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryDiskSpace + NSPrivacyAccessedAPITypeReasons + + E174.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategorySystemBootTime + NSPrivacyAccessedAPITypeReasons + + 35F9.1 + + + + + diff --git a/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift b/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift index e5f3ce6..d2cb9c2 100644 --- a/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift +++ b/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift @@ -42,7 +42,7 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp break; case "setSystemScreenBrightness": - handleSetSystemScreenBrightnessMethodCall(call, result: result) + handleSetSystemScreenBrightnessMethodCall(call: call, result: result) break; case "getApplicationScreenBrightness": @@ -131,7 +131,7 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp systemScreenBrightness = _systemScreenBrightness if (applicationScreenBrightness == nil) { - handleApplicationScreenBrightnessChanged(systemScreenBrightness) + handleApplicationScreenBrightnessChanged(_systemScreenBrightness) } result(nil) } diff --git a/screen_brightness_macos/example/macos/Podfile b/screen_brightness_macos/example/macos/Podfile index dade8df..049abe2 100644 --- a/screen_brightness_macos/example/macos/Podfile +++ b/screen_brightness_macos/example/macos/Podfile @@ -1,4 +1,4 @@ -platform :osx, '10.11' +platform :osx, '10.14' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' diff --git a/screen_brightness_macos/example/macos/Runner.xcodeproj/project.pbxproj b/screen_brightness_macos/example/macos/Runner.xcodeproj/project.pbxproj index 2671fbb..291c0fd 100644 --- a/screen_brightness_macos/example/macos/Runner.xcodeproj/project.pbxproj +++ b/screen_brightness_macos/example/macos/Runner.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 51; + objectVersion = 54; objects = { /* Begin PBXAggregateTarget section */ @@ -203,7 +203,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0920; - LastUpgradeCheck = 1300; + LastUpgradeCheck = 1510; ORGANIZATIONNAME = ""; TargetAttributes = { 33CC10EC2044A3C60003C045 = { @@ -256,6 +256,7 @@ /* Begin PBXShellScriptBuildPhase section */ 3399D490228B24CF009A79C7 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; buildActionMask = 2147483647; files = ( ); @@ -404,7 +405,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.11; + MACOSX_DEPLOYMENT_TARGET = 10.14; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; @@ -483,7 +484,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.11; + MACOSX_DEPLOYMENT_TARGET = 10.14; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; @@ -530,7 +531,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.11; + MACOSX_DEPLOYMENT_TARGET = 10.14; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; diff --git a/screen_brightness_macos/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/screen_brightness_macos/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 90bdf03..ac312b4 100644 --- a/screen_brightness_macos/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/screen_brightness_macos/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -1,6 +1,6 @@ Date: Fri, 14 Jun 2024 18:46:02 +0800 Subject: [PATCH 08/22] fix: macOS and iOS plugin code error --- screen_brightness_ios/example/lib/main.dart | 107 ++++++++++++------ ...ScreenBrightnessChangeStreamHandler.swift} | 6 +- .../SwiftScreenBrightnessIosPlugin.swift | 21 +++- .../screen_brightness_ios.iml | 51 +++++++++ screen_brightness_macos/example/lib/main.dart | 107 ++++++++++++------ .../Classes/ScreenBrightnessMacosPlugin.swift | 41 ++++--- ...ScreenBrightnessChangeStreamHandler.swift} | 6 +- .../screen_brightness_macos.iml | 36 ++++++ .../lib/method_channel_screen_brightness.dart | 35 +++++- .../screen_brightness_platform_interface.dart | 13 ++- ...en_brightness_platform_interface_test.dart | 45 +++++++- 11 files changed, 358 insertions(+), 110 deletions(-) rename screen_brightness_ios/ios/Classes/StreamHandler/{ApplicationScreenBrightnessChangeStreamHandler.swift => ScreenBrightnessChangeStreamHandler.swift} (51%) rename screen_brightness_macos/macos/Classes/StreamHandler/{ApplicationScreenBrightnessChangeStreamHandler.swift => ScreenBrightnessChangeStreamHandler.swift} (50%) diff --git a/screen_brightness_ios/example/lib/main.dart b/screen_brightness_ios/example/lib/main.dart index ad2f90c..56d5320 100644 --- a/screen_brightness_ios/example/lib/main.dart +++ b/screen_brightness_ios/example/lib/main.dart @@ -69,25 +69,50 @@ class HomePage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + FutureBuilder( + future: ScreenBrightnessPlatform.instance.system, + builder: (context, snapshot) { + double systemScreenBrightness = 0; + if (snapshot.hasData) { + systemScreenBrightness = snapshot.data!; + } + + return StreamBuilder( + stream: ScreenBrightnessPlatform + .instance.onSystemScreenBrightnessChanged, + builder: (context, snapshot) { + double changedSystemScreenBrightness = + systemScreenBrightness; + if (snapshot.hasData) { + changedSystemScreenBrightness = snapshot.data!; + } + + return Text( + 'System screen brightness $changedSystemScreenBrightness'); + }, + ); + }, + ), FutureBuilder( future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { - double applicationBrightness = 0; + double applicationScreenBrightness = 0; if (snapshot.hasData) { - applicationBrightness = snapshot.data!; + applicationScreenBrightness = snapshot.data!; } return StreamBuilder( stream: ScreenBrightnessPlatform - .instance.onApplicationBrightnessChanged, + .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { - double changedApplicationBrightness = applicationBrightness; + double changedApplicationScreenBrightness = + applicationScreenBrightness; if (snapshot.hasData) { - changedApplicationBrightness = snapshot.data!; + changedApplicationScreenBrightness = snapshot.data!; } return Text( - 'Application brightness $changedApplicationBrightness'); + 'Application screen brightness $changedApplicationScreenBrightness'); }, ); }, @@ -124,33 +149,33 @@ class ControllerPage extends StatefulWidget { } class _ControllerPageState extends State { - Future setSystemBrightness(double brightness) async { + Future setSystemScreenBrightness(double brightness) async { try { await ScreenBrightnessPlatform.instance .setSystemScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set system brightness'; + throw 'Failed to set system screen brightness'; } } - Future setApplicationBrightness(double brightness) async { + Future setApplicationScreenBrightness(double brightness) async { try { await ScreenBrightnessPlatform.instance .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set application brightness'; + throw 'Failed to set application screen brightness'; } } - Future resetApplicationBrightness() async { + Future resetApplicationScreenBrightness() async { try { await ScreenBrightnessPlatform.instance .resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); - throw 'Failed to reset application brightness'; + throw 'Failed to reset application screen brightness'; } } @@ -166,40 +191,48 @@ class _ControllerPageState extends State { FutureBuilder( future: ScreenBrightnessPlatform.instance.system, builder: (context, snapshot) { - double systemBrightness = 0; - if (snapshot.hasData) { - systemBrightness = snapshot.data!; - } + double systemScreenBrightness = snapshot.data ?? 0; + + return StreamBuilder( + stream: ScreenBrightnessPlatform + .instance.onSystemScreenBrightnessChanged, + builder: (context, snapshot) { + double changedSystemScreenBrightness = + snapshot.data ?? systemScreenBrightness; - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text('System brightness: $systemBrightness'), - Slider.adaptive( - value: systemBrightness, - onChanged: (value) { - setSystemBrightness(value); - }, - ), - ], + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'System screen brightness: $changedSystemScreenBrightness'), + Slider.adaptive( + value: changedSystemScreenBrightness, + onChanged: (value) { + setSystemScreenBrightness(value); + }, + ), + ], + ); + }, ); }, ), FutureBuilder( future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { - double applicationBrightness = 0; + double applicationScreenBrightness = 0; if (snapshot.hasData) { - applicationBrightness = snapshot.data!; + applicationScreenBrightness = snapshot.data!; } return StreamBuilder( stream: ScreenBrightnessPlatform - .instance.onApplicationBrightnessChanged, + .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { - double changedApplicationBrightness = applicationBrightness; + double changedApplicationScreenBrightness = + applicationScreenBrightness; if (snapshot.hasData) { - changedApplicationBrightness = snapshot.data!; + changedApplicationScreenBrightness = snapshot.data!; } return Column( @@ -210,20 +243,20 @@ class _ControllerPageState extends State { .instance.hasApplicationScreenBrightnessChanged, builder: (context, snapshot) { return Text( - 'Application brightness has changed via plugin: ${snapshot.data}'); + 'Application screen brightness has changed via plugin: ${snapshot.data}'); }, ), Text( - 'Application brightness: $changedApplicationBrightness'), + 'Application screen brightness: $changedApplicationScreenBrightness'), Slider.adaptive( - value: changedApplicationBrightness, + value: changedApplicationScreenBrightness, onChanged: (value) { - setApplicationBrightness(value); + setApplicationScreenBrightness(value); }, ), ElevatedButton( onPressed: () { - resetApplicationBrightness(); + resetApplicationScreenBrightness(); }, child: const Text('reset brightness'), ), diff --git a/screen_brightness_ios/ios/Classes/StreamHandler/ApplicationScreenBrightnessChangeStreamHandler.swift b/screen_brightness_ios/ios/Classes/StreamHandler/ScreenBrightnessChangeStreamHandler.swift similarity index 51% rename from screen_brightness_ios/ios/Classes/StreamHandler/ApplicationScreenBrightnessChangeStreamHandler.swift rename to screen_brightness_ios/ios/Classes/StreamHandler/ScreenBrightnessChangeStreamHandler.swift index 231737a..543aed2 100644 --- a/screen_brightness_ios/ios/Classes/StreamHandler/ApplicationScreenBrightnessChangeStreamHandler.swift +++ b/screen_brightness_ios/ios/Classes/StreamHandler/ScreenBrightnessChangeStreamHandler.swift @@ -9,12 +9,12 @@ import Foundation import Flutter import UIKit -public class ApplicationScreenBrightnessChangeStreamHandler: BaseStreamHandler { - public func addApplicationScreenBrightnessToEventSink(_ applicationScreenBrightness: CGFloat) { +public class ScreenBrightnessChangeStreamHandler: BaseStreamHandler { + public func addScreenBrightnessToEventSink(_ screenBrightness: CGFloat) { guard let eventSink = eventSink else { return } - eventSink(Double(applicationScreenBrightness)) + eventSink(Double(screenBrightness)) } } diff --git a/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift b/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift index d2cb9c2..50cc6e9 100644 --- a/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift +++ b/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift @@ -5,7 +5,10 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp var methodChannel: FlutterMethodChannel? var applicationScreenBrightnessChangedEventChannel: FlutterEventChannel? - let applicationScreenBrightnessChangeStreamHandler: ApplicationScreenBrightnessChangeStreamHandler = ApplicationScreenBrightnessChangeStreamHandler() + let applicationScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler() + + var systemScreenBrightnessChangedEventChannel: FlutterEventChannel? + let systemScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler() var systemScreenBrightness: CGFloat? var applicationScreenBrightness: CGFloat? @@ -27,6 +30,9 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp instance.applicationScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_change", binaryMessenger: registrar.messenger()) instance.applicationScreenBrightnessChangedEventChannel!.setStreamHandler(instance.applicationScreenBrightnessChangeStreamHandler) + instance.systemScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/system_brightness_changed", binaryMessenger: registrar.messenger()) + instance.systemScreenBrightnessChangedEventChannel!.setStreamHandler(instance.systemScreenBrightnessChangeStreamHandler) + registrar.addApplicationDelegate(instance) } @@ -127,15 +133,19 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp } let _systemScreenBrightness = CGFloat(brightness.doubleValue) - setScreenBrightness(targetBrightness: _systemScreenBrightness, animated: isAnimate) - systemScreenBrightness = _systemScreenBrightness + handleSystemScreenBrightnessChanged(_systemScreenBrightness) if (applicationScreenBrightness == nil) { + setScreenBrightness(targetBrightness: _systemScreenBrightness, animated: isAnimate) handleApplicationScreenBrightnessChanged(_systemScreenBrightness) } result(nil) } + private func handleSystemScreenBrightnessChanged(_ systemScreenBrightness: CGFloat) { + systemScreenBrightnessChangeStreamHandler.addScreenBrightnessToEventSink(systemScreenBrightness) + } + private func handleGetApplicationScreenBrightnessMethodCall(result: FlutterResult) { result(UIScreen.main.brightness) } @@ -168,7 +178,7 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp } private func handleApplicationScreenBrightnessChanged(_ applicationScreenBrightness: CGFloat) { - applicationScreenBrightnessChangeStreamHandler.addApplicationScreenBrightnessToEventSink(applicationScreenBrightness) + applicationScreenBrightnessChangeStreamHandler.addScreenBrightnessToEventSink(applicationScreenBrightness) } private func handleHasApplicationScreenBrightnessChangedMethodCall(result: FlutterResult) { @@ -209,6 +219,7 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp } systemScreenBrightness = brightness + handleSystemScreenBrightnessChanged(brightness) if (applicationScreenBrightness == nil) { handleApplicationScreenBrightnessChanged(brightness) } @@ -246,6 +257,7 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp NotificationCenter.default.removeObserver(self, name: UIScreen.brightnessDidChangeNotification, object: nil) systemScreenBrightness = UIScreen.main.brightness + handleSystemScreenBrightnessChanged(systemScreenBrightness!) if (applicationScreenBrightness == nil) { handleApplicationScreenBrightnessChanged(systemScreenBrightness!) } @@ -263,5 +275,6 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp methodChannel?.setMethodCallHandler(nil) applicationScreenBrightnessChangedEventChannel?.setStreamHandler(nil) + systemScreenBrightnessChangedEventChannel?.setStreamHandler(nil) } } diff --git a/screen_brightness_ios/screen_brightness_ios.iml b/screen_brightness_ios/screen_brightness_ios.iml index 46c3243..28938c1 100644 --- a/screen_brightness_ios/screen_brightness_ios.iml +++ b/screen_brightness_ios/screen_brightness_ios.iml @@ -12,6 +12,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/screen_brightness_macos/example/lib/main.dart b/screen_brightness_macos/example/lib/main.dart index ad2f90c..56d5320 100644 --- a/screen_brightness_macos/example/lib/main.dart +++ b/screen_brightness_macos/example/lib/main.dart @@ -69,25 +69,50 @@ class HomePage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + FutureBuilder( + future: ScreenBrightnessPlatform.instance.system, + builder: (context, snapshot) { + double systemScreenBrightness = 0; + if (snapshot.hasData) { + systemScreenBrightness = snapshot.data!; + } + + return StreamBuilder( + stream: ScreenBrightnessPlatform + .instance.onSystemScreenBrightnessChanged, + builder: (context, snapshot) { + double changedSystemScreenBrightness = + systemScreenBrightness; + if (snapshot.hasData) { + changedSystemScreenBrightness = snapshot.data!; + } + + return Text( + 'System screen brightness $changedSystemScreenBrightness'); + }, + ); + }, + ), FutureBuilder( future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { - double applicationBrightness = 0; + double applicationScreenBrightness = 0; if (snapshot.hasData) { - applicationBrightness = snapshot.data!; + applicationScreenBrightness = snapshot.data!; } return StreamBuilder( stream: ScreenBrightnessPlatform - .instance.onApplicationBrightnessChanged, + .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { - double changedApplicationBrightness = applicationBrightness; + double changedApplicationScreenBrightness = + applicationScreenBrightness; if (snapshot.hasData) { - changedApplicationBrightness = snapshot.data!; + changedApplicationScreenBrightness = snapshot.data!; } return Text( - 'Application brightness $changedApplicationBrightness'); + 'Application screen brightness $changedApplicationScreenBrightness'); }, ); }, @@ -124,33 +149,33 @@ class ControllerPage extends StatefulWidget { } class _ControllerPageState extends State { - Future setSystemBrightness(double brightness) async { + Future setSystemScreenBrightness(double brightness) async { try { await ScreenBrightnessPlatform.instance .setSystemScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set system brightness'; + throw 'Failed to set system screen brightness'; } } - Future setApplicationBrightness(double brightness) async { + Future setApplicationScreenBrightness(double brightness) async { try { await ScreenBrightnessPlatform.instance .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set application brightness'; + throw 'Failed to set application screen brightness'; } } - Future resetApplicationBrightness() async { + Future resetApplicationScreenBrightness() async { try { await ScreenBrightnessPlatform.instance .resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); - throw 'Failed to reset application brightness'; + throw 'Failed to reset application screen brightness'; } } @@ -166,40 +191,48 @@ class _ControllerPageState extends State { FutureBuilder( future: ScreenBrightnessPlatform.instance.system, builder: (context, snapshot) { - double systemBrightness = 0; - if (snapshot.hasData) { - systemBrightness = snapshot.data!; - } + double systemScreenBrightness = snapshot.data ?? 0; + + return StreamBuilder( + stream: ScreenBrightnessPlatform + .instance.onSystemScreenBrightnessChanged, + builder: (context, snapshot) { + double changedSystemScreenBrightness = + snapshot.data ?? systemScreenBrightness; - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text('System brightness: $systemBrightness'), - Slider.adaptive( - value: systemBrightness, - onChanged: (value) { - setSystemBrightness(value); - }, - ), - ], + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'System screen brightness: $changedSystemScreenBrightness'), + Slider.adaptive( + value: changedSystemScreenBrightness, + onChanged: (value) { + setSystemScreenBrightness(value); + }, + ), + ], + ); + }, ); }, ), FutureBuilder( future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { - double applicationBrightness = 0; + double applicationScreenBrightness = 0; if (snapshot.hasData) { - applicationBrightness = snapshot.data!; + applicationScreenBrightness = snapshot.data!; } return StreamBuilder( stream: ScreenBrightnessPlatform - .instance.onApplicationBrightnessChanged, + .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { - double changedApplicationBrightness = applicationBrightness; + double changedApplicationScreenBrightness = + applicationScreenBrightness; if (snapshot.hasData) { - changedApplicationBrightness = snapshot.data!; + changedApplicationScreenBrightness = snapshot.data!; } return Column( @@ -210,20 +243,20 @@ class _ControllerPageState extends State { .instance.hasApplicationScreenBrightnessChanged, builder: (context, snapshot) { return Text( - 'Application brightness has changed via plugin: ${snapshot.data}'); + 'Application screen brightness has changed via plugin: ${snapshot.data}'); }, ), Text( - 'Application brightness: $changedApplicationBrightness'), + 'Application screen brightness: $changedApplicationScreenBrightness'), Slider.adaptive( - value: changedApplicationBrightness, + value: changedApplicationScreenBrightness, onChanged: (value) { - setApplicationBrightness(value); + setApplicationScreenBrightness(value); }, ), ElevatedButton( onPressed: () { - resetApplicationBrightness(); + resetApplicationScreenBrightness(); }, child: const Text('reset brightness'), ), diff --git a/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift b/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift index 915c9d7..07110e3 100644 --- a/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift +++ b/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift @@ -9,7 +9,10 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { var methodChannel: FlutterMethodChannel? var applicationScreenBrightnessChangeEventChannel: FlutterEventChannel? - let applicationScreenBrightnessChangeStreamHandler: ApplicationScreenBrightnessChangeStreamHandler = ApplicationScreenBrightnessChangeStreamHandler() + let applicationScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler() + + var systemScreenBrightnessChangeEventChannel: FlutterEventChannel? + let systemScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler() var systemScreenBrightness: Float? var applicationScreenBrightness: Float? @@ -26,6 +29,9 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { instance.applicationScreenBrightnessChangeEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_change", binaryMessenger: registrar.messenger) instance.applicationScreenBrightnessChangeEventChannel!.setStreamHandler(instance.applicationScreenBrightnessChangeStreamHandler) + + instance.systemScreenBrightnessChangeEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/system_brightness_change", binaryMessenger: registrar.messenger) + instance.systemScreenBrightnessChangeEventChannel!.setStreamHandler(instance.systemScreenBrightnessChangeStreamHandler) } override init() { @@ -142,16 +148,21 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { } let _systemScreenBrightness = Float(brightness.doubleValue) - do { - try setScreenBrightness(targetBrightness: _systemScreenBrightness) + if (applicationScreenBrightness == nil) { + try setScreenBrightness(targetBrightness: _systemScreenBrightness) + handleApplicationScreenBrightnessChanged(_systemScreenBrightness) + } + systemScreenBrightness = _systemScreenBrightness + handleSystemScreenBrightnessChanged(_systemScreenBrightness) + result(nil) } catch { result(FlutterError.init(code: "-1", message: "Unable to change system screen brightness", details: nil)) } - - systemScreenBrightness = _systemScreenBrightness - handleApplicationScreenBrightnessChanged(_systemScreenBrightness) - result(nil) + } + + private func handleSystemScreenBrightnessChanged(_ systemScreenBrightness: Float) { + systemScreenBrightnessChangeStreamHandler.addScreenBrightnessToEventSink(systemScreenBrightness) } private func handleGetApplicationScreenBrightnessMethodCall(result: FlutterResult) { @@ -173,13 +184,12 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { do { try setScreenBrightness(targetBrightness: _applicationBrightness) + applicationScreenBrightness = _applicationBrightness + handleApplicationScreenBrightnessChanged(_applicationBrightness) + result(nil) } catch { result(FlutterError.init(code: "-1", message: "Unable to change application screen brightness", details: nil)) } - - applicationScreenBrightness = _applicationBrightness - handleApplicationScreenBrightnessChanged(_applicationBrightness) - result(nil) } private func handleResetApplicationScreenBrightnessMethodCall(result: FlutterResult) { @@ -190,17 +200,16 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { do { try setScreenBrightness(targetBrightness: systemScreenBrightness) + applicationScreenBrightness = nil + handleApplicationScreenBrightnessChanged(systemScreenBrightness) + result(nil) } catch { result(FlutterError.init(code: "-1", message: "Unable to change screen brightness", details: nil)) } - - applicationScreenBrightness = nil - handleApplicationScreenBrightnessChanged(systemScreenBrightness) - result(nil) } private func handleApplicationScreenBrightnessChanged(_ applicationScreenBrightness: Float) { - applicationScreenBrightnessChangeStreamHandler.addApplicationScreenBrightnessToEventSink(applicationScreenBrightness) + applicationScreenBrightnessChangeStreamHandler.addScreenBrightnessToEventSink(applicationScreenBrightness) } private func handleHasApplicationScreenBrightnessChangedMethodCall(result: FlutterResult) { diff --git a/screen_brightness_macos/macos/Classes/StreamHandler/ApplicationScreenBrightnessChangeStreamHandler.swift b/screen_brightness_macos/macos/Classes/StreamHandler/ScreenBrightnessChangeStreamHandler.swift similarity index 50% rename from screen_brightness_macos/macos/Classes/StreamHandler/ApplicationScreenBrightnessChangeStreamHandler.swift rename to screen_brightness_macos/macos/Classes/StreamHandler/ScreenBrightnessChangeStreamHandler.swift index a418891..2ea4727 100644 --- a/screen_brightness_macos/macos/Classes/StreamHandler/ApplicationScreenBrightnessChangeStreamHandler.swift +++ b/screen_brightness_macos/macos/Classes/StreamHandler/ScreenBrightnessChangeStreamHandler.swift @@ -8,12 +8,12 @@ import Cocoa import FlutterMacOS -public class ApplicationScreenBrightnessChangeStreamHandler: BaseStreamHandler { - public func addApplicationScreenBrightnessToEventSink(_ applicationScreenBrightness: Float) { +public class ScreenBrightnessChangeStreamHandler: BaseStreamHandler { + public func addScreenBrightnessToEventSink(_ screenBrightness: Float) { guard let eventSink = eventSink else { return } - eventSink(Double(applicationScreenBrightness)) + eventSink(Double(screenBrightness)) } } diff --git a/screen_brightness_macos/screen_brightness_macos.iml b/screen_brightness_macos/screen_brightness_macos.iml index ded73d4..cd4d49c 100644 --- a/screen_brightness_macos/screen_brightness_macos.iml +++ b/screen_brightness_macos/screen_brightness_macos.iml @@ -12,6 +12,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart b/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart index 8f92d86..5167b89 100644 --- a/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart +++ b/screen_brightness_platform_interface/lib/method_channel_screen_brightness.dart @@ -8,9 +8,13 @@ import 'constant/plugin_channel.dart'; /// Implementation of screen brightness platform interface class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { - /// Private stream which is listened to event channel for preventing creating - /// new stream - Stream? _onApplicationBrightnessChanged; + /// Private application screen brightness changed stream which is listened to + /// event channel for preventing creating new stream. + Stream? _onApplicationScreenBrightnessChanged; + + /// Private system screen brightness changed stream which is listened to event + /// channel for preventing creating new stream. + Stream? _onSystemScreenBrightnessChanged; /// Returns system screen brightness. /// @@ -73,6 +77,21 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { methodNameSetSystemScreenBrightness, {"brightness": brightness}); } + /// Returns stream with system screen brightness changes including + /// [ScreenBrightness.setSystemScreenBrightness], system control center or + /// system setting. + /// + /// This stream is useful for user to listen to system screen brightness + /// changes. + @override + Stream get onSystemScreenBrightnessChanged { + _onSystemScreenBrightnessChanged ??= + pluginEventChannelSystemBrightnessChanged + .receiveBroadcastStream() + .cast(); + return _onSystemScreenBrightnessChanged!; + } + /// Returns application screen brightness value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will @@ -163,6 +182,10 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { .invokeMethod(methodNameResetApplicationScreenBrightness); } + /// Old API on [onApplicationScreenBrightnessChanged] + Stream get onApplicationBrightnessChanged => + onApplicationScreenBrightnessChanged; + /// Returns stream with application screen brightness changes including /// [ScreenBrightness.setApplicationScreenBrightness], /// [ScreenBrightness.resetApplicationScreenBrightness], system control center or system @@ -170,12 +193,12 @@ class MethodChannelScreenBrightness extends ScreenBrightnessPlatform { /// /// This stream is useful for user to listen to brightness changes. @override - Stream get onApplicationBrightnessChanged { - _onApplicationBrightnessChanged ??= + Stream get onApplicationScreenBrightnessChanged { + _onApplicationScreenBrightnessChanged ??= pluginEventChannelApplicationBrightnessChanged .receiveBroadcastStream() .cast(); - return _onApplicationBrightnessChanged!; + return _onApplicationScreenBrightnessChanged!; } /// Returns boolean to identify application screen brightness has changed by diff --git a/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart b/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart index 7b1afd8..77350e4 100644 --- a/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart +++ b/screen_brightness_platform_interface/lib/screen_brightness_platform_interface.dart @@ -56,6 +56,17 @@ abstract class ScreenBrightnessPlatform extends PlatformInterface { 'setSystemScreenBrightness(brightness) has not been implemented.'); } + /// Returns stream with system screen brightness changes including + /// [ScreenBrightness.setSystemScreenBrightness], system control center or + /// system setting. + /// + /// This stream is useful for user to listen to system screen brightness + /// changes. + Stream get onSystemScreenBrightnessChanged { + throw UnimplementedError( + 'onApplicationBrightnessChanged has not been implemented.'); + } + /// Returns application screen brightness value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will @@ -95,7 +106,7 @@ abstract class ScreenBrightnessPlatform extends PlatformInterface { /// setting. /// /// This stream is useful for user to listen to brightness changes. - Stream get onApplicationBrightnessChanged { + Stream get onApplicationScreenBrightnessChanged { throw UnimplementedError( 'onApplicationBrightnessChanged has not been implemented.'); } diff --git a/screen_brightness_platform_interface/test/screen_brightness_platform_interface_test.dart b/screen_brightness_platform_interface/test/screen_brightness_platform_interface_test.dart index 90fe712..e8e5eec 100644 --- a/screen_brightness_platform_interface/test/screen_brightness_platform_interface_test.dart +++ b/screen_brightness_platform_interface/test/screen_brightness_platform_interface_test.dart @@ -30,9 +30,11 @@ void main() { double? applicationBrightness; bool isAutoReset = true; bool isAnimate = true; + late MethodChannelScreenBrightness methodChannelScreenBrightness; const pluginEventChannelApplicationBrightnessChanged = MethodChannel(pluginEventChannelApplicationBrightnessChangedName); - late MethodChannelScreenBrightness methodChannelScreenBrightness; + const pluginEventChannelSystemBrightnessChanged = + MethodChannel(pluginEventChannelSystemBrightnessChangedName); setUp(() { systemBrightness = 0.5; @@ -100,6 +102,29 @@ void main() { return null; }); + + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(pluginEventChannelSystemBrightnessChanged, + (call) async { + switch (call.method) { + case 'listen': + await TestDefaultBinaryMessengerBinding + .instance.defaultBinaryMessenger + .handlePlatformMessage( + pluginEventChannelSystemBrightnessChanged.name, + pluginEventChannelSystemBrightnessChanged.codec + .encodeSuccessEnvelope(0.1.toDouble()), + (_) {}, + ); + break; + + case 'cancel': + default: + return null; + } + + return null; + }); }); tearDown(() { @@ -108,6 +133,9 @@ void main() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler( pluginEventChannelApplicationBrightnessChanged, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + pluginEventChannelSystemBrightnessChanged, null); }); test('get platform instance', () { @@ -154,6 +182,12 @@ void main() { expect(error, isA()); }); + test('on system screen brightness changed', () async { + final result = await methodChannelScreenBrightness + .onSystemScreenBrightnessChanged.first; + expect(result, 0.1); + }); + test('get application screen brightness', () async { expect(await methodChannelScreenBrightness.application, systemBrightness); }); @@ -257,6 +291,11 @@ void main() { throwsUnimplementedError); }); + test('unimplemented onSystemScreenBrightnessChanged stream', () { + expect(() => platform.onSystemScreenBrightnessChanged, + throwsUnimplementedError); + }); + test('unimplemented application current brightness', () { expect(() => platform.application, throwsUnimplementedError); }); @@ -271,8 +310,8 @@ void main() { throwsUnimplementedError); }); - test('unimplemented onApplicationBrightnessChanged stream', () { - expect(() => platform.onApplicationBrightnessChanged, + test('unimplemented onApplicationScreenBrightnessChanged stream', () { + expect(() => platform.onApplicationScreenBrightnessChanged, throwsUnimplementedError); }); From d5acc0a1efbdcc8bc56c1bd86d08c4e5a0a89fc1 Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Fri, 2 Aug 2024 08:18:21 +0800 Subject: [PATCH 09/22] feat(screen-brightness-android): added system brightness stream --- .idea/deploymentTargetDropDown.xml | 15 ++- screen_brightness/example/pubspec.lock | 28 ++--- screen_brightness/lib/screen_brightness.dart | 23 +++- .../test/screen_brightness_test.dart | 52 +++++++-- .../ScreenBrightnessAndroidPlugin.kt | 90 +++++++++------ ...tionScreenBrightnessChangeStreamHandler.kt | 46 -------- .../ScreenBrightnessChangeStreamHandler.kt | 18 +++ .../example/lib/main.dart | 37 ++++--- .../example/pubspec.lock | 28 ++--- screen_brightness_android/pubspec.yaml | 3 +- screen_brightness_ios/example/lib/main.dart | 103 ++++++------------ .../SwiftScreenBrightnessIosPlugin.swift | 16 +-- screen_brightness_macos/example/lib/main.dart | 103 ++++++------------ .../lib/constant/plugin_channel.dart | 2 +- .../example/lib/main.dart | 4 +- .../example/pubspec.lock | 28 ++--- .../src/screen_brightness_windows_plugin.cpp | 20 ++-- 17 files changed, 309 insertions(+), 307 deletions(-) delete mode 100644 screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ApplicationScreenBrightnessChangeStreamHandler.kt create mode 100644 screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ScreenBrightnessChangeStreamHandler.kt diff --git a/.idea/deploymentTargetDropDown.xml b/.idea/deploymentTargetDropDown.xml index ee9d103..1fceffc 100644 --- a/.idea/deploymentTargetDropDown.xml +++ b/.idea/deploymentTargetDropDown.xml @@ -3,7 +3,20 @@ - + + + + + + + + + + + + + + diff --git a/screen_brightness/example/pubspec.lock b/screen_brightness/example/pubspec.lock index eae1366..b923291 100644 --- a/screen_brightness/example/pubspec.lock +++ b/screen_brightness/example/pubspec.lock @@ -71,26 +71,26 @@ packages: dependency: transitive description: name: leak_tracker - sha256: "78eb209deea09858f5269f5a5b02be4049535f568c07b275096836f01ea323fa" + sha256: "7f0df31977cb2c0b88585095d168e689669a2cc9b97c309665e3386f3e9d341a" url: "https://pub.dev" source: hosted - version: "10.0.0" + version: "10.0.4" leak_tracker_flutter_testing: dependency: transitive description: name: leak_tracker_flutter_testing - sha256: b46c5e37c19120a8a01918cfaf293547f47269f7cb4b0058f21531c2465d6ef0 + sha256: "06e98f569d004c1315b991ded39924b21af84cf14cc94791b8aea337d25b57f8" url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "3.0.3" leak_tracker_testing: dependency: transitive description: name: leak_tracker_testing - sha256: a597f72a664dbd293f3bfc51f9ba69816f84dcd403cdac7066cb3f6003f3ab47 + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "3.0.1" lints: dependency: transitive description: @@ -119,10 +119,10 @@ packages: dependency: transitive description: name: meta - sha256: d584fa6707a52763a52446f02cc621b077888fb63b93bbcb1143a7be5a0c0c04 + sha256: "7687075e408b093f36e6bbf6c91878cc0d4cd10f409506f7bc996f68220b9136" url: "https://pub.dev" source: hosted - version: "1.11.0" + version: "1.12.0" path: dependency: transitive description: @@ -235,10 +235,10 @@ packages: dependency: transitive description: name: test_api - sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + sha256: "9955ae474176f7ac8ee4e989dadfb411a58c30415bcfb648fa04b2b8a03afa7f" url: "https://pub.dev" source: hosted - version: "0.6.1" + version: "0.7.0" vector_math: dependency: transitive description: @@ -251,10 +251,10 @@ packages: dependency: transitive description: name: vm_service - sha256: b3d56ff4341b8f182b96aceb2fa20e3dcb336b9f867bc0eafc0de10f1048e957 + sha256: "3923c89304b715fb1eb6423f017651664a03bf5f4b29983627c4da791f74a4ec" url: "https://pub.dev" source: hosted - version: "13.0.0" + version: "14.2.1" sdks: - dart: ">=3.2.0-0 <4.0.0" - flutter: ">=3.0.0" + dart: ">=3.3.0 <4.0.0" + flutter: ">=3.18.0-18.0.pre.54" diff --git a/screen_brightness/lib/screen_brightness.dart b/screen_brightness/lib/screen_brightness.dart index 34b3384..d8d15dd 100644 --- a/screen_brightness/lib/screen_brightness.dart +++ b/screen_brightness/lib/screen_brightness.dart @@ -66,6 +66,14 @@ class ScreenBrightness { Future setSystemScreenBrightness(double brightness) => _platform.setSystemScreenBrightness(brightness); + /// Returns stream with system screen brightness changes including + /// [ScreenBrightness.setSystemScreenBrightness], system control center or + /// system setting. + /// + /// This stream is useful for user to listen to system brightness changes. + Stream get onSystemScreenBrightnessChanged => + _platform.onSystemScreenBrightnessChanged; + /// Returns application screen brightness value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will @@ -133,14 +141,19 @@ class ScreenBrightness { Future resetApplicationScreenBrightness() => _platform.resetApplicationScreenBrightness(); + /// This stream is useful for user to listen to brightness changes. + @Deprecated('Use onApplicationScreenBrightnessChanged instead, reason rename') + Stream get onApplicationBrightnessChanged => + onApplicationScreenBrightnessChanged; + /// Returns stream with application screen brightness changes including /// [ScreenBrightness.setApplicationScreenBrightness], - /// [ScreenBrightness.resetApplicationScreenBrightness], system control center or system - /// setting. + /// [ScreenBrightness.resetApplicationScreenBrightness], system control center + /// or system setting. /// - /// This stream is useful for user to listen to brightness changes. - Stream get onApplicationBrightnessChanged => - _platform.onApplicationBrightnessChanged; + /// This stream is useful for user to listen to application brightness changes. + Stream get onApplicationScreenBrightnessChanged => + _platform.onApplicationScreenBrightnessChanged; /// Returns boolean to identify application screen brightness has changed by /// this plugin. diff --git a/screen_brightness/test/screen_brightness_test.dart b/screen_brightness/test/screen_brightness_test.dart index fb63c7f..3f3c5ea 100644 --- a/screen_brightness/test/screen_brightness_test.dart +++ b/screen_brightness/test/screen_brightness_test.dart @@ -8,7 +8,9 @@ import 'package:screen_brightness_platform_interface/screen_brightness_platform_ const double systemBrightness = 0.5; -late StreamController controller; +late StreamController applicationScreenBrightnessController; + +late StreamController systemScreenBrightnessController; class MockScreenBrightnessPlatform with MockPlatformInterfaceMixin @@ -45,7 +47,12 @@ class MockScreenBrightnessPlatform } @override - Stream get onApplicationBrightnessChanged => controller.stream; + Stream get onApplicationScreenBrightnessChanged => + applicationScreenBrightnessController.stream; + + @override + Stream get onSystemScreenBrightnessChanged => + systemScreenBrightnessController.stream; @override Future get hasApplicationScreenBrightnessChanged async => @@ -105,27 +112,54 @@ void main() { group('on application screen brightness changed stream', () { setUp(() { - controller = StreamController(); + applicationScreenBrightnessController = StreamController(); + }); + + tearDown(() { + applicationScreenBrightnessController.close(); + }); + + test('receive values', () async { + final queue = StreamQueue( + screenBrightness.onApplicationScreenBrightnessChanged); + + applicationScreenBrightnessController.add(0.2); + expect(await queue.next, 0.2); + + applicationScreenBrightnessController.add(systemBrightness); + expect(await queue.next, systemBrightness); + + applicationScreenBrightnessController.add(0); + expect(await queue.next, 0); + + applicationScreenBrightnessController.add(1); + expect(await queue.next, 1); + }); + }); + + group('on system screen brightness changed stream', () { + setUp(() { + systemScreenBrightnessController = StreamController(); }); tearDown(() { - controller.close(); + systemScreenBrightnessController.close(); }); test('receive values', () async { final queue = - StreamQueue(screenBrightness.onApplicationBrightnessChanged); + StreamQueue(screenBrightness.onSystemScreenBrightnessChanged); - controller.add(0.2); + systemScreenBrightnessController.add(0.2); expect(await queue.next, 0.2); - controller.add(systemBrightness); + systemScreenBrightnessController.add(systemBrightness); expect(await queue.next, systemBrightness); - controller.add(0); + systemScreenBrightnessController.add(0); expect(await queue.next, 0); - controller.add(1); + systemScreenBrightnessController.add(1); expect(await queue.next, 1); }); }); diff --git a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt index 811ec41..288f73a 100644 --- a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt +++ b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt @@ -3,12 +3,15 @@ package com.aaassseee.screen_brightness_android import android.app.Activity import android.content.Context import android.content.Intent +import android.database.ContentObserver import android.net.Uri import android.os.Build +import android.os.Handler +import android.os.Looper import android.os.PowerManager import android.provider.Settings import android.view.WindowManager -import com.aaassseee.screen_brightness_android.stream_handler.ApplicationScreenBrightnessChangeStreamHandler +import com.aaassseee.screen_brightness_android.stream_handler.ScreenBrightnessChangeStreamHandler import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.activity.ActivityAware import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding @@ -32,12 +35,29 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity */ private lateinit var methodChannel: MethodChannel + private lateinit var systemScreenBrightnessChangedEventChannel: EventChannel + + private var systemScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler? = null + private lateinit var applicationScreenBrightnessChangedEventChannel: EventChannel - private var applicationScreenBrightnessChangeStreamHandler: ApplicationScreenBrightnessChangeStreamHandler? = null + private var applicationScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler? = null private var activity: Activity? = null + private val contextObserver: ContentObserver = object : ContentObserver(Handler(Looper.getMainLooper())) { + override fun onChange(selfChange: Boolean) { + super.onChange(selfChange) + activity?.let { + systemScreenBrightness = getSystemBrightness(it) + systemScreenBrightnessChangeStreamHandler?.eventSink?.success(systemScreenBrightness) + if (applicationScreenBrightness == null) { + applicationScreenBrightnessChangeStreamHandler?.eventSink?.success(systemScreenBrightness) + } + } + } + } + /** * The value which will be init when this plugin is attached to the Flutter engine * @@ -69,15 +89,18 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { methodChannel = MethodChannel( - flutterPluginBinding.binaryMessenger, - "github.com/aaassseee/screen_brightness" + flutterPluginBinding.binaryMessenger, "github.com/aaassseee/screen_brightness" ) methodChannel.setMethodCallHandler(this) + systemScreenBrightnessChangedEventChannel = EventChannel( + flutterPluginBinding.binaryMessenger, "github.com/aaassseee/screen_brightness/system_brightness_changed" + ) + applicationScreenBrightnessChangedEventChannel = EventChannel( flutterPluginBinding.binaryMessenger, - "github.com/aaassseee/screen_brightness/application_brightness_change" + "github.com/aaassseee/screen_brightness/application_brightness_changed" ) try { @@ -90,17 +113,15 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity override fun onAttachedToActivity(binding: ActivityPluginBinding) { activity = binding.activity + binding.activity.contentResolver.registerContentObserver( + Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS), + false, + contextObserver, + ) + systemScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler(null) + systemScreenBrightnessChangedEventChannel.setStreamHandler(systemScreenBrightnessChangeStreamHandler) - applicationScreenBrightnessChangeStreamHandler = - ApplicationScreenBrightnessChangeStreamHandler( - binding.activity, - onListenStart = null, - onChange = { eventSink -> - systemScreenBrightness = getSystemBrightness(binding.activity) - if (applicationScreenBrightness == null) { - eventSink.success(systemScreenBrightness) - } - }) + applicationScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler(null) applicationScreenBrightnessChangedEventChannel.setStreamHandler(applicationScreenBrightnessChangeStreamHandler) } @@ -122,8 +143,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity private fun getSystemBrightness(context: Context): Float { return Settings.System.getInt( - context.contentResolver, - Settings.System.SCREEN_BRIGHTNESS + context.contentResolver, Settings.System.SCREEN_BRIGHTNESS ) / maximumScreenBrightness } @@ -131,8 +151,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!Settings.System.canWrite(context)) { Intent( - Settings.ACTION_MANAGE_WRITE_SETTINGS, - Uri.parse("package:${context.packageName}") + Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:${context.packageName}") ).let { it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(it) @@ -142,9 +161,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity } return Settings.System.putInt( - context.contentResolver, - Settings.System.SCREEN_BRIGHTNESS, - (maximumScreenBrightness * brightness).toInt() + context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, (maximumScreenBrightness * brightness).toInt() ) } @@ -153,8 +170,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity } private fun handleSetSystemBrightnessMethodCall( - call: MethodCall, - result: MethodChannel.Result + call: MethodCall, result: MethodChannel.Result ) { val activity = activity if (activity == null) { @@ -175,9 +191,13 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity } systemScreenBrightness = brightness + handleSystemScreenBrightnessChanged(brightness) result.success(null) } + private fun handleSystemScreenBrightnessChanged(brightness: Float) { + systemScreenBrightnessChangeStreamHandler?.addScreenBrightnessToEventSink(brightness.toDouble()) + } private fun handleGetApplicationScreenBrightnessMethodCall(result: MethodChannel.Result) { val activity = activity @@ -211,8 +231,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity private fun getScreenMaximumBrightness(context: Context): Float { try { val powerManager: PowerManager = - context.getSystemService(Context.POWER_SERVICE) as PowerManager? - ?: throw ClassNotFoundException() + context.getSystemService(Context.POWER_SERVICE) as PowerManager? ?: throw ClassNotFoundException() val fields: Array = powerManager.javaClass.declaredFields for (field in fields) { if (field.name.equals("BRIGHTNESS_ON")) { @@ -239,8 +258,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity } private fun handleSetApplicationScreenBrightnessMethodCall( - call: MethodCall, - result: MethodChannel.Result + call: MethodCall, result: MethodChannel.Result ) { val activity = activity if (activity == null) { @@ -261,7 +279,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity } applicationScreenBrightness = brightness - handleCurrentBrightnessChanged(brightness) + handleApplicationScreenBrightnessChanged(brightness) result.success(null) } @@ -272,20 +290,19 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity return } - val isSet = - setWindowsAttributesBrightness(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE) + val isSet = setWindowsAttributesBrightness(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE) if (!isSet) { result.error("-1", "Unable to change screen brightness", null) return } applicationScreenBrightness = null - handleCurrentBrightnessChanged(systemScreenBrightness) + handleApplicationScreenBrightnessChanged(systemScreenBrightness) result.success(null) } - private fun handleCurrentBrightnessChanged(currentBrightness: Float) { - applicationScreenBrightnessChangeStreamHandler?.addCurrentBrightnessToEventSink(currentBrightness.toDouble()) + private fun handleApplicationScreenBrightnessChanged(brightness: Float) { + applicationScreenBrightnessChangeStreamHandler?.addScreenBrightnessToEventSink(brightness.toDouble()) } private fun handleHasApplicationScreenBrightnessChangedMethodCall(result: MethodChannel.Result) { @@ -331,13 +348,18 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity } override fun onDetachedFromActivity() { + activity?.contentResolver?.unregisterContentObserver(contextObserver) activity = null + systemScreenBrightnessChangedEventChannel.setStreamHandler(null) + systemScreenBrightnessChangeStreamHandler = null applicationScreenBrightnessChangedEventChannel.setStreamHandler(null) applicationScreenBrightnessChangeStreamHandler = null } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { methodChannel.setMethodCallHandler(null) + systemScreenBrightnessChangedEventChannel.setStreamHandler(null) + systemScreenBrightnessChangeStreamHandler = null applicationScreenBrightnessChangedEventChannel.setStreamHandler(null) applicationScreenBrightnessChangeStreamHandler = null } diff --git a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ApplicationScreenBrightnessChangeStreamHandler.kt b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ApplicationScreenBrightnessChangeStreamHandler.kt deleted file mode 100644 index 0d9a176..0000000 --- a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ApplicationScreenBrightnessChangeStreamHandler.kt +++ /dev/null @@ -1,46 +0,0 @@ -package com.aaassseee.screen_brightness_android.stream_handler - -import android.content.Context -import android.database.ContentObserver -import android.os.Handler -import android.os.Looper -import android.provider.Settings -import io.flutter.plugin.common.EventChannel - -class ApplicationScreenBrightnessChangeStreamHandler( - private val context: Context, - val onListenStart: ((eventSink: EventChannel.EventSink) -> Unit)?, - val onChange: ((eventSink: EventChannel.EventSink) -> Unit) -) : BaseStreamHandler() { - private val contentObserver: ContentObserver = - object : ContentObserver(Handler(Looper.getMainLooper())) { - override fun onChange(selfChange: Boolean) { - super.onChange(selfChange) - val eventSink = eventSink ?: return - onChange.invoke( - eventSink - ) - } - } - - override fun onListen(arguments: Any?, events: EventChannel.EventSink?) { - super.onListen(arguments, events) - context.contentResolver.registerContentObserver( - Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS), - false, - contentObserver - ) - val eventSink = eventSink ?: return - onListenStart?.invoke(eventSink) - } - - override fun onCancel(arguments: Any?) { - super.onCancel(arguments) - context.contentResolver.unregisterContentObserver(contentObserver) - } - - fun addCurrentBrightnessToEventSink(brightness: Double) { - val eventSink = eventSink ?: return - eventSink.success(brightness) - } -} \ No newline at end of file diff --git a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ScreenBrightnessChangeStreamHandler.kt b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ScreenBrightnessChangeStreamHandler.kt new file mode 100644 index 0000000..08a0b78 --- /dev/null +++ b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ScreenBrightnessChangeStreamHandler.kt @@ -0,0 +1,18 @@ +package com.aaassseee.screen_brightness_android.stream_handler + +import io.flutter.plugin.common.EventChannel + +class ScreenBrightnessChangeStreamHandler( + private val onListenStart: ((eventSink: EventChannel.EventSink) -> Unit)?, +) : BaseStreamHandler() { + override fun onListen(arguments: Any?, events: EventChannel.EventSink?) { + super.onListen(arguments, events) + val eventSink = eventSink ?: return + onListenStart?.invoke(eventSink) + } + + fun addScreenBrightnessToEventSink(brightness: Double) { + val eventSink = eventSink ?: return + eventSink.success(brightness) + } +} \ No newline at end of file diff --git a/screen_brightness_android/example/lib/main.dart b/screen_brightness_android/example/lib/main.dart index ad2f90c..99efcfa 100644 --- a/screen_brightness_android/example/lib/main.dart +++ b/screen_brightness_android/example/lib/main.dart @@ -79,7 +79,7 @@ class HomePage extends StatelessWidget { return StreamBuilder( stream: ScreenBrightnessPlatform - .instance.onApplicationBrightnessChanged, + .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { @@ -171,18 +171,27 @@ class _ControllerPageState extends State { systemBrightness = snapshot.data!; } - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text('System brightness: $systemBrightness'), - Slider.adaptive( - value: systemBrightness, - onChanged: (value) { - setSystemBrightness(value); - }, - ), - ], - ); + return StreamBuilder( + stream: ScreenBrightnessPlatform + .instance.onSystemScreenBrightnessChanged, + builder: (context, snapshot) { + double changedSystemBrightness = systemBrightness; + if (snapshot.hasData) { + changedSystemBrightness = snapshot.data!; + } + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('System brightness: $changedSystemBrightness'), + Slider.adaptive( + value: changedSystemBrightness, + onChanged: (value) { + setSystemBrightness(value); + }, + ), + ], + ); + }); }, ), FutureBuilder( @@ -195,7 +204,7 @@ class _ControllerPageState extends State { return StreamBuilder( stream: ScreenBrightnessPlatform - .instance.onApplicationBrightnessChanged, + .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { diff --git a/screen_brightness_android/example/pubspec.lock b/screen_brightness_android/example/pubspec.lock index 77c5158..5a4bbad 100644 --- a/screen_brightness_android/example/pubspec.lock +++ b/screen_brightness_android/example/pubspec.lock @@ -71,26 +71,26 @@ packages: dependency: transitive description: name: leak_tracker - sha256: "78eb209deea09858f5269f5a5b02be4049535f568c07b275096836f01ea323fa" + sha256: "7f0df31977cb2c0b88585095d168e689669a2cc9b97c309665e3386f3e9d341a" url: "https://pub.dev" source: hosted - version: "10.0.0" + version: "10.0.4" leak_tracker_flutter_testing: dependency: transitive description: name: leak_tracker_flutter_testing - sha256: b46c5e37c19120a8a01918cfaf293547f47269f7cb4b0058f21531c2465d6ef0 + sha256: "06e98f569d004c1315b991ded39924b21af84cf14cc94791b8aea337d25b57f8" url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "3.0.3" leak_tracker_testing: dependency: transitive description: name: leak_tracker_testing - sha256: a597f72a664dbd293f3bfc51f9ba69816f84dcd403cdac7066cb3f6003f3ab47 + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "3.0.1" lints: dependency: transitive description: @@ -119,10 +119,10 @@ packages: dependency: transitive description: name: meta - sha256: d584fa6707a52763a52446f02cc621b077888fb63b93bbcb1143a7be5a0c0c04 + sha256: "7687075e408b093f36e6bbf6c91878cc0d4cd10f409506f7bc996f68220b9136" url: "https://pub.dev" source: hosted - version: "1.11.0" + version: "1.12.0" path: dependency: transitive description: @@ -202,10 +202,10 @@ packages: dependency: transitive description: name: test_api - sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + sha256: "9955ae474176f7ac8ee4e989dadfb411a58c30415bcfb648fa04b2b8a03afa7f" url: "https://pub.dev" source: hosted - version: "0.6.1" + version: "0.7.0" vector_math: dependency: transitive description: @@ -218,10 +218,10 @@ packages: dependency: transitive description: name: vm_service - sha256: b3d56ff4341b8f182b96aceb2fa20e3dcb336b9f867bc0eafc0de10f1048e957 + sha256: "3923c89304b715fb1eb6423f017651664a03bf5f4b29983627c4da791f74a4ec" url: "https://pub.dev" source: hosted - version: "13.0.0" + version: "14.2.1" sdks: - dart: ">=3.2.0-0 <4.0.0" - flutter: ">=3.0.0" + dart: ">=3.3.0 <4.0.0" + flutter: ">=3.18.0-18.0.pre.54" diff --git a/screen_brightness_android/pubspec.yaml b/screen_brightness_android/pubspec.yaml index ff5b3af..b7c28dd 100644 --- a/screen_brightness_android/pubspec.yaml +++ b/screen_brightness_android/pubspec.yaml @@ -17,7 +17,8 @@ environment: dependencies: flutter: sdk: flutter - screen_brightness_platform_interface: ">=1.0.0 <2.0.0" + screen_brightness_platform_interface: + path: ../screen_brightness_platform_interface/ dev_dependencies: flutter_test: diff --git a/screen_brightness_ios/example/lib/main.dart b/screen_brightness_ios/example/lib/main.dart index 56d5320..4bd05a8 100644 --- a/screen_brightness_ios/example/lib/main.dart +++ b/screen_brightness_ios/example/lib/main.dart @@ -69,50 +69,25 @@ class HomePage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - FutureBuilder( - future: ScreenBrightnessPlatform.instance.system, - builder: (context, snapshot) { - double systemScreenBrightness = 0; - if (snapshot.hasData) { - systemScreenBrightness = snapshot.data!; - } - - return StreamBuilder( - stream: ScreenBrightnessPlatform - .instance.onSystemScreenBrightnessChanged, - builder: (context, snapshot) { - double changedSystemScreenBrightness = - systemScreenBrightness; - if (snapshot.hasData) { - changedSystemScreenBrightness = snapshot.data!; - } - - return Text( - 'System screen brightness $changedSystemScreenBrightness'); - }, - ); - }, - ), FutureBuilder( future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { - double applicationScreenBrightness = 0; + double applicationBrightness = 0; if (snapshot.hasData) { - applicationScreenBrightness = snapshot.data!; + applicationBrightness = snapshot.data!; } return StreamBuilder( stream: ScreenBrightnessPlatform .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { - double changedApplicationScreenBrightness = - applicationScreenBrightness; + double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { - changedApplicationScreenBrightness = snapshot.data!; + changedApplicationBrightness = snapshot.data!; } return Text( - 'Application screen brightness $changedApplicationScreenBrightness'); + 'Application brightness $changedApplicationBrightness'); }, ); }, @@ -149,33 +124,33 @@ class ControllerPage extends StatefulWidget { } class _ControllerPageState extends State { - Future setSystemScreenBrightness(double brightness) async { + Future setSystemBrightness(double brightness) async { try { await ScreenBrightnessPlatform.instance .setSystemScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set system screen brightness'; + throw 'Failed to set system brightness'; } } - Future setApplicationScreenBrightness(double brightness) async { + Future setApplicationBrightness(double brightness) async { try { await ScreenBrightnessPlatform.instance .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set application screen brightness'; + throw 'Failed to set application brightness'; } } - Future resetApplicationScreenBrightness() async { + Future resetApplicationBrightness() async { try { await ScreenBrightnessPlatform.instance .resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); - throw 'Failed to reset application screen brightness'; + throw 'Failed to reset application brightness'; } } @@ -191,48 +166,40 @@ class _ControllerPageState extends State { FutureBuilder( future: ScreenBrightnessPlatform.instance.system, builder: (context, snapshot) { - double systemScreenBrightness = snapshot.data ?? 0; - - return StreamBuilder( - stream: ScreenBrightnessPlatform - .instance.onSystemScreenBrightnessChanged, - builder: (context, snapshot) { - double changedSystemScreenBrightness = - snapshot.data ?? systemScreenBrightness; + double systemBrightness = 0; + if (snapshot.hasData) { + systemBrightness = snapshot.data!; + } - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - 'System screen brightness: $changedSystemScreenBrightness'), - Slider.adaptive( - value: changedSystemScreenBrightness, - onChanged: (value) { - setSystemScreenBrightness(value); - }, - ), - ], - ); - }, + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('System brightness: $systemBrightness'), + Slider.adaptive( + value: systemBrightness, + onChanged: (value) { + setSystemBrightness(value); + }, + ), + ], ); }, ), FutureBuilder( future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { - double applicationScreenBrightness = 0; + double applicationBrightness = 0; if (snapshot.hasData) { - applicationScreenBrightness = snapshot.data!; + applicationBrightness = snapshot.data!; } return StreamBuilder( stream: ScreenBrightnessPlatform .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { - double changedApplicationScreenBrightness = - applicationScreenBrightness; + double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { - changedApplicationScreenBrightness = snapshot.data!; + changedApplicationBrightness = snapshot.data!; } return Column( @@ -243,20 +210,20 @@ class _ControllerPageState extends State { .instance.hasApplicationScreenBrightnessChanged, builder: (context, snapshot) { return Text( - 'Application screen brightness has changed via plugin: ${snapshot.data}'); + 'Application brightness has changed via plugin: ${snapshot.data}'); }, ), Text( - 'Application screen brightness: $changedApplicationScreenBrightness'), + 'Application brightness: $changedApplicationBrightness'), Slider.adaptive( - value: changedApplicationScreenBrightness, + value: changedApplicationBrightness, onChanged: (value) { - setApplicationScreenBrightness(value); + setApplicationBrightness(value); }, ), ElevatedButton( onPressed: () { - resetApplicationScreenBrightness(); + resetApplicationBrightness(); }, child: const Text('reset brightness'), ), diff --git a/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift b/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift index 50cc6e9..b9d7dca 100644 --- a/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift +++ b/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift @@ -3,12 +3,12 @@ import UIKit public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApplicationLifeCycleDelegate { var methodChannel: FlutterMethodChannel? - - var applicationScreenBrightnessChangedEventChannel: FlutterEventChannel? - let applicationScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler() - + var systemScreenBrightnessChangedEventChannel: FlutterEventChannel? let systemScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler() + + var applicationScreenBrightnessChangedEventChannel: FlutterEventChannel? + let applicationScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler() var systemScreenBrightness: CGFloat? var applicationScreenBrightness: CGFloat? @@ -26,12 +26,12 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp let instance = SwiftScreenBrightnessIosPlugin() instance.methodChannel = FlutterMethodChannel(name: "github.com/aaassseee/screen_brightness", binaryMessenger: registrar.messenger()) registrar.addMethodCallDelegate(instance, channel: instance.methodChannel!) - - instance.applicationScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_change", binaryMessenger: registrar.messenger()) - instance.applicationScreenBrightnessChangedEventChannel!.setStreamHandler(instance.applicationScreenBrightnessChangeStreamHandler) - + instance.systemScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/system_brightness_changed", binaryMessenger: registrar.messenger()) instance.systemScreenBrightnessChangedEventChannel!.setStreamHandler(instance.systemScreenBrightnessChangeStreamHandler) + + instance.applicationScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_changed", binaryMessenger: registrar.messenger()) + instance.applicationScreenBrightnessChangedEventChannel!.setStreamHandler(instance.applicationScreenBrightnessChangeStreamHandler) registrar.addApplicationDelegate(instance) } diff --git a/screen_brightness_macos/example/lib/main.dart b/screen_brightness_macos/example/lib/main.dart index 56d5320..4bd05a8 100644 --- a/screen_brightness_macos/example/lib/main.dart +++ b/screen_brightness_macos/example/lib/main.dart @@ -69,50 +69,25 @@ class HomePage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - FutureBuilder( - future: ScreenBrightnessPlatform.instance.system, - builder: (context, snapshot) { - double systemScreenBrightness = 0; - if (snapshot.hasData) { - systemScreenBrightness = snapshot.data!; - } - - return StreamBuilder( - stream: ScreenBrightnessPlatform - .instance.onSystemScreenBrightnessChanged, - builder: (context, snapshot) { - double changedSystemScreenBrightness = - systemScreenBrightness; - if (snapshot.hasData) { - changedSystemScreenBrightness = snapshot.data!; - } - - return Text( - 'System screen brightness $changedSystemScreenBrightness'); - }, - ); - }, - ), FutureBuilder( future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { - double applicationScreenBrightness = 0; + double applicationBrightness = 0; if (snapshot.hasData) { - applicationScreenBrightness = snapshot.data!; + applicationBrightness = snapshot.data!; } return StreamBuilder( stream: ScreenBrightnessPlatform .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { - double changedApplicationScreenBrightness = - applicationScreenBrightness; + double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { - changedApplicationScreenBrightness = snapshot.data!; + changedApplicationBrightness = snapshot.data!; } return Text( - 'Application screen brightness $changedApplicationScreenBrightness'); + 'Application brightness $changedApplicationBrightness'); }, ); }, @@ -149,33 +124,33 @@ class ControllerPage extends StatefulWidget { } class _ControllerPageState extends State { - Future setSystemScreenBrightness(double brightness) async { + Future setSystemBrightness(double brightness) async { try { await ScreenBrightnessPlatform.instance .setSystemScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set system screen brightness'; + throw 'Failed to set system brightness'; } } - Future setApplicationScreenBrightness(double brightness) async { + Future setApplicationBrightness(double brightness) async { try { await ScreenBrightnessPlatform.instance .setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); - throw 'Failed to set application screen brightness'; + throw 'Failed to set application brightness'; } } - Future resetApplicationScreenBrightness() async { + Future resetApplicationBrightness() async { try { await ScreenBrightnessPlatform.instance .resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); - throw 'Failed to reset application screen brightness'; + throw 'Failed to reset application brightness'; } } @@ -191,48 +166,40 @@ class _ControllerPageState extends State { FutureBuilder( future: ScreenBrightnessPlatform.instance.system, builder: (context, snapshot) { - double systemScreenBrightness = snapshot.data ?? 0; - - return StreamBuilder( - stream: ScreenBrightnessPlatform - .instance.onSystemScreenBrightnessChanged, - builder: (context, snapshot) { - double changedSystemScreenBrightness = - snapshot.data ?? systemScreenBrightness; + double systemBrightness = 0; + if (snapshot.hasData) { + systemBrightness = snapshot.data!; + } - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - 'System screen brightness: $changedSystemScreenBrightness'), - Slider.adaptive( - value: changedSystemScreenBrightness, - onChanged: (value) { - setSystemScreenBrightness(value); - }, - ), - ], - ); - }, + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('System brightness: $systemBrightness'), + Slider.adaptive( + value: systemBrightness, + onChanged: (value) { + setSystemBrightness(value); + }, + ), + ], ); }, ), FutureBuilder( future: ScreenBrightnessPlatform.instance.application, builder: (context, snapshot) { - double applicationScreenBrightness = 0; + double applicationBrightness = 0; if (snapshot.hasData) { - applicationScreenBrightness = snapshot.data!; + applicationBrightness = snapshot.data!; } return StreamBuilder( stream: ScreenBrightnessPlatform .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { - double changedApplicationScreenBrightness = - applicationScreenBrightness; + double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { - changedApplicationScreenBrightness = snapshot.data!; + changedApplicationBrightness = snapshot.data!; } return Column( @@ -243,20 +210,20 @@ class _ControllerPageState extends State { .instance.hasApplicationScreenBrightnessChanged, builder: (context, snapshot) { return Text( - 'Application screen brightness has changed via plugin: ${snapshot.data}'); + 'Application brightness has changed via plugin: ${snapshot.data}'); }, ), Text( - 'Application screen brightness: $changedApplicationScreenBrightness'), + 'Application brightness: $changedApplicationBrightness'), Slider.adaptive( - value: changedApplicationScreenBrightness, + value: changedApplicationBrightness, onChanged: (value) { - setApplicationScreenBrightness(value); + setApplicationBrightness(value); }, ), ElevatedButton( onPressed: () { - resetApplicationScreenBrightness(); + resetApplicationBrightness(); }, child: const Text('reset brightness'), ), diff --git a/screen_brightness_platform_interface/lib/constant/plugin_channel.dart b/screen_brightness_platform_interface/lib/constant/plugin_channel.dart index a6e97ba..8be65e2 100644 --- a/screen_brightness_platform_interface/lib/constant/plugin_channel.dart +++ b/screen_brightness_platform_interface/lib/constant/plugin_channel.dart @@ -4,7 +4,7 @@ const pluginMethodChannelName = 'github.com/aaassseee/screen_brightness'; const pluginMethodChannel = MethodChannel(pluginMethodChannelName); const pluginEventChannelApplicationBrightnessChangedName = - 'github.com/aaassseee/screen_brightness/application_brightness_change'; + 'github.com/aaassseee/screen_brightness/application_brightness_changed'; const pluginEventChannelApplicationBrightnessChanged = EventChannel(pluginEventChannelApplicationBrightnessChangedName); diff --git a/screen_brightness_windows/example/lib/main.dart b/screen_brightness_windows/example/lib/main.dart index ad2f90c..4bd05a8 100644 --- a/screen_brightness_windows/example/lib/main.dart +++ b/screen_brightness_windows/example/lib/main.dart @@ -79,7 +79,7 @@ class HomePage extends StatelessWidget { return StreamBuilder( stream: ScreenBrightnessPlatform - .instance.onApplicationBrightnessChanged, + .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { @@ -195,7 +195,7 @@ class _ControllerPageState extends State { return StreamBuilder( stream: ScreenBrightnessPlatform - .instance.onApplicationBrightnessChanged, + .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { diff --git a/screen_brightness_windows/example/pubspec.lock b/screen_brightness_windows/example/pubspec.lock index 1af82f9..3b32f9c 100644 --- a/screen_brightness_windows/example/pubspec.lock +++ b/screen_brightness_windows/example/pubspec.lock @@ -71,26 +71,26 @@ packages: dependency: transitive description: name: leak_tracker - sha256: "78eb209deea09858f5269f5a5b02be4049535f568c07b275096836f01ea323fa" + sha256: "7f0df31977cb2c0b88585095d168e689669a2cc9b97c309665e3386f3e9d341a" url: "https://pub.dev" source: hosted - version: "10.0.0" + version: "10.0.4" leak_tracker_flutter_testing: dependency: transitive description: name: leak_tracker_flutter_testing - sha256: b46c5e37c19120a8a01918cfaf293547f47269f7cb4b0058f21531c2465d6ef0 + sha256: "06e98f569d004c1315b991ded39924b21af84cf14cc94791b8aea337d25b57f8" url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "3.0.3" leak_tracker_testing: dependency: transitive description: name: leak_tracker_testing - sha256: a597f72a664dbd293f3bfc51f9ba69816f84dcd403cdac7066cb3f6003f3ab47 + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "3.0.1" lints: dependency: transitive description: @@ -119,10 +119,10 @@ packages: dependency: transitive description: name: meta - sha256: d584fa6707a52763a52446f02cc621b077888fb63b93bbcb1143a7be5a0c0c04 + sha256: "7687075e408b093f36e6bbf6c91878cc0d4cd10f409506f7bc996f68220b9136" url: "https://pub.dev" source: hosted - version: "1.11.0" + version: "1.12.0" path: dependency: transitive description: @@ -202,10 +202,10 @@ packages: dependency: transitive description: name: test_api - sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + sha256: "9955ae474176f7ac8ee4e989dadfb411a58c30415bcfb648fa04b2b8a03afa7f" url: "https://pub.dev" source: hosted - version: "0.6.1" + version: "0.7.0" vector_math: dependency: transitive description: @@ -218,10 +218,10 @@ packages: dependency: transitive description: name: vm_service - sha256: b3d56ff4341b8f182b96aceb2fa20e3dcb336b9f867bc0eafc0de10f1048e957 + sha256: "3923c89304b715fb1eb6423f017651664a03bf5f4b29983627c4da791f74a4ec" url: "https://pub.dev" source: hosted - version: "13.0.0" + version: "14.2.1" sdks: - dart: ">=3.2.0-0 <4.0.0" - flutter: ">=3.0.0" + dart: ">=3.3.0 <4.0.0" + flutter: ">=3.18.0-18.0.pre.54" diff --git a/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp b/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp index a1ab0b8..14884ae 100644 --- a/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp +++ b/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp @@ -145,7 +145,7 @@ namespace screen_brightness { DWORD physical_monitor_array_size = 0; HMONITOR monitor_handler = MonitorFromWindow(window_handler_, MONITOR_DEFAULTTOPRIMARY); - DWORD minimum_screen_brightness_ = 0, screen_brightness_ = 0, maximum_screen_brightness_ = 0; + DWORD minimum_brightness_ = 0, brightness_ = 0, maximum_brightness_ = 0; if (!GetNumberOfPhysicalMonitorsFromHMONITOR(monitor_handler, &physical_monitor_array_size)) { @@ -164,14 +164,14 @@ namespace screen_brightness throw std::exception("Problem getting physical monitors"); } - if (!GetMonitorBrightness(physical_monitor->hPhysicalMonitor, &minimum_screen_brightness_, &screen_brightness_, &maximum_screen_brightness_)) + if (!GetMonitorBrightness(physical_monitor->hPhysicalMonitor, &minimum_brightness_, &brightness_, &maximum_brightness_)) { throw std::exception("Problem getting monitor brightness"); } - minimum_screen_brightness = minimum_screen_brightness_; - screen_brightness = screen_brightness_; - maximum_screen_brightness = maximum_screen_brightness_; + minimum_screen_brightness = minimum_brightness_; + screen_brightness = brightness_; + maximum_screen_brightness = maximum_brightness_; DestroyPhysicalMonitors(physical_monitor_array_size, physical_monitor); @@ -249,9 +249,13 @@ namespace screen_brightness const long changed_brightness = GetScreenBrightnessValueByPercentage(brightness); try { - SetScreenBrightness(changed_brightness); - changed_screen_brightness_ = changed_brightness; - HandleCurrentBrightnessChanged(changed_brightness); + if (changed_screen_brightness_ == -1) + { + SetScreenBrightness(changed_brightness); + HandleCurrentBrightnessChanged(changed_brightness); + } + system_screen_brightness_ = changed_brightness; + result->Success(nullptr); } catch (const std::exception& exception) From 74f57cb564a057835ac92c185b02ab1b419f5eec Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Thu, 8 Aug 2024 23:48:39 +0800 Subject: [PATCH 10/22] style: sync macOS Android iOS code style --- .../ScreenBrightnessAndroidPlugin.kt | 174 +++++++-------- ...> ScreenBrightnessChangedStreamHandler.kt} | 2 +- ...creenBrightnessChangedStreamHandler.swift} | 2 +- .../SwiftScreenBrightnessIosPlugin.swift | 160 +++++++------- .../Classes/ScreenBrightnessMacosPlugin.swift | 206 +++++++++--------- ...creenBrightnessChangedStreamHandler.swift} | 2 +- 6 files changed, 274 insertions(+), 272 deletions(-) rename screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/{ScreenBrightnessChangeStreamHandler.kt => ScreenBrightnessChangedStreamHandler.kt} (92%) rename screen_brightness_ios/ios/Classes/StreamHandler/{ScreenBrightnessChangeStreamHandler.swift => ScreenBrightnessChangedStreamHandler.swift} (84%) rename screen_brightness_macos/macos/Classes/StreamHandler/{ScreenBrightnessChangeStreamHandler.swift => ScreenBrightnessChangedStreamHandler.swift} (83%) diff --git a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt index 288f73a..4ee0253 100644 --- a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt +++ b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt @@ -11,7 +11,7 @@ import android.os.Looper import android.os.PowerManager import android.provider.Settings import android.view.WindowManager -import com.aaassseee.screen_brightness_android.stream_handler.ScreenBrightnessChangeStreamHandler +import com.aaassseee.screen_brightness_android.stream_handler.ScreenBrightnessChangedStreamHandler import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.activity.ActivityAware import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding @@ -35,36 +35,29 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity */ private lateinit var methodChannel: MethodChannel + private var activity: Activity? = null + private lateinit var systemScreenBrightnessChangedEventChannel: EventChannel - private var systemScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler? = null + private var systemScreenBrightnessChangedStreamHandler: ScreenBrightnessChangedStreamHandler? = null private lateinit var applicationScreenBrightnessChangedEventChannel: EventChannel - private var applicationScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler? = null - - private var activity: Activity? = null + private var applicationScreenBrightnessChangedStreamHandler: ScreenBrightnessChangedStreamHandler? = null private val contextObserver: ContentObserver = object : ContentObserver(Handler(Looper.getMainLooper())) { override fun onChange(selfChange: Boolean) { super.onChange(selfChange) activity?.let { - systemScreenBrightness = getSystemBrightness(it) - systemScreenBrightnessChangeStreamHandler?.eventSink?.success(systemScreenBrightness) + systemScreenBrightness = getSystemScreenBrightness(it) + systemScreenBrightnessChangedStreamHandler?.eventSink?.success(systemScreenBrightness) if (applicationScreenBrightness == null) { - applicationScreenBrightnessChangeStreamHandler?.eventSink?.success(systemScreenBrightness) + applicationScreenBrightnessChangedStreamHandler?.eventSink?.success(systemScreenBrightness) } } } } - /** - * The value which will be init when this plugin is attached to the Flutter engine - * - * This value refer to the brightness value between 0 and 1 when the application initialized. - */ - private var systemScreenBrightness by Delegates.notNull() - /** * The value which will be init when this plugin is attached to the Flutter engine * @@ -75,6 +68,13 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity */ private var maximumScreenBrightness by Delegates.notNull() + /** + * The value which will be init when this plugin is attached to the Flutter engine + * + * This value refer to the brightness value between 0 and 1 when the application initialized. + */ + private var systemScreenBrightness by Delegates.notNull() + /** * The value which will be set when user called [handleSetApplicationScreenBrightnessMethodCall] * or [handleResetApplicationScreenBrightnessMethodCall] @@ -105,7 +105,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity try { maximumScreenBrightness = getScreenMaximumBrightness(flutterPluginBinding.applicationContext) - systemScreenBrightness = getSystemBrightness(flutterPluginBinding.applicationContext) + systemScreenBrightness = getSystemScreenBrightness(flutterPluginBinding.applicationContext) } catch (e: Settings.SettingNotFoundException) { e.printStackTrace() } @@ -118,17 +118,17 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity false, contextObserver, ) - systemScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler(null) - systemScreenBrightnessChangedEventChannel.setStreamHandler(systemScreenBrightnessChangeStreamHandler) + systemScreenBrightnessChangedStreamHandler = ScreenBrightnessChangedStreamHandler(null) + systemScreenBrightnessChangedEventChannel.setStreamHandler(systemScreenBrightnessChangedStreamHandler) - applicationScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler(null) - applicationScreenBrightnessChangedEventChannel.setStreamHandler(applicationScreenBrightnessChangeStreamHandler) + applicationScreenBrightnessChangedStreamHandler = ScreenBrightnessChangedStreamHandler(null) + applicationScreenBrightnessChangedEventChannel.setStreamHandler(applicationScreenBrightnessChangedStreamHandler) } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { when (call.method) { - "getSystemScreenBrightness" -> handleGetSystemBrightnessMethodCall(result) - "setSystemScreenBrightness" -> handleSetSystemBrightnessMethodCall(call, result) + "getSystemScreenBrightness" -> handleGetSystemScreenBrightnessMethodCall(result) + "setSystemScreenBrightness" -> handleSetSystemScreenBrightnessMethodCall(call, result) "getApplicationScreenBrightness" -> handleGetApplicationScreenBrightnessMethodCall(result) "setApplicationScreenBrightness" -> handleSetApplicationScreenBrightnessMethodCall(call, result) "resetApplicationScreenBrightness" -> handleResetApplicationScreenBrightnessMethodCall(result) @@ -141,35 +141,11 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity } } - private fun getSystemBrightness(context: Context): Float { - return Settings.System.getInt( - context.contentResolver, Settings.System.SCREEN_BRIGHTNESS - ) / maximumScreenBrightness - } - - private fun setSystemBrightness(context: Context, brightness: Float): Boolean { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - if (!Settings.System.canWrite(context)) { - Intent( - Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:${context.packageName}") - ).let { - it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - context.startActivity(it) - } - return false - } - } - - return Settings.System.putInt( - context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, (maximumScreenBrightness * brightness).toInt() - ) - } - - private fun handleGetSystemBrightnessMethodCall(result: MethodChannel.Result) { + private fun handleGetSystemScreenBrightnessMethodCall(result: MethodChannel.Result) { result.success(systemScreenBrightness) } - private fun handleSetSystemBrightnessMethodCall( + private fun handleSetSystemScreenBrightnessMethodCall( call: MethodCall, result: MethodChannel.Result ) { val activity = activity @@ -184,9 +160,9 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity return } - val isSet = setSystemBrightness(activity.applicationContext, brightness) + val isSet = setSystemScreenBrightness(activity.applicationContext, brightness) if (!isSet) { - result.error("-1", "Unable to change system brightness", null) + result.error("-1", "Unable to change system screen brightness", null) return } @@ -196,7 +172,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity } private fun handleSystemScreenBrightnessChanged(brightness: Float) { - systemScreenBrightnessChangeStreamHandler?.addScreenBrightnessToEventSink(brightness.toDouble()) + systemScreenBrightnessChangedStreamHandler?.addScreenBrightnessToEventSink(brightness.toDouble()) } private fun handleGetApplicationScreenBrightnessMethodCall(result: MethodChannel.Result) { @@ -219,7 +195,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity // get system setting brightness try { - brightness = getSystemBrightness(activity) + brightness = getSystemScreenBrightness(activity) result.success(brightness) } catch (e: Settings.SettingNotFoundException) { e.printStackTrace() @@ -228,35 +204,6 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity } } - private fun getScreenMaximumBrightness(context: Context): Float { - try { - val powerManager: PowerManager = - context.getSystemService(Context.POWER_SERVICE) as PowerManager? ?: throw ClassNotFoundException() - val fields: Array = powerManager.javaClass.declaredFields - for (field in fields) { - if (field.name.equals("BRIGHTNESS_ON")) { - field.isAccessible = true - return (field[powerManager] as Int).toFloat() - } - } - - return 255.0f - } catch (e: Exception) { - return 255.0f - } - } - - private fun setWindowsAttributesBrightness(brightness: Float): Boolean { - return try { - val layoutParams: WindowManager.LayoutParams = activity!!.window.attributes - layoutParams.screenBrightness = brightness - activity!!.window.attributes = layoutParams - true - } catch (e: Exception) { - false - } - } - private fun handleSetApplicationScreenBrightnessMethodCall( call: MethodCall, result: MethodChannel.Result ) { @@ -274,7 +221,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity val isSet = setWindowsAttributesBrightness(brightness) if (!isSet) { - result.error("-1", "Unable to change screen brightness", null) + result.error("-1", "Unable to change application screen brightness", null) return } @@ -302,7 +249,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity } private fun handleApplicationScreenBrightnessChanged(brightness: Float) { - applicationScreenBrightnessChangeStreamHandler?.addScreenBrightnessToEventSink(brightness.toDouble()) + applicationScreenBrightnessChangedStreamHandler?.addScreenBrightnessToEventSink(brightness.toDouble()) } private fun handleHasApplicationScreenBrightnessChangedMethodCall(result: MethodChannel.Result) { @@ -351,16 +298,69 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity activity?.contentResolver?.unregisterContentObserver(contextObserver) activity = null systemScreenBrightnessChangedEventChannel.setStreamHandler(null) - systemScreenBrightnessChangeStreamHandler = null + systemScreenBrightnessChangedStreamHandler = null applicationScreenBrightnessChangedEventChannel.setStreamHandler(null) - applicationScreenBrightnessChangeStreamHandler = null + applicationScreenBrightnessChangedStreamHandler = null } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { methodChannel.setMethodCallHandler(null) systemScreenBrightnessChangedEventChannel.setStreamHandler(null) - systemScreenBrightnessChangeStreamHandler = null + systemScreenBrightnessChangedStreamHandler = null applicationScreenBrightnessChangedEventChannel.setStreamHandler(null) - applicationScreenBrightnessChangeStreamHandler = null + applicationScreenBrightnessChangedStreamHandler = null + } + + private fun getSystemScreenBrightness(context: Context): Float { + return Settings.System.getInt( + context.contentResolver, Settings.System.SCREEN_BRIGHTNESS + ) / maximumScreenBrightness + } + + private fun setSystemScreenBrightness(context: Context, brightness: Float): Boolean { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (!Settings.System.canWrite(context)) { + Intent( + Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:${context.packageName}") + ).let { + it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(it) + } + return false + } + } + + return Settings.System.putInt( + context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, (maximumScreenBrightness * brightness).toInt() + ) + } + + private fun getScreenMaximumBrightness(context: Context): Float { + try { + val powerManager: PowerManager = + context.getSystemService(Context.POWER_SERVICE) as PowerManager? ?: throw ClassNotFoundException() + val fields: Array = powerManager.javaClass.declaredFields + for (field in fields) { + if (field.name.equals("BRIGHTNESS_ON")) { + field.isAccessible = true + return (field[powerManager] as Int).toFloat() + } + } + + return 255.0f + } catch (e: Exception) { + return 255.0f + } + } + + private fun setWindowsAttributesBrightness(brightness: Float): Boolean { + return try { + val layoutParams: WindowManager.LayoutParams = activity!!.window.attributes + layoutParams.screenBrightness = brightness + activity!!.window.attributes = layoutParams + true + } catch (e: Exception) { + false + } } } diff --git a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ScreenBrightnessChangeStreamHandler.kt b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ScreenBrightnessChangedStreamHandler.kt similarity index 92% rename from screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ScreenBrightnessChangeStreamHandler.kt rename to screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ScreenBrightnessChangedStreamHandler.kt index 08a0b78..ebc6577 100644 --- a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ScreenBrightnessChangeStreamHandler.kt +++ b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/stream_handler/ScreenBrightnessChangedStreamHandler.kt @@ -2,7 +2,7 @@ package com.aaassseee.screen_brightness_android.stream_handler import io.flutter.plugin.common.EventChannel -class ScreenBrightnessChangeStreamHandler( +class ScreenBrightnessChangedStreamHandler( private val onListenStart: ((eventSink: EventChannel.EventSink) -> Unit)?, ) : BaseStreamHandler() { override fun onListen(arguments: Any?, events: EventChannel.EventSink?) { diff --git a/screen_brightness_ios/ios/Classes/StreamHandler/ScreenBrightnessChangeStreamHandler.swift b/screen_brightness_ios/ios/Classes/StreamHandler/ScreenBrightnessChangedStreamHandler.swift similarity index 84% rename from screen_brightness_ios/ios/Classes/StreamHandler/ScreenBrightnessChangeStreamHandler.swift rename to screen_brightness_ios/ios/Classes/StreamHandler/ScreenBrightnessChangedStreamHandler.swift index 543aed2..58c05e8 100644 --- a/screen_brightness_ios/ios/Classes/StreamHandler/ScreenBrightnessChangeStreamHandler.swift +++ b/screen_brightness_ios/ios/Classes/StreamHandler/ScreenBrightnessChangedStreamHandler.swift @@ -9,7 +9,7 @@ import Foundation import Flutter import UIKit -public class ScreenBrightnessChangeStreamHandler: BaseStreamHandler { +public class ScreenBrightnessChangedStreamHandler: BaseStreamHandler { public func addScreenBrightnessToEventSink(_ screenBrightness: CGFloat) { guard let eventSink = eventSink else { return diff --git a/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift b/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift index b9d7dca..5293b99 100644 --- a/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift +++ b/screen_brightness_ios/ios/Classes/SwiftScreenBrightnessIosPlugin.swift @@ -5,10 +5,10 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp var methodChannel: FlutterMethodChannel? var systemScreenBrightnessChangedEventChannel: FlutterEventChannel? - let systemScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler() + let systemScreenBrightnessChangedStreamHandler: ScreenBrightnessChangedStreamHandler = ScreenBrightnessChangedStreamHandler() var applicationScreenBrightnessChangedEventChannel: FlutterEventChannel? - let applicationScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler() + let applicationScreenBrightnessChangedStreamHandler: ScreenBrightnessChangedStreamHandler = ScreenBrightnessChangedStreamHandler() var systemScreenBrightness: CGFloat? var applicationScreenBrightness: CGFloat? @@ -28,10 +28,10 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp registrar.addMethodCallDelegate(instance, channel: instance.methodChannel!) instance.systemScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/system_brightness_changed", binaryMessenger: registrar.messenger()) - instance.systemScreenBrightnessChangedEventChannel!.setStreamHandler(instance.systemScreenBrightnessChangeStreamHandler) + instance.systemScreenBrightnessChangedEventChannel!.setStreamHandler(instance.systemScreenBrightnessChangedStreamHandler) instance.applicationScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_changed", binaryMessenger: registrar.messenger()) - instance.applicationScreenBrightnessChangedEventChannel!.setStreamHandler(instance.applicationScreenBrightnessChangeStreamHandler) + instance.applicationScreenBrightnessChangedEventChannel!.setStreamHandler(instance.applicationScreenBrightnessChangedStreamHandler) registrar.addApplicationDelegate(instance) } @@ -85,38 +85,6 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp } } - public func setScreenBrightness(targetBrightness: CGFloat, animated: Bool, duration: TimeInterval = 1.0) { - taskQueue.cancelAllOperations() - if !animated { - UIScreen.main.brightness = targetBrightness - return - } - - let currentBrightness = UIScreen.main.brightness - var framePerSecond = 60.0 - if #available(iOS 10.3, *) { - framePerSecond = Double(UIScreen.main.maximumFramesPerSecond) - } - let changes = 0.01 / (framePerSecond / 60.0) - let step = changes * ((targetBrightness > currentBrightness) ? 1 : -1) - - taskQueue.addOperations(stride(from: currentBrightness, through: targetBrightness, by: step).map({ _brightness -> Operation in - let blockOperation = BlockOperation() - unowned let _unownedOperation = blockOperation - blockOperation.addExecutionBlock({ - guard !_unownedOperation.isCancelled else { - return - } - - Thread.sleep(forTimeInterval: duration * changes) - OperationQueue.main.addOperation({ - UIScreen.main.brightness = _brightness - }) - }) - return blockOperation - }), waitUntilFinished: false) - } - private func handleGetSystemScreenBrightnessMethodCall(result: FlutterResult) { guard let systemScreenBrightness = systemScreenBrightness else { result(FlutterError.init(code: "-11", message: "Could not found system screen brightness value", details: nil)) @@ -132,18 +100,18 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp return } - let _systemScreenBrightness = CGFloat(brightness.doubleValue) - systemScreenBrightness = _systemScreenBrightness - handleSystemScreenBrightnessChanged(_systemScreenBrightness) + let _brightness = CGFloat(brightness.doubleValue) + systemScreenBrightness = _brightness + handleSystemScreenBrightnessChanged(_brightness) if (applicationScreenBrightness == nil) { - setScreenBrightness(targetBrightness: _systemScreenBrightness, animated: isAnimate) - handleApplicationScreenBrightnessChanged(_systemScreenBrightness) + setScreenBrightness(targetBrightness: _brightness, animated: isAnimate) + handleApplicationScreenBrightnessChanged(_brightness) } result(nil) } - private func handleSystemScreenBrightnessChanged(_ systemScreenBrightness: CGFloat) { - systemScreenBrightnessChangeStreamHandler.addScreenBrightnessToEventSink(systemScreenBrightness) + private func handleSystemScreenBrightnessChanged(_ brightness: CGFloat) { + systemScreenBrightnessChangedStreamHandler.addScreenBrightnessToEventSink(brightness) } private func handleGetApplicationScreenBrightnessMethodCall(result: FlutterResult) { @@ -156,29 +124,29 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp return } - let _applicationScreenBrightness = CGFloat(brightness.doubleValue) - setScreenBrightness(targetBrightness: _applicationScreenBrightness, animated: isAnimate) + let _brightness = CGFloat(brightness.doubleValue) + setScreenBrightness(targetBrightness: _brightness, animated: isAnimate) - applicationScreenBrightness = _applicationScreenBrightness - handleApplicationScreenBrightnessChanged(_applicationScreenBrightness) + applicationScreenBrightness = _brightness + handleApplicationScreenBrightnessChanged(_brightness) result(nil) } private func handleResetApplicationScreenBrightnessMethodCall(result: FlutterResult) { - guard let systemScreenBrightness = systemScreenBrightness else { + guard let brightness = systemScreenBrightness else { result(FlutterError.init(code: "-2", message: "Unexpected error on null brightness", details: nil)) return } - setScreenBrightness(targetBrightness: systemScreenBrightness, animated: isAnimate) + setScreenBrightness(targetBrightness: brightness, animated: isAnimate) applicationScreenBrightness = nil - handleApplicationScreenBrightnessChanged(systemScreenBrightness) + handleApplicationScreenBrightnessChanged(brightness) result(nil) } - private func handleApplicationScreenBrightnessChanged(_ applicationScreenBrightness: CGFloat) { - applicationScreenBrightnessChangeStreamHandler.addScreenBrightnessToEventSink(applicationScreenBrightness) + private func handleApplicationScreenBrightnessChanged(_ brightness: CGFloat) { + applicationScreenBrightnessChangedStreamHandler.addScreenBrightnessToEventSink(brightness) } private func handleHasApplicationScreenBrightnessChangedMethodCall(result: FlutterResult) { @@ -212,34 +180,6 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp self.isAnimate = isAnimate result(nil) } - - @objc private func onSystemScreenBrightnessChanged(notification: Notification) { - guard let screenObject = notification.object, let brightness = (screenObject as AnyObject).brightness else { - return - } - - systemScreenBrightness = brightness - handleSystemScreenBrightnessChanged(brightness) - if (applicationScreenBrightness == nil) { - handleApplicationScreenBrightnessChanged(brightness) - } - } - - func onApplicationPause() { - guard let systemScreenBrightness = systemScreenBrightness else { - return - } - - setScreenBrightness(targetBrightness: systemScreenBrightness, animated: isAnimate, duration: 0.5) - } - - func onApplicationResume() { - guard let applicationScreenBrightness = applicationScreenBrightness else { - return - } - - setScreenBrightness(targetBrightness: applicationScreenBrightness, animated: isAnimate, duration: 0.5) - } public func applicationWillResignActive(_ application: UIApplication) { guard isAutoReset else { @@ -277,4 +217,64 @@ public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApp applicationScreenBrightnessChangedEventChannel?.setStreamHandler(nil) systemScreenBrightnessChangedEventChannel?.setStreamHandler(nil) } + + public func setScreenBrightness(targetBrightness: CGFloat, animated: Bool, duration: TimeInterval = 1.0) { + taskQueue.cancelAllOperations() + if !animated { + UIScreen.main.brightness = targetBrightness + return + } + + let currentBrightness = UIScreen.main.brightness + var framePerSecond = 60.0 + if #available(iOS 10.3, *) { + framePerSecond = Double(UIScreen.main.maximumFramesPerSecond) + } + let changes = 0.01 / (framePerSecond / 60.0) + let step = changes * ((targetBrightness > currentBrightness) ? 1 : -1) + + taskQueue.addOperations(stride(from: currentBrightness, through: targetBrightness, by: step).map({ _brightness -> Operation in + let blockOperation = BlockOperation() + unowned let _unownedOperation = blockOperation + blockOperation.addExecutionBlock({ + guard !_unownedOperation.isCancelled else { + return + } + + Thread.sleep(forTimeInterval: duration * changes) + OperationQueue.main.addOperation({ + UIScreen.main.brightness = _brightness + }) + }) + return blockOperation + }), waitUntilFinished: false) + } + + @objc private func onSystemScreenBrightnessChanged(notification: Notification) { + guard let screenObject = notification.object, let brightness = (screenObject as AnyObject).brightness else { + return + } + + systemScreenBrightness = brightness + handleSystemScreenBrightnessChanged(brightness) + if (applicationScreenBrightness == nil) { + handleApplicationScreenBrightnessChanged(brightness) + } + } + + func onApplicationPause() { + guard let systemScreenBrightness = systemScreenBrightness else { + return + } + + setScreenBrightness(targetBrightness: systemScreenBrightness, animated: isAnimate, duration: 0.5) + } + + func onApplicationResume() { + guard let applicationScreenBrightness = applicationScreenBrightness else { + return + } + + setScreenBrightness(targetBrightness: applicationScreenBrightness, animated: isAnimate, duration: 0.5) + } } diff --git a/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift b/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift index 07110e3..317ed6c 100644 --- a/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift +++ b/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift @@ -8,11 +8,11 @@ enum ScreenBrightnessError: Error { public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { var methodChannel: FlutterMethodChannel? - var applicationScreenBrightnessChangeEventChannel: FlutterEventChannel? - let applicationScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler() + var systemScreenBrightnessChangedEventChannel: FlutterEventChannel? + let systemScreenBrightnessChangedStreamHandler: ScreenBrightnessChangedStreamHandler = ScreenBrightnessChangedStreamHandler() - var systemScreenBrightnessChangeEventChannel: FlutterEventChannel? - let systemScreenBrightnessChangeStreamHandler: ScreenBrightnessChangeStreamHandler = ScreenBrightnessChangeStreamHandler() + var applicationScreenBrightnessChangedEventChannel: FlutterEventChannel? + let applicationScreenBrightnessChangedStreamHandler: ScreenBrightnessChangedStreamHandler = ScreenBrightnessChangedStreamHandler() var systemScreenBrightness: Float? var applicationScreenBrightness: Float? @@ -27,11 +27,11 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { instance.methodChannel = FlutterMethodChannel(name: "github.com/aaassseee/screen_brightness", binaryMessenger: registrar.messenger) registrar.addMethodCallDelegate(instance, channel: instance.methodChannel!) - instance.applicationScreenBrightnessChangeEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_change", binaryMessenger: registrar.messenger) - instance.applicationScreenBrightnessChangeEventChannel!.setStreamHandler(instance.applicationScreenBrightnessChangeStreamHandler) + instance.applicationScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_change", binaryMessenger: registrar.messenger) + instance.applicationScreenBrightnessChangedEventChannel!.setStreamHandler(instance.applicationScreenBrightnessChangedStreamHandler) - instance.systemScreenBrightnessChangeEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/system_brightness_change", binaryMessenger: registrar.messenger) - instance.systemScreenBrightnessChangeEventChannel!.setStreamHandler(instance.systemScreenBrightnessChangeStreamHandler) + instance.systemScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/system_brightness_change", binaryMessenger: registrar.messenger) + instance.systemScreenBrightnessChangedEventChannel!.setStreamHandler(instance.systemScreenBrightnessChangedStreamHandler) } override init() { @@ -48,7 +48,7 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "getSystemScreenBrightness": - handleGetSystemBrightnessMethodCall(result: result) + handleGetSystemScreenBrightnessMethodCall(result: result) break; case "setSystemScreenBrightness": @@ -82,57 +82,14 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { case "setAnimate": handleSetAnimateMethodCall(call: call, result: result) - + default: result(FlutterMethodNotImplemented) break; } } - @discardableResult private func getIODisplayConnectServices(iterator: inout io_iterator_t) throws -> kern_return_t { - var port: mach_port_t = kIOMasterPortDefault - if #available(macOS 12.0, *) { - port = kIOMainPortDefault - } - - let result = IOServiceGetMatchingServices(port, IOServiceMatching("IODisplayConnect"), &iterator) - - guard result == kIOReturnSuccess else { - throw ScreenBrightnessError.serviceMissing - } - - return result - } - - private func getScreenBrightness() throws -> Float { - var brightness: Float = 0.0 - - var service: io_object_t = 1 - var iterator: io_iterator_t = 0 - try getIODisplayConnectServices(iterator: &iterator) - - while service != 0 { - service = IOIteratorNext(iterator) - IODisplayGetFloatParameter(service, 0, kIODisplayBrightnessKey as CFString, &brightness) - IOObjectRelease(service) - } - - return brightness - } - - private func setScreenBrightness(targetBrightness: Float) throws { - var service: io_object_t = 1 - var iterator: io_iterator_t = 0 - try getIODisplayConnectServices(iterator: &iterator) - - while service != 0 { - service = IOIteratorNext(iterator) - IODisplaySetFloatParameter(service, 0, kIODisplayBrightnessKey as CFString, targetBrightness) - IOObjectRelease(service) - } - } - - private func handleGetSystemBrightnessMethodCall(result: FlutterResult) { + private func handleGetSystemScreenBrightnessMethodCall(result: FlutterResult) { guard let systemScreenBrightness = systemScreenBrightness else { result(FlutterError.init(code: "-11", message: "Could not found system screen brightness value", details: nil)) return @@ -147,28 +104,28 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { return } - let _systemScreenBrightness = Float(brightness.doubleValue) + let _brightness = Float(brightness.doubleValue) do { if (applicationScreenBrightness == nil) { - try setScreenBrightness(targetBrightness: _systemScreenBrightness) - handleApplicationScreenBrightnessChanged(_systemScreenBrightness) + try setScreenBrightness(targetBrightness: _brightness) + handleApplicationScreenBrightnessChanged(_brightness) } - systemScreenBrightness = _systemScreenBrightness - handleSystemScreenBrightnessChanged(_systemScreenBrightness) + systemScreenBrightness = _brightness + handleSystemScreenBrightnessChanged(_brightness) result(nil) } catch { result(FlutterError.init(code: "-1", message: "Unable to change system screen brightness", details: nil)) } } - private func handleSystemScreenBrightnessChanged(_ systemScreenBrightness: Float) { - systemScreenBrightnessChangeStreamHandler.addScreenBrightnessToEventSink(systemScreenBrightness) + private func handleSystemScreenBrightnessChanged(_ brightness: Float) { + systemScreenBrightnessChangedStreamHandler.addScreenBrightnessToEventSink(brightness) } private func handleGetApplicationScreenBrightnessMethodCall(result: FlutterResult) { do { - let _applicationBrightness = try getScreenBrightness() - result(_applicationBrightness) + let _brightness = try getScreenBrightness() + result(_brightness) } catch { result(FlutterError.init(code: "-2", message: "Unexpected error on null brightness", details: nil)) } @@ -180,12 +137,11 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { return } - let _applicationBrightness = Float(brightness.doubleValue) - + let _brightness = Float(brightness.doubleValue) do { - try setScreenBrightness(targetBrightness: _applicationBrightness) - applicationScreenBrightness = _applicationBrightness - handleApplicationScreenBrightnessChanged(_applicationBrightness) + try setScreenBrightness(targetBrightness: _brightness) + applicationScreenBrightness = _brightness + handleApplicationScreenBrightnessChanged(_brightness) result(nil) } catch { result(FlutterError.init(code: "-1", message: "Unable to change application screen brightness", details: nil)) @@ -193,23 +149,23 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { } private func handleResetApplicationScreenBrightnessMethodCall(result: FlutterResult) { - guard let systemScreenBrightness = systemScreenBrightness else { + guard let brightness = systemScreenBrightness else { result(FlutterError.init(code: "-2", message: "Unexpected error on null brightness", details: nil)) return } do { - try setScreenBrightness(targetBrightness: systemScreenBrightness) + try setScreenBrightness(targetBrightness: brightness) applicationScreenBrightness = nil - handleApplicationScreenBrightnessChanged(systemScreenBrightness) + handleApplicationScreenBrightnessChanged(brightness) result(nil) } catch { - result(FlutterError.init(code: "-1", message: "Unable to change screen brightness", details: nil)) + result(FlutterError.init(code: "-1", message: "Unable to reset screen brightness", details: nil)) } } - private func handleApplicationScreenBrightnessChanged(_ applicationScreenBrightness: Float) { - applicationScreenBrightnessChangeStreamHandler.addScreenBrightnessToEventSink(applicationScreenBrightness) + private func handleApplicationScreenBrightnessChanged(_ brightness: Float) { + applicationScreenBrightnessChangedStreamHandler.addScreenBrightnessToEventSink(brightness) } private func handleHasApplicationScreenBrightnessChangedMethodCall(result: FlutterResult) { @@ -244,33 +200,6 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { result(nil) } - @objc private func getSystemBrightness(_: Timer) { - guard let brightness = try? getScreenBrightness(), systemScreenBrightness != brightness else { - return - } - - systemScreenBrightness = brightness - if (applicationScreenBrightness == nil) { - handleApplicationScreenBrightnessChanged(brightness) - } - } - - func onApplicationPause() { - guard let systemScreenBrightness = systemScreenBrightness else { - return - } - - try! setScreenBrightness(targetBrightness: systemScreenBrightness) - } - - func onApplicationResume() { - guard let applicationScreenBrightness = applicationScreenBrightness else { - return - } - - try! setScreenBrightness(targetBrightness: applicationScreenBrightness) - } - @objc public func applicationWillResignActive(notification: Notification) { guard isAutoReset else { return @@ -290,6 +219,7 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { if let _systemScreenBrightness = try? getScreenBrightness() { systemScreenBrightness = _systemScreenBrightness + handleSystemScreenBrightnessChanged(systemScreenBrightness!) if (applicationScreenBrightness == nil) { handleApplicationScreenBrightnessChanged(systemScreenBrightness!) } @@ -310,6 +240,78 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { NotificationCenter.default.removeObserver(self) methodChannel?.setMethodCallHandler(nil) - applicationScreenBrightnessChangeEventChannel?.setStreamHandler(nil) + applicationScreenBrightnessChangedEventChannel?.setStreamHandler(nil) + systemScreenBrightnessChangedEventChannel?.setStreamHandler(nil) + } + + @discardableResult private func getIODisplayConnectServices(iterator: inout io_iterator_t) throws -> kern_return_t { + var port: mach_port_t = kIOMasterPortDefault + if #available(macOS 12.0, *) { + port = kIOMainPortDefault + } + + let result = IOServiceGetMatchingServices(port, IOServiceMatching("IODisplayConnect"), &iterator) + + guard result == kIOReturnSuccess else { + throw ScreenBrightnessError.serviceMissing + } + + return result + } + + private func getScreenBrightness() throws -> Float { + var brightness: Float = 0.0 + + var service: io_object_t = 1 + var iterator: io_iterator_t = 0 + try getIODisplayConnectServices(iterator: &iterator) + + while service != 0 { + service = IOIteratorNext(iterator) + IODisplayGetFloatParameter(service, 0, kIODisplayBrightnessKey as CFString, &brightness) + IOObjectRelease(service) + } + + return brightness + } + + private func setScreenBrightness(targetBrightness: Float) throws { + var service: io_object_t = 1 + var iterator: io_iterator_t = 0 + try getIODisplayConnectServices(iterator: &iterator) + + while service != 0 { + service = IOIteratorNext(iterator) + IODisplaySetFloatParameter(service, 0, kIODisplayBrightnessKey as CFString, targetBrightness) + IOObjectRelease(service) + } + } + + @objc private func getSystemBrightness(_: Timer) { + guard let brightness = try? getScreenBrightness(), systemScreenBrightness != brightness else { + return + } + + systemScreenBrightness = brightness + handleSystemScreenBrightnessChanged(brightness) + if (applicationScreenBrightness == nil) { + handleApplicationScreenBrightnessChanged(brightness) + } + } + + func onApplicationPause() { + guard let systemScreenBrightness = systemScreenBrightness else { + return + } + + try! setScreenBrightness(targetBrightness: systemScreenBrightness) + } + + func onApplicationResume() { + guard let applicationScreenBrightness = applicationScreenBrightness else { + return + } + + try! setScreenBrightness(targetBrightness: applicationScreenBrightness) } } diff --git a/screen_brightness_macos/macos/Classes/StreamHandler/ScreenBrightnessChangeStreamHandler.swift b/screen_brightness_macos/macos/Classes/StreamHandler/ScreenBrightnessChangedStreamHandler.swift similarity index 83% rename from screen_brightness_macos/macos/Classes/StreamHandler/ScreenBrightnessChangeStreamHandler.swift rename to screen_brightness_macos/macos/Classes/StreamHandler/ScreenBrightnessChangedStreamHandler.swift index 2ea4727..9baee9a 100644 --- a/screen_brightness_macos/macos/Classes/StreamHandler/ScreenBrightnessChangeStreamHandler.swift +++ b/screen_brightness_macos/macos/Classes/StreamHandler/ScreenBrightnessChangedStreamHandler.swift @@ -8,7 +8,7 @@ import Cocoa import FlutterMacOS -public class ScreenBrightnessChangeStreamHandler: BaseStreamHandler { +public class ScreenBrightnessChangedStreamHandler: BaseStreamHandler { public func addScreenBrightnessToEventSink(_ screenBrightness: Float) { guard let eventSink = eventSink else { return From 596e90f3681e917194b10f6d8a7200e0b6db9ef7 Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Fri, 9 Aug 2024 01:21:16 +0800 Subject: [PATCH 11/22] feat(screen-brightness-windows): support system brightness changed stream --- .../ScreenBrightnessAndroidPlugin.kt | 4 +- .../windows/CMakeLists.txt | 4 +- ..._screen_brightness_change_stream_handler.h | 15 - ...screen_brightness_changed_stream_handler.h | 15 + .../screen_brightness_windows_plugin.h | 36 ++- ...creen_brightness_change_stream_handler.cpp | 13 - ...reen_brightness_changed_stream_handler.cpp | 13 + .../src/screen_brightness_windows_plugin.cpp | 291 +++++++++++------- 8 files changed, 229 insertions(+), 162 deletions(-) delete mode 100644 screen_brightness_windows/windows/include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h create mode 100644 screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_changed_stream_handler.h delete mode 100644 screen_brightness_windows/windows/src/application_screen_brightness_change_stream_handler.cpp create mode 100644 screen_brightness_windows/windows/src/screen_brightness_changed_stream_handler.cpp diff --git a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt index 4ee0253..b7ae29d 100644 --- a/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt +++ b/screen_brightness_android/android/src/main/kotlin/com/aaassseee/screen_brightness_android/ScreenBrightnessAndroidPlugin.kt @@ -199,7 +199,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity result.success(brightness) } catch (e: Settings.SettingNotFoundException) { e.printStackTrace() - result.error("-11", "Could not found system setting screen brightness value", null) + result.error("-11", "Could not found application screen brightness", null) return } } @@ -239,7 +239,7 @@ class ScreenBrightnessAndroidPlugin : FlutterPlugin, MethodCallHandler, Activity val isSet = setWindowsAttributesBrightness(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE) if (!isSet) { - result.error("-1", "Unable to change screen brightness", null) + result.error("-1", "Unable to reset screen brightness", null) return } diff --git a/screen_brightness_windows/windows/CMakeLists.txt b/screen_brightness_windows/windows/CMakeLists.txt index 1241565..cefb85c 100644 --- a/screen_brightness_windows/windows/CMakeLists.txt +++ b/screen_brightness_windows/windows/CMakeLists.txt @@ -10,8 +10,8 @@ add_library(${PLUGIN_NAME} SHARED "include/screen_brightness_windows/screen_brightness_windows_plugin.h" "src/screen_brightness_windows_plugin.cpp" "include/screen_brightness_windows/base_stream_handler.h" - "include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h" - "src/application_screen_brightness_change_stream_handler.cpp" + "include/screen_brightness_windows/screen_brightness_changed_stream_handler.h" + "src/screen_brightness_changed_stream_handler.cpp" ) apply_standard_settings(${PLUGIN_NAME}) set_target_properties(${PLUGIN_NAME} PROPERTIES diff --git a/screen_brightness_windows/windows/include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h b/screen_brightness_windows/windows/include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h deleted file mode 100644 index a05b6c0..0000000 --- a/screen_brightness_windows/windows/include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef FLUTTER_PLUGIN_SCREEN_BRIGHTNESS_WINDOWS_PLUGIN_APPLICATION_SCREEN_BRIGHTNESS_CHNAGE_STREAM_HANDLER_H -#define FLUTTER_PLUGIN_SCREEN_BRIGHTNESS_WINDOWS_PLUGIN_APPLICATION_SCREEN_BRIGHTNESS_CHNAGE_STREAM_HANDLER_H - -#include "base_stream_handler.h" - -namespace screen_brightness -{ - class ApplicationScreenBrightnessChangeStreamHandler final : public BaseStreamHandler - { - public: - void AddApplicationScreenBrightnessToEventSink(double applicationScreenBrightness) const; - }; -} - -#endif \ No newline at end of file diff --git a/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_changed_stream_handler.h b/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_changed_stream_handler.h new file mode 100644 index 0000000..1f23629 --- /dev/null +++ b/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_changed_stream_handler.h @@ -0,0 +1,15 @@ +#ifndef FLUTTER_PLUGIN_SCREEN_BRIGHTNESS_WINDOWS_PLUGIN_SCREEN_BRIGHTNESS_CHANGED_STREAM_HANDLER_H +#define FLUTTER_PLUGIN_SCREEN_BRIGHTNESS_WINDOWS_PLUGIN_SCREEN_BRIGHTNESS_CHANGED_STREAM_HANDLER_H + +#include "base_stream_handler.h" + +namespace screen_brightness +{ + class ScreenBrightnessChangedStreamHandler final : public BaseStreamHandler + { + public: + void AddScreenBrightnessToEventSink(double brightness) const; + }; +} + +#endif \ No newline at end of file diff --git a/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_windows_plugin.h b/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_windows_plugin.h index 62783ec..f975df0 100644 --- a/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_windows_plugin.h +++ b/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_windows_plugin.h @@ -3,7 +3,7 @@ #include -#include "../include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h" +#include "../include/screen_brightness_windows/screen_brightness_changed_stream_handler.h" #include @@ -41,42 +41,36 @@ namespace screen_brightness HWND window_handler_ = nullptr; - long system_screen_brightness_ = -1; + int window_proc_id_ = -1; + + ScreenBrightnessChangedStreamHandler* system_screen_brightness_changed_stream_handler_ = nullptr; + + ScreenBrightnessChangedStreamHandler* application_screen_brightness_changed_stream_handler_ = nullptr; long minimum_screen_brightness_ = -1; long maximum_screen_brightness_ = -1; - long application_screen_brightness_ = -1; + long system_screen_brightness_ = -1; - long changed_screen_brightness_ = -1; + long application_screen_brightness_ = -1; bool is_auto_reset_ = true; bool is_animate_ = true; - ApplicationScreenBrightnessChangeStreamHandler* application_screen_brightness_change_stream_handler_ = nullptr; - - int window_proc_id_ = -1; - // Called when a method is called on this plugin's channel from Dart. void HandleMethodCall(const flutter::MethodCall& method_call, std::unique_ptr> result); - void GetScreenBrightness(long& minimum_screen_brightness, long& screen_brightness, long& maximum_screen_brightness); - - void SetScreenBrightness(long screen_brightness); - - [[nodiscard]] double GetScreenBrightnessPercentage(long screen_brightness) const; - - [[nodiscard]] long GetScreenBrightnessValueByPercentage(double percentage) const; - void HandleGetSystemScreenBrightnessMethodCall(std::unique_ptr> result) const; void HandleSetSystemScreenBrightnessMethodCall( const flutter::MethodCall& call, std::unique_ptr> result); + void HandleSystemScreenBrightnessChanged(long brightness); + void HandleGetApplicationScreenBrightnessMethodCall(std::unique_ptr> result); void HandleSetApplicationScreenBrightnessMethodCall( @@ -85,7 +79,7 @@ namespace screen_brightness void HandleResetApplicationScreenBrightnessMethodCall(std::unique_ptr> result); - void HandleCurrentBrightnessChanged(long brightness); + void HandleApplicationScreenBrightnessChanged(long brightness); void HandleHasApplicationScreenBrightnessChangedMethodCall(std::unique_ptr> result) const; @@ -100,6 +94,14 @@ namespace screen_brightness std::unique_ptr> result); std::optional HandleWindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); + + void GetScreenBrightness(long& minimum_screen_brightness, long& screen_brightness, long& maximum_screen_brightness); + + void SetScreenBrightness(long screen_brightness); + + [[nodiscard]] double GetScreenBrightnessPercentage(long screen_brightness) const; + + [[nodiscard]] long GetScreenBrightnessValueByPercentage(double percentage) const; }; } diff --git a/screen_brightness_windows/windows/src/application_screen_brightness_change_stream_handler.cpp b/screen_brightness_windows/windows/src/application_screen_brightness_change_stream_handler.cpp deleted file mode 100644 index 22fb9df..0000000 --- a/screen_brightness_windows/windows/src/application_screen_brightness_change_stream_handler.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include "../include/screen_brightness_windows/application_screen_brightness_change_stream_handler.h" - -namespace screen_brightness -{ - void ApplicationScreenBrightnessChangeStreamHandler::AddApplicationScreenBrightnessToEventSink(double applicationScreenBrightness) const - { - if (sink_ == nullptr) { - return; - } - - sink_->Success(applicationScreenBrightness); - } -} \ No newline at end of file diff --git a/screen_brightness_windows/windows/src/screen_brightness_changed_stream_handler.cpp b/screen_brightness_windows/windows/src/screen_brightness_changed_stream_handler.cpp new file mode 100644 index 0000000..af1c448 --- /dev/null +++ b/screen_brightness_windows/windows/src/screen_brightness_changed_stream_handler.cpp @@ -0,0 +1,13 @@ +#include "../include/screen_brightness_windows/screen_brightness_changed_stream_handler.h" + +namespace screen_brightness +{ + void ScreenBrightnessChangedStreamHandler::AddScreenBrightnessToEventSink(double brightness) const + { + if (sink_ == nullptr) { + return; + } + + sink_->Success(brightness); + } +} \ No newline at end of file diff --git a/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp b/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp index 14884ae..5b9b96b 100644 --- a/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp +++ b/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp @@ -58,18 +58,31 @@ namespace screen_brightness plugin_pointer->HandleMethodCall(call, std::move(result)); }); - const auto application_screen_brightness_change_event_channel = + const auto system_screen_brightness_changed_event_channel = std::make_unique>( - registrar->messenger(), "github.com/aaassseee/screen_brightness/application_brightness_change", + registrar->messenger(), "github.com/aaassseee/screen_brightness/system_brightness_changed", &flutter::StandardMethodCodec::GetInstance()); - plugin->application_screen_brightness_change_stream_handler_ = new ApplicationScreenBrightnessChangeStreamHandler(); + plugin->system_screen_brightness_changed_stream_handler_ = new ScreenBrightnessChangedStreamHandler(); std::unique_ptr> - application_screen_brightness_change_stream_handler_unique_pointer + system_screen_brightness_changed_stream_handler_unique_pointer { - static_cast*>(plugin->application_screen_brightness_change_stream_handler_) + static_cast*>(plugin->system_screen_brightness_changed_stream_handler_) }; - application_screen_brightness_change_event_channel->SetStreamHandler(std::move(application_screen_brightness_change_stream_handler_unique_pointer)); + system_screen_brightness_changed_event_channel->SetStreamHandler(std::move(system_screen_brightness_changed_stream_handler_unique_pointer)); + + const auto application_screen_brightness_changed_event_channel = + std::make_unique>( + registrar->messenger(), "github.com/aaassseee/screen_brightness/application_brightness_changed", + &flutter::StandardMethodCodec::GetInstance()); + + plugin->application_screen_brightness_changed_stream_handler_ = new ScreenBrightnessChangedStreamHandler(); + std::unique_ptr> + application_screen_brightness_changed_stream_handler_unique_pointer + { + static_cast*>(plugin->application_screen_brightness_changed_stream_handler_) + }; + application_screen_brightness_changed_event_channel->SetStreamHandler(std::move(application_screen_brightness_changed_stream_handler_unique_pointer)); registrar->AddPlugin(std::move(plugin)); } @@ -141,92 +154,14 @@ namespace screen_brightness result->NotImplemented(); } - void ScreenBrightnessWindowsPlugin::GetScreenBrightness(long& minimum_screen_brightness, long& screen_brightness, long& maximum_screen_brightness) - { - DWORD physical_monitor_array_size = 0; - HMONITOR monitor_handler = MonitorFromWindow(window_handler_, MONITOR_DEFAULTTOPRIMARY); - DWORD minimum_brightness_ = 0, brightness_ = 0, maximum_brightness_ = 0; - - if (!GetNumberOfPhysicalMonitorsFromHMONITOR(monitor_handler, &physical_monitor_array_size)) - { - throw std::exception("Problem getting numbers of monitor"); - } - - LPPHYSICAL_MONITOR physical_monitor = (LPPHYSICAL_MONITOR)malloc(physical_monitor_array_size * sizeof(PHYSICAL_MONITOR)); - - if (physical_monitor == NULL) - { - throw std::exception("No monitors"); - } - - if (!GetPhysicalMonitorsFromHMONITOR(monitor_handler, physical_monitor_array_size, physical_monitor)) - { - throw std::exception("Problem getting physical monitors"); - } - - if (!GetMonitorBrightness(physical_monitor->hPhysicalMonitor, &minimum_brightness_, &brightness_, &maximum_brightness_)) - { - throw std::exception("Problem getting monitor brightness"); - } - - minimum_screen_brightness = minimum_brightness_; - screen_brightness = brightness_; - maximum_screen_brightness = maximum_brightness_; - - DestroyPhysicalMonitors(physical_monitor_array_size, physical_monitor); - - free(physical_monitor); - } - - void ScreenBrightnessWindowsPlugin::SetScreenBrightness(const long screen_brightness) - { - DWORD physical_monitor_array_size = 0; - HMONITOR monitor_handler = MonitorFromWindow(window_handler_, MONITOR_DEFAULTTOPRIMARY); - - if (!GetNumberOfPhysicalMonitorsFromHMONITOR(monitor_handler, &physical_monitor_array_size)) - { - throw std::exception("Problem getting numbers of monitor"); - } - - LPPHYSICAL_MONITOR physical_monitor = (LPPHYSICAL_MONITOR)malloc(physical_monitor_array_size * sizeof(PHYSICAL_MONITOR)); - - if (physical_monitor == NULL) - { - throw std::exception("No monitors"); - } - - if (!GetPhysicalMonitorsFromHMONITOR(monitor_handler, physical_monitor_array_size, physical_monitor)) - { - throw std::exception("Problem getting physical monitors"); - } - - if (!SetMonitorBrightness(physical_monitor->hPhysicalMonitor, screen_brightness)) - { - throw std::exception("Problem setting monitor brightness"); - } - - DestroyPhysicalMonitors(physical_monitor_array_size, physical_monitor); - - free(physical_monitor); - } - - double ScreenBrightnessWindowsPlugin::GetScreenBrightnessPercentage(const long screen_brightness) const - { - if (screen_brightness < 0) - { - return 0; - } - - return static_cast(screen_brightness - minimum_screen_brightness_) / (maximum_screen_brightness_ - minimum_screen_brightness_); - } - - long ScreenBrightnessWindowsPlugin::GetScreenBrightnessValueByPercentage(const double percentage) const - { - return static_cast((percentage * (maximum_screen_brightness_ - minimum_screen_brightness_)) + minimum_screen_brightness_); - } - void ScreenBrightnessWindowsPlugin::HandleGetSystemScreenBrightnessMethodCall(const std::unique_ptr> result) const { + if (system_screen_brightness_ == -1) + { + result->Error("-11", "Could not found system screen brightness value"); + return; + } + result->Success(GetScreenBrightnessPercentage(system_screen_brightness_)); } @@ -246,21 +181,39 @@ namespace screen_brightness return; } - const long changed_brightness = GetScreenBrightnessValueByPercentage(brightness); + const long brightness_value = GetScreenBrightnessValueByPercentage(brightness); try { - if (changed_screen_brightness_ == -1) + system_screen_brightness_ = brightness_value; + HandleSystemScreenBrightnessChanged(brightness_value); + if (application_screen_brightness_ == -1) { - SetScreenBrightness(changed_brightness); - HandleCurrentBrightnessChanged(changed_brightness); + SetScreenBrightness(brightness_value); + HandleApplicationScreenBrightnessChanged(brightness_value); } - system_screen_brightness_ = changed_brightness; - result->Success(nullptr); } catch (const std::exception& exception) { - result->Error("-1", "Unable to change screen brightness.", exception.what()); + result->Error("-1", "Unable to change system screen brightness", exception.what()); + } + } + + void ScreenBrightnessWindowsPlugin::HandleSystemScreenBrightnessChanged(const long brightness) + { + if (system_screen_brightness_changed_stream_handler_ == nullptr) + { + return; + } + + try + { + const double brightness_percentage = GetScreenBrightnessPercentage(brightness); + system_screen_brightness_changed_stream_handler_->AddScreenBrightnessToEventSink(brightness_percentage); + } + catch (const std::exception& exception) + { + std::cout << exception.what() << std::endl; } } @@ -279,7 +232,7 @@ namespace screen_brightness } catch (const std::exception& exception) { - result->Error("-11", "Could not found monitor brightness value.", exception.what()); + result->Error("-11", "Could not found application screen brightness", exception.what()); } } @@ -299,17 +252,18 @@ namespace screen_brightness return; } - const long changed_brightness = GetScreenBrightnessValueByPercentage(brightness); + const long brightness_value = GetScreenBrightnessValueByPercentage(brightness); try { - SetScreenBrightness(changed_brightness); - changed_screen_brightness_ = changed_brightness; - HandleCurrentBrightnessChanged(changed_brightness); + SetScreenBrightness(brightness_value); + + application_screen_brightness_ = brightness_value; + HandleApplicationScreenBrightnessChanged(brightness_value); result->Success(nullptr); } catch (const std::exception& exception) { - result->Error("-1", "Unable to change screen brightness.", exception.what()); + result->Error("-1", "Unable to change application screen brightness", exception.what()); } } @@ -324,19 +278,20 @@ namespace screen_brightness try { SetScreenBrightness(system_screen_brightness_); - changed_screen_brightness_ = -1; - HandleCurrentBrightnessChanged(system_screen_brightness_); + + application_screen_brightness_ = -1; + HandleApplicationScreenBrightnessChanged(system_screen_brightness_); result->Success(nullptr); } catch (const std::exception& exception) { - result->Error("-1", "Unable reset screen brightness. error: ", exception.what()); + result->Error("-1", "Unable reset screen brightness", exception.what()); } } - void ScreenBrightnessWindowsPlugin::HandleCurrentBrightnessChanged(const long brightness) + void ScreenBrightnessWindowsPlugin::HandleApplicationScreenBrightnessChanged(const long brightness) { - if (application_screen_brightness_change_stream_handler_ == nullptr) + if (application_screen_brightness_changed_stream_handler_ == nullptr) { return; } @@ -344,7 +299,7 @@ namespace screen_brightness try { const double brightness_percentage = GetScreenBrightnessPercentage(brightness); - application_screen_brightness_change_stream_handler_->AddApplicationScreenBrightnessToEventSink(brightness_percentage); + application_screen_brightness_changed_stream_handler_->AddScreenBrightnessToEventSink(brightness_percentage); } catch (const std::exception& exception) { @@ -354,7 +309,7 @@ namespace screen_brightness void ScreenBrightnessWindowsPlugin::HandleHasApplicationScreenBrightnessChangedMethodCall(const std::unique_ptr> result) const { - result->Success(changed_screen_brightness_ != -1); + result->Success(application_screen_brightness_ != -1); } void ScreenBrightnessWindowsPlugin::HandleIsAutoResetMethodCall(const std::unique_ptr> result) @@ -387,7 +342,7 @@ namespace screen_brightness std::optional ScreenBrightnessWindowsPlugin::HandleWindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - if (changed_screen_brightness_ == -1 || !is_auto_reset_) + if (!is_auto_reset_) { return std::nullopt; } @@ -398,29 +353,139 @@ namespace screen_brightness switch (wParam) { case SIZE_MINIMIZED: + if (system_screen_brightness_ == -1) + { + break; + } SetScreenBrightness(system_screen_brightness_); break; case SIZE_MAXIMIZED: case SIZE_RESTORED: - SetScreenBrightness(changed_screen_brightness_); + if (application_screen_brightness_ == -1) + { + break; + } + SetScreenBrightness(application_screen_brightness_); break; } break; case WM_DESTROY: + if (system_screen_brightness_ == -1) + { + break; + } SetScreenBrightness(system_screen_brightness_); break; case WM_ACTIVATEAPP: bool is_activate = bool(wParam); - SetScreenBrightness(is_activate ? changed_screen_brightness_ : system_screen_brightness_); + if (is_activate) + { + if (application_screen_brightness_ == -1) + { + break; + } + SetScreenBrightness(application_screen_brightness_); + break; + } + + if (application_screen_brightness_ == -1) + { + break; + } + SetScreenBrightness(system_screen_brightness_); break; } // allow another plugin to process message return std::nullopt; } + + void ScreenBrightnessWindowsPlugin::GetScreenBrightness(long& minimum_screen_brightness, long& screen_brightness, long& maximum_screen_brightness) + { + DWORD physical_monitor_array_size = 0; + HMONITOR monitor_handler = MonitorFromWindow(window_handler_, MONITOR_DEFAULTTOPRIMARY); + DWORD minimum_brightness_ = 0, brightness_ = 0, maximum_brightness_ = 0; + + if (!GetNumberOfPhysicalMonitorsFromHMONITOR(monitor_handler, &physical_monitor_array_size)) + { + throw std::exception("Problem getting numbers of monitor"); + } + + LPPHYSICAL_MONITOR physical_monitor = (LPPHYSICAL_MONITOR)malloc(physical_monitor_array_size * sizeof(PHYSICAL_MONITOR)); + + if (physical_monitor == NULL) + { + throw std::exception("No monitors"); + } + + if (!GetPhysicalMonitorsFromHMONITOR(monitor_handler, physical_monitor_array_size, physical_monitor)) + { + throw std::exception("Problem getting physical monitors"); + } + + if (!GetMonitorBrightness(physical_monitor->hPhysicalMonitor, &minimum_brightness_, &brightness_, &maximum_brightness_)) + { + throw std::exception("Problem getting monitor brightness"); + } + + minimum_screen_brightness = minimum_brightness_; + screen_brightness = brightness_; + maximum_screen_brightness = maximum_brightness_; + + DestroyPhysicalMonitors(physical_monitor_array_size, physical_monitor); + + free(physical_monitor); + } + + void ScreenBrightnessWindowsPlugin::SetScreenBrightness(const long screen_brightness) + { + DWORD physical_monitor_array_size = 0; + HMONITOR monitor_handler = MonitorFromWindow(window_handler_, MONITOR_DEFAULTTOPRIMARY); + + if (!GetNumberOfPhysicalMonitorsFromHMONITOR(monitor_handler, &physical_monitor_array_size)) + { + throw std::exception("Problem getting numbers of monitor"); + } + + LPPHYSICAL_MONITOR physical_monitor = (LPPHYSICAL_MONITOR)malloc(physical_monitor_array_size * sizeof(PHYSICAL_MONITOR)); + + if (physical_monitor == NULL) + { + throw std::exception("No monitors"); + } + + if (!GetPhysicalMonitorsFromHMONITOR(monitor_handler, physical_monitor_array_size, physical_monitor)) + { + throw std::exception("Problem getting physical monitors"); + } + + if (!SetMonitorBrightness(physical_monitor->hPhysicalMonitor, screen_brightness)) + { + throw std::exception("Problem setting monitor brightness"); + } + + DestroyPhysicalMonitors(physical_monitor_array_size, physical_monitor); + + free(physical_monitor); + } + + double ScreenBrightnessWindowsPlugin::GetScreenBrightnessPercentage(const long screen_brightness) const + { + if (screen_brightness < 0) + { + return 0; + } + + return static_cast(screen_brightness - minimum_screen_brightness_) / (maximum_screen_brightness_ - minimum_screen_brightness_); + } + + long ScreenBrightnessWindowsPlugin::GetScreenBrightnessValueByPercentage(const double percentage) const + { + return static_cast((percentage * (maximum_screen_brightness_ - minimum_screen_brightness_)) + minimum_screen_brightness_); + } } void ScreenBrightnessWindowsPluginRegisterWithRegistrar(FlutterDesktopPluginRegistrarRef registrar) From 1267586134ca03de6b37e75274565927c6af9030 Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Fri, 9 Aug 2024 01:21:39 +0800 Subject: [PATCH 12/22] feat: updated example --- screen_brightness/example/lib/main.dart | 41 +++++++++++-------- screen_brightness_ios/example/lib/main.dart | 33 +++++++++------ screen_brightness_macos/example/lib/main.dart | 33 +++++++++------ .../example/lib/main.dart | 33 +++++++++------ 4 files changed, 88 insertions(+), 52 deletions(-) diff --git a/screen_brightness/example/lib/main.dart b/screen_brightness/example/lib/main.dart index 3438404..e22a1cb 100644 --- a/screen_brightness/example/lib/main.dart +++ b/screen_brightness/example/lib/main.dart @@ -78,8 +78,8 @@ class HomePage extends StatelessWidget { } return StreamBuilder( - stream: - ScreenBrightness.instance.onApplicationBrightnessChanged, + stream: ScreenBrightness + .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { @@ -169,18 +169,27 @@ class _ControllerPageState extends State { systemBrightness = snapshot.data!; } - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text('System brightness: $systemBrightness'), - Slider.adaptive( - value: systemBrightness, - onChanged: (value) { - setSystemBrightness(value); - }, - ), - ], - ); + return StreamBuilder( + stream: + ScreenBrightness.instance.onSystemScreenBrightnessChanged, + builder: (context, snapshot) { + double changedSystemBrightness = systemBrightness; + if (snapshot.hasData) { + changedSystemBrightness = snapshot.data!; + } + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('System brightness: $changedSystemBrightness'), + Slider.adaptive( + value: changedSystemBrightness, + onChanged: (value) { + setSystemBrightness(value); + }, + ), + ], + ); + }); }, ), FutureBuilder( @@ -192,8 +201,8 @@ class _ControllerPageState extends State { } return StreamBuilder( - stream: - ScreenBrightness.instance.onApplicationBrightnessChanged, + stream: ScreenBrightness + .instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { diff --git a/screen_brightness_ios/example/lib/main.dart b/screen_brightness_ios/example/lib/main.dart index 4bd05a8..99efcfa 100644 --- a/screen_brightness_ios/example/lib/main.dart +++ b/screen_brightness_ios/example/lib/main.dart @@ -171,18 +171,27 @@ class _ControllerPageState extends State { systemBrightness = snapshot.data!; } - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text('System brightness: $systemBrightness'), - Slider.adaptive( - value: systemBrightness, - onChanged: (value) { - setSystemBrightness(value); - }, - ), - ], - ); + return StreamBuilder( + stream: ScreenBrightnessPlatform + .instance.onSystemScreenBrightnessChanged, + builder: (context, snapshot) { + double changedSystemBrightness = systemBrightness; + if (snapshot.hasData) { + changedSystemBrightness = snapshot.data!; + } + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('System brightness: $changedSystemBrightness'), + Slider.adaptive( + value: changedSystemBrightness, + onChanged: (value) { + setSystemBrightness(value); + }, + ), + ], + ); + }); }, ), FutureBuilder( diff --git a/screen_brightness_macos/example/lib/main.dart b/screen_brightness_macos/example/lib/main.dart index 4bd05a8..99efcfa 100644 --- a/screen_brightness_macos/example/lib/main.dart +++ b/screen_brightness_macos/example/lib/main.dart @@ -171,18 +171,27 @@ class _ControllerPageState extends State { systemBrightness = snapshot.data!; } - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text('System brightness: $systemBrightness'), - Slider.adaptive( - value: systemBrightness, - onChanged: (value) { - setSystemBrightness(value); - }, - ), - ], - ); + return StreamBuilder( + stream: ScreenBrightnessPlatform + .instance.onSystemScreenBrightnessChanged, + builder: (context, snapshot) { + double changedSystemBrightness = systemBrightness; + if (snapshot.hasData) { + changedSystemBrightness = snapshot.data!; + } + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('System brightness: $changedSystemBrightness'), + Slider.adaptive( + value: changedSystemBrightness, + onChanged: (value) { + setSystemBrightness(value); + }, + ), + ], + ); + }); }, ), FutureBuilder( diff --git a/screen_brightness_windows/example/lib/main.dart b/screen_brightness_windows/example/lib/main.dart index 4bd05a8..99efcfa 100644 --- a/screen_brightness_windows/example/lib/main.dart +++ b/screen_brightness_windows/example/lib/main.dart @@ -171,18 +171,27 @@ class _ControllerPageState extends State { systemBrightness = snapshot.data!; } - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text('System brightness: $systemBrightness'), - Slider.adaptive( - value: systemBrightness, - onChanged: (value) { - setSystemBrightness(value); - }, - ), - ], - ); + return StreamBuilder( + stream: ScreenBrightnessPlatform + .instance.onSystemScreenBrightnessChanged, + builder: (context, snapshot) { + double changedSystemBrightness = systemBrightness; + if (snapshot.hasData) { + changedSystemBrightness = snapshot.data!; + } + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('System brightness: $changedSystemBrightness'), + Slider.adaptive( + value: changedSystemBrightness, + onChanged: (value) { + setSystemBrightness(value); + }, + ), + ], + ); + }); }, ), FutureBuilder( From c4207ccdd5e18a193862e59346dab5cd2bb87bbb Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Thu, 15 Aug 2024 21:29:12 +0800 Subject: [PATCH 13/22] feat: fixed get application brightness actually set the application brightness --- .../windows/src/screen_brightness_windows_plugin.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp b/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp index 5b9b96b..d8cbf43 100644 --- a/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp +++ b/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp @@ -227,8 +227,9 @@ namespace screen_brightness try { - GetScreenBrightness(minimum_screen_brightness_, application_screen_brightness_, maximum_screen_brightness_); - result->Success(GetScreenBrightnessPercentage(application_screen_brightness_)); + long application_screen_brightness = -1; + GetScreenBrightness(minimum_screen_brightness_, application_screen_brightness, maximum_screen_brightness_); + result->Success(GetScreenBrightnessPercentage(application_screen_brightness)); } catch (const std::exception& exception) { From 61ecd5430b15dad42b2b6f508de1837a17499f44 Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Sat, 24 Aug 2024 19:25:31 +0800 Subject: [PATCH 14/22] fix(screen-brightness-macos): wrong channel name --- .../macos/Classes/ScreenBrightnessMacosPlugin.swift | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift b/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift index 317ed6c..bd09712 100644 --- a/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift +++ b/screen_brightness_macos/macos/Classes/ScreenBrightnessMacosPlugin.swift @@ -26,12 +26,12 @@ public class ScreenBrightnessMacosPlugin: NSObject, FlutterPlugin { let instance = ScreenBrightnessMacosPlugin() instance.methodChannel = FlutterMethodChannel(name: "github.com/aaassseee/screen_brightness", binaryMessenger: registrar.messenger) registrar.addMethodCallDelegate(instance, channel: instance.methodChannel!) - - instance.applicationScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_change", binaryMessenger: registrar.messenger) - instance.applicationScreenBrightnessChangedEventChannel!.setStreamHandler(instance.applicationScreenBrightnessChangedStreamHandler) - - instance.systemScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/system_brightness_change", binaryMessenger: registrar.messenger) + + instance.systemScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/system_brightness_changed", binaryMessenger: registrar.messenger) instance.systemScreenBrightnessChangedEventChannel!.setStreamHandler(instance.systemScreenBrightnessChangedStreamHandler) + + instance.applicationScreenBrightnessChangedEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/application_brightness_changed", binaryMessenger: registrar.messenger) + instance.applicationScreenBrightnessChangedEventChannel!.setStreamHandler(instance.applicationScreenBrightnessChangedStreamHandler) } override init() { From 369dd24e108e5851b99dc94896f1a6ed44b38add Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Sat, 5 Oct 2024 12:41:02 +0800 Subject: [PATCH 15/22] feat(screen-brightness-windows): support auto reset feature on HandleWindowProc --- .idea/misc.xml | 2 +- .../example/pubspec.lock | 24 +++--- .../screen_brightness_windows_plugin.h | 4 + .../src/screen_brightness_windows_plugin.cpp | 82 +++++++++++++------ 4 files changed, 73 insertions(+), 39 deletions(-) diff --git a/.idea/misc.xml b/.idea/misc.xml index 4c025d9..9e78c04 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -3,5 +3,5 @@ - + \ No newline at end of file diff --git a/screen_brightness_windows/example/pubspec.lock b/screen_brightness_windows/example/pubspec.lock index 3b32f9c..bdeaad1 100644 --- a/screen_brightness_windows/example/pubspec.lock +++ b/screen_brightness_windows/example/pubspec.lock @@ -71,18 +71,18 @@ packages: dependency: transitive description: name: leak_tracker - sha256: "7f0df31977cb2c0b88585095d168e689669a2cc9b97c309665e3386f3e9d341a" + sha256: "3f87a60e8c63aecc975dda1ceedbc8f24de75f09e4856ea27daf8958f2f0ce05" url: "https://pub.dev" source: hosted - version: "10.0.4" + version: "10.0.5" leak_tracker_flutter_testing: dependency: transitive description: name: leak_tracker_flutter_testing - sha256: "06e98f569d004c1315b991ded39924b21af84cf14cc94791b8aea337d25b57f8" + sha256: "932549fb305594d82d7183ecd9fa93463e9914e1b67cacc34bc40906594a1806" url: "https://pub.dev" source: hosted - version: "3.0.3" + version: "3.0.5" leak_tracker_testing: dependency: transitive description: @@ -111,18 +111,18 @@ packages: dependency: transitive description: name: material_color_utilities - sha256: "0e0a020085b65b6083975e499759762399b4475f766c21668c4ecca34ea74e5a" + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec url: "https://pub.dev" source: hosted - version: "0.8.0" + version: "0.11.1" meta: dependency: transitive description: name: meta - sha256: "7687075e408b093f36e6bbf6c91878cc0d4cd10f409506f7bc996f68220b9136" + sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7 url: "https://pub.dev" source: hosted - version: "1.12.0" + version: "1.15.0" path: dependency: transitive description: @@ -202,10 +202,10 @@ packages: dependency: transitive description: name: test_api - sha256: "9955ae474176f7ac8ee4e989dadfb411a58c30415bcfb648fa04b2b8a03afa7f" + sha256: "5b8a98dafc4d5c4c9c72d8b31ab2b23fc13422348d2997120294d3bac86b4ddb" url: "https://pub.dev" source: hosted - version: "0.7.0" + version: "0.7.2" vector_math: dependency: transitive description: @@ -218,10 +218,10 @@ packages: dependency: transitive description: name: vm_service - sha256: "3923c89304b715fb1eb6423f017651664a03bf5f4b29983627c4da791f74a4ec" + sha256: "5c5f338a667b4c644744b661f309fb8080bb94b18a7e91ef1dbd343bed00ed6d" url: "https://pub.dev" source: hosted - version: "14.2.1" + version: "14.2.5" sdks: dart: ">=3.3.0 <4.0.0" flutter: ">=3.18.0-18.0.pre.54" diff --git a/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_windows_plugin.h b/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_windows_plugin.h index f975df0..35f8368 100644 --- a/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_windows_plugin.h +++ b/screen_brightness_windows/windows/include/screen_brightness_windows/screen_brightness_windows_plugin.h @@ -102,6 +102,10 @@ namespace screen_brightness [[nodiscard]] double GetScreenBrightnessPercentage(long screen_brightness) const; [[nodiscard]] long GetScreenBrightnessValueByPercentage(double percentage) const; + + void OnApplicationPause(); + + void OnApplicationResume(); }; } diff --git a/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp b/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp index d8cbf43..9925f1d 100644 --- a/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp +++ b/screen_brightness_windows/windows/src/screen_brightness_windows_plugin.cpp @@ -201,7 +201,7 @@ namespace screen_brightness void ScreenBrightnessWindowsPlugin::HandleSystemScreenBrightnessChanged(const long brightness) { - if (system_screen_brightness_changed_stream_handler_ == nullptr) + if (system_screen_brightness_changed_stream_handler_ == nullptr || brightness == -1) { return; } @@ -343,60 +343,67 @@ namespace screen_brightness std::optional ScreenBrightnessWindowsPlugin::HandleWindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - if (!is_auto_reset_) - { - return std::nullopt; - } - switch (message) { case WM_SIZE: switch (wParam) { case SIZE_MINIMIZED: - if (system_screen_brightness_ == -1) + if (!is_auto_reset_) { - break; + return std::nullopt; } - SetScreenBrightness(system_screen_brightness_); + + OnApplicationPause(); break; case SIZE_MAXIMIZED: case SIZE_RESTORED: - if (application_screen_brightness_ == -1) + if (!is_auto_reset_) { - break; + return std::nullopt; } - SetScreenBrightness(application_screen_brightness_); + + GetScreenBrightness(minimum_screen_brightness_, system_screen_brightness_, maximum_screen_brightness_); + HandleSystemScreenBrightnessChanged(system_screen_brightness_); + if (application_screen_brightness_ == -1) + { + HandleApplicationScreenBrightnessChanged(system_screen_brightness_); + } + + OnApplicationResume(); break; } break; case WM_DESTROY: - if (system_screen_brightness_ == -1) - { - break; - } - SetScreenBrightness(system_screen_brightness_); + case WM_CLOSE: + OnApplicationPause(); break; case WM_ACTIVATEAPP: + if (!is_auto_reset_) + { + return std::nullopt; + } + bool is_activate = bool(wParam); if (is_activate) { - if (application_screen_brightness_ == -1) - { - break; - } - SetScreenBrightness(application_screen_brightness_); + GetScreenBrightness(minimum_screen_brightness_, system_screen_brightness_, maximum_screen_brightness_); + HandleSystemScreenBrightnessChanged(system_screen_brightness_); + if (application_screen_brightness_ == -1) + { + HandleApplicationScreenBrightnessChanged(system_screen_brightness_); + } + + OnApplicationResume(); break; } - - if (application_screen_brightness_ == -1) + else { - break; + OnApplicationPause(); } - SetScreenBrightness(system_screen_brightness_); break; } @@ -443,6 +450,11 @@ namespace screen_brightness void ScreenBrightnessWindowsPlugin::SetScreenBrightness(const long screen_brightness) { + if (screen_brightness < 0) + { + return; + } + DWORD physical_monitor_array_size = 0; HMONITOR monitor_handler = MonitorFromWindow(window_handler_, MONITOR_DEFAULTTOPRIMARY); @@ -487,6 +499,24 @@ namespace screen_brightness { return static_cast((percentage * (maximum_screen_brightness_ - minimum_screen_brightness_)) + minimum_screen_brightness_); } + + void ScreenBrightnessWindowsPlugin::OnApplicationPause() { + if (system_screen_brightness_ == -1) + { + return; + } + + SetScreenBrightness(system_screen_brightness_); + } + + void ScreenBrightnessWindowsPlugin::OnApplicationResume() { + if (application_screen_brightness_ == -1) + { + return; + } + + SetScreenBrightness(application_screen_brightness_); + } } void ScreenBrightnessWindowsPluginRegisterWithRegistrar(FlutterDesktopPluginRegistrarRef registrar) From 72e24c610cf2b99332a4dc5973e939ebdcd72436 Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Sat, 5 Oct 2024 15:34:02 +0800 Subject: [PATCH 16/22] fix(screen-brightness-android): change screen_brightness_platform_interface using non local version --- screen_brightness_android/pubspec.yaml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/screen_brightness_android/pubspec.yaml b/screen_brightness_android/pubspec.yaml index b7c28dd..ff5b3af 100644 --- a/screen_brightness_android/pubspec.yaml +++ b/screen_brightness_android/pubspec.yaml @@ -17,8 +17,7 @@ environment: dependencies: flutter: sdk: flutter - screen_brightness_platform_interface: - path: ../screen_brightness_platform_interface/ + screen_brightness_platform_interface: ">=1.0.0 <2.0.0" dev_dependencies: flutter_test: From bf6d64d6ea30f909249151227ffa285618c6b81c Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Sat, 5 Oct 2024 15:34:42 +0800 Subject: [PATCH 17/22] chore(screen-brightness-android): updated example pubspec.lock --- .../example/pubspec.lock | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/screen_brightness_android/example/pubspec.lock b/screen_brightness_android/example/pubspec.lock index 5a4bbad..fbf47ac 100644 --- a/screen_brightness_android/example/pubspec.lock +++ b/screen_brightness_android/example/pubspec.lock @@ -71,18 +71,18 @@ packages: dependency: transitive description: name: leak_tracker - sha256: "7f0df31977cb2c0b88585095d168e689669a2cc9b97c309665e3386f3e9d341a" + sha256: "3f87a60e8c63aecc975dda1ceedbc8f24de75f09e4856ea27daf8958f2f0ce05" url: "https://pub.dev" source: hosted - version: "10.0.4" + version: "10.0.5" leak_tracker_flutter_testing: dependency: transitive description: name: leak_tracker_flutter_testing - sha256: "06e98f569d004c1315b991ded39924b21af84cf14cc94791b8aea337d25b57f8" + sha256: "932549fb305594d82d7183ecd9fa93463e9914e1b67cacc34bc40906594a1806" url: "https://pub.dev" source: hosted - version: "3.0.3" + version: "3.0.5" leak_tracker_testing: dependency: transitive description: @@ -111,18 +111,18 @@ packages: dependency: transitive description: name: material_color_utilities - sha256: "0e0a020085b65b6083975e499759762399b4475f766c21668c4ecca34ea74e5a" + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec url: "https://pub.dev" source: hosted - version: "0.8.0" + version: "0.11.1" meta: dependency: transitive description: name: meta - sha256: "7687075e408b093f36e6bbf6c91878cc0d4cd10f409506f7bc996f68220b9136" + sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7 url: "https://pub.dev" source: hosted - version: "1.12.0" + version: "1.15.0" path: dependency: transitive description: @@ -202,10 +202,10 @@ packages: dependency: transitive description: name: test_api - sha256: "9955ae474176f7ac8ee4e989dadfb411a58c30415bcfb648fa04b2b8a03afa7f" + sha256: "5b8a98dafc4d5c4c9c72d8b31ab2b23fc13422348d2997120294d3bac86b4ddb" url: "https://pub.dev" source: hosted - version: "0.7.0" + version: "0.7.2" vector_math: dependency: transitive description: @@ -218,10 +218,10 @@ packages: dependency: transitive description: name: vm_service - sha256: "3923c89304b715fb1eb6423f017651664a03bf5f4b29983627c4da791f74a4ec" + sha256: "5c5f338a667b4c644744b661f309fb8080bb94b18a7e91ef1dbd343bed00ed6d" url: "https://pub.dev" source: hosted - version: "14.2.1" + version: "14.2.5" sdks: dart: ">=3.3.0 <4.0.0" flutter: ">=3.18.0-18.0.pre.54" From 17d280808e6d168c068b69dfe6a51c64c118d326 Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Sat, 5 Oct 2024 20:30:18 +0800 Subject: [PATCH 18/22] chore: removed local dependencies override --- screen_brightness/pubspec.yaml | 22 +++++++++++----------- screen_brightness_android/pubspec.yaml | 6 +++--- screen_brightness_ios/pubspec.yaml | 6 +++--- screen_brightness_macos/pubspec.yaml | 6 +++--- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/screen_brightness/pubspec.yaml b/screen_brightness/pubspec.yaml index 6c070fc..d3f90ca 100644 --- a/screen_brightness/pubspec.yaml +++ b/screen_brightness/pubspec.yaml @@ -30,17 +30,17 @@ dev_dependencies: plugin_platform_interface: ">=2.0.0 <3.0.0" async: ">=2.0.0 <3.0.0" -dependency_overrides: - screen_brightness_platform_interface: - path: ../screen_brightness_platform_interface/ - screen_brightness_android: - path: ../screen_brightness_android - screen_brightness_ios: - path: ../screen_brightness_ios - screen_brightness_macos: - path: ../screen_brightness_macos - screen_brightness_windows: - path: ../screen_brightness_windows +#dependency_overrides: +# screen_brightness_platform_interface: +# path: ../screen_brightness_platform_interface/ +# screen_brightness_android: +# path: ../screen_brightness_android +# screen_brightness_ios: +# path: ../screen_brightness_ios +# screen_brightness_macos: +# path: ../screen_brightness_macos +# screen_brightness_windows: +# path: ../screen_brightness_windows # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/screen_brightness_android/pubspec.yaml b/screen_brightness_android/pubspec.yaml index ff5b3af..f65dcda 100644 --- a/screen_brightness_android/pubspec.yaml +++ b/screen_brightness_android/pubspec.yaml @@ -24,9 +24,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -dependency_overrides: - screen_brightness_platform_interface: - path: ../screen_brightness_platform_interface/ +#dependency_overrides: +# screen_brightness_platform_interface: +# path: ../screen_brightness_platform_interface/ flutter: plugin: diff --git a/screen_brightness_ios/pubspec.yaml b/screen_brightness_ios/pubspec.yaml index d361fae..5670cf3 100644 --- a/screen_brightness_ios/pubspec.yaml +++ b/screen_brightness_ios/pubspec.yaml @@ -24,9 +24,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -dependency_overrides: - screen_brightness_platform_interface: - path: ../screen_brightness_platform_interface/ +#dependency_overrides: +# screen_brightness_platform_interface: +# path: ../screen_brightness_platform_interface/ flutter: plugin: diff --git a/screen_brightness_macos/pubspec.yaml b/screen_brightness_macos/pubspec.yaml index 02722c1..6701f2b 100644 --- a/screen_brightness_macos/pubspec.yaml +++ b/screen_brightness_macos/pubspec.yaml @@ -24,9 +24,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -dependency_overrides: - screen_brightness_platform_interface: - path: ../screen_brightness_platform_interface/ +#dependency_overrides: +# screen_brightness_platform_interface: +# path: ../screen_brightness_platform_interface/ flutter: plugin: From cb068f6af7cb9d4cee63feffdc23e52df3688a0c Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Sat, 12 Oct 2024 00:48:26 +0800 Subject: [PATCH 19/22] feat: added old method deprecation for easy migration --- .idea/vcs.xml | 6 -- screen_brightness/lib/screen_brightness.dart | 95 +++++++++++++++++++- 2 files changed, 91 insertions(+), 10 deletions(-) diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 7ddfc9e..35eb1dd 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -1,11 +1,5 @@ - - - - - - diff --git a/screen_brightness/lib/screen_brightness.dart b/screen_brightness/lib/screen_brightness.dart index d8d15dd..4f0024c 100644 --- a/screen_brightness/lib/screen_brightness.dart +++ b/screen_brightness/lib/screen_brightness.dart @@ -37,7 +37,7 @@ class ScreenBrightness { /// after calling [resetApplicationScreenBrightness] /// /// Platform difference: - /// (macOS)(Windows): return initial brightness + /// (iOS)(macOS)(Windows): return initial brightness /// /// When [_channel.invokeMethod] fails to get system screen brightness, it /// throws [PlatformException] with code and message: @@ -74,6 +74,32 @@ class ScreenBrightness { Stream get onSystemScreenBrightnessChanged => _platform.onSystemScreenBrightnessChanged; + /// Returns application screen brightness value. + /// + /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will + /// be throw. + /// + /// This parameter is useful for user to get application screen brightness + /// value after calling [setApplicationScreenBrightness] + /// + /// Calling this method after calling [resetApplicationScreenBrightness] may return wrong + /// value in iOS because UIScreen.main.brightness returns old brightness value + /// + /// When [_channel.invokeMethod] fails to get application screen brightness, + /// it throws [PlatformException] with code and message: + /// + /// Code: -9, Message: value returns null + /// + /// (Android only) Code: -10, Message: Unexpected error on activity binding + /// Unexpected error when getting activity, activity may be null + /// + /// (Android only) (macOS only) Code: -11, Message: Could not found system + /// screen brightness value + /// Unexpected error when getting brightness from Setting using + /// (Android) Settings.System.SCREEN_BRIGHTNESS + @Deprecated('refactored to application (will be remove after version 2.1.0)') + Future get current => application; + /// Returns application screen brightness value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will @@ -99,6 +125,29 @@ class ScreenBrightness { /// (Android) Settings.System.SCREEN_BRIGHTNESS Future get application => _platform.application; + /// Set application screen brightness with double value. + /// + /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will + /// be throw. + /// + /// This method is useful for user to change application screen brightness. + /// + /// When [_channel.invokeMethod] fails to set application screen brightness, + /// it throws [PlatformException] with code and message: + /// + /// Code: -1, Message: Unable to change application screen brightness + /// Failed to set brightness + /// + /// Code: -2, Message: Unexpected error on null brightness + /// Cannot read parameter from method channel map, or parameter is null + /// + /// (Android only) Code: -10, Message: Unexpected error on activity binding + /// Unexpected error when getting activity, activity may be null + @Deprecated( + 'refactored to setApplicationScreenBrightness (will be remove after version 2.1.0)') + Future setScreenBrightness(double brightness) => + setApplicationScreenBrightness(brightness); + /// Set application screen brightness with double value. /// /// The value should be within 0.0 - 1.0. Otherwise, [RangeError.range] will @@ -120,6 +169,28 @@ class ScreenBrightness { Future setApplicationScreenBrightness(double brightness) => _platform.setApplicationScreenBrightness(brightness); + /// Reset application screen brightness with (Android) -1 or (iOS)system + /// brightness value. + /// + /// This method is useful for user to reset application screen brightness + /// when user leave the page which has change the application screen + /// brightness value. + /// + /// When [_channel.invokeMethod] fails to get application screen brightness, + /// it throws [PlatformException] with code and message: + /// + /// Code: -1, Message: Unable to reset application screen brightness + /// Failed to reset application screen brightness + /// + /// Code: -2, Message: Unexpected error on null brightness + /// System brightness in plugin is null + /// + /// (Android only) Code: -10, Message: Unexpected error on activity binding + /// Unexpected error when getting activity, activity may be null + @Deprecated( + 'refactored to resetScreenBrightness (will be remove after version 2.1.0)') + Future resetScreenBrightness() => resetApplicationScreenBrightness(); + /// Reset application screen brightness with (Android) -1 or (iOS)system /// brightness value. /// @@ -141,9 +212,15 @@ class ScreenBrightness { Future resetApplicationScreenBrightness() => _platform.resetApplicationScreenBrightness(); - /// This stream is useful for user to listen to brightness changes. - @Deprecated('Use onApplicationScreenBrightnessChanged instead, reason rename') - Stream get onApplicationBrightnessChanged => + /// Returns stream with application screen brightness changes including + /// [ScreenBrightness.setApplicationScreenBrightness], + /// [ScreenBrightness.resetApplicationScreenBrightness], system control center + /// or system setting. + /// + /// This stream is useful for user to listen to application brightness changes. + @Deprecated( + 'refactored to onApplicationScreenBrightnessChanged (will be remove after version 2.1.0)') + Stream get onCurrentBrightnessChanged => onApplicationScreenBrightnessChanged; /// Returns stream with application screen brightness changes including @@ -155,6 +232,16 @@ class ScreenBrightness { Stream get onApplicationScreenBrightnessChanged => _platform.onApplicationScreenBrightnessChanged; + /// Returns boolean to identify application screen brightness has changed by + /// this plugin. + /// + /// e.g + /// [ScreenBrightness.setApplicationScreenBrightness] will make this true + /// [ScreenBrightness.resetApplicationScreenBrightness] will make this false + @Deprecated( + 'refactored to hasApplicationScreenBrightnessChanged (will be remove after version 2.1.0)') + Future get hasChanged => hasApplicationScreenBrightnessChanged; + /// Returns boolean to identify application screen brightness has changed by /// this plugin. /// From 30846bc2d720ce5afad10af7a1fa6002f4ad958d Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Sat, 12 Oct 2024 00:54:43 +0800 Subject: [PATCH 20/22] fix: uncomment dependency overrides for passing tests --- screen_brightness/pubspec.yaml | 22 +++++++++++----------- screen_brightness_android/pubspec.yaml | 6 +++--- screen_brightness_ios/pubspec.yaml | 6 +++--- screen_brightness_macos/pubspec.yaml | 6 +++--- screen_brightness_windows/pubspec.yaml | 6 +++--- 5 files changed, 23 insertions(+), 23 deletions(-) diff --git a/screen_brightness/pubspec.yaml b/screen_brightness/pubspec.yaml index d3f90ca..6c070fc 100644 --- a/screen_brightness/pubspec.yaml +++ b/screen_brightness/pubspec.yaml @@ -30,17 +30,17 @@ dev_dependencies: plugin_platform_interface: ">=2.0.0 <3.0.0" async: ">=2.0.0 <3.0.0" -#dependency_overrides: -# screen_brightness_platform_interface: -# path: ../screen_brightness_platform_interface/ -# screen_brightness_android: -# path: ../screen_brightness_android -# screen_brightness_ios: -# path: ../screen_brightness_ios -# screen_brightness_macos: -# path: ../screen_brightness_macos -# screen_brightness_windows: -# path: ../screen_brightness_windows +dependency_overrides: + screen_brightness_platform_interface: + path: ../screen_brightness_platform_interface/ + screen_brightness_android: + path: ../screen_brightness_android + screen_brightness_ios: + path: ../screen_brightness_ios + screen_brightness_macos: + path: ../screen_brightness_macos + screen_brightness_windows: + path: ../screen_brightness_windows # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/screen_brightness_android/pubspec.yaml b/screen_brightness_android/pubspec.yaml index f65dcda..ff5b3af 100644 --- a/screen_brightness_android/pubspec.yaml +++ b/screen_brightness_android/pubspec.yaml @@ -24,9 +24,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -#dependency_overrides: -# screen_brightness_platform_interface: -# path: ../screen_brightness_platform_interface/ +dependency_overrides: + screen_brightness_platform_interface: + path: ../screen_brightness_platform_interface/ flutter: plugin: diff --git a/screen_brightness_ios/pubspec.yaml b/screen_brightness_ios/pubspec.yaml index 5670cf3..d361fae 100644 --- a/screen_brightness_ios/pubspec.yaml +++ b/screen_brightness_ios/pubspec.yaml @@ -24,9 +24,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -#dependency_overrides: -# screen_brightness_platform_interface: -# path: ../screen_brightness_platform_interface/ +dependency_overrides: + screen_brightness_platform_interface: + path: ../screen_brightness_platform_interface/ flutter: plugin: diff --git a/screen_brightness_macos/pubspec.yaml b/screen_brightness_macos/pubspec.yaml index 6701f2b..02722c1 100644 --- a/screen_brightness_macos/pubspec.yaml +++ b/screen_brightness_macos/pubspec.yaml @@ -24,9 +24,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -#dependency_overrides: -# screen_brightness_platform_interface: -# path: ../screen_brightness_platform_interface/ +dependency_overrides: + screen_brightness_platform_interface: + path: ../screen_brightness_platform_interface/ flutter: plugin: diff --git a/screen_brightness_windows/pubspec.yaml b/screen_brightness_windows/pubspec.yaml index 2395651..cbe4825 100644 --- a/screen_brightness_windows/pubspec.yaml +++ b/screen_brightness_windows/pubspec.yaml @@ -24,9 +24,9 @@ dev_dependencies: sdk: flutter flutter_lints: ">=3.0.0 <4.0.0" -#dependency_overrides: -# screen_brightness_platform_interface: -# path: ../screen_brightness_platform_interface/ +dependency_overrides: + screen_brightness_platform_interface: + path: ../screen_brightness_platform_interface/ flutter: plugin: From 7826dc6a712387d7222428204f4a2006f5a31b49 Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Sat, 12 Oct 2024 16:35:49 +0800 Subject: [PATCH 21/22] test: updated test case cover deprecated methods --- .../test/screen_brightness_test.dart | 81 ++++++++++++++++--- 1 file changed, 68 insertions(+), 13 deletions(-) diff --git a/screen_brightness/test/screen_brightness_test.dart b/screen_brightness/test/screen_brightness_test.dart index 3f3c5ea..88547ca 100644 --- a/screen_brightness/test/screen_brightness_test.dart +++ b/screen_brightness/test/screen_brightness_test.dart @@ -8,7 +8,7 @@ import 'package:screen_brightness_platform_interface/screen_brightness_platform_ const double systemBrightness = 0.5; -late StreamController applicationScreenBrightnessController; +late StreamController screenBrightnessController; late StreamController systemScreenBrightnessController; @@ -46,14 +46,14 @@ class MockScreenBrightnessPlatform _changedBrightness = null; } - @override - Stream get onApplicationScreenBrightnessChanged => - applicationScreenBrightnessController.stream; - @override Stream get onSystemScreenBrightnessChanged => systemScreenBrightnessController.stream; + @override + Stream get onApplicationScreenBrightnessChanged => + screenBrightnessController.stream; + @override Future get hasApplicationScreenBrightnessChanged async => _changedBrightness != null; @@ -95,44 +95,86 @@ void main() { expect(await screenBrightness.system, targetBrightness); }); + test('get current screen brightness', () async { + expect(await screenBrightness.current, systemBrightness); + }); + test('get application screen brightness', () async { expect(await screenBrightness.application, systemBrightness); }); + test('set screen brightness with valid number', () async { + const targetBrightness = 0.1; + await screenBrightness.setScreenBrightness(targetBrightness); + expect(await screenBrightness.current, targetBrightness); + }); + test('set application screen brightness with valid number', () async { const targetBrightness = 0.1; await screenBrightness.setApplicationScreenBrightness(targetBrightness); expect(await screenBrightness.application, targetBrightness); }); + test('reset screen brightness', () async { + await screenBrightness.resetScreenBrightness(); + expect(await screenBrightness.current, systemBrightness); + }); + test('reset application screen brightness', () async { await screenBrightness.resetApplicationScreenBrightness(); expect(await screenBrightness.application, systemBrightness); }); + group('on screen brightness changed stream', () { + setUp(() { + screenBrightnessController = StreamController(); + }); + + tearDown(() { + screenBrightnessController.close(); + }); + + test('on screen brightness receive values', () async { + final queue = + StreamQueue(screenBrightness.onCurrentBrightnessChanged); + + screenBrightnessController.add(0.2); + expect(await queue.next, 0.2); + + screenBrightnessController.add(systemBrightness); + expect(await queue.next, systemBrightness); + + screenBrightnessController.add(0); + expect(await queue.next, 0); + + screenBrightnessController.add(1); + expect(await queue.next, 1); + }); + }); + group('on application screen brightness changed stream', () { setUp(() { - applicationScreenBrightnessController = StreamController(); + screenBrightnessController = StreamController(); }); tearDown(() { - applicationScreenBrightnessController.close(); + screenBrightnessController.close(); }); - test('receive values', () async { + test('on application screen brightness receive values', () async { final queue = StreamQueue( screenBrightness.onApplicationScreenBrightnessChanged); - applicationScreenBrightnessController.add(0.2); + screenBrightnessController.add(0.2); expect(await queue.next, 0.2); - applicationScreenBrightnessController.add(systemBrightness); + screenBrightnessController.add(systemBrightness); expect(await queue.next, systemBrightness); - applicationScreenBrightnessController.add(0); + screenBrightnessController.add(0); expect(await queue.next, 0); - applicationScreenBrightnessController.add(1); + screenBrightnessController.add(1); expect(await queue.next, 1); }); }); @@ -146,7 +188,7 @@ void main() { systemScreenBrightnessController.close(); }); - test('receive values', () async { + test('on system screen brightness receive values', () async { final queue = StreamQueue(screenBrightness.onSystemScreenBrightnessChanged); @@ -164,6 +206,19 @@ void main() { }); }); + test('has screen brightness changed', () async { + expect(await screenBrightness.hasChanged, false); + + await screenBrightness.setScreenBrightness(0.1); + expect(await screenBrightness.hasChanged, true); + + await screenBrightness.setScreenBrightness(systemBrightness); + expect(await screenBrightness.hasChanged, true); + + await screenBrightness.resetScreenBrightness(); + expect(await screenBrightness.hasChanged, false); + }); + test('has application screen brightness changed', () async { expect(await screenBrightness.hasApplicationScreenBrightnessChanged, false); From 7ab4165471333455680615ad73b60dc35b1d5332 Mon Sep 17 00:00:00 2001 From: Jack Liu Date: Sat, 12 Oct 2024 16:40:22 +0800 Subject: [PATCH 22/22] test: ignore deprecated method warning --- screen_brightness/test/screen_brightness_test.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/screen_brightness/test/screen_brightness_test.dart b/screen_brightness/test/screen_brightness_test.dart index 88547ca..b50a23c 100644 --- a/screen_brightness/test/screen_brightness_test.dart +++ b/screen_brightness/test/screen_brightness_test.dart @@ -1,3 +1,5 @@ +// ignore_for_file: deprecated_member_use_from_same_package + import 'dart:async'; import 'package:async/async.dart';