Skip to content

Commit

Permalink
Changes based on review the code.
Browse files Browse the repository at this point in the history
Generate random color for a shortcut of the action is null.
Added missing `Platfom.isAndroid` guard in BasePage.dart.
Upstream should be a list of `Object?` and not `Object`, not every item in the list should have to return an object.
  • Loading branch information
jeroen1602 committed Mar 18, 2021
1 parent 2d62462 commit 668bceb
Show file tree
Hide file tree
Showing 9 changed files with 41 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.security.MessageDigest
import kotlin.math.floor
import kotlin.math.pow
import kotlin.math.roundToInt

Expand Down Expand Up @@ -136,48 +137,34 @@ class Shortcut {
error("Name was null or empty!")
}

// Create an intent to launch the main function with some extra data.
// Create an intent to launch the main activity with some extra data.
val intent = Intent(context, MainActivity::class.java).apply {
putExtra(TOGGLE_EXTRA, action)
setAction(Intent.ACTION_MAIN)
}

// Create the shortcut info
// Create the shortcut icon
val foreground =
context.resources.getDrawable(R.drawable.ic_launcher_foreground, context.theme)
foreground.setTint(stringToGradientColor(action!!))
foreground.setTint(stringToGradientColor(action))
val background =
context.resources.getDrawable(R.drawable.ic_launcher_background, context.theme)
background.setTint(Color.WHITE)
val adaptiveIconDrawable = AdaptiveIconDrawable(background, foreground)

val bitmap = drawableToBitmap(adaptiveIconDrawable, context)
val icon = Icon.createWithAdaptiveBitmap(bitmap)
// Create the shortcut info.
val pinShortcutInfo = ShortcutInfo.Builder(context, action)
.setShortLabel(name ?: "null")
.setLongLabel("Change ${name ?: "null"}")
.setIcon(icon)
.setIntent(intent)
.build()

// Create the PendingIntent object only if your app needs to be notified
// that the user allowed the shortcut to be pinned. Note that, if the
// pinning operation fails, your app isn't notified. We assume here that the
// app has implemented a method called createShortcutResultIntent() that
// returns a broadcast intent.
val pinnedShortcutCallbackIntent =
shortcutManager!!.createShortcutResultIntent(pinShortcutInfo)

// Configure the intent so that your app's broadcast receiver gets
// the callback successfully.For details, see PendingIntent.getBroadcast().
val successCallback = PendingIntent.getBroadcast(
context, /* request code */ 0,
pinnedShortcutCallbackIntent, /* flags */ 0
)

shortcutManager!!.requestPinShortcut(
pinShortcutInfo,
successCallback.intentSender
null
)

// TODO: handle the success callback
Expand Down Expand Up @@ -250,7 +237,7 @@ class Shortcut {
* the app theme.
*/
@ColorInt
private fun stringToGradientColor(string: String): Int {
private fun stringToGradientColor(string: String?): Int {
// Because I didn't feel like finding a gradient implementation I decide to use the included
// gradient implementation from Android.

Expand Down Expand Up @@ -279,7 +266,14 @@ class Shortcut {
canvas.drawPaint(paint)

// Pick a color from the bitmap (that now contains the gradient) based on the hash.
var hash: Int = (md5ToNumber(string) % bitmap.width).toInt()

var hash: Int = if (string != null) {
// convert the input string to an index in the gradient.
(md5ToNumber(string) % bitmap.width).toInt()
} else {
// string is null so just take a random position.
(Math.random() * (bitmap.width - 1)).toInt()
}
if (hash < 0) {
hash += bitmap.width
}
Expand Down Expand Up @@ -358,4 +352,4 @@ class Shortcut {
private data class QueData(val methodName: String, val data: Any?)
}

}
}
2 changes: 1 addition & 1 deletion lib/lighthouseProvider/devices/LighthouseV2Device.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:lighthouse_pm/lighthouseProvider/deviceExtensions/ShortcutExtension.dart';

import '../../bloc.dart';
import '../LighthousePowerState.dart';
Expand All @@ -15,6 +14,7 @@ import '../deviceExtensions/DeviceExtension.dart';
import '../deviceExtensions/DeviceWithExtensions.dart';
import '../deviceExtensions/IdentifyDeviceExtension.dart';
import '../deviceExtensions/OnExtension.dart';
import '../deviceExtensions/ShortcutExtension.dart';
import '../deviceExtensions/SleepExtension.dart';
import '../deviceExtensions/StandbyExtension.dart';
import 'BLEDevice.dart';
Expand Down
9 changes: 2 additions & 7 deletions lib/lighthouseProvider/widgets/LighthouseMetadataPage.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import 'package:lighthouse_pm/data/Database.dart';
import 'package:lighthouse_pm/lighthouseProvider/LighthouseDevice.dart';
import 'package:lighthouse_pm/lighthouseProvider/deviceExtensions/DeviceWithExtensions.dart';
import 'package:lighthouse_pm/widgets/NicknameAlertWidget.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';
import 'package:toast/toast.dart';
import 'package:vibration/vibration.dart';
Expand All @@ -25,21 +24,17 @@ class LighthouseMetadataPage extends StatefulWidget {
}

class LighthouseMetadataState extends State<LighthouseMetadataPage> {

LighthousePMBloc get _blocWithoutListen =>
Provider.of<LighthousePMBloc>(context, listen: false);

Future<void> changeNicknameHandler(String? currentNickname) async {
final newNickname = await NicknameAlertWidget.showCustomDialog(context,
macAddress: widget.device.deviceIdentifier.toString(),
deviceName: widget.device.name,
nickname: currentNickname);
if (newNickname != null) {
if (newNickname.nickname == null) {
await _blocWithoutListen.nicknames
await blocWithoutListen.nicknames
.deleteNicknames([newNickname.macAddress]);
} else {
await _blocWithoutListen.nicknames
await blocWithoutListen.nicknames
.insertNickname(newNickname.toNickname()!);
}
}
Expand Down
8 changes: 5 additions & 3 deletions lib/pages/BasePage.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,11 @@ class _ShortcutLaunchHandleState extends State<_ShortcutLaunchHandleWidget> {
void initState() {
super.initState();
// Notify the Shortcut handler native code that the app is ready for data.
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
AndroidLauncherShortcut.instance.readyForData();
});
if (Platform.isAndroid) {
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
AndroidLauncherShortcut.instance.readyForData();
});
}
}

@override
Expand Down
2 changes: 1 addition & 1 deletion lib/pages/shortcut/states/GetDeviceStateStream.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class GetDeviceStateStream extends WaterfallStreamWidget<LighthousePowerState>

GetDeviceStateStream(this.settingsIndex,
{Key? key,
required List<Object> upStream,
required List<Object?> upStream,
List<DownStreamBuilder> downStreamBuilders = const []})
: super(
key: key,
Expand Down
7 changes: 4 additions & 3 deletions lib/pages/shortcut/states/GetDeviceStream.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class GetDeviceStream extends WaterfallStreamWidget<LighthouseDevice>
final int settingsIndex;

GetDeviceStream(this.macAddress, this.settingsIndex,
{required List<Object> upStream,
{required List<Object?> upStream,
required List<DownStreamBuilder> downStreamBuilders})
: super(upStream: upStream, downStreamBuilders: downStreamBuilders);

Expand Down Expand Up @@ -82,8 +82,9 @@ class GetDeviceStream extends WaterfallStreamWidget<LighthouseDevice>
builder: (BuildContext context,
AsyncSnapshot<WithTimeout<LighthouseDevice?>> snapshot) {
if (snapshot.requireData.timeoutExpired) {
stopScan();
closeCurrentRouteWithWait(context);
stopScan().then((_) {
closeCurrentRouteWithWait(context);
});
return Text('Scan timeout reached!');
}
final data = snapshot.requireData.data;
Expand Down
2 changes: 1 addition & 1 deletion lib/pages/shortcut/states/PermissionStream.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class PermissionsStream extends WaterfallStreamWidget<PermissionStatus>
with ScanningMixin, CloseCurrentRouteMixin {
PermissionsStream(
{Key? key,
required List<Object> upStream,
required List<Object?> upStream,
List<DownStreamBuilder> downStreamBuilders = const []})
: super(
key: key,
Expand Down
8 changes: 6 additions & 2 deletions lib/pages/shortcut/states/SettingsStream.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:lighthouse_pm/bloc.dart';
import 'package:lighthouse_pm/data/local/MainPageSettings.dart';
Expand All @@ -7,7 +8,7 @@ class SettingsStream extends WaterfallStreamWidget<MainPageSettings>
with WithBlocStateless {
SettingsStream(
{Key? key,
required List<Object> upStream,
required List<Object?> upStream,
List<DownStreamBuilder> downStreamBuilders = const []})
: super(
key: key,
Expand All @@ -19,7 +20,10 @@ class SettingsStream extends WaterfallStreamWidget<MainPageSettings>
return MainPageSettings.mainPageSettingsStreamBuilder(
bloc: blocWithoutListen(context),
builder: (context, settings) {
return getNextStreamDown(context, settings!);
if (settings == null) {
return CircularProgressIndicator();
}
return getNextStreamDown(context, settings);
});
}

Expand Down
12 changes: 5 additions & 7 deletions lib/widgets/WaterfallWidget.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,25 @@ import 'package:flutter/widgets.dart';

typedef Name = Widget Function(BuildContext);
typedef DownStreamBuilder<T> = WaterfallStreamWidget<T> Function(
BuildContext, List<Object> upStream, List<Object> downStreamBuilders);
BuildContext, List<Object?> upStream, List<Object> downStreamBuilders);

abstract class WaterfallStreamWidget<T> extends StatelessWidget {
final List<Object> upStream;
final List<Object?> upStream;
final List<DownStreamBuilder> downStreamBuilders;

WaterfallStreamWidget(
{Key? key, required this.upStream, this.downStreamBuilders = const []})
: super(key: key);

WaterfallStreamWidget getNextStreamDown(
BuildContext context, T upstreamData) {
BuildContext context, T? upstreamData) {
if (downStreamBuilders.isEmpty) {
throw Exception("Down stream builders shouldn't be empty if you want to "
"create an item down stream!");
}
final localUpStream = <Object>[];
final localUpStream = <Object?>[];
localUpStream.addAll(upStream);
if (upstreamData != null) {
localUpStream.add(upstreamData);
}
localUpStream.add(upstreamData);

return downStreamBuilders[0](
context, localUpStream, downStreamBuilders.sublist(1));
Expand Down

0 comments on commit 668bceb

Please sign in to comment.