From a2f85ef47529dcdcb6aec72965c1236c3fe85b5f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Mar 2023 12:05:54 -0500 Subject: [PATCH] Bump org.jlleitschuh.gradle.ktlint from 11.1.0 to 11.2.0 (#3334) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Bump org.jlleitschuh.gradle.ktlint from 11.1.0 to 11.2.0 Bumps org.jlleitschuh.gradle.ktlint from 11.1.0 to 11.2.0. --- updated-dependencies: - dependency-name: org.jlleitschuh.gradle.ktlint dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * gradlew ktlintFormat * Rename packages with underscores > Task :app:ktlintMainSourceSetFormat FAILED home-assistant-android\app\src\main\java\io\homeassistant\companion\android\widgets\media_player_controls\MediaPlayerControlsWidget.kt:1:1 Package name must not contain underscore (cannot be auto-corrected) home-assistant-android\app\src\main\java\io\homeassistant\companion\android\widgets\media_player_controls\MediaPlayerControlsWidgetConfigureActivity.kt:1:1 Package name must not contain underscore (cannot be auto-corrected) Rename: media_player_controls to mediaplayer > Task :wear:ktlintMainSourceSetFormat FAILED home-assistant-android\wear\src\main\java\io\homeassistant\companion\android\onboarding\manual_setup\ManualSetupActivity.kt:1:1 Package name must not contain underscore (cannot be auto-corrected) home-assistant-android\wear\src\main\java\io\homeassistant\companion\android\onboarding\manual_setup\ManualSetupModule.kt:1:1 Package name must not contain underscore (cannot be auto-corrected) home-assistant-android\wear\src\main\java\io\homeassistant\companion\android\onboarding\manual_setup\ManualSetupPresenter.kt:1:1 Package name must not contain underscore (cannot be auto-corrected) home-assistant-android\wear\src\main\java\io\homeassistant\companion\android\onboarding\manual_setup\ManualSetupPresenterImpl.kt:1:1 Package name must not contain underscore (cannot be auto-corrected) home-assistant-android\wear\src\main\java\io\homeassistant\companion\android\onboarding\manual_setup\ManualSetupView.kt:1:1 Package name must not contain underscore (cannot be auto-corrected) Rename: manual_setup to manual --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Joris Pelgröm --- .../companion/android/CrashHandling.kt | 6 +- .../location/HighAccuracyLocationService.kt | 1 - .../matter/MatterCommissioningViewModel.kt | 14 +- .../android/sensors/ActivitySensorManager.kt | 5 +- .../sensors/AndroidAutoSensorManager.kt | 7 +- .../android/sensors/LocationSensorManager.kt | 51 ++++-- .../settings/wear/SettingsWearActivity.kt | 4 - .../settings/wear/SettingsWearDetection.kt | 2 +- .../settings/wear/SettingsWearViewModel.kt | 12 +- .../wear/views/SettingsWearMainView.kt | 3 +- .../vehicle/EntityGridVehicleScreen.kt | 2 +- .../android/vehicle/HaCarAppService.kt | 4 +- .../android/vehicle/MainVehicleScreen.kt | 4 +- .../android/vehicle/MapVehicleScreen.kt | 2 +- app/src/main/AndroidManifest.xml | 4 +- .../android/HomeAssistantApplication.kt | 5 +- .../android/authenticator/Authenticator.kt | 8 +- .../android/controls/CameraControl.kt | 4 +- .../android/controls/ClimateControl.kt | 11 +- .../android/controls/CoverControl.kt | 5 +- .../controls/HaControlsProviderService.kt | 33 ++-- .../android/controls/LightControl.kt | 5 +- .../android/controls/VacuumControl.kt | 11 +- .../android/launch/LaunchActivity.kt | 3 +- .../companion/android/nfc/NFCUtil.kt | 6 +- .../companion/android/nfc/NfcSetupActivity.kt | 3 +- .../android/nfc/TagReaderActivity.kt | 7 +- .../android/nfc/views/NfcNavigationView.kt | 11 +- .../android/nfc/views/NfcWelcomeView.kt | 2 +- .../android/nfc/views/NfcWriteView.kt | 9 +- .../android/notifications/MessagingManager.kt | 165 +++++++++++------- .../NotificationActionReceiver.kt | 1 - .../NotificationDeleteReceiver.kt | 1 - .../android/onboarding/OnboardingActivity.kt | 4 +- .../authentication/AuthenticationFragment.kt | 13 +- .../discovery/HomeAssistantSearcher.kt | 6 +- .../MobileAppIntegrationFragment.kt | 1 - .../onboarding/manual/ManualSetupView.kt | 1 - .../NotificationPermissionFragment.kt | 7 +- .../companion/android/qs/Tile10Service.kt | 5 +- .../companion/android/qs/Tile11Service.kt | 5 +- .../companion/android/qs/Tile12Service.kt | 5 +- .../companion/android/qs/Tile13Service.kt | 5 +- .../companion/android/qs/Tile14Service.kt | 5 +- .../companion/android/qs/Tile15Service.kt | 5 +- .../companion/android/qs/Tile16Service.kt | 5 +- .../companion/android/qs/Tile17Service.kt | 5 +- .../companion/android/qs/Tile18Service.kt | 5 +- .../companion/android/qs/Tile19Service.kt | 5 +- .../companion/android/qs/Tile1Service.kt | 5 +- .../companion/android/qs/Tile20Service.kt | 5 +- .../companion/android/qs/Tile21Service.kt | 5 +- .../companion/android/qs/Tile22Service.kt | 5 +- .../companion/android/qs/Tile23Service.kt | 5 +- .../companion/android/qs/Tile24Service.kt | 5 +- .../companion/android/qs/Tile25Service.kt | 5 +- .../companion/android/qs/Tile26Service.kt | 5 +- .../companion/android/qs/Tile27Service.kt | 5 +- .../companion/android/qs/Tile28Service.kt | 5 +- .../companion/android/qs/Tile29Service.kt | 5 +- .../companion/android/qs/Tile2Service.kt | 5 +- .../companion/android/qs/Tile30Service.kt | 5 +- .../companion/android/qs/Tile31Service.kt | 5 +- .../companion/android/qs/Tile32Service.kt | 5 +- .../companion/android/qs/Tile33Service.kt | 5 +- .../companion/android/qs/Tile34Service.kt | 5 +- .../companion/android/qs/Tile35Service.kt | 5 +- .../companion/android/qs/Tile36Service.kt | 5 +- .../companion/android/qs/Tile37Service.kt | 5 +- .../companion/android/qs/Tile38Service.kt | 5 +- .../companion/android/qs/Tile39Service.kt | 5 +- .../companion/android/qs/Tile3Service.kt | 5 +- .../companion/android/qs/Tile40Service.kt | 5 +- .../companion/android/qs/Tile4Service.kt | 5 +- .../companion/android/qs/Tile5Service.kt | 5 +- .../companion/android/qs/Tile6Service.kt | 5 +- .../companion/android/qs/Tile7Service.kt | 5 +- .../companion/android/qs/Tile8Service.kt | 5 +- .../companion/android/qs/Tile9Service.kt | 5 +- .../companion/android/qs/TileExtensions.kt | 25 ++- .../android/sensors/DevicePolicyManager.kt | 4 +- .../sensors/DynamicColorSensorManager.kt | 6 +- .../android/sensors/LastAppSensorManager.kt | 4 +- .../sensors/NotificationSensorManager.kt | 32 ++-- .../android/sensors/QuestSensorManager.kt | 3 +- .../android/sensors/SensorReceiver.kt | 2 +- .../android/settings/SettingsActivity.kt | 15 +- .../android/settings/SettingsFragment.kt | 7 +- .../android/settings/SettingsPresenterImpl.kt | 7 +- .../settings/language/LanguagesManager.kt | 25 ++- .../android/settings/log/LogFragment.kt | 8 +- .../NotificationDetailFragment.kt | 3 +- .../NotificationHistoryFragment.kt | 6 +- .../settings/qs/ManageTilesViewModel.kt | 21 ++- .../settings/sensor/SensorDetailFragment.kt | 7 +- .../settings/sensor/SensorDetailViewModel.kt | 18 +- .../settings/sensor/views/SensorDetailView.kt | 78 ++++++--- .../settings/sensor/views/SensorListView.kt | 8 +- .../settings/server/ServerSettingsFragment.kt | 24 ++- .../shortcuts/ManageShortcutsViewModel.kt | 21 ++- .../shortcuts/views/ManageShortcutsView.kt | 42 +++-- .../android/settings/ssid/views/SsidView.kt | 32 +++- .../url/views/ExternalUrlInputView.kt | 4 +- .../android/settings/views/SettingsRow.kt | 7 +- .../widgets/views/ManageWidgetsView.kt | 14 +- .../companion/android/share/ShareActivity.kt | 5 +- .../companion/android/themes/ThemesManager.kt | 11 +- .../companion/android/util/ChangeLog.kt | 6 +- .../android/util/ForegroundServiceLauncher.kt | 15 +- .../companion/android/util/OnSwipeListener.kt | 14 +- .../android/util/compose/TransparentChip.kt | 7 +- .../android/websocket/WebsocketManager.kt | 3 +- .../android/webview/WebViewActivity.kt | 116 +++++++----- .../android/webview/WebViewPresenterImpl.kt | 15 +- .../widgets/BaseWidgetConfigureActivity.kt | 7 +- .../android/widgets/BaseWidgetProvider.kt | 5 +- .../android/widgets/button/ButtonWidget.kt | 1 - .../button/ButtonWidgetConfigureActivity.kt | 34 ++-- .../android/widgets/camera/CameraWidget.kt | 3 +- .../camera/CameraWidgetConfigureActivity.kt | 13 +- .../common/WidgetDynamicFieldAdapter.kt | 7 +- .../entity/EntityWidgetConfigureActivity.kt | 39 +++-- .../MediaPlayerControlsWidget.kt | 14 +- ...iaPlayerControlsWidgetConfigureActivity.kt | 18 +- .../widgets/template/TemplateWidget.kt | 4 +- .../TemplateWidgetConfigureActivity.kt | 33 ++-- .../xml/media_player_control_widget_info.xml | 2 +- build.gradle.kts | 2 +- .../android/common/LocalStorageImpl.kt | 4 +- .../common/bluetooth/BluetoothUtils.kt | 1 - .../common/bluetooth/ble/IBeaconMonitor.kt | 7 +- .../bluetooth/ble/TransmitterManager.kt | 6 +- .../data/authentication/SessionState.kt | 2 +- .../android/common/data/integration/Entity.kt | 26 +-- .../impl/IntegrationRepositoryImpl.kt | 114 ++++++++---- .../common/data/servers/ServerManagerImpl.kt | 7 +- .../websocket/impl/WebSocketRepositoryImpl.kt | 18 +- .../impl/entities/CompressedEntity.kt | 14 +- .../android/common/data/wifi/WifiHelper.kt | 1 + .../common/notifications/DeviceCommands.kt | 17 +- .../notifications/NotificationFunctions.kt | 16 +- .../common/sensors/AppSensorManagerBase.kt | 43 +++-- .../common/sensors/AudioSensorManager.kt | 67 ++++--- .../common/sensors/BatterySensorManager.kt | 21 ++- .../common/sensors/BluetoothSensorManager.kt | 30 ++-- .../common/sensors/DNDSensorManager.kt | 7 +- .../common/sensors/DisplaySensorManager.kt | 6 +- .../common/sensors/KeyguardSensorManager.kt | 22 +-- .../common/sensors/LastRebootSensorManager.kt | 6 +- .../common/sensors/LastUpdateManager.kt | 7 +- .../common/sensors/LightSensorManager.kt | 3 +- .../common/sensors/MobileDataManager.kt | 13 +- .../common/sensors/NetworkSensorManager.kt | 37 ++-- .../common/sensors/NextAlarmManager.kt | 7 +- .../common/sensors/PhoneStateSensorManager.kt | 12 +- .../common/sensors/PowerSensorManager.kt | 12 +- .../common/sensors/PressureSensorManager.kt | 3 +- .../common/sensors/ProximitySensorManager.kt | 3 +- .../android/common/sensors/SensorManager.kt | 13 +- .../common/sensors/SensorReceiverBase.kt | 21 ++- .../common/sensors/SensorWorkerBase.kt | 4 +- .../common/sensors/StepsSensorManager.kt | 3 +- .../common/sensors/StorageSensorManager.kt | 6 +- .../android/common/sensors/TimeZoneManager.kt | 4 +- .../common/sensors/TrafficStatsManager.kt | 23 +-- .../common/util/DisabledLocationHandler.kt | 14 +- .../util/LocationPermissionInfoHandler.kt | 4 +- .../util/NotificationManagerExtensions.kt | 39 +++-- .../android/common/util/TextToSpeech.kt | 15 +- .../companion/android/database/AppDatabase.kt | 18 +- .../android/database/sensor/SensorSetting.kt | 4 +- .../settings/SensorUpdateFrequencySetting.kt | 1 + .../database/settings/WebsocketSetting.kt | 1 + .../database/widget/ThemeableWidgetEntity.kt | 1 + .../companion/android/util/UrlUtil.kt | 26 +-- wear/src/main/AndroidManifest.xml | 2 +- .../complications/AssistDataSourceService.kt | 3 +- .../EntityStateDataSourceService.kt | 10 +- .../views/ComplicationConfigMainView.kt | 5 +- .../conversation/ConversationViewModel.kt | 7 +- .../conversation/views/ConversationView.kt | 21 ++- .../companion/android/home/HomeActivity.kt | 3 +- .../android/home/HomePresenterImpl.kt | 5 +- .../companion/android/home/MainViewModel.kt | 28 +-- .../android/home/views/DetailsPanelView.kt | 20 ++- .../companion/android/home/views/EntityUi.kt | 5 +- .../companion/android/home/views/HomeView.kt | 2 +- .../companion/android/home/views/MainView.kt | 13 +- .../android/home/views/SensorManagerUi.kt | 7 +- .../companion/android/home/views/SensorUi.kt | 20 ++- .../android/home/views/SensorsView.kt | 3 +- .../android/home/views/SetFavoriteView.kt | 8 +- .../home/views/SetTileShortcutsView.kt | 13 +- .../android/home/views/SettingsView.kt | 32 ++-- .../home/views/TemplateTileSettingsView.kt | 1 - .../companion/android/home/views/TimeText.kt | 2 +- .../android/notifications/MessagingManager.kt | 3 +- .../android/onboarding/OnboardingActivity.kt | 16 +- .../ManualSetupActivity.kt | 2 +- .../ManualSetupModule.kt | 2 +- .../ManualSetupPresenter.kt | 2 +- .../ManualSetupPresenterImpl.kt | 2 +- .../ManualSetupView.kt | 2 +- .../sensors/BedtimeModeSensorManager.kt | 4 +- .../sensors/HealthServicesSensorManager.kt | 33 ++-- .../android/sensors/HeartRateSensorManager.kt | 6 +- .../android/sensors/OnBodySensorManager.kt | 3 +- .../android/sensors/SensorReceiver.kt | 5 +- .../sensors/TheaterModeSensorManager.kt | 4 +- .../android/sensors/WetModeSensorManager.kt | 3 +- .../companion/android/tiles/TemplateTile.kt | 14 +- .../android/tiles/TileActionReceiver.kt | 5 +- .../companion/android/util/CommonFunctions.kt | 6 +- .../companion/android/util/WearToggleChip.kt | 28 ++- .../android/views/ExpandableListHeader.kt | 4 +- 215 files changed, 1609 insertions(+), 914 deletions(-) rename app/src/main/java/io/homeassistant/companion/android/widgets/{media_player_controls => mediaplayer}/MediaPlayerControlsWidget.kt (98%) rename app/src/main/java/io/homeassistant/companion/android/widgets/{media_player_controls => mediaplayer}/MediaPlayerControlsWidgetConfigureActivity.kt (96%) rename wear/src/main/java/io/homeassistant/companion/android/onboarding/{manual_setup => manual}/ManualSetupActivity.kt (97%) rename wear/src/main/java/io/homeassistant/companion/android/onboarding/{manual_setup => manual}/ManualSetupModule.kt (82%) rename wear/src/main/java/io/homeassistant/companion/android/onboarding/{manual_setup => manual}/ManualSetupPresenter.kt (67%) rename wear/src/main/java/io/homeassistant/companion/android/onboarding/{manual_setup => manual}/ManualSetupPresenterImpl.kt (98%) rename wear/src/main/java/io/homeassistant/companion/android/onboarding/{manual_setup => manual}/ManualSetupView.kt (75%) diff --git a/app/src/full/java/io/homeassistant/companion/android/CrashHandling.kt b/app/src/full/java/io/homeassistant/companion/android/CrashHandling.kt index b1c5a0c19d6..0753db14023 100644 --- a/app/src/full/java/io/homeassistant/companion/android/CrashHandling.kt +++ b/app/src/full/java/io/homeassistant/companion/android/CrashHandling.kt @@ -23,8 +23,9 @@ private const val FATAL_CRASH_FILE = "/fatalcrash/last_crash" fun initCrashReporting(context: Context, enabled: Boolean) { // Don't init on debug builds or when disabled - if (!shouldEnableCrashHandling(enabled)) + if (!shouldEnableCrashHandling(enabled)) { return + } SentryAndroid.init(context) { options -> options.isEnableAutoSessionTracking = true @@ -66,8 +67,9 @@ fun initCrashReporting(context: Context, enabled: Boolean) { } suspend fun getLatestFatalCrash(context: Context, enabled: Boolean): String? = withContext(Dispatchers.IO) { - if (!shouldEnableCrashHandling(enabled)) + if (!shouldEnableCrashHandling(enabled)) { return@withContext null + } var toReturn: String? = null try { diff --git a/app/src/full/java/io/homeassistant/companion/android/location/HighAccuracyLocationService.kt b/app/src/full/java/io/homeassistant/companion/android/location/HighAccuracyLocationService.kt index 7995f0557b2..421b585a84b 100644 --- a/app/src/full/java/io/homeassistant/companion/android/location/HighAccuracyLocationService.kt +++ b/app/src/full/java/io/homeassistant/companion/android/location/HighAccuracyLocationService.kt @@ -51,7 +51,6 @@ class HighAccuracyLocationService : Service() { @Synchronized fun stopService(context: Context) { - Log.d(TAG, "Try stopping high accuracy location service...") LAUNCHER.stopService(context) } diff --git a/app/src/full/java/io/homeassistant/companion/android/matter/MatterCommissioningViewModel.kt b/app/src/full/java/io/homeassistant/companion/android/matter/MatterCommissioningViewModel.kt index 9b4a7317196..da9f0c3b05c 100644 --- a/app/src/full/java/io/homeassistant/companion/android/matter/MatterCommissioningViewModel.kt +++ b/app/src/full/java/io/homeassistant/companion/android/matter/MatterCommissioningViewModel.kt @@ -74,8 +74,11 @@ class MatterCommissioningViewModel @Inject constructor( val coreSupport = matterManager.coreSupportsCommissioning(id) step = - if (coreSupport) CommissioningFlowStep.Confirmation - else CommissioningFlowStep.NotSupported + if (coreSupport) { + CommissioningFlowStep.Confirmation + } else { + CommissioningFlowStep.NotSupported + } } } @@ -101,8 +104,11 @@ class MatterCommissioningViewModel @Inject constructor( val result = matterManager.commissionDevice(code, serverId) step = - if (result?.success == true) CommissioningFlowStep.Success - else CommissioningFlowStep.Failure(result?.errorCode) + if (result?.success == true) { + CommissioningFlowStep.Success + } else { + CommissioningFlowStep.Failure(result?.errorCode) + } } } } diff --git a/app/src/full/java/io/homeassistant/companion/android/sensors/ActivitySensorManager.kt b/app/src/full/java/io/homeassistant/companion/android/sensors/ActivitySensorManager.kt index f76970d766e..476ef6c653f 100644 --- a/app/src/full/java/io/homeassistant/companion/android/sensors/ActivitySensorManager.kt +++ b/app/src/full/java/io/homeassistant/companion/android/sensors/ActivitySensorManager.kt @@ -64,7 +64,6 @@ class ActivitySensorManager : BroadcastReceiver(), SensorManager { } override fun onReceive(context: Context, intent: Intent) { - when (intent.action) { ACTION_UPDATE_ACTIVITY -> handleActivityUpdate(intent, context) ACTION_SLEEP_ACTIVITY -> handleSleepUpdate(intent, context) @@ -100,8 +99,9 @@ class ActivitySensorManager : BroadcastReceiver(), SensorManager { val result = ActivityRecognitionResult.extractResult(intent) var probActivity = result?.let { typeToString(it.mostProbableActivity) } - if (probActivity == "on_foot") + if (probActivity == "on_foot") { probActivity = result?.let { getSubActivity(it) } + } if (probActivity != null && result != null) { onSensorUpdated( @@ -274,7 +274,6 @@ class ActivitySensorManager : BroadcastReceiver(), SensorManager { } private fun getSensorIcon(activity: String): String { - return when (activity) { "in_vehicle" -> "mdi:car" "on_bicycle" -> "mdi:bike" diff --git a/app/src/full/java/io/homeassistant/companion/android/sensors/AndroidAutoSensorManager.kt b/app/src/full/java/io/homeassistant/companion/android/sensors/AndroidAutoSensorManager.kt index 25567d03b89..cbe47c365a2 100644 --- a/app/src/full/java/io/homeassistant/companion/android/sensors/AndroidAutoSensorManager.kt +++ b/app/src/full/java/io/homeassistant/companion/android/sensors/AndroidAutoSensorManager.kt @@ -31,10 +31,11 @@ class AndroidAutoSensorManager : SensorManager, Observer { get() = commonR.string.sensor_name_android_auto override suspend fun getAvailableSensors(context: Context): List { - return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { listOf(androidAutoConnected) - else + } else { emptyList() + } } override fun requiredPermissions(sensorId: String): Array { @@ -85,7 +86,7 @@ class AndroidAutoSensorManager : SensorManager, Observer { androidAutoConnected.statelessIcon, mapOf( "connection_type" to typeString - ), + ) ) } } diff --git a/app/src/full/java/io/homeassistant/companion/android/sensors/LocationSensorManager.kt b/app/src/full/java/io/homeassistant/companion/android/sensors/LocationSensorManager.kt index d4d5acf0c07..ba8b5be7010 100644 --- a/app/src/full/java/io/homeassistant/companion/android/sensors/LocationSensorManager.kt +++ b/app/src/full/java/io/homeassistant/companion/android/sensors/LocationSensorManager.kt @@ -199,8 +199,11 @@ class LocationSensorManager : LocationSensorManagerBase() { when (command) { DeviceCommandData.TURN_ON, DeviceCommandData.TURN_OFF, MessagingManager.FORCE_ON -> { var turnOn = command != DeviceCommandData.TURN_OFF - if (turnOn) Log.d(TAG, "Forcing of high accuracy mode enabled") - else Log.d(TAG, "Forcing of high accuracy mode disabled") + if (turnOn) { + Log.d(TAG, "Forcing of high accuracy mode enabled") + } else { + Log.d(TAG, "Forcing of high accuracy mode disabled") + } forceHighAccuracyModeOn = turnOn forceHighAccuracyModeOff = false setHighAccuracyModeSetting(latestContext, turnOn) @@ -219,8 +222,9 @@ class LocationSensorManager : LocationSensorManagerBase() { } MessagingManager.HIGH_ACCURACY_SET_UPDATE_INTERVAL -> { - if (lastHighAccuracyMode) + if (lastHighAccuracyMode) { restartHighAccuracyService(getHighAccuracyModeIntervalSetting(latestContext)) + } } } } @@ -311,7 +315,6 @@ class LocationSensorManager : LocationSensorManagerBase() { if (highAccuracyModeEnabled != lastHighAccuracyMode || updateIntervalHighAccuracySeconds != lastHighAccuracyUpdateInterval ) { - if (highAccuracyModeEnabled) { Log.d(TAG, "High accuracy mode parameters changed. Enable high accuracy mode.") if (updateIntervalHighAccuracySeconds != lastHighAccuracyUpdateInterval) { @@ -416,7 +419,6 @@ class LocationSensorManager : LocationSensorManagerBase() { } private fun getHighAccuracyModeState(): Boolean { - var highAccuracyMode = getHighAccuracyModeSetting() if (!highAccuracyMode) return false @@ -447,7 +449,6 @@ class LocationSensorManager : LocationSensorManagerBase() { } private fun shouldEnableHighAccuracyMode(): Boolean { - val highAccuracyModeBTDevicesSetting = getSetting( latestContext, backgroundLocation, @@ -485,8 +486,9 @@ class LocationSensorManager : LocationSensorManagerBase() { if (foundDevices.isNotEmpty()) { highAccuracyModeBTDevices.remove(it) foundDevices.forEach { btDevice -> - if (!highAccuracyModeBTDevices.contains(btDevice.address)) + if (!highAccuracyModeBTDevices.contains(btDevice.address)) { highAccuracyModeBTDevices.add(btDevice.address) + } } updatedBtDeviceNames = true } @@ -506,8 +508,11 @@ class LocationSensorManager : LocationSensorManagerBase() { btDevConnected = bluetoothDevices.any { it.connected && highAccuracyModeBTDevices.contains(it.address) } if (!forceHighAccuracyModeOn && !forceHighAccuracyModeOff) { - if (!btDevConnected) Log.d(TAG, "High accuracy mode disabled, because defined ($highAccuracyModeBTDevices) bluetooth device(s) not connected (Connected devices: $bluetoothDevices)") - else Log.d(TAG, "High accuracy mode enabled, because defined ($highAccuracyModeBTDevices) bluetooth device(s) connected (Connected devices: $bluetoothDevices)") + if (!btDevConnected) { + Log.d(TAG, "High accuracy mode disabled, because defined ($highAccuracyModeBTDevices) bluetooth device(s) not connected (Connected devices: $bluetoothDevices)") + } else { + Log.d(TAG, "High accuracy mode enabled, because defined ($highAccuracyModeBTDevices) bluetooth device(s) connected (Connected devices: $bluetoothDevices)") + } } } @@ -524,8 +529,11 @@ class LocationSensorManager : LocationSensorManagerBase() { inZone = zoneExpEntered || zoneExited if (!forceHighAccuracyModeOn && !forceHighAccuracyModeOff) { - if (!inZone) Log.d(TAG, "High accuracy mode disabled, because not in zone $highAccuracyExpZones") - else Log.d(TAG, "High accuracy mode enabled, because in zone $highAccuracyExpZones") + if (!inZone) { + Log.d(TAG, "High accuracy mode disabled, because not in zone $highAccuracyExpZones") + } else { + Log.d(TAG, "High accuracy mode enabled, because in zone $highAccuracyExpZones") + } } } @@ -572,11 +580,14 @@ class LocationSensorManager : LocationSensorManagerBase() { settingName = SETTING_SEND_LOCATION_AS, settingType = SensorSettingType.LIST, entries = listOf( - SEND_LOCATION_AS_EXACT, SEND_LOCATION_AS_ZONE_ONLY + SEND_LOCATION_AS_EXACT, + SEND_LOCATION_AS_ZONE_ONLY ), default = SEND_LOCATION_AS_EXACT ) - } else SEND_LOCATION_AS_EXACT + } else { + SEND_LOCATION_AS_EXACT + } } private fun removeAllLocationUpdateRequests() { @@ -590,7 +601,9 @@ class LocationSensorManager : LocationSensorManagerBase() { Log.d(TAG, "Removing background location requests.") val backgroundIntent = getLocationUpdateIntent(false) fusedLocationProviderClient?.removeLocationUpdates(backgroundIntent) - } else Log.d(TAG, "Cannot remove background location requests. Location provider is not set.") + } else { + Log.d(TAG, "Cannot remove background location requests. Location provider is not set.") + } } private fun removeGeofenceUpdateRequests() { @@ -601,7 +614,9 @@ class LocationSensorManager : LocationSensorManagerBase() { geofenceRegistered.clear() lastEnteredGeoZones.clear() lastExitedGeoZones.clear() - } else Log.d(TAG, "Cannot remove geofence location requests. Geofence provider is not set.") + } else { + Log.d(TAG, "Cannot remove geofence location requests. Geofence provider is not set.") + } } private fun requestLocationUpdates() { @@ -1148,8 +1163,9 @@ class LocationSensorManager : LocationSensorManagerBase() { context: Context ) { latestContext = context - if (isEnabled(context, zoneLocation) || isEnabled(context, backgroundLocation)) + if (isEnabled(context, zoneLocation) || isEnabled(context, backgroundLocation)) { setupLocationTracking() + } val sensorDao = AppDatabase.getInstance(latestContext).sensorDao() val sensorSetting = sensorDao.getSettings(singleAccurateLocation.id) val includeSensorUpdate = sensorSetting.firstOrNull { it.name == SETTING_INCLUDE_SENSOR_UPDATE }?.value ?: "false" @@ -1161,7 +1177,8 @@ class LocationSensorManager : LocationSensorManagerBase() { } ) } - } else + } else { sensorDao.add(SensorSetting(singleAccurateLocation.id, SETTING_INCLUDE_SENSOR_UPDATE, "false", SensorSettingType.TOGGLE)) + } } } diff --git a/app/src/full/java/io/homeassistant/companion/android/settings/wear/SettingsWearActivity.kt b/app/src/full/java/io/homeassistant/companion/android/settings/wear/SettingsWearActivity.kt index da61a3d5576..638ff3c3d17 100644 --- a/app/src/full/java/io/homeassistant/companion/android/settings/wear/SettingsWearActivity.kt +++ b/app/src/full/java/io/homeassistant/companion/android/settings/wear/SettingsWearActivity.kt @@ -115,7 +115,6 @@ class SettingsWearActivity : AppCompatActivity(), CapabilityClient.OnCapabilityC } private suspend fun findWearDevicesWithApp() { - try { val capabilityInfo = capabilityClient .getCapability(CAPABILITY_WEAR_APP, CapabilityClient.FILTER_ALL) @@ -135,7 +134,6 @@ class SettingsWearActivity : AppCompatActivity(), CapabilityClient.OnCapabilityC } private suspend fun findAllWearDevices() { - try { val connectedNodes = nodeClient.connectedNodes.await() @@ -151,7 +149,6 @@ class SettingsWearActivity : AppCompatActivity(), CapabilityClient.OnCapabilityC } private fun updateUI() { - val wearNodesWithApp = wearNodesWithApp val allConnectedNodes = allConnectedNodes @@ -185,7 +182,6 @@ class SettingsWearActivity : AppCompatActivity(), CapabilityClient.OnCapabilityC } private fun openPlayStoreOnWearDevicesWithoutApp() { - val wearNodesWithApp = wearNodesWithApp ?: return val allConnectedNodes = allConnectedNodes ?: return diff --git a/app/src/full/java/io/homeassistant/companion/android/settings/wear/SettingsWearDetection.kt b/app/src/full/java/io/homeassistant/companion/android/settings/wear/SettingsWearDetection.kt index b9058472e19..449f5046c51 100644 --- a/app/src/full/java/io/homeassistant/companion/android/settings/wear/SettingsWearDetection.kt +++ b/app/src/full/java/io/homeassistant/companion/android/settings/wear/SettingsWearDetection.kt @@ -22,7 +22,7 @@ object SettingsWearDetection { } catch (e: Exception) { if (e is ApiException && e.statusCode == CommonStatusCodes.API_NOT_CONNECTED && e.message?.contains("API_UNAVAILABLE") == true) { // Wearable.API is not available on this device. - Log.d(TAG, "API unavailable for discovering nodes (no Wear)",) + Log.d(TAG, "API unavailable for discovering nodes (no Wear)") } else { Log.e(TAG, "Exception while discovering nodes", e) } diff --git a/app/src/full/java/io/homeassistant/companion/android/settings/wear/SettingsWearViewModel.kt b/app/src/full/java/io/homeassistant/companion/android/settings/wear/SettingsWearViewModel.kt index 76097c7acb8..473e7c42ddc 100644 --- a/app/src/full/java/io/homeassistant/companion/android/settings/wear/SettingsWearViewModel.kt +++ b/app/src/full/java/io/homeassistant/companion/android/settings/wear/SettingsWearViewModel.kt @@ -125,8 +125,11 @@ class SettingsWearViewModel @Inject constructor( Log.e(TAG, "Exception while rendering template", e) // JsonMappingException suggests that template is not a String (= error) templateTileContentRendered.value = getApplication().getString( - if (e.cause is JsonMappingException) commonR.string.template_error - else commonR.string.template_render_error + if (e.cause is JsonMappingException) { + commonR.string.template_error + } else { + commonR.string.template_render_error + } ) } } @@ -136,10 +139,11 @@ class SettingsWearViewModel @Inject constructor( } fun onEntitySelected(checked: Boolean, entityId: String) { - if (checked) + if (checked) { favoriteEntityIds.add(entityId) - else + } else { favoriteEntityIds.remove(entityId) + } sendHomeFavorites(favoriteEntityIds.toList()) } diff --git a/app/src/full/java/io/homeassistant/companion/android/settings/wear/views/SettingsWearMainView.kt b/app/src/full/java/io/homeassistant/companion/android/settings/wear/views/SettingsWearMainView.kt index f00922028db..fe91cd90877 100644 --- a/app/src/full/java/io/homeassistant/companion/android/settings/wear/views/SettingsWearMainView.kt +++ b/app/src/full/java/io/homeassistant/companion/android/settings/wear/views/SettingsWearMainView.kt @@ -79,7 +79,8 @@ class SettingsWearMainView : AppCompatActivity() { if (result != null) { val (url, authCode, deviceName, deviceTrackingEnabled, _) = result settingsWearViewModel.sendAuthToWear(url, authCode, deviceName, deviceTrackingEnabled, true) - } else + } else { Log.e(TAG, "onOnboardingComplete: Activity result returned null intent data") + } } } diff --git a/app/src/full/java/io/homeassistant/companion/android/vehicle/EntityGridVehicleScreen.kt b/app/src/full/java/io/homeassistant/companion/android/vehicle/EntityGridVehicleScreen.kt index f7cdfabe2ec..dc707c2f384 100644 --- a/app/src/full/java/io/homeassistant/companion/android/vehicle/EntityGridVehicleScreen.kt +++ b/app/src/full/java/io/homeassistant/companion/android/vehicle/EntityGridVehicleScreen.kt @@ -33,7 +33,7 @@ class EntityGridVehicleScreen( carContext: CarContext, val integrationRepository: IntegrationRepository, val title: String, - val entitiesFlow: Flow>>, + val entitiesFlow: Flow>> ) : Screen(carContext) { companion object { diff --git a/app/src/full/java/io/homeassistant/companion/android/vehicle/HaCarAppService.kt b/app/src/full/java/io/homeassistant/companion/android/vehicle/HaCarAppService.kt index 85cb83b3d87..879d6b14db5 100644 --- a/app/src/full/java/io/homeassistant/companion/android/vehicle/HaCarAppService.kt +++ b/app/src/full/java/io/homeassistant/companion/android/vehicle/HaCarAppService.kt @@ -86,7 +86,9 @@ class HaCarAppService : CarAppService() { serverManager.integrationRepository(id).getEntities() ?.associate { it.entityId to it } ?.toMutableMap() - } else null + } else { + null + } if (entities != null) { allEntities.emit(entities.toImmutableMap()) serverManager.integrationRepository(id).getEntityUpdates()?.collect { entity -> diff --git a/app/src/full/java/io/homeassistant/companion/android/vehicle/MainVehicleScreen.kt b/app/src/full/java/io/homeassistant/companion/android/vehicle/MainVehicleScreen.kt index 9761f9693a3..659923bb7a2 100644 --- a/app/src/full/java/io/homeassistant/companion/android/vehicle/MainVehicleScreen.kt +++ b/app/src/full/java/io/homeassistant/companion/android/vehicle/MainVehicleScreen.kt @@ -58,7 +58,7 @@ class MainVehicleScreen( "lock" to commonR.string.locks, "scene" to commonR.string.scenes, "script" to commonR.string.scripts, - "switch" to commonR.string.switches, + "switch" to commonR.string.switches ) private val SUPPORTED_DOMAINS = SUPPORTED_DOMAINS_WITH_STRING.keys @@ -66,7 +66,7 @@ class MainVehicleScreen( "device_tracker", "person", "sensor", - "zone", + "zone" ) } diff --git a/app/src/full/java/io/homeassistant/companion/android/vehicle/MapVehicleScreen.kt b/app/src/full/java/io/homeassistant/companion/android/vehicle/MapVehicleScreen.kt index f8fc029e009..17978dab2db 100644 --- a/app/src/full/java/io/homeassistant/companion/android/vehicle/MapVehicleScreen.kt +++ b/app/src/full/java/io/homeassistant/companion/android/vehicle/MapVehicleScreen.kt @@ -34,7 +34,7 @@ import io.homeassistant.companion.android.common.R as commonR class MapVehicleScreen( carContext: CarContext, val integrationRepository: IntegrationRepository, - val entitiesFlow: Flow>>, + val entitiesFlow: Flow>> ) : Screen(carContext) { companion object { diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 03ae314dbb8..832b3adb062 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -142,7 +142,7 @@ android:resource="@xml/entity_widget_info" /> - @@ -205,7 +205,7 @@ - diff --git a/app/src/main/java/io/homeassistant/companion/android/HomeAssistantApplication.kt b/app/src/main/java/io/homeassistant/companion/android/HomeAssistantApplication.kt index 536d6b42c9b..d6be6cfba71 100644 --- a/app/src/main/java/io/homeassistant/companion/android/HomeAssistantApplication.kt +++ b/app/src/main/java/io/homeassistant/companion/android/HomeAssistantApplication.kt @@ -22,7 +22,7 @@ import io.homeassistant.companion.android.util.LifecycleHandler import io.homeassistant.companion.android.websocket.WebsocketBroadcastReceiver import io.homeassistant.companion.android.widgets.button.ButtonWidget import io.homeassistant.companion.android.widgets.entity.EntityWidget -import io.homeassistant.companion.android.widgets.media_player_controls.MediaPlayerControlsWidget +import io.homeassistant.companion.android.widgets.mediaplayer.MediaPlayerControlsWidget import io.homeassistant.companion.android.widgets.template.TemplateWidget import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -213,11 +213,12 @@ open class HomeAssistantApplication : Application() { // Register for faster sensor updates if enabled val settingDao = AppDatabase.getInstance(applicationContext).settingsDao().get(0) - if (settingDao != null && (settingDao.sensorUpdateFrequency == SensorUpdateFrequencySetting.FAST_WHILE_CHARGING || settingDao.sensorUpdateFrequency == SensorUpdateFrequencySetting.FAST_ALWAYS)) + if (settingDao != null && (settingDao.sensorUpdateFrequency == SensorUpdateFrequencySetting.FAST_WHILE_CHARGING || settingDao.sensorUpdateFrequency == SensorUpdateFrequencySetting.FAST_ALWAYS)) { registerReceiver( sensorReceiver, IntentFilter(Intent.ACTION_TIME_TICK) ) + } // Update widgets when the screen turns on, updates are skipped if widgets were not added val buttonWidget = ButtonWidget() diff --git a/app/src/main/java/io/homeassistant/companion/android/authenticator/Authenticator.kt b/app/src/main/java/io/homeassistant/companion/android/authenticator/Authenticator.kt index a741379420f..c7f4b73658b 100644 --- a/app/src/main/java/io/homeassistant/companion/android/authenticator/Authenticator.kt +++ b/app/src/main/java/io/homeassistant/companion/android/authenticator/Authenticator.kt @@ -18,15 +18,17 @@ class Authenticator(context: Context, fragmentActivity: FragmentActivity, callba private val executor = ContextCompat.getMainExecutor(context) private val biometricPrompt = BiometricPrompt( - fragmentActivity, executor, + fragmentActivity, + executor, object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { super.onAuthenticationError(errorCode, errString) Log.d("Unlock", "onAuthenticationError -> $errorCode :: $errString") - if (errorCode == BiometricPrompt.ERROR_USER_CANCELED) + if (errorCode == BiometricPrompt.ERROR_USER_CANCELED) { callback(CANCELED) - else + } else { callback(ERROR) + } } override fun onAuthenticationFailed() { super.onAuthenticationFailed() diff --git a/app/src/main/java/io/homeassistant/companion/android/controls/CameraControl.kt b/app/src/main/java/io/homeassistant/companion/android/controls/CameraControl.kt index 4bb6d185487..82bfb8253a1 100644 --- a/app/src/main/java/io/homeassistant/companion/android/controls/CameraControl.kt +++ b/app/src/main/java/io/homeassistant/companion/android/controls/CameraControl.kt @@ -46,7 +46,9 @@ object CameraControl : HaControl { val image = if (baseUrl != null && (entity.attributes["entity_picture"] as? String)?.isNotBlank() == true) { getThumbnail(baseUrl + entity.attributes["entity_picture"] as String) - } else null + } else { + null + } val icon = if (image != null) { Icon.createWithBitmap(image) } else { diff --git a/app/src/main/java/io/homeassistant/companion/android/controls/ClimateControl.kt b/app/src/main/java/io/homeassistant/companion/android/controls/ClimateControl.kt index df9979099cd..b5808120889 100644 --- a/app/src/main/java/io/homeassistant/companion/android/controls/ClimateControl.kt +++ b/app/src/main/java/io/homeassistant/companion/android/controls/ClimateControl.kt @@ -58,10 +58,12 @@ object ClimateControl : HaControl { entity.attributes["current_temperature"] as? Number )?.toFloat() ?: 0f // Ensure the current value is never lower than the minimum or higher than the maximum - if (currentValue < minValue) + if (currentValue < minValue) { currentValue = minValue - if (currentValue > maxValue) + } + if (currentValue > maxValue) { currentValue = maxValue + } val temperatureUnit = entity.attributes["temperature_unit"] ?: "" val temperatureStepSize = (entity.attributes["target_temperature_step"] as? Number)?.toFloat() @@ -100,10 +102,11 @@ object ClimateControl : HaControl { } override fun getDeviceType(entity: Entity>): Int = - if (entityShouldBePresentedAsThermostat(entity)) + if (entityShouldBePresentedAsThermostat(entity)) { DeviceTypes.TYPE_THERMOSTAT - else + } else { DeviceTypes.TYPE_AC_HEATER + } override fun getDomainString(context: Context, entity: Entity>): String = context.getString(commonR.string.domain_climate) diff --git a/app/src/main/java/io/homeassistant/companion/android/controls/CoverControl.kt b/app/src/main/java/io/homeassistant/companion/android/controls/CoverControl.kt index 4459c3fbd58..6a693ffbdc0 100644 --- a/app/src/main/java/io/homeassistant/companion/android/controls/CoverControl.kt +++ b/app/src/main/java/io/homeassistant/companion/android/controls/CoverControl.kt @@ -40,7 +40,7 @@ object CoverControl : HaControl { ) val position = entity.getCoverPosition() control.setControlTemplate( - if ((entity.attributes["supported_features"] as Int) and SUPPORT_SET_POSITION == SUPPORT_SET_POSITION) + if ((entity.attributes["supported_features"] as Int) and SUPPORT_SET_POSITION == SUPPORT_SET_POSITION) { ToggleRangeTemplate( entity.entityId, entity.state in listOf("open", "opening"), @@ -54,7 +54,7 @@ object CoverControl : HaControl { "%.0f%%" ) ) - else + } else { ToggleTemplate( entity.entityId, ControlButton( @@ -62,6 +62,7 @@ object CoverControl : HaControl { "Description" ) ) + } ) return control } diff --git a/app/src/main/java/io/homeassistant/companion/android/controls/HaControlsProviderService.kt b/app/src/main/java/io/homeassistant/companion/android/controls/HaControlsProviderService.kt index d164bc5e2c3..9373a660d2c 100644 --- a/app/src/main/java/io/homeassistant/companion/android/controls/HaControlsProviderService.kt +++ b/app/src/main/java/io/homeassistant/companion/android/controls/HaControlsProviderService.kt @@ -247,8 +247,11 @@ class HaControlsProviderService : ControlsProviderService() { if (serverManager.getServer(serverId) == null) { controlIds.forEach { val entityId = - if (it.split(".")[0].toIntOrNull() != null) it.removePrefix("$serverId.") - else it + if (it.split(".")[0].toIntOrNull() != null) { + it.removePrefix("$serverId.") + } else { + it + } val entity = getFailedEntity(entityId, Exception()) domainToHaControl["ha_failed"]?.createControl( applicationContext, @@ -257,7 +260,7 @@ class HaControlsProviderService : ControlsProviderService() { systemId = it, entityId = entityId, serverId = serverId, - area = getAreaForEntity(entity.entityId, serverId), + area = getAreaForEntity(entity.entityId, serverId) ) )?.let { control -> subscriber.onNext(control) } } @@ -269,8 +272,11 @@ class HaControlsProviderService : ControlsProviderService() { val getDeviceRegistry = ioScope.async { serverManager.webSocketRepository(serverId).getDeviceRegistry() } val getEntityRegistry = ioScope.async { serverManager.webSocketRepository(serverId).getEntityRegistry() } val entityIds = controlIds.map { - if (it.split(".")[0].toIntOrNull() != null) it.removePrefix("$serverId.") - else it + if (it.split(".")[0].toIntOrNull() != null) { + it.removePrefix("$serverId.") + } else { + it + } } val entities = mutableMapOf>>() val baseUrl = serverManager.getServer(serverId)?.connection?.getUrl()?.toString()?.removeSuffix("/") ?: "" @@ -386,8 +392,9 @@ class HaControlsProviderService : ControlsProviderService() { baseUrl = baseUrl ) ) - if (control != null) + if (control != null) { subscriber.onNext(control) + } } } } @@ -422,8 +429,11 @@ class HaControlsProviderService : ControlsProviderService() { baseUrl: String ) { val entityIds = controlIds.map { - if (it.split(".")[0].toIntOrNull() != null) it.removePrefix("$serverId.") - else it + if (it.split(".")[0].toIntOrNull() != null) { + it.removePrefix("$serverId.") + } else { + it + } } entities.forEach { coroutineScope.launch { @@ -449,8 +459,9 @@ class HaControlsProviderService : ControlsProviderService() { info ) } - if (control != null) + if (control != null) { subscriber.onNext(control) + } } } } @@ -485,6 +496,8 @@ class HaControlsProviderService : ControlsProviderService() { } else { setting == ControlsAuthRequiredSetting.ALL } - } else false + } else { + false + } } } diff --git a/app/src/main/java/io/homeassistant/companion/android/controls/LightControl.kt b/app/src/main/java/io/homeassistant/companion/android/controls/LightControl.kt index 97828024451..7e1777804e1 100644 --- a/app/src/main/java/io/homeassistant/companion/android/controls/LightControl.kt +++ b/app/src/main/java/io/homeassistant/companion/android/controls/LightControl.kt @@ -30,7 +30,7 @@ object LightControl : HaControl { ): Control.StatefulBuilder { val position = entity.getLightBrightness() control.setControlTemplate( - if (entity.supportsLightBrightness()) + if (entity.supportsLightBrightness()) { ToggleRangeTemplate( entity.entityId, entity.state == "on", @@ -44,7 +44,7 @@ object LightControl : HaControl { "%.0f%%" ) ) - else + } else { ToggleTemplate( entity.entityId, ControlButton( @@ -52,6 +52,7 @@ object LightControl : HaControl { "Description" ) ) + } ) return control } diff --git a/app/src/main/java/io/homeassistant/companion/android/controls/VacuumControl.kt b/app/src/main/java/io/homeassistant/companion/android/controls/VacuumControl.kt index 1f6169c8b8f..6dcc583880a 100644 --- a/app/src/main/java/io/homeassistant/companion/android/controls/VacuumControl.kt +++ b/app/src/main/java/io/homeassistant/companion/android/controls/VacuumControl.kt @@ -45,10 +45,11 @@ object VacuumControl : HaControl { ToggleTemplate( entity.entityId, ControlButton( - if (entitySupportedFeatures and SUPPORT_TURN_ON == SUPPORT_TURN_ON) + if (entitySupportedFeatures and SUPPORT_TURN_ON == SUPPORT_TURN_ON) { entity.state == "on" - else - entity.state == "cleaning", + } else { + entity.state == "cleaning" + }, "Description" ) ) @@ -68,9 +69,9 @@ object VacuumControl : HaControl { ): Boolean { integrationRepository.callService( action.templateId.split(".")[0], - if (entitySupportedFeatures and SUPPORT_TURN_ON == SUPPORT_TURN_ON) + if (entitySupportedFeatures and SUPPORT_TURN_ON == SUPPORT_TURN_ON) { if ((action as? BooleanAction)?.newState == true) "turn_on" else "turn_off" - else if ((action as? BooleanAction)?.newState == true) "start" else "return_to_base", + } else if ((action as? BooleanAction)?.newState == true) "start" else "return_to_base", hashMapOf( "entity_id" to action.templateId ) diff --git a/app/src/main/java/io/homeassistant/companion/android/launch/LaunchActivity.kt b/app/src/main/java/io/homeassistant/companion/android/launch/LaunchActivity.kt index 2a9f1dc4361..3d71c1b2180 100644 --- a/app/src/main/java/io/homeassistant/companion/android/launch/LaunchActivity.kt +++ b/app/src/main/java/io/homeassistant/companion/android/launch/LaunchActivity.kt @@ -126,8 +126,9 @@ class LaunchActivity : AppCompatActivity(), LaunchView { notificationsEnabled ) } - } else + } else { Log.e(TAG, "onOnboardingComplete: Activity result returned null intent data") + } } } diff --git a/app/src/main/java/io/homeassistant/companion/android/nfc/NFCUtil.kt b/app/src/main/java/io/homeassistant/companion/android/nfc/NFCUtil.kt index 95793245df0..5666499f2ce 100644 --- a/app/src/main/java/io/homeassistant/companion/android/nfc/NFCUtil.kt +++ b/app/src/main/java/io/homeassistant/companion/android/nfc/NFCUtil.kt @@ -47,8 +47,10 @@ object NFCUtil { fun enableNFCInForeground(nfcAdapter: NfcAdapter, activity: Activity, classType: Class) { val pendingIntent = PendingIntent.getActivity( - activity, 0, - Intent(activity, classType).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_MUTABLE + activity, + 0, + Intent(activity, classType).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), + PendingIntent.FLAG_MUTABLE ) val nfcIntentFilter = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED) val filters = arrayOf(nfcIntentFilter) diff --git a/app/src/main/java/io/homeassistant/companion/android/nfc/NfcSetupActivity.kt b/app/src/main/java/io/homeassistant/companion/android/nfc/NfcSetupActivity.kt index e9c401ed31e..f56f38703b1 100644 --- a/app/src/main/java/io/homeassistant/companion/android/nfc/NfcSetupActivity.kt +++ b/app/src/main/java/io/homeassistant/companion/android/nfc/NfcSetupActivity.kt @@ -46,8 +46,9 @@ class NfcSetupActivity : BaseActivity() { fun newInstance(context: Context, tagId: String? = null, messageId: Int = -1): Intent { return Intent(context, NfcSetupActivity::class.java).apply { putExtra(EXTRA_MESSAGE_ID, messageId) - if (tagId != null) + if (tagId != null) { putExtra(EXTRA_TAG_VALUE, tagId) + } } } } diff --git a/app/src/main/java/io/homeassistant/companion/android/nfc/TagReaderActivity.kt b/app/src/main/java/io/homeassistant/companion/android/nfc/TagReaderActivity.kt index bf48aa364c9..3d717a13a51 100644 --- a/app/src/main/java/io/homeassistant/companion/android/nfc/TagReaderActivity.kt +++ b/app/src/main/java/io/homeassistant/companion/android/nfc/TagReaderActivity.kt @@ -44,8 +44,11 @@ class TagReaderActivity : BaseActivity() { val isNfcTag = intent.action == NfcAdapter.ACTION_NDEF_DISCOVERED val url = - if (isNfcTag) NFCUtil.extractUrlFromNFCIntent(intent) - else intent.data + if (isNfcTag) { + NFCUtil.extractUrlFromNFCIntent(intent) + } else { + intent.data + } try { handleTag(url, isNfcTag) } catch (e: Exception) { diff --git a/app/src/main/java/io/homeassistant/companion/android/nfc/views/NfcNavigationView.kt b/app/src/main/java/io/homeassistant/companion/android/nfc/views/NfcNavigationView.kt index 33fa7b0b462..f8bc179b8ff 100644 --- a/app/src/main/java/io/homeassistant/companion/android/nfc/views/NfcNavigationView.kt +++ b/app/src/main/java/io/homeassistant/companion/android/nfc/views/NfcNavigationView.kt @@ -69,8 +69,11 @@ fun LoadNfcView( title = { Text(stringResource(commonR.string.nfc_title_settings)) }, navigationIcon = { IconButton(onClick = { - if (canNavigateUp.value) navController.navigateUp() - else pressedUpAtRoot() + if (canNavigateUp.value) { + navController.navigateUp() + } else { + pressedUpAtRoot() + } }) { Icon( imageVector = Icons.Outlined.ArrowBack, @@ -116,7 +119,9 @@ fun LoadNfcView( identifier = viewModel.nfcTagIdentifier, onSetIdentifier = if (viewModel.nfcIdentifierIsEditable) { { viewModel.setTagIdentifier(it) } - } else null + } else { + null + } ) } composable(NfcSetupActivity.NAV_EDIT) { diff --git a/app/src/main/java/io/homeassistant/companion/android/nfc/views/NfcWelcomeView.kt b/app/src/main/java/io/homeassistant/companion/android/nfc/views/NfcWelcomeView.kt index 03ce73e2337..fd05e60a0d9 100644 --- a/app/src/main/java/io/homeassistant/companion/android/nfc/views/NfcWelcomeView.kt +++ b/app/src/main/java/io/homeassistant/companion/android/nfc/views/NfcWelcomeView.kt @@ -20,7 +20,7 @@ import io.homeassistant.companion.android.common.R as commonR fun NfcWelcomeView( isNfcEnabled: Boolean, onReadClicked: () -> Unit, - onWriteClicked: () -> Unit, + onWriteClicked: () -> Unit ) { LazyColumn(contentPadding = PaddingValues(all = 16.dp)) { item { diff --git a/app/src/main/java/io/homeassistant/companion/android/nfc/views/NfcWriteView.kt b/app/src/main/java/io/homeassistant/companion/android/nfc/views/NfcWriteView.kt index 95f3fae63b4..46415fc3637 100644 --- a/app/src/main/java/io/homeassistant/companion/android/nfc/views/NfcWriteView.kt +++ b/app/src/main/java/io/homeassistant/companion/android/nfc/views/NfcWriteView.kt @@ -57,12 +57,15 @@ fun NfcWriteView( ) { Image( asset = CommunityMaterial.Icon3.cmd_nfc_tap, - colorFilter = ColorFilter.tint(MaterialTheme.colors.onSurface), + colorFilter = ColorFilter.tint(MaterialTheme.colors.onSurface) ) Text( text = - if (isNfcEnabled) stringResource(commonR.string.nfc_write_tag_instructions, identifier ?: "") - else stringResource(commonR.string.nfc_write_tag_turnon), + if (isNfcEnabled) { + stringResource(commonR.string.nfc_write_tag_instructions, identifier ?: "") + } else { + stringResource(commonR.string.nfc_write_tag_turnon) + }, textAlign = TextAlign.Center, modifier = Modifier .fillMaxWidth(0.75f) diff --git a/app/src/main/java/io/homeassistant/companion/android/notifications/MessagingManager.kt b/app/src/main/java/io/homeassistant/companion/android/notifications/MessagingManager.kt index 32e0c5c8ea7..baa608dcb43 100644 --- a/app/src/main/java/io/homeassistant/companion/android/notifications/MessagingManager.kt +++ b/app/src/main/java/io/homeassistant/companion/android/notifications/MessagingManager.kt @@ -229,8 +229,14 @@ class MessagingManager @Inject constructor( ) val FORCE_COMMANDS = listOf(FORCE_OFF, FORCE_ON) val MEDIA_COMMANDS = listOf( - MEDIA_FAST_FORWARD, MEDIA_NEXT, MEDIA_PAUSE, MEDIA_PLAY, - MEDIA_PLAY_PAUSE, MEDIA_PREVIOUS, MEDIA_REWIND, MEDIA_STOP + MEDIA_FAST_FORWARD, + MEDIA_NEXT, + MEDIA_PAUSE, + MEDIA_PLAY, + MEDIA_PLAY_PAUSE, + MEDIA_PREVIOUS, + MEDIA_REWIND, + MEDIA_STOP ) // Video Values @@ -249,7 +255,6 @@ class MessagingManager @Inject constructor( private val mainScope: CoroutineScope = CoroutineScope(Dispatchers.Main + Job()) fun handleMessage(notificationData: Map, source: String) { - var now = System.currentTimeMillis() var jsonData = notificationData val notificationId: Long @@ -310,9 +315,9 @@ class MessagingManager @Inject constructor( when (jsonData[NotificationData.MESSAGE]) { COMMAND_DND -> { if (jsonData[NotificationData.COMMAND] in DND_COMMANDS) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { handleDeviceCommands(jsonData) - else { + } else { mainScope.launch { Log.d( TAG, @@ -345,9 +350,9 @@ class MessagingManager @Inject constructor( } } COMMAND_BROADCAST_INTENT -> { - if (!jsonData[INTENT_ACTION].isNullOrEmpty() && !jsonData[INTENT_PACKAGE_NAME].isNullOrEmpty()) + if (!jsonData[INTENT_ACTION].isNullOrEmpty() && !jsonData[INTENT_PACKAGE_NAME].isNullOrEmpty()) { handleDeviceCommands(jsonData) - else { + } else { mainScope.launch { Log.d( TAG, @@ -360,9 +365,9 @@ class MessagingManager @Inject constructor( COMMAND_VOLUME_LEVEL -> { if (!jsonData[NotificationData.MEDIA_STREAM].isNullOrEmpty() && jsonData[NotificationData.MEDIA_STREAM] in CHANNEL_VOLUME_STREAM && !jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND]?.toIntOrNull() != null - ) + ) { handleDeviceCommands(jsonData) - else { + } else { mainScope.launch { Log.d( TAG, @@ -377,9 +382,9 @@ class MessagingManager @Inject constructor( !jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND] in DeviceCommandData.ENABLE_COMMANDS && Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU - ) + ) { handleDeviceCommands(jsonData) - else { + } else { mainScope.launch { Log.d( TAG, @@ -410,9 +415,9 @@ class MessagingManager @Inject constructor( !jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND] == HIGH_ACCURACY_SET_UPDATE_INTERVAL && jsonData[HIGH_ACCURACY_UPDATE_INTERVAL]?.toIntOrNull() != null && jsonData[HIGH_ACCURACY_UPDATE_INTERVAL]?.toInt()!! >= 5 ) - ) + ) { handleDeviceCommands(jsonData) - else { + } else { mainScope.launch { Log.d( TAG, @@ -423,9 +428,9 @@ class MessagingManager @Inject constructor( } } COMMAND_ACTIVITY -> { - if (!jsonData[INTENT_ACTION].isNullOrEmpty()) + if (!jsonData[INTENT_ACTION].isNullOrEmpty()) { handleDeviceCommands(jsonData) - else { + } else { mainScope.launch { Log.d( TAG, @@ -449,9 +454,9 @@ class MessagingManager @Inject constructor( (appLockTimeoutPresent && (appLockTimeoutValue == null || appLockTimeoutValue < 0)) || (homeBypassEnablePresent && homeBypassEnableValue == null) - if (!invalid) + if (!invalid) { handleDeviceCommands(jsonData) - else { + } else { mainScope.launch { Log.d( TAG, @@ -531,20 +536,22 @@ class MessagingManager @Inject constructor( } TextToSpeechData.COMMAND_STOP_TTS -> stopTTS() COMMAND_AUTO_SCREEN_BRIGHTNESS -> { - if (!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND] in DeviceCommandData.ENABLE_COMMANDS) + if (!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND] in DeviceCommandData.ENABLE_COMMANDS) { handleDeviceCommands(jsonData) - else + } else { mainScope.launch { sendNotification(jsonData) } + } } COMMAND_SCREEN_BRIGHTNESS_LEVEL, COMMAND_SCREEN_OFF_TIMEOUT -> { - if (!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND]?.toIntOrNull() != null) + if (!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND]?.toIntOrNull() != null) { handleDeviceCommands(jsonData) - else + } else { mainScope.launch { sendNotification(jsonData) } + } } else -> Log.d(TAG, "No command received") } @@ -633,8 +640,9 @@ class MessagingManager @Inject constructor( addExtrasToIntent(intent, extras) } intent.`package` = packageName - if (!packageName.isNullOrEmpty() && !className.isNullOrEmpty()) + if (!packageName.isNullOrEmpty() && !className.isNullOrEmpty()) { intent.setClassName(packageName, className) + } Log.d(TAG, "Sending broadcast intent") context.sendBroadcast(intent) } catch (e: Exception) { @@ -684,10 +692,11 @@ class MessagingManager @Inject constructor( } } @Suppress("DEPRECATION") - if (command == DeviceCommandData.TURN_OFF) + if (command == DeviceCommandData.TURN_OFF) { bluetoothAdapter?.disable() - else if (command == DeviceCommandData.TURN_ON) + } else if (command == DeviceCommandData.TURN_ON) { bluetoothAdapter?.enable() + } } COMMAND_HIGH_ACCURACY_MODE -> { when (command) { @@ -703,9 +712,9 @@ class MessagingManager @Inject constructor( } COMMAND_ACTIVITY -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - if (!Settings.canDrawOverlays(context)) + if (!Settings.canDrawOverlays(context)) { notifyMissingPermission(message.toString()) - else if (ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED && data["tag"] == Intent.ACTION_CALL) { + } else if (ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED && data["tag"] == Intent.ACTION_CALL) { Handler(Looper.getMainLooper()).post { Toast.makeText( context, @@ -714,10 +723,12 @@ class MessagingManager @Inject constructor( ).show() } navigateAppDetails() - } else + } else { processActivityCommand(data) - } else + } + } else { processActivityCommand(data) + } } COMMAND_APP_LOCK -> { mainScope.launch { @@ -726,12 +737,14 @@ class MessagingManager @Inject constructor( } COMMAND_WEBVIEW -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - if (!Settings.canDrawOverlays(context)) + if (!Settings.canDrawOverlays(context)) { notifyMissingPermission(message.toString()) - else + } else { openWebview(command, data) - } else + } + } else { openWebview(command, data) + } } COMMAND_SCREEN_ON -> { if (!command.isNullOrEmpty()) { @@ -756,21 +769,23 @@ class MessagingManager @Inject constructor( if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { if (!NotificationManagerCompat.getEnabledListenerPackages(context) .contains(context.packageName) - ) + ) { notifyMissingPermission(message.toString()) - else { + } else { processMediaCommand(data) } } } COMMAND_LAUNCH_APP -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - if (!Settings.canDrawOverlays(context)) + if (!Settings.canDrawOverlays(context)) { notifyMissingPermission(message.toString()) - else + } else { launchApp(data) - } else + } + } else { launchApp(data) + } } COMMAND_PERSISTENT_CONNECTION -> { togglePersistentConnection(data[PERSISTENT].toString()) @@ -778,12 +793,15 @@ class MessagingManager @Inject constructor( COMMAND_AUTO_SCREEN_BRIGHTNESS, COMMAND_SCREEN_BRIGHTNESS_LEVEL, COMMAND_SCREEN_OFF_TIMEOUT -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Settings.System.canWrite(context)) { - if (!processScreenCommands(data)) + if (!processScreenCommands(data)) { mainScope.launch { sendNotification(data) } - } else + } + } else { notifyMissingPermission(message.toString()) - } else if (!processScreenCommands(data)) + } + } else if (!processScreenCommands(data)) { mainScope.launch { sendNotification(data) } + } } else -> Log.d(TAG, "No command received") } @@ -829,12 +847,13 @@ class MessagingManager @Inject constructor( } } else { // Try to guess the correct type - if (value.isDigitsOnly()) + if (value.isDigitsOnly()) { intent.putExtra(chunks[0], value.toInt()) - else if ((value.lowercase() == "true") || (value.lowercase() == "false")) + } else if ((value.lowercase() == "true") || (value.lowercase() == "false")) { intent.putExtra(chunks[0], value.toBoolean()) - else + } else { intent.putExtra(chunks[0], value) + } } } } @@ -858,7 +877,6 @@ class MessagingManager @Inject constructor( groupId = group.hashCode() } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - val notification = notificationManagerCompat.getActiveNotification(tag, messageId) if (notification != null && notification.isGroup) { previousGroup = NotificationData.GROUP_PREFIX + notification.tag @@ -1020,8 +1038,9 @@ class MessagingManager @Inject constructor( } else { builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) } - if (data[NotificationData.ALERT_ONCE].toBoolean()) + if (data[NotificationData.ALERT_ONCE].toBoolean()) { builder.setOnlyAlertOnce(true) + } } private fun handleLegacyLedColor( @@ -1051,7 +1070,6 @@ class MessagingManager @Inject constructor( builder: NotificationCompat.Builder, data: Map ) { - // Use importance property for legacy priority support val priority = data[NotificationData.IMPORTANCE] @@ -1089,8 +1107,9 @@ class MessagingManager @Inject constructor( ) { if (!group.isNullOrBlank()) { builder.setGroup(group) - if (alertOnce == true) + if (alertOnce == true) { builder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN) + } } } @@ -1162,8 +1181,9 @@ class MessagingManager @Inject constructor( withContext( Dispatchers.IO ) { - if (url == null) + if (url == null) { return@withContext null + } var image: Bitmap? = null try { @@ -1410,18 +1430,20 @@ class MessagingManager @Inject constructor( Intent.parseUri(uri, Intent.URI_INTENT_SCHEME) } uri.startsWith(SETTINGS_PREFIX) -> { - if (uri.substringAfter(SETTINGS_PREFIX) == NOTIFICATION_HISTORY) + if (uri.substringAfter(SETTINGS_PREFIX) == NOTIFICATION_HISTORY) { SettingsActivity.newInstance(context) - else + } else { WebViewActivity.newInstance(context, null, serverId) + } } UrlHandler.isAbsoluteUrl(uri) || uri.startsWith(DEEP_LINK_PREFIX) -> { Intent(Intent.ACTION_VIEW).apply { this.data = Uri.parse( - if (uri.startsWith(DEEP_LINK_PREFIX)) + if (uri.startsWith(DEEP_LINK_PREFIX)) { uri.removePrefix(DEEP_LINK_PREFIX) - else + } else { uri + } ) } } @@ -1430,8 +1452,9 @@ class MessagingManager @Inject constructor( } } ?: WebViewActivity.newInstance(context, null, serverId) - if (uri.startsWith(SETTINGS_PREFIX) && uri.substringAfter(SETTINGS_PREFIX) == NOTIFICATION_HISTORY) + if (uri.startsWith(SETTINGS_PREFIX) && uri.substringAfter(SETTINGS_PREFIX) == NOTIFICATION_HISTORY) { intent.putExtra("fragment", NOTIFICATION_HISTORY) + } intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) if (!otherApp) { @@ -1452,10 +1475,12 @@ class MessagingManager @Inject constructor( val marketIntent = Intent(Intent.ACTION_VIEW) marketIntent.data = Uri.parse(MARKET_PREFIX + if (uri.startsWith(INTENT_PREFIX)) intent.`package`.toString() else uri.removePrefix(APP_PREFIX)) marketIntent - } else + } else { intent - } else - intent, + } + } else { + intent + }, PendingIntent.FLAG_IMMUTABLE ) } @@ -1606,10 +1631,11 @@ class MessagingManager @Inject constructor( private fun adjustVolumeStream(stream: Int, volume: Int, audioManager: AudioManager) { var volumeLevel = volume - if (volumeLevel > audioManager.getStreamMaxVolume(stream)) + if (volumeLevel > audioManager.getStreamMaxVolume(stream)) { volumeLevel = audioManager.getStreamMaxVolume(stream) - else if (volumeLevel < 0) + } else if (volumeLevel < 0) { volumeLevel = 0 + } audioManager.setStreamVolume( stream, volumeLevel, @@ -1625,10 +1651,12 @@ class MessagingManager @Inject constructor( val intentUri = if (!data[INTENT_URI].isNullOrEmpty()) Uri.parse(data[INTENT_URI]) else null val intent = if (intentUri != null) Intent(action, intentUri) else Intent(action) val type = data[INTENT_TYPE] - if (!type.isNullOrEmpty()) + if (!type.isNullOrEmpty()) { intent.type = type - if (!className.isNullOrEmpty() && !packageName.isNullOrEmpty()) + } + if (!className.isNullOrEmpty() && !packageName.isNullOrEmpty()) { intent.setClassName(packageName, className) + } val extras = data[INTENT_EXTRAS] if (!extras.isNullOrEmpty()) { addExtrasToIntent(intent, extras) @@ -1637,9 +1665,9 @@ class MessagingManager @Inject constructor( if (!packageName.isNullOrEmpty()) { intent.setPackage(packageName) context.startActivity(intent) - } else if (intent.resolveActivity(context.packageManager) != null) + } else if (intent.resolveActivity(context.packageManager) != null) { context.startActivity(intent) - else + } else { mainScope.launch { Log.d( TAG, @@ -1647,6 +1675,7 @@ class MessagingManager @Inject constructor( ) sendNotification(data) } + } } catch (e: Exception) { Log.e(TAG, "Unable to send activity intent please check command format", e) Handler(Looper.getMainLooper()).post { @@ -1665,10 +1694,11 @@ class MessagingManager @Inject constructor( ) { try { val serverId = data[THIS_SERVER_ID]!!.toInt() - val intent = if (title.isNullOrEmpty()) + val intent = if (title.isNullOrEmpty()) { WebViewActivity.newInstance(context, null, serverId) - else + } else { WebViewActivity.newInstance(context, title, serverId) + } intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) context.startActivity(intent) @@ -1680,9 +1710,9 @@ class MessagingManager @Inject constructor( private fun launchApp(data: Map) { try { val launchIntent = context.packageManager.getLaunchIntentForPackage(data[PACKAGE_NAME]!!) - if (launchIntent != null) + if (launchIntent != null) { context.startActivity(launchIntent) - else { + } else { Log.w(TAG, "No intent to launch app found, opening app store") val marketIntent = Intent(Intent.ACTION_VIEW) marketIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) @@ -1764,10 +1794,11 @@ class MessagingManager @Inject constructor( when (data[NotificationData.MESSAGE].toString()) { COMMAND_SCREEN_BRIGHTNESS_LEVEL -> command!!.toInt().coerceIn(0, 255) COMMAND_AUTO_SCREEN_BRIGHTNESS -> { - if (command == DeviceCommandData.TURN_ON) + if (command == DeviceCommandData.TURN_ON) { Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC - else + } else { Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL + } } else -> command!!.toInt() } diff --git a/app/src/main/java/io/homeassistant/companion/android/notifications/NotificationActionReceiver.kt b/app/src/main/java/io/homeassistant/companion/android/notifications/NotificationActionReceiver.kt index 841b34ce8f9..dbae9b9acf8 100644 --- a/app/src/main/java/io/homeassistant/companion/android/notifications/NotificationActionReceiver.kt +++ b/app/src/main/java/io/homeassistant/companion/android/notifications/NotificationActionReceiver.kt @@ -44,7 +44,6 @@ class NotificationActionReceiver : BroadcastReceiver() { lateinit var notificationDao: NotificationDao override fun onReceive(context: Context, intent: Intent) { - val notificationAction = intent.getParcelableExtra(EXTRA_NOTIFICATION_ACTION) diff --git a/app/src/main/java/io/homeassistant/companion/android/notifications/NotificationDeleteReceiver.kt b/app/src/main/java/io/homeassistant/companion/android/notifications/NotificationDeleteReceiver.kt index 99d47daf1af..fa01641fb67 100644 --- a/app/src/main/java/io/homeassistant/companion/android/notifications/NotificationDeleteReceiver.kt +++ b/app/src/main/java/io/homeassistant/companion/android/notifications/NotificationDeleteReceiver.kt @@ -29,7 +29,6 @@ class NotificationDeleteReceiver : BroadcastReceiver() { lateinit var notificationDao: NotificationDao override fun onReceive(context: Context, intent: Intent) { - val hashData = intent.getSerializableExtra(EXTRA_DATA) as HashMap val group = intent.getStringExtra(EXTRA_NOTIFICATION_GROUP) val groupId = intent.getIntExtra(EXTRA_NOTIFICATION_GROUP_ID, -1) diff --git a/app/src/main/java/io/homeassistant/companion/android/onboarding/OnboardingActivity.kt b/app/src/main/java/io/homeassistant/companion/android/onboarding/OnboardingActivity.kt index 8dfec2f7595..bf694ce0c30 100644 --- a/app/src/main/java/io/homeassistant/companion/android/onboarding/OnboardingActivity.kt +++ b/app/src/main/java/io/homeassistant/companion/android/onboarding/OnboardingActivity.kt @@ -39,7 +39,9 @@ class OnboardingActivity : AppCompatActivity() { Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || NotificationManagerCompat.from(this).areNotificationsEnabled() ) - } else false + } else { + false + } viewModel.deviceIsWatch = input.isWatch if (savedInstanceState == null) { diff --git a/app/src/main/java/io/homeassistant/companion/android/onboarding/authentication/AuthenticationFragment.kt b/app/src/main/java/io/homeassistant/companion/android/onboarding/authentication/AuthenticationFragment.kt index e68379df4fb..e75e25c7643 100644 --- a/app/src/main/java/io/homeassistant/companion/android/onboarding/authentication/AuthenticationFragment.kt +++ b/app/src/main/java/io/homeassistant/companion/android/onboarding/authentication/AuthenticationFragment.kt @@ -92,10 +92,11 @@ class AuthenticationFragment : Fragment() { requireContext().getString( commonR.string.error_http_generic, error?.errorCode, - if (error?.description.isNullOrBlank()) + if (error?.description.isNullOrBlank()) { commonR.string.no_description - else + } else { error?.description + } ), null, error @@ -131,12 +132,14 @@ class AuthenticationFragment : Fragment() { requireContext().getString( commonR.string.error_http_generic, errorResponse?.statusCode, - if (errorResponse?.reasonPhrase.isNullOrBlank()) + if (errorResponse?.reasonPhrase.isNullOrBlank()) { requireContext().getString(commonR.string.no_description) - else + } else { errorResponse?.reasonPhrase + } ), - null, null + null, + null ) } } diff --git a/app/src/main/java/io/homeassistant/companion/android/onboarding/discovery/HomeAssistantSearcher.kt b/app/src/main/java/io/homeassistant/companion/android/onboarding/discovery/HomeAssistantSearcher.kt index dde842af9d8..8ac130fdde0 100644 --- a/app/src/main/java/io/homeassistant/companion/android/onboarding/discovery/HomeAssistantSearcher.kt +++ b/app/src/main/java/io/homeassistant/companion/android/onboarding/discovery/HomeAssistantSearcher.kt @@ -30,8 +30,9 @@ class HomeAssistantSearcher constructor( private var multicastLock: WifiManager.MulticastLock? = null fun beginSearch() { - if (isSearching) + if (isSearching) { return + } isSearching = true try { nsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, this) @@ -54,8 +55,9 @@ class HomeAssistantSearcher constructor( } fun stopSearch() { - if (!isSearching) + if (!isSearching) { return + } isSearching = false try { nsdManager.stopServiceDiscovery(this) diff --git a/app/src/main/java/io/homeassistant/companion/android/onboarding/integration/MobileAppIntegrationFragment.kt b/app/src/main/java/io/homeassistant/companion/android/onboarding/integration/MobileAppIntegrationFragment.kt index 7960269bdb1..0fb9651a31c 100644 --- a/app/src/main/java/io/homeassistant/companion/android/onboarding/integration/MobileAppIntegrationFragment.kt +++ b/app/src/main/java/io/homeassistant/companion/android/onboarding/integration/MobileAppIntegrationFragment.kt @@ -61,7 +61,6 @@ class MobileAppIntegrationFragment : Fragment() { private fun onLocationTrackingChanged(isChecked: Boolean) { var checked = isChecked if (isChecked) { - val locationEnabled = DisabledLocationHandler.isLocationEnabled(requireContext()) val permissionOk = LocationSensorManager().checkPermission( requireContext(), diff --git a/app/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupView.kt b/app/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupView.kt index c2bcaf690ab..23e2d414884 100644 --- a/app/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupView.kt +++ b/app/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupView.kt @@ -40,7 +40,6 @@ fun ManualSetupView( .fillMaxWidth() .padding(16.dp) ) { - OnboardingHeaderView( icon = CommunityMaterial.Icon3.cmd_web, title = stringResource(id = commonR.string.manual_title) diff --git a/app/src/main/java/io/homeassistant/companion/android/onboarding/notifications/NotificationPermissionFragment.kt b/app/src/main/java/io/homeassistant/companion/android/onboarding/notifications/NotificationPermissionFragment.kt index e4cd63cd649..5f66a99283c 100644 --- a/app/src/main/java/io/homeassistant/companion/android/onboarding/notifications/NotificationPermissionFragment.kt +++ b/app/src/main/java/io/homeassistant/companion/android/onboarding/notifications/NotificationPermissionFragment.kt @@ -30,8 +30,11 @@ class NotificationPermissionFragment : Fragment() { Log.i(TAG, "Notification permission was ${if (isGranted) "granted" else "not granted"}") viewModel.setNotifications(isGranted) - if (isGranted) onComplete() - else showPermissionDeniedDialog() + if (isGranted) { + onComplete() + } else { + showPermissionDeniedDialog() + } } override fun onCreateView( diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile10Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile10Service.kt index bcb963208e4..98bc1bb4f0b 100755 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile10Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile10Service.kt @@ -12,10 +12,11 @@ class Tile10Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile11Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile11Service.kt index d66c91ed321..e07a0910af5 100755 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile11Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile11Service.kt @@ -12,10 +12,11 @@ class Tile11Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile12Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile12Service.kt index 2da1f09aac1..e28a09f86f8 100755 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile12Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile12Service.kt @@ -12,10 +12,11 @@ class Tile12Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile13Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile13Service.kt index db5fb25dbb9..38791158e02 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile13Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile13Service.kt @@ -12,10 +12,11 @@ class Tile13Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile14Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile14Service.kt index bf979abd353..51e8e3f64f4 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile14Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile14Service.kt @@ -12,10 +12,11 @@ class Tile14Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile15Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile15Service.kt index f47a5098e9b..fc8d6569c0c 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile15Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile15Service.kt @@ -12,10 +12,11 @@ class Tile15Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile16Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile16Service.kt index b94432c02a8..814e7d75840 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile16Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile16Service.kt @@ -12,10 +12,11 @@ class Tile16Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile17Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile17Service.kt index 9e291f58713..be050217178 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile17Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile17Service.kt @@ -12,10 +12,11 @@ class Tile17Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile18Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile18Service.kt index 75dfd514b13..949393c1c5f 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile18Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile18Service.kt @@ -12,10 +12,11 @@ class Tile18Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile19Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile19Service.kt index ce35c4c821d..50732cb30a4 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile19Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile19Service.kt @@ -12,10 +12,11 @@ class Tile19Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile1Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile1Service.kt index e64a6d2d93d..5495ceafe6c 100755 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile1Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile1Service.kt @@ -8,10 +8,11 @@ import androidx.annotation.RequiresApi class Tile1Service : TileExtensions() { override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile20Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile20Service.kt index b065d0b80eb..bb0ab16ef8e 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile20Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile20Service.kt @@ -12,10 +12,11 @@ class Tile20Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile21Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile21Service.kt index c013bdb1c37..fb5aa4255cf 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile21Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile21Service.kt @@ -12,10 +12,11 @@ class Tile21Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile22Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile22Service.kt index ad656535cae..a21a43d3416 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile22Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile22Service.kt @@ -12,10 +12,11 @@ class Tile22Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile23Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile23Service.kt index ae8cc6d6f59..5868c276e85 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile23Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile23Service.kt @@ -12,10 +12,11 @@ class Tile23Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile24Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile24Service.kt index 825d9a8c6fb..a31ecc442b7 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile24Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile24Service.kt @@ -12,10 +12,11 @@ class Tile24Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile25Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile25Service.kt index 2ca487e7241..f414a142cfc 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile25Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile25Service.kt @@ -12,10 +12,11 @@ class Tile25Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile26Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile26Service.kt index 5a9fb94c115..bd21b3105a2 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile26Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile26Service.kt @@ -12,10 +12,11 @@ class Tile26Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile27Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile27Service.kt index d2908017cab..7463fc44433 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile27Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile27Service.kt @@ -12,10 +12,11 @@ class Tile27Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile28Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile28Service.kt index 0af716c08ae..bad10fbe186 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile28Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile28Service.kt @@ -12,10 +12,11 @@ class Tile28Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile29Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile29Service.kt index 0e7785ff234..36758e7155b 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile29Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile29Service.kt @@ -12,10 +12,11 @@ class Tile29Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile2Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile2Service.kt index 8c39dd7d038..28581c237c8 100755 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile2Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile2Service.kt @@ -8,10 +8,11 @@ import androidx.annotation.RequiresApi class Tile2Service : TileExtensions() { override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile30Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile30Service.kt index e051c470d86..45739cad443 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile30Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile30Service.kt @@ -12,10 +12,11 @@ class Tile30Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile31Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile31Service.kt index 64bfaa15336..c0d8316e853 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile31Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile31Service.kt @@ -12,10 +12,11 @@ class Tile31Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile32Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile32Service.kt index c806d160159..bdcf4c2b08f 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile32Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile32Service.kt @@ -12,10 +12,11 @@ class Tile32Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile33Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile33Service.kt index 9d427da5385..e6cf45ab808 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile33Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile33Service.kt @@ -12,10 +12,11 @@ class Tile33Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile34Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile34Service.kt index 29ad8d2a6f9..2c4c22192bd 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile34Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile34Service.kt @@ -12,10 +12,11 @@ class Tile34Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile35Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile35Service.kt index e835d4f4bae..7b68c2ae99f 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile35Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile35Service.kt @@ -12,10 +12,11 @@ class Tile35Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile36Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile36Service.kt index 324b9ecbc15..383ee6bbe85 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile36Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile36Service.kt @@ -12,10 +12,11 @@ class Tile36Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile37Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile37Service.kt index 82325da181e..c71204753e1 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile37Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile37Service.kt @@ -12,10 +12,11 @@ class Tile37Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile38Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile38Service.kt index 2aa92cad2ab..42adaab3773 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile38Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile38Service.kt @@ -12,10 +12,11 @@ class Tile38Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile39Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile39Service.kt index e8674ae18b1..0945e6bf63f 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile39Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile39Service.kt @@ -12,10 +12,11 @@ class Tile39Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile3Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile3Service.kt index 37384fd9518..673d1730615 100755 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile3Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile3Service.kt @@ -8,10 +8,11 @@ import androidx.annotation.RequiresApi class Tile3Service : TileExtensions() { override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile40Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile40Service.kt index 6637a9c5704..ca29a993c09 100644 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile40Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile40Service.kt @@ -12,10 +12,11 @@ class Tile40Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile4Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile4Service.kt index e14e2637da4..cdf9a22b786 100755 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile4Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile4Service.kt @@ -12,10 +12,11 @@ class Tile4Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile5Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile5Service.kt index 9c08bd534c7..f419c93e9e4 100755 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile5Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile5Service.kt @@ -12,10 +12,11 @@ class Tile5Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile6Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile6Service.kt index cf296637209..d38afc6e363 100755 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile6Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile6Service.kt @@ -12,10 +12,11 @@ class Tile6Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile7Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile7Service.kt index 857164158c2..b101f8f9b3a 100755 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile7Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile7Service.kt @@ -12,10 +12,11 @@ class Tile7Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile8Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile8Service.kt index 873be42ae17..b02a7e3c55f 100755 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile8Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile8Service.kt @@ -12,10 +12,11 @@ class Tile8Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/Tile9Service.kt b/app/src/main/java/io/homeassistant/companion/android/qs/Tile9Service.kt index 0d21a06eb3b..cd2c57d2e7a 100755 --- a/app/src/main/java/io/homeassistant/companion/android/qs/Tile9Service.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/Tile9Service.kt @@ -12,10 +12,11 @@ class Tile9Service : TileExtensions() { } override fun getTile(): Tile? { - return if (qsTile != null) + return if (qsTile != null) { qsTile - else + } else { null + } } override fun getTileId(): String { diff --git a/app/src/main/java/io/homeassistant/companion/android/qs/TileExtensions.kt b/app/src/main/java/io/homeassistant/companion/android/qs/TileExtensions.kt index be27329b4b7..abd7b3f81c6 100755 --- a/app/src/main/java/io/homeassistant/companion/android/qs/TileExtensions.kt +++ b/app/src/main/java/io/homeassistant/companion/android/qs/TileExtensions.kt @@ -157,15 +157,18 @@ abstract class TileExtensions : TileService() { null } } - } else null + } else { + null + } if (tileData.entityId.split('.')[0] in toggleDomainsWithLock) { tile.state = when { state?.state in validActiveStates -> Tile.STATE_ACTIVE state?.state != null && state.state !in validActiveStates -> Tile.STATE_INACTIVE else -> Tile.STATE_UNAVAILABLE } - } else + } else { tile.state = Tile.STATE_INACTIVE + } getTileIcon(tileData.iconId, state, context)?.let { icon -> tile.icon = Icon.createWithBitmap(icon) @@ -180,8 +183,11 @@ abstract class TileExtensions : TileService() { Log.d(TAG, "No tile data found for tile ID: $tileId") } tile.state = - if (serverManager.isRegistered()) Tile.STATE_INACTIVE - else Tile.STATE_UNAVAILABLE + if (serverManager.isRegistered()) { + Tile.STATE_INACTIVE + } else { + Tile.STATE_UNAVAILABLE + } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { tile.subtitle = getString(commonR.string.tile_not_setup) } @@ -207,8 +213,9 @@ abstract class TileExtensions : TileService() { if (tileData?.shouldVibrate == true) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { vm?.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK)) - } else + } else { vm?.vibrate(500) + } } if (tileData?.authRequired == true && isSecure) { unlockAndRun { @@ -238,10 +245,11 @@ abstract class TileExtensions : TileService() { in toggleDomains -> "toggle" "lock" -> { val state = serverManager.integrationRepository(tileData.serverId).getEntity(tileData.entityId) - if (state?.state == "locked") + if (state?.state == "locked") { "unlock" - else + } else { "lock" + } } else -> "turn_on" }, @@ -276,8 +284,9 @@ abstract class TileExtensions : TileService() { val vm = getSystemService() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { vm?.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK)) - } else + } else { vm?.vibrate(1000) + } } withContext(Dispatchers.Main) { Toast.makeText( diff --git a/app/src/main/java/io/homeassistant/companion/android/sensors/DevicePolicyManager.kt b/app/src/main/java/io/homeassistant/companion/android/sensors/DevicePolicyManager.kt index 38cc015cd69..ed6ee28813e 100644 --- a/app/src/main/java/io/homeassistant/companion/android/sensors/DevicePolicyManager.kt +++ b/app/src/main/java/io/homeassistant/companion/android/sensors/DevicePolicyManager.kt @@ -52,9 +52,9 @@ class DevicePolicyManager : SensorManager { } private fun updateWorkProfile(context: Context) { - - if (!isEnabled(context, isWorkProfile)) + if (!isEnabled(context, isWorkProfile)) { return + } onSensorUpdated( context, diff --git a/app/src/main/java/io/homeassistant/companion/android/sensors/DynamicColorSensorManager.kt b/app/src/main/java/io/homeassistant/companion/android/sensors/DynamicColorSensorManager.kt index bee4b3f5689..9c63da70d3e 100755 --- a/app/src/main/java/io/homeassistant/companion/android/sensors/DynamicColorSensorManager.kt +++ b/app/src/main/java/io/homeassistant/companion/android/sensors/DynamicColorSensorManager.kt @@ -45,13 +45,13 @@ class DynamicColorSensorManager : SensorManager { } private fun updateAccentColor(context: Context) { - - if (!isEnabled(context, accentColorSensor)) + if (!isEnabled(context, accentColorSensor)) { return + } val dynamicColorContext = DynamicColors.wrapContextIfAvailable(context) val attrsToResolve = intArrayOf( - android.R.attr.colorAccent, // 0 + android.R.attr.colorAccent // 0 ) val test = dynamicColorContext.obtainStyledAttributes(attrsToResolve) val accent = test.getColor(0, 0) diff --git a/app/src/main/java/io/homeassistant/companion/android/sensors/LastAppSensorManager.kt b/app/src/main/java/io/homeassistant/companion/android/sensors/LastAppSensorManager.kt index 56fb9be4466..e44ab11a43f 100755 --- a/app/src/main/java/io/homeassistant/companion/android/sensors/LastAppSensorManager.kt +++ b/app/src/main/java/io/homeassistant/companion/android/sensors/LastAppSensorManager.kt @@ -37,6 +37,7 @@ class LastAppSensorManager : SensorManager { override fun hasSensor(context: Context): Boolean { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M } + @RequiresApi(Build.VERSION_CODES.M) override fun requiredPermissions(sensorId: String): Array { return arrayOf(Manifest.permission.PACKAGE_USAGE_STATS) @@ -51,8 +52,9 @@ class LastAppSensorManager : SensorManager { @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1) private fun updateLastApp(context: Context) { - if (!isEnabled(context, last_used)) + if (!isEnabled(context, last_used)) { return + } val usageStats = context.getSystemService()!! val current = System.currentTimeMillis() diff --git a/app/src/main/java/io/homeassistant/companion/android/sensors/NotificationSensorManager.kt b/app/src/main/java/io/homeassistant/companion/android/sensors/NotificationSensorManager.kt index 93cd205c995..ef8cf06be23 100644 --- a/app/src/main/java/io/homeassistant/companion/android/sensors/NotificationSensorManager.kt +++ b/app/src/main/java/io/homeassistant/companion/android/sensors/NotificationSensorManager.kt @@ -107,8 +107,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager { updateActiveNotificationCount() - if (!isEnabled(applicationContext, lastNotification)) + if (!isEnabled(applicationContext, lastNotification)) { return + } val allowPackages = getSetting( applicationContext, @@ -141,8 +142,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager { .plus("category" to sbn.notification.category) .toMutableMap() - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { attr["channel_id"] = sbn.notification.channelId + } // Attempt to use the text of the notification but fallback to package name if all else fails. val state = attr["android.text"] ?: attr["android.title"] ?: sbn.packageName @@ -153,7 +155,7 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager { state.toString().take(255), lastNotification.statelessIcon, attr, - forceUpdate = true, + forceUpdate = true ) // Need to send update! @@ -165,8 +167,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager { updateActiveNotificationCount() - if (!isEnabled(applicationContext, lastRemovedNotification)) + if (!isEnabled(applicationContext, lastRemovedNotification)) { return + } val allowPackages = getSetting( applicationContext, @@ -199,8 +202,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager { .plus("category" to sbn.notification.category) .toMutableMap() - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { attr["channel_id"] = sbn.notification.channelId + } // Attempt to use the text of the notification but fallback to package name if all else fails. val state = attr["android.text"] ?: attr["android.title"] ?: sbn.packageName @@ -211,7 +215,7 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager { state.toString().take(255), lastRemovedNotification.statelessIcon, attr, - forceUpdate = true, + forceUpdate = true ) // Need to send update! @@ -219,8 +223,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager { } private fun updateActiveNotificationCount() { - if (!isEnabled(applicationContext, activeNotificationCount) || !listenerConnected) + if (!isEnabled(applicationContext, activeNotificationCount) || !listenerConnected) { return + } try { val attr: MutableMap = mutableMapOf() @@ -232,8 +237,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager { .plus("${item.packageName}_${item.id}_group_id" to item.notification.group) .plus("${item.packageName}_${item.id}_category" to item.notification.category) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { attr["${item.packageName}_${item.id}_channel_id"] = item.notification.channelId + } } onSensorUpdated( applicationContext, @@ -248,8 +254,9 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager { } private fun updateMediaSession(context: Context) { - if (!isEnabled(context, mediaSession)) + if (!isEnabled(context, mediaSession)) { return + } val mediaSessionManager = context.getSystemService()!! val mediaList = mediaSessionManager.getActiveSessions(ComponentName(context, NotificationSensorManager::class.java)) @@ -307,8 +314,11 @@ class NotificationSensorManager : NotificationListenerService(), SensorManager { bundle.keySet().associate { key -> val keyValue = when (val value = bundle.get(key)) { is Array<*> -> { - if (value.all { it is Bundle }) value.map { mappedBundle(it as Bundle) ?: value } - else value.toList() + if (value.all { it is Bundle }) { + value.map { mappedBundle(it as Bundle) ?: value } + } else { + value.toList() + } } is BooleanArray -> value.toList() is Bundle -> mappedBundle(value) ?: value diff --git a/app/src/main/java/io/homeassistant/companion/android/sensors/QuestSensorManager.kt b/app/src/main/java/io/homeassistant/companion/android/sensors/QuestSensorManager.kt index eaea507d9e7..11312f047d3 100644 --- a/app/src/main/java/io/homeassistant/companion/android/sensors/QuestSensorManager.kt +++ b/app/src/main/java/io/homeassistant/companion/android/sensors/QuestSensorManager.kt @@ -59,8 +59,9 @@ class QuestSensorManager : SensorManager { } private fun updateHeadsetMount(context: Context, intent: Intent) { - if (!isEnabled(context, headsetMounted)) + if (!isEnabled(context, headsetMounted)) { return + } val state: Boolean = getHeadsetState(intent) diff --git a/app/src/main/java/io/homeassistant/companion/android/sensors/SensorReceiver.kt b/app/src/main/java/io/homeassistant/companion/android/sensors/SensorReceiver.kt index 23753d29b66..9a2eebe1c54 100644 --- a/app/src/main/java/io/homeassistant/companion/android/sensors/SensorReceiver.kt +++ b/app/src/main/java/io/homeassistant/companion/android/sensors/SensorReceiver.kt @@ -110,7 +110,7 @@ class SensorReceiver : SensorReceiverBase() { AudioManager.RINGER_MODE_CHANGED_ACTION to AudioSensorManager.audioSensor.id, Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE to DevicePolicyManager.isWorkProfile.id, Intent.ACTION_MANAGED_PROFILE_AVAILABLE to DevicePolicyManager.isWorkProfile.id, - WifiManager.WIFI_STATE_CHANGED_ACTION to NetworkSensorManager.wifiState.id, + WifiManager.WIFI_STATE_CHANGED_ACTION to NetworkSensorManager.wifiState.id ) override fun getSensorSettingsIntent( diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/SettingsActivity.kt b/app/src/main/java/io/homeassistant/companion/android/settings/SettingsActivity.kt index f3f257f3851..567fa2c8285 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/SettingsActivity.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/SettingsActivity.kt @@ -88,8 +88,11 @@ class SettingsActivity : BaseActivity() { R.id.content, when { settingsNavigation == "websocket" -> - if (serverManager.defaultServers.size == 1) WebsocketSettingFragment::class.java - else SettingsFragment::class.java + if (serverManager.defaultServers.size == 1) { + WebsocketSettingFragment::class.java + } else { + SettingsFragment::class.java + } settingsNavigation == "notification_history" -> NotificationHistoryFragment::class.java settingsNavigation?.startsWith("sensors/") == true -> SensorDetailFragment::class.java settingsNavigation?.startsWith("tiles/") == true -> ManageTilesFragment::class.java @@ -105,8 +108,12 @@ class SettingsActivity : BaseActivity() { val servers = serverManager.defaultServers if (servers.size == 1) { Bundle().apply { putInt(WebsocketSettingFragment.EXTRA_SERVER, servers[0].id) } - } else null - } else null + } else { + null + } + } else { + null + } ) } } diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/SettingsFragment.kt b/app/src/main/java/io/homeassistant/companion/android/settings/SettingsFragment.kt index 2e27eb49cda..a8aca616bd2 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/SettingsFragment.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/SettingsFragment.kt @@ -221,7 +221,6 @@ class SettingsFragment( if (BuildConfig.FLAVOR == "full") { findPreference("notification_rate_limit")?.let { - lifecycleScope.launch(Dispatchers.Main) { // Runs in IO Dispatcher val rateLimits = presenter.getNotificationRateLimits() @@ -263,9 +262,11 @@ class SettingsFragment( } findPreference("changelog_github")?.let { - val link = if (BuildConfig.VERSION_NAME.startsWith("LOCAL")) + val link = if (BuildConfig.VERSION_NAME.startsWith("LOCAL")) { "https://github.com/home-assistant/android/releases" - else "https://github.com/home-assistant/android/releases/tag/${BuildConfig.VERSION_NAME.replace("-full", "").replace("-minimal", "")}" + } else { + "https://github.com/home-assistant/android/releases/tag/${BuildConfig.VERSION_NAME.replace("-full", "").replace("-minimal", "")}" + } it.summary = link it.intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)) } diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/SettingsPresenterImpl.kt b/app/src/main/java/io/homeassistant/companion/android/settings/SettingsPresenterImpl.kt index 33d910de362..e7ff4cb0bcb 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/SettingsPresenterImpl.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/SettingsPresenterImpl.kt @@ -118,8 +118,11 @@ class SettingsPresenterImpl @Inject constructor( override suspend fun getNotificationRateLimits(): RateLimitResponse? = withContext(Dispatchers.IO) { try { - if (serverManager.isRegistered()) serverManager.integrationRepository().getNotificationRateLimits() - else null + if (serverManager.isRegistered()) { + serverManager.integrationRepository().getNotificationRateLimits() + } else { + null + } } catch (e: Exception) { Log.d(TAG, "Unable to get rate limits") return@withContext null diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/language/LanguagesManager.kt b/app/src/main/java/io/homeassistant/companion/android/settings/language/LanguagesManager.kt index 32d15e73e90..e8bbaf67aa4 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/language/LanguagesManager.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/language/LanguagesManager.kt @@ -31,7 +31,9 @@ class LanguagesManager @Inject constructor( if (lang.isNullOrEmpty()) { prefs.saveLang(DEF_LOCALE) DEF_LOCALE - } else lang + } else { + lang + } } } } @@ -42,8 +44,11 @@ class LanguagesManager @Inject constructor( val currentLang = getCurrentLang() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { val languages = - if (lang == DEF_LOCALE) LocaleListCompat.getEmptyLocaleList() - else LocaleListCompat.forLanguageTags(lang) + if (lang == DEF_LOCALE) { + LocaleListCompat.getEmptyLocaleList() + } else { + LocaleListCompat.forLanguageTags(lang) + } AppCompatDelegate.setApplicationLocales(languages) // Applying will also save it } else if (currentLang != lang) { prefs.saveLang(lang) @@ -59,8 +64,11 @@ class LanguagesManager @Inject constructor( if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.TIRAMISU) { val lang = getCurrentLang() val languages = - if (lang == DEF_LOCALE) LocaleListCompat.getEmptyLocaleList() - else LocaleListCompat.forLanguageTags(lang) + if (lang == DEF_LOCALE) { + LocaleListCompat.getEmptyLocaleList() + } else { + LocaleListCompat.forLanguageTags(lang) + } AppCompatDelegate.setApplicationLocales(languages) } // else on Android 13+ the system will manage the app's language } @@ -72,8 +80,11 @@ class LanguagesManager @Inject constructor( // First run on Android 13: save in AndroidX, update app preference val languages = - if (lang == DEF_LOCALE) LocaleListCompat.getEmptyLocaleList() - else LocaleListCompat.forLanguageTags(lang) + if (lang == DEF_LOCALE) { + LocaleListCompat.getEmptyLocaleList() + } else { + LocaleListCompat.forLanguageTags(lang) + } AppCompatDelegate.setApplicationLocales(languages) prefs.saveLang(SYSTEM_MANAGES_LOCALE) } diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/log/LogFragment.kt b/app/src/main/java/io/homeassistant/companion/android/settings/log/LogFragment.kt index 3df6a70d24c..5b661422588 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/log/LogFragment.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/log/LogFragment.kt @@ -78,8 +78,11 @@ class LogFragment : Fragment() { override fun onTabReselected(tab: TabLayout.Tab?) { (requireView().findViewById(R.id.logScrollview))?.apply { post { - if (tab?.id == R.id.logTabCrash) fullScroll(ScrollView.FOCUS_UP) - else fullScroll(ScrollView.FOCUS_DOWN) + if (tab?.id == R.id.logTabCrash) { + fullScroll(ScrollView.FOCUS_UP) + } else { + fullScroll(ScrollView.FOCUS_DOWN) + } } } } @@ -160,7 +163,6 @@ class LogFragment : Fragment() { fLogFile.appendText(currentLog) if (fLogFile.exists()) { - val uriToLog: Uri = FileProvider.getUriForFile(requireContext(), requireContext().packageName + ".provider", fLogFile) val sendIntent: Intent = Intent().apply { diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/notification/NotificationDetailFragment.kt b/app/src/main/java/io/homeassistant/companion/android/settings/notification/NotificationDetailFragment.kt index 0a75f394396..02d9e126bd3 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/notification/NotificationDetailFragment.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/notification/NotificationDetailFragment.kt @@ -52,8 +52,9 @@ class NotificationDetailFragment : Fragment() { } override fun onOptionsItemSelected(item: MenuItem): Boolean { - if (item.itemId == R.id.action_delete) + if (item.itemId == R.id.action_delete) { deleteConfirmation() + } return super.onOptionsItemSelected(item) } diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/notification/NotificationHistoryFragment.kt b/app/src/main/java/io/homeassistant/companion/android/settings/notification/NotificationHistoryFragment.kt index 27c529e0da9..f2112ce36ba 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/notification/NotificationHistoryFragment.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/notification/NotificationHistoryFragment.kt @@ -70,8 +70,9 @@ class NotificationHistoryFragment : PreferenceFragmentCompat() { var searchList: Array = emptyArray() if (!query.isNullOrEmpty()) { for (item in allNotifications) { - if (item.message.contains(query, true)) + if (item.message.contains(query, true)) { searchList += item + } } prefCategory?.title = getString(commonR.string.search_results) reloadNotifications(searchList, prefCategory) @@ -96,8 +97,9 @@ class NotificationHistoryFragment : PreferenceFragmentCompat() { } item.isChecked = !item.isChecked filterNotifications(filterValue, notificationDao, prefCategory) - } else if (item.itemId == R.id.action_delete) + } else if (item.itemId == R.id.action_delete) { deleteAllConfirmation(notificationDao) + } return super.onOptionsItemSelected(item) } diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/qs/ManageTilesViewModel.kt b/app/src/main/java/io/homeassistant/companion/android/settings/qs/ManageTilesViewModel.kt index 254c8f5bed5..05ed7d8a16c 100755 --- a/app/src/main/java/io/homeassistant/companion/android/settings/qs/ManageTilesViewModel.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/qs/ManageTilesViewModel.kt @@ -222,13 +222,19 @@ class ManageTilesViewModel @Inject constructor( selectedTileId = it?.id ?: 0 selectedTileAdded = it?.added ?: false selectedServerId = - if (it?.serverId == null || it.serverId == 0) serverManager.getServer()?.id ?: 0 - else it.serverId + if (it?.serverId == null || it.serverId == 0) { + serverManager.getServer()?.id ?: 0 + } else { + it.serverId + } selectedShouldVibrate = it?.shouldVibrate ?: false tileAuthRequired = it?.authRequired ?: false submitButtonLabel = - if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2 || it?.added == true) commonR.string.tile_save - else commonR.string.tile_add + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2 || it?.added == true) { + commonR.string.tile_save + } else { + commonR.string.tile_add + } loadEntities(selectedServerId) if (it?.isSetup == true) { updateExistingTileFields(it) @@ -278,8 +284,11 @@ class ManageTilesViewModel @Inject constructor( tileAuthRequired = currentTile.authRequired selectIcon( currentTile.iconId?.let { - if (::iconPack.isInitialized) iconPack.getIcon(it) - else null + if (::iconPack.isInitialized) { + iconPack.getIcon(it) + } else { + null + } } ) } diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/sensor/SensorDetailFragment.kt b/app/src/main/java/io/homeassistant/companion/android/settings/sensor/SensorDetailFragment.kt index ac0c8d176fb..b4b71b8baba 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/sensor/SensorDetailFragment.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/sensor/SensorDetailFragment.kt @@ -136,13 +136,16 @@ class SensorDetailFragment : Fragment() { DisabledLocationHandler.showLocationDisabledWarnDialog(requireActivity(), it.sensors) } else { LocationPermissionInfoHandler.showLocationPermInfoDialogIfNeeded( - requireContext(), it.permissions!!, + requireContext(), + it.permissions!!, continueYesCallback = { requestForServer = it.serverId permissionsRequest.launch( if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) { it.permissions.toSet().minus(Manifest.permission.ACCESS_BACKGROUND_LOCATION).toTypedArray() - } else it.permissions + } else { + it.permissions + } ) } ) diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/sensor/SensorDetailViewModel.kt b/app/src/main/java/io/homeassistant/companion/android/settings/sensor/SensorDetailViewModel.kt index b02850d2958..7b5f48fe500 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/sensor/SensorDetailViewModel.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/sensor/SensorDetailViewModel.kt @@ -102,6 +102,7 @@ class SensorDetailViewModel @Inject constructor( /** A list of all sensors (for each server) with states */ var sensors by mutableStateOf>(emptyList()) private set + /** A sensor for displaying the main state in the UI */ var sensor by mutableStateOf(null) private set @@ -208,10 +209,12 @@ class SensorDetailViewModel @Inject constructor( viewModelScope.launch { updateSensorEntity(isEnabled, serverId) - if (isEnabled) try { - sensorManager?.requestSensorUpdate(getApplication()) - } catch (e: Exception) { - Log.e(TAG, "Exception while requesting update for sensor $sensorId", e) + if (isEnabled) { + try { + sensorManager?.requestSensorUpdate(getApplication()) + } catch (e: Exception) { + Log.e(TAG, "Exception while requesting update for sensor $sensorId", e) + } } } } @@ -274,8 +277,11 @@ class SensorDetailViewModel @Inject constructor( private suspend fun updateSensorEntity(isEnabled: Boolean, serverId: Int?) { val serverIds = - if (serverId == null) serverManager.defaultServers.map { it.id } - else listOf(serverId) + if (serverId == null) { + serverManager.defaultServers.map { it.id } + } else { + listOf(serverId) + } sensorDao.setSensorEnabled(sensorId, serverIds, isEnabled) refreshSensorData() } diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/sensor/views/SensorDetailView.kt b/app/src/main/java/io/homeassistant/companion/android/settings/sensor/views/SensorDetailView.kt index a2ca6876048..68231a76d3e 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/sensor/views/SensorDetailView.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/sensor/views/SensorDetailView.kt @@ -106,8 +106,11 @@ fun SensorDetailView( context.getString(commonR.string.settings) ).let { result -> if (result == SnackbarResult.ActionPerformed) { - if (it.actionOpensSettings) context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))) - else onSetEnabled(true, it.serverId) + if (it.actionOpensSettings) { + context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))) + } else { + onSetEnabled(true, it.serverId) + } } } }.launchIn(this) @@ -121,13 +124,15 @@ fun SensorDetailView( userSetting = viewModel.settingUpdateFrequency, onDismiss = { sensorUpdateTypeInfo = false } ) - } else viewModel.sensorSettingsDialog?.let { - SensorDetailSettingDialog( - viewModel = viewModel, - state = it, - onDismiss = { viewModel.cancelSettingWithDialog() }, - onSubmit = { state -> onDialogSettingSubmitted(state) } - ) + } else { + viewModel.sensorSettingsDialog?.let { + SensorDetailSettingDialog( + viewModel = viewModel, + state = it, + onDismiss = { viewModel.cancelSettingWithDialog() }, + onSubmit = { state -> onDialogSettingSubmitted(state) } + ) + } } LazyColumn(modifier = Modifier.padding(contentPadding)) { if (viewModel.sensorManager != null && viewModel.basicSensor != null) { @@ -214,8 +219,11 @@ fun SensorDetailView( SensorDetailRow( title = viewModel.getSettingTranslatedTitle(setting.name), summary = - if (summaryValues.any()) viewModel.getSettingEntries(setting, summaryValues).joinToString(", ") - else stringResource(commonR.string.none_selected), + if (summaryValues.any()) { + viewModel.getSettingEntries(setting, summaryValues).joinToString(", ") + } else { + stringResource(commonR.string.none_selected) + }, enabled = setting.enabled, clickable = setting.enabled, onClick = { onDialogSettingClicked(setting) } @@ -283,8 +291,11 @@ fun SensorDetailTopPanel( .size(24.dp) .alpha(if (sensor?.enabled == true) ContentAlpha.high else ContentAlpha.disabled), colorFilter = ColorFilter.tint( - if (sensor?.enabled == true) colorResource(commonR.color.colorSensorIconEnabled) - else contentColorFor(backgroundColor = MaterialTheme.colors.background) + if (sensor?.enabled == true) { + colorResource(commonR.color.colorSensorIconEnabled) + } else { + contentColorFor(backgroundColor = MaterialTheme.colors.background) + } ) ) Spacer(modifier = Modifier.width(16.dp)) @@ -301,8 +312,11 @@ fun SensorDetailTopPanel( if (sensor.state.isBlank()) { stringResource(commonR.string.enabled) } else { - if (sensor.unitOfMeasurement.isNullOrBlank()) sensor.state - else "${sensor.state} ${sensor.unitOfMeasurement}" + if (sensor.unitOfMeasurement.isNullOrBlank()) { + sensor.state + } else { + "${sensor.state} ${sensor.unitOfMeasurement}" + } } } else { stringResource(commonR.string.disabled) @@ -350,15 +364,21 @@ fun SensorDetailEnableRow( .heightIn(min = 64.dp) .clickable { onSetEnabled() } val switchDescription = stringResource( - if (basicSensor.type == "binary_sensor" || basicSensor.type == "sensor") commonR.string.enable_sensor - else (if (enabled) commonR.string.enabled else commonR.string.disabled) + if (basicSensor.type == "binary_sensor" || basicSensor.type == "sensor") { + commonR.string.enable_sensor + } else { + (if (enabled) commonR.string.enabled else commonR.string.disabled) + } ) Box( modifier = - if (enabled) Modifier - .background(colorResource(commonR.color.colorSensorTopEnabled)) - .then(enableBarModifier) - else enableBarModifier, + if (enabled) { + Modifier + .background(colorResource(commonR.color.colorSensorTopEnabled)) + .then(enableBarModifier) + } else { + enableBarModifier + }, contentAlignment = Alignment.Center ) { Row( @@ -432,8 +452,11 @@ fun SensorDetailRow( Text(text = title, style = MaterialTheme.typography.body1) if (summary != null) { CompositionLocalProvider(LocalContentAlpha provides (if (enabled) ContentAlpha.medium else ContentAlpha.disabled)) { - if (selectingEnabled) SelectionContainer { Text(text = summary, style = MaterialTheme.typography.body2) } - else Text(text = summary, style = MaterialTheme.typography.body2) + if (selectingEnabled) { + SelectionContainer { Text(text = summary, style = MaterialTheme.typography.body2) } + } else { + Text(text = summary, style = MaterialTheme.typography.body2) + } } } } @@ -479,8 +502,9 @@ fun SensorDetailSettingDialog( inputValue.value = id onSubmit(state.copy().apply { setting.value = inputValue.value }) } else { - if (checkedValue.contains(id) && !isChecked) checkedValue.remove(id) - else if (!checkedValue.contains(id) && isChecked) checkedValue.add(id) + if (checkedValue.contains(id) && !isChecked) { + checkedValue.remove(id) + } else if (!checkedValue.contains(id) && isChecked) checkedValue.add(id) } } ) @@ -512,7 +536,9 @@ fun SensorDetailSettingDialog( } onSubmit(state.copy().apply { setting.value = inputValue.value }) } - } else null, // list is saved when selecting a value + } else { + null + }, // list is saved when selecting a value contentPadding = if (listSettingDialog) PaddingValues(all = 0.dp) else PaddingValues(horizontal = 24.dp) ) } diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/sensor/views/SensorListView.kt b/app/src/main/java/io/homeassistant/companion/android/settings/sensor/views/SensorListView.kt index a9449aef3b1..5cb42eddf10 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/sensor/views/SensorListView.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/sensor/views/SensorListView.kt @@ -33,7 +33,6 @@ fun SensorListView( viewModel: SensorSettingsViewModel, onSensorClicked: (String) -> Unit ) { - LazyColumn { viewModel.allSensors.forEach { (manager, currentSensors) -> stickyHeader( @@ -101,8 +100,11 @@ fun SensorRow( if (dbSensor.state.isBlank()) { stringResource(commonR.string.enabled) } else { - if (basicSensor.unitOfMeasurement.isNullOrBlank()) dbSensor.state - else "${dbSensor.state} ${basicSensor.unitOfMeasurement}" + if (basicSensor.unitOfMeasurement.isNullOrBlank()) { + dbSensor.state + } else { + "${dbSensor.state} ${basicSensor.unitOfMeasurement}" + } } } else { stringResource(commonR.string.disabled) diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/server/ServerSettingsFragment.kt b/app/src/main/java/io/homeassistant/companion/android/settings/server/ServerSettingsFragment.kt index fae091b73cb..a730bdc380b 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/server/ServerSettingsFragment.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/server/ServerSettingsFragment.kt @@ -236,16 +236,22 @@ class ServerSettingsFragment : ServerSettingsView, PreferenceFragmentCompat() { override fun updateExternalUrl(url: String, useCloud: Boolean) { findPreference("connection_external")?.let { it.summary = - if (useCloud) getString(commonR.string.input_cloud) - else url + if (useCloud) { + getString(commonR.string.input_cloud) + } else { + url + } } } override fun updateSsids(ssids: List) { findPreference("connection_internal_ssids")?.let { it.summary = - if (ssids.isEmpty()) getString(commonR.string.pref_connection_ssids_empty) - else ssids.joinToString() + if (ssids.isEmpty()) { + getString(commonR.string.pref_connection_ssids_empty) + } else { + ssids.joinToString() + } } } @@ -259,13 +265,16 @@ class ServerSettingsFragment : ServerSettingsView, PreferenceFragmentCompat() { if (DisabledLocationHandler.isLocationEnabled(requireContext())) { if (!checkPermission(permissionsToCheck)) { LocationPermissionInfoHandler.showLocationPermInfoDialogIfNeeded( - requireContext(), permissionsToCheck, + requireContext(), + permissionsToCheck, continueYesCallback = { requestLocationPermission() // showSsidSettings() will be called if permission is granted } ) - } else showSsidSettings() + } else { + showSsidSettings() + } } else { if (presenter.isSsidUsed()) { DisabledLocationHandler.showLocationDisabledWarnDialog( @@ -273,7 +282,8 @@ class ServerSettingsFragment : ServerSettingsView, PreferenceFragmentCompat() { arrayOf( getString(commonR.string.pref_connection_wifi) ), - showAsNotification = false, withDisableOption = true + showAsNotification = false, + withDisableOption = true ) { presenter.clearSsids() } diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/shortcuts/ManageShortcutsViewModel.kt b/app/src/main/java/io/homeassistant/companion/android/settings/shortcuts/ManageShortcutsViewModel.kt index 5a4928d507f..98e4ca49177 100755 --- a/app/src/main/java/io/homeassistant/companion/android/settings/shortcuts/ManageShortcutsViewModel.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/shortcuts/ManageShortcutsViewModel.kt @@ -132,10 +132,11 @@ class ManageShortcutsViewModel @Inject constructor( .setShortLabel(shortcutLabel) .setLongLabel(shortcutDesc) .setIcon( - if (bitmap != null) + if (bitmap != null) { Icon.createWithBitmap(bitmap) - else + } else { Icon.createWithResource(getApplication(), R.drawable.ic_stat_ic_notification_blue) + } ) .setIntent(intent) .build() @@ -177,12 +178,14 @@ class ManageShortcutsViewModel @Inject constructor( shortcuts.last().desc.value = item.longLabel.toString() shortcuts.last().path.value = item.intent?.action.toString() shortcuts.last().selectedIcon.value = item.intent?.extras?.getInt("iconId").toString().toIntOrNull() ?: 0 - if (shortcuts.last().selectedIcon.value != 0) + if (shortcuts.last().selectedIcon.value != 0) { shortcuts.last().drawable.value = getTileIcon(shortcuts.last().selectedIcon.value) - if (shortcuts.last().path.value.startsWith("entityId:")) + } + if (shortcuts.last().path.value.startsWith("entityId:")) { shortcuts.last().type.value = "entityId" - else + } else { shortcuts.last().type.value = "lovelace" + } } } } @@ -197,12 +200,14 @@ class ManageShortcutsViewModel @Inject constructor( shortcuts[index].desc.value = item.longLabel.toString() shortcuts[index].path.value = item.intent?.action.toString() shortcuts[index].selectedIcon.value = item.intent?.extras?.getInt("iconId").toString().toIntOrNull() ?: 0 - if (shortcuts[index].selectedIcon.value != 0) + if (shortcuts[index].selectedIcon.value != 0) { shortcuts[index].drawable.value = getTileIcon(shortcuts[index].selectedIcon.value) - if (shortcuts[index].path.value.startsWith("entityId:")) + } + if (shortcuts[index].path.value.startsWith("entityId:")) { shortcuts[index].type.value = "entityId" - else + } else { shortcuts[index].type.value = "lovelace" + } } } } diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/shortcuts/views/ManageShortcutsView.kt b/app/src/main/java/io/homeassistant/companion/android/settings/shortcuts/views/ManageShortcutsView.kt index 3680431be29..39fa9011b9c 100755 --- a/app/src/main/java/io/homeassistant/companion/android/settings/shortcuts/views/ManageShortcutsView.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/shortcuts/views/ManageShortcutsView.kt @@ -57,10 +57,11 @@ fun ManageShortcutsView( Divider() } - val shortcutCount = if (viewModel.canPinShortcuts) + val shortcutCount = if (viewModel.canPinShortcuts) { ManageShortcutsSettingsFragment.MAX_SHORTCUTS + 1 - else + } else { ManageShortcutsSettingsFragment.MAX_SHORTCUTS + } items(shortcutCount) { i -> CreateShortcutView( @@ -85,9 +86,13 @@ private fun CreateShortcutView(i: Int, viewModel: ManageShortcutsViewModel, icon val shortcutId = ManageShortcutsSettingsFragment.SHORTCUT_PREFIX + "_" + index Text( - text = if (index < 6) stringResource(id = R.string.shortcut) + " $index" else stringResource( - id = R.string.shortcut_pinned - ), + text = if (index < 6) { + stringResource(id = R.string.shortcut) + " $index" + } else { + stringResource( + id = R.string.shortcut_pinned + ) + }, fontSize = 20.sp, color = colorResource(id = R.color.colorAccent), modifier = Modifier.padding(top = 20.dp) @@ -169,10 +174,11 @@ private fun CreateShortcutView(i: Int, viewModel: ManageShortcutsViewModel, icon onValueChange = { viewModel.shortcuts[i].label.value = it }, label = { Text( - if (index < 6) + if (index < 6) { "${stringResource(id = R.string.shortcut)} $index ${stringResource(id = R.string.label)}" - else + } else { stringResource(id = R.string.shortcut_pinned_label) + } ) }, modifier = Modifier.padding(top = 16.dp) @@ -183,10 +189,11 @@ private fun CreateShortcutView(i: Int, viewModel: ManageShortcutsViewModel, icon onValueChange = { viewModel.shortcuts[i].desc.value = it }, label = { Text( - if (index < 6) + if (index < 6) { "${stringResource(id = R.string.shortcut)} $index ${stringResource(id = R.string.description)}" - else + } else { stringResource(id = R.string.shortcut_pinned_desc) + } ) }, modifier = Modifier.padding(top = 16.dp, bottom = 16.dp) @@ -251,8 +258,9 @@ private fun CreateShortcutView(i: Int, viewModel: ManageShortcutsViewModel, icon Button( onClick = { if (index < 6) { - if (viewModel.shortcuts[i].delete.value) + if (viewModel.shortcuts[i].delete.value) { Toast.makeText(context, R.string.shortcut_updated, Toast.LENGTH_SHORT).show() + } viewModel.shortcuts[i].delete.value = true } viewModel.createShortcut( @@ -276,13 +284,13 @@ private fun CreateShortcutView(i: Int, viewModel: ManageShortcutsViewModel, icon text = stringResource( id = if ( - if (index < 6) + if (index < 6) { viewModel.shortcuts[i].delete.value - else { + } else { var isCurrentPinned = false - if (viewModel.pinnedShortcuts.isEmpty()) + if (viewModel.pinnedShortcuts.isEmpty()) { isCurrentPinned = false - else { + } else { for (item in viewModel.pinnedShortcuts) { isCurrentPinned = when (item.id) { viewModel.shortcuts.last().id.value -> true @@ -292,7 +300,11 @@ private fun CreateShortcutView(i: Int, viewModel: ManageShortcutsViewModel, icon } isCurrentPinned } - ) R.string.update_shortcut else R.string.add_shortcut + ) { + R.string.update_shortcut + } else { + R.string.add_shortcut + } ) ) } diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/ssid/views/SsidView.kt b/app/src/main/java/io/homeassistant/companion/android/settings/ssid/views/SsidView.kt index 6280f20ea43..47296ef8f2f 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/ssid/views/SsidView.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/ssid/views/SsidView.kt @@ -109,7 +109,9 @@ fun SsidView( contentDescription = stringResource(commonR.string.manage_ssids_input_exists) ) } - } else null, + } else { + null + }, modifier = Modifier.weight(1f) ) Button( @@ -169,16 +171,25 @@ fun SsidView( imageVector = Icons.Default.Wifi, contentDescription = null, tint = - if (connected) colorResource(commonR.color.colorAccent) - else LocalContentColor.current.copy(alpha = LocalContentAlpha.current) + if (connected) { + colorResource(commonR.color.colorAccent) + } else { + LocalContentColor.current.copy(alpha = LocalContentAlpha.current) + } ) Text( text = - if (it.startsWith(WifiHelper.BSSID_PREFIX)) it.removePrefix(WifiHelper.BSSID_PREFIX) - else it, + if (it.startsWith(WifiHelper.BSSID_PREFIX)) { + it.removePrefix(WifiHelper.BSSID_PREFIX) + } else { + it + }, fontFamily = - if (it.startsWith(WifiHelper.BSSID_PREFIX)) FontFamily.Monospace - else null, + if (it.startsWith(WifiHelper.BSSID_PREFIX)) { + FontFamily.Monospace + } else { + null + }, modifier = Modifier .padding(horizontal = 16.dp) .weight(1f) @@ -215,8 +226,11 @@ fun SsidView( CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Text( text = stringResource( - if (prioritizeInternal) commonR.string.prioritize_internal_on - else commonR.string.prioritize_internal_off + if (prioritizeInternal) { + commonR.string.prioritize_internal_on + } else { + commonR.string.prioritize_internal_off + } ), style = MaterialTheme.typography.body2 ) diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/url/views/ExternalUrlInputView.kt b/app/src/main/java/io/homeassistant/companion/android/settings/url/views/ExternalUrlInputView.kt index 02ec50ee3d7..11df8021d74 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/url/views/ExternalUrlInputView.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/url/views/ExternalUrlInputView.kt @@ -73,7 +73,9 @@ fun ExternalUrlInputView( contentDescription = stringResource(commonR.string.url_invalid) ) } - } else null, + } else { + null + }, modifier = Modifier .focusRequester(focusRequester) .fillMaxWidth() diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/views/SettingsRow.kt b/app/src/main/java/io/homeassistant/companion/android/settings/views/SettingsRow.kt index 526ece99391..01231d2a777 100644 --- a/app/src/main/java/io/homeassistant/companion/android/settings/views/SettingsRow.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/views/SettingsRow.kt @@ -48,8 +48,11 @@ fun SettingsRow( .size(24.dp) .alpha(if (enabled) ContentAlpha.high else ContentAlpha.disabled), colorFilter = ColorFilter.tint( - if (enabled) MaterialTheme.colors.primary - else contentColorFor(backgroundColor = MaterialTheme.colors.background) + if (enabled) { + MaterialTheme.colors.primary + } else { + contentColorFor(backgroundColor = MaterialTheme.colors.background) + } ) ) } else { diff --git a/app/src/main/java/io/homeassistant/companion/android/settings/widgets/views/ManageWidgetsView.kt b/app/src/main/java/io/homeassistant/companion/android/settings/widgets/views/ManageWidgetsView.kt index cac9cb71249..313fc88a2e6 100755 --- a/app/src/main/java/io/homeassistant/companion/android/settings/widgets/views/ManageWidgetsView.kt +++ b/app/src/main/java/io/homeassistant/companion/android/settings/widgets/views/ManageWidgetsView.kt @@ -46,7 +46,7 @@ import io.homeassistant.companion.android.util.compose.MdcAlertDialog import io.homeassistant.companion.android.widgets.button.ButtonWidgetConfigureActivity import io.homeassistant.companion.android.widgets.camera.CameraWidgetConfigureActivity import io.homeassistant.companion.android.widgets.entity.EntityWidgetConfigureActivity -import io.homeassistant.companion.android.widgets.media_player_controls.MediaPlayerControlsWidgetConfigureActivity +import io.homeassistant.companion.android.widgets.mediaplayer.MediaPlayerControlsWidgetConfigureActivity import io.homeassistant.companion.android.widgets.template.TemplateWidgetConfigureActivity enum class WidgetType(val widgetIcon: IIcon) { @@ -150,13 +150,13 @@ fun ManageWidgetsView( widgetLabel = { item -> val label = item.label if (!label.isNullOrEmpty()) label else "${item.domain}.${item.service}" - }, + } ) widgetItems( viewModel.cameraWidgetList.value, widgetType = WidgetType.CAMERA, title = R.string.camera_widgets, - widgetLabel = { item -> item.entityId }, + widgetLabel = { item -> item.entityId } ) widgetItems( viewModel.staticWidgetList.value, @@ -165,7 +165,7 @@ fun ManageWidgetsView( widgetLabel = { item -> val label = item.label if (!label.isNullOrEmpty()) label else "${item.entityId} ${item.stateSeparator} ${item.attributeIds.orEmpty()}" - }, + } ) widgetItems( viewModel.mediaWidgetList.value, @@ -174,13 +174,13 @@ fun ManageWidgetsView( widgetLabel = { item -> val label = item.label if (!label.isNullOrEmpty()) label else item.entityId - }, + } ) widgetItems( viewModel.templateWidgetList.value, widgetType = WidgetType.TEMPLATE, title = R.string.template_widgets, - widgetLabel = { item -> item.template }, + widgetLabel = { item -> item.template } ) } } @@ -239,7 +239,7 @@ private fun PopupWidgetRow( private fun WidgetRow( widgetLabel: String, widgetId: Int, - widgetType: WidgetType, + widgetType: WidgetType ) { val context = LocalContext.current Row { diff --git a/app/src/main/java/io/homeassistant/companion/android/share/ShareActivity.kt b/app/src/main/java/io/homeassistant/companion/android/share/ShareActivity.kt index 2d4ee5373c2..38f97abde79 100644 --- a/app/src/main/java/io/homeassistant/companion/android/share/ShareActivity.kt +++ b/app/src/main/java/io/homeassistant/companion/android/share/ShareActivity.kt @@ -35,10 +35,11 @@ class ShareActivity : BaseActivity() { data["subject"] = it } intent.getStringExtra(Intent.EXTRA_TEXT)?.let { - if (it.toHttpUrlOrNull() == null) + if (it.toHttpUrlOrNull() == null) { data["text"] = it - else + } else { data["url"] = it + } } } runBlocking { diff --git a/app/src/main/java/io/homeassistant/companion/android/themes/ThemesManager.kt b/app/src/main/java/io/homeassistant/companion/android/themes/ThemesManager.kt index 739d22a5b98..3220caf510f 100644 --- a/app/src/main/java/io/homeassistant/companion/android/themes/ThemesManager.kt +++ b/app/src/main/java/io/homeassistant/companion/android/themes/ThemesManager.kt @@ -21,10 +21,14 @@ class ThemesManager @Inject constructor( if (theme.isNullOrEmpty()) { val toSetTheme = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { "system" - } else "light" + } else { + "light" + } themesUseCase.saveTheme(toSetTheme) toSetTheme - } else theme + } else { + theme + } } } @@ -54,7 +58,8 @@ class ThemesManager @Inject constructor( // unable to update. These deprecated settings are set to preserve compatibility for // those users. Issue: https://github.com/home-assistant/android/issues/2985 WebSettingsCompat.setForceDarkStrategy( - webSettings, WebSettingsCompat.DARK_STRATEGY_WEB_THEME_DARKENING_ONLY + webSettings, + WebSettingsCompat.DARK_STRATEGY_WEB_THEME_DARKENING_ONLY ) when (theme) { "dark" -> { diff --git a/app/src/main/java/io/homeassistant/companion/android/util/ChangeLog.kt b/app/src/main/java/io/homeassistant/companion/android/util/ChangeLog.kt index 3c32bafa621..8fa55731d5b 100755 --- a/app/src/main/java/io/homeassistant/companion/android/util/ChangeLog.kt +++ b/app/src/main/java/io/homeassistant/companion/android/util/ChangeLog.kt @@ -25,12 +25,14 @@ class ChangeLog @Inject constructor() { } if (isDarkTheme) { val darkThemeChangeLog = DarkThemeChangeLog(context) - if ((!darkThemeChangeLog.isFirstRunEver && darkThemeChangeLog.isFirstRun) || forceShow) + if ((!darkThemeChangeLog.isFirstRunEver && darkThemeChangeLog.isFirstRun) || forceShow) { darkThemeChangeLog.fullLogDialog.show() + } } else { val changeLog = ChangeLog(context) - if ((!changeLog.isFirstRunEver && changeLog.isFirstRun) || forceShow) + if ((!changeLog.isFirstRunEver && changeLog.isFirstRun) || forceShow) { changeLog.fullLogDialog.show() + } } } } diff --git a/app/src/main/java/io/homeassistant/companion/android/util/ForegroundServiceLauncher.kt b/app/src/main/java/io/homeassistant/companion/android/util/ForegroundServiceLauncher.kt index 23fbbc22e92..39249ce5f25 100644 --- a/app/src/main/java/io/homeassistant/companion/android/util/ForegroundServiceLauncher.kt +++ b/app/src/main/java/io/homeassistant/companion/android/util/ForegroundServiceLauncher.kt @@ -31,8 +31,9 @@ class ForegroundServiceLauncher(private val serviceClass: Class) { ContextCompat.startForegroundService(context, Intent(context, serviceClass).apply { block() }) Log.d(TAG, "Start service ${serviceClass.simpleName}") } else { - if (restartInProcess) Log.w(TAG, "Cannot start service ${serviceClass.simpleName}. Service currently restarting...") - else if (isRunning) Log.w(TAG, "Cannot start service ${serviceClass.simpleName}. Service is not running...") + if (restartInProcess) { + Log.w(TAG, "Cannot start service ${serviceClass.simpleName}. Service currently restarting...") + } else if (isRunning) Log.w(TAG, "Cannot start service ${serviceClass.simpleName}. Service is not running...") } } @@ -40,8 +41,9 @@ class ForegroundServiceLauncher(private val serviceClass: Class) { fun stopService(context: Context) { if (isStarting || restartInProcess) { shouldStop = true - if (restartInProcess) Log.d(TAG, "Stop service ${serviceClass.simpleName}. Service currently restarting. Stopping service after it is restarted.") - else if (isStarting) Log.d(TAG, "Stop service ${serviceClass.simpleName}. Service is currently starting. Stopping service after it is started.") + if (restartInProcess) { + Log.d(TAG, "Stop service ${serviceClass.simpleName}. Service currently restarting. Stopping service after it is restarted.") + } else if (isStarting) Log.d(TAG, "Stop service ${serviceClass.simpleName}. Service is currently starting. Stopping service after it is started.") } else if (isRunning) { context.stopService(Intent(context, serviceClass)) Log.d(TAG, "Stop service ${serviceClass.simpleName}") @@ -72,8 +74,9 @@ class ForegroundServiceLauncher(private val serviceClass: Class) { startService(context, block) } } else { - if (restartInProcess) Log.w(TAG, "Cannot restart service ${serviceClass.simpleName}. Service currently restarting...") - else if (isStarting) Log.w(TAG, "Cannot restart service ${serviceClass.simpleName}. Service is currently starting...") + if (restartInProcess) { + Log.w(TAG, "Cannot restart service ${serviceClass.simpleName}. Service currently restarting...") + } else if (isStarting) Log.w(TAG, "Cannot restart service ${serviceClass.simpleName}. Service is currently starting...") } } diff --git a/app/src/main/java/io/homeassistant/companion/android/util/OnSwipeListener.kt b/app/src/main/java/io/homeassistant/companion/android/util/OnSwipeListener.kt index 7125ea10d2a..281bb71bada 100644 --- a/app/src/main/java/io/homeassistant/companion/android/util/OnSwipeListener.kt +++ b/app/src/main/java/io/homeassistant/companion/android/util/OnSwipeListener.kt @@ -148,11 +148,17 @@ abstract class OnSwipeListener : View.OnTouchListener { companion object { fun fromVelocity(velocityX: Float, velocityY: Float): SwipeDirection { return if (abs(velocityX) > abs(velocityY)) { - if (velocityX > 0) RIGHT - else LEFT + if (velocityX > 0) { + RIGHT + } else { + LEFT + } } else { - if (velocityY > 0) DOWN - else UP + if (velocityY > 0) { + DOWN + } else { + UP + } } } } diff --git a/app/src/main/java/io/homeassistant/companion/android/util/compose/TransparentChip.kt b/app/src/main/java/io/homeassistant/companion/android/util/compose/TransparentChip.kt index d8d57430e08..42744991df1 100644 --- a/app/src/main/java/io/homeassistant/companion/android/util/compose/TransparentChip.kt +++ b/app/src/main/java/io/homeassistant/companion/android/util/compose/TransparentChip.kt @@ -59,8 +59,11 @@ fun TransparentChip( color = contentColorFor(MaterialTheme.colors.onSurface), style = MaterialTheme.typography.body2, modifier = - if (icon != null) Modifier.padding(end = 16.dp) - else Modifier.padding(horizontal = 16.dp) + if (icon != null) { + Modifier.padding(end = 16.dp) + } else { + Modifier.padding(horizontal = 16.dp) + } ) } } diff --git a/app/src/main/java/io/homeassistant/companion/android/websocket/WebsocketManager.kt b/app/src/main/java/io/homeassistant/companion/android/websocket/WebsocketManager.kt index 1b8d5fb6f23..d80c2153691 100644 --- a/app/src/main/java/io/homeassistant/companion/android/websocket/WebsocketManager.kt +++ b/app/src/main/java/io/homeassistant/companion/android/websocket/WebsocketManager.kt @@ -198,8 +198,9 @@ class WebsocketManager( } // Message and title are in the root unlike all the others. listOf("message", "title").forEach { key -> - if (it.containsKey(key)) + if (it.containsKey(key)) { flattened[key] = it[key].toString() + } } serverManager.getServer(serverId)?.let { server -> flattened["webhook_id"] = server.connection.webhookId.toString() diff --git a/app/src/main/java/io/homeassistant/companion/android/webview/WebViewActivity.kt b/app/src/main/java/io/homeassistant/companion/android/webview/WebViewActivity.kt index 3602edd6be4..83d0477d222 100644 --- a/app/src/main/java/io/homeassistant/companion/android/webview/WebViewActivity.kt +++ b/app/src/main/java/io/homeassistant/companion/android/webview/WebViewActivity.kt @@ -368,8 +368,9 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi realm: String ) { var authError = false - if (System.currentTimeMillis() <= (firstAuthTime + 500)) + if (System.currentTimeMillis() <= (firstAuthTime + 500)) { authError = true + } authenticationDialog(handler, host, realm, authError) } @@ -431,16 +432,18 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi marketIntent.data = Uri.parse(MARKET_PREFIX + intent.`package`.toString()) startActivity(marketIntent) - } else + } else { startActivity(intent) + } return true } else if (!webView.url.toString().contains(it.toString())) { Log.d(TAG, "Launching browser") val browserIntent = Intent(Intent.ACTION_VIEW, it) startActivity(browserIntent) return true - } else + } else { Log.d(TAG, "No unique cases found to override") + } } catch (e: Exception) { Log.e(TAG, "Unable to override the URL", e) } @@ -495,7 +498,6 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi } override fun onPermissionRequest(request: PermissionRequest?) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { request?.resources?.forEach { if (it == PermissionRequest.RESOURCE_VIDEO_CAPTURE) { @@ -561,8 +563,9 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi override fun onHideCustomView() { decor.removeView(myCustomView) - if (!presenter.isFullScreen()) + if (!presenter.isFullScreen()) { showSystemUI() + } isVideoFullScreen = false super.onHideCustomView() } @@ -681,13 +684,16 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi cookieManager.setAcceptThirdPartyCookies(webView, true) window.decorView.setOnSystemUiVisibilityChangeListener { visibility -> - if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) - if (presenter.isFullScreen()) + if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) { + if (presenter.isFullScreen()) { hideSystemUI() + } + } } - if (presenter.isKeepScreenOnEnabled()) + if (presenter.isKeepScreenOnEnabled()) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } currentAutoplay = presenter.isAutoPlayVideoEnabled() @@ -751,8 +757,9 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi override fun onResume() { super.onResume() - if (currentAutoplay != presenter.isAutoPlayVideoEnabled()) + if (currentAutoplay != presenter.isAutoPlayVideoEnabled()) { recreate() + } presenter.updateActiveServer() @@ -769,10 +776,11 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi else -> ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED } - if (presenter.isKeepScreenOnEnabled()) + if (presenter.isKeepScreenOnEnabled()) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) - else + } else { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } SensorWorker.start(this) WebsocketManager.start(this) @@ -837,7 +845,10 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi ).setLiveMaxSpeed(8.0f) ).setLoadControl( DefaultLoadControl.Builder().setBufferDurationsMs( - 0, 30000, 0, 0 + 0, + 30000, + 0, + 0 ).build() ).build() exoPlayer?.setMediaItem(MediaItem.fromUri(uri)) @@ -969,22 +980,25 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi Log.d(TAG, "Processing haptic tag for $hapticType") when (hapticType) { "success" -> { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { webView.performHapticFeedback(HapticFeedbackConstants.CONFIRM) - else + } else { vm?.vibrate(500) + } } "warning" -> { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { vm?.vibrate(VibrationEffect.createOneShot(400, VibrationEffect.EFFECT_HEAVY_CLICK)) - else + } else { vm?.vibrate(1500) + } } "failure" -> { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { webView.performHapticFeedback(HapticFeedbackConstants.REJECT) - else + } else { vm?.vibrate(1000) + } } "light" -> { webView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP) @@ -996,10 +1010,11 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi webView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) } "selection" -> { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { webView.performHapticFeedback(HapticFeedbackConstants.GESTURE_START) - else + } else { vm?.vibrate(50) + } } } } @@ -1025,14 +1040,16 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi unlockAppIfNeeded() val path = intent.getStringExtra(EXTRA_PATH) presenter.onViewReady(path) - if (path?.startsWith("entityId:") == true) + if (path?.startsWith("entityId:") == true) { moreInfoEntity = path.substringAfter("entityId:") + } intent.removeExtra(EXTRA_PATH) - if (presenter.isFullScreen() || isVideoFullScreen) + if (presenter.isFullScreen() || isVideoFullScreen) { hideSystemUI() - else + } else { showSystemUI() + } } } @@ -1152,8 +1169,9 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi error: SslError?, description: String? ) { - if (isShowingError || !isStarted) + if (isShowingError || !isStarted) { return + } isShowingError = true val alert = AlertDialog.Builder(this) @@ -1217,20 +1235,21 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi } } } else if (errorType == ErrorType.SSL) { - if (description != null) + if (description != null) { alert.setMessage(getString(commonR.string.webview_error_description) + " " + description) - else if (error!!.primaryError == SslError.SSL_DATE_INVALID) + } else if (error!!.primaryError == SslError.SSL_DATE_INVALID) { alert.setMessage(commonR.string.webview_error_SSL_DATE_INVALID) - else if (error.primaryError == SslError.SSL_EXPIRED) + } else if (error.primaryError == SslError.SSL_EXPIRED) { alert.setMessage(commonR.string.webview_error_SSL_EXPIRED) - else if (error.primaryError == SslError.SSL_IDMISMATCH) + } else if (error.primaryError == SslError.SSL_IDMISMATCH) { alert.setMessage(commonR.string.webview_error_SSL_IDMISMATCH) - else if (error.primaryError == SslError.SSL_INVALID) + } else if (error.primaryError == SslError.SSL_INVALID) { alert.setMessage(commonR.string.webview_error_SSL_INVALID) - else if (error.primaryError == SslError.SSL_NOTYETVALID) + } else if (error.primaryError == SslError.SSL_NOTYETVALID) { alert.setMessage(commonR.string.webview_error_SSL_NOTYETVALID) - else if (error.primaryError == SslError.SSL_UNTRUSTED) + } else if (error.primaryError == SslError.SSL_UNTRUSTED) { alert.setMessage(commonR.string.webview_error_SSL_UNTRUSTED) + } alert.setPositiveButton(commonR.string.settings) { _, _ -> startActivity(SettingsActivity.newInstance(this)) } @@ -1255,10 +1274,11 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi } val isInternal = serverManager.getServer(presenter.getActiveServer())?.connection?.isInternal() == true alert.setNegativeButton( - if (failedConnection == "external" && isInternal) + if (failedConnection == "external" && isInternal) { commonR.string.refresh_internal - else + } else { commonR.string.refresh_external + } ) { _, _ -> runBlocking { failedConnection = if (failedConnection == "external") { @@ -1317,10 +1337,11 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi var message = host + " " + getString(commonR.string.required_fields) if (resourceURL.length >= 5) { - message = if (resourceURL.subSequence(0, 5).toString() == "http:") + message = if (resourceURL.subSequence(0, 5).toString() == "http:") { "http://" + message + " " + getString(commonR.string.not_private) - else + } else { "https://$message" + } } if (!autoAuth || authError) { AlertDialog.Builder(this, R.style.Authentication_Dialog) @@ -1330,7 +1351,7 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi .setPositiveButton(android.R.string.ok) { _, _ -> if (username.text.toString() != "" && password.text.toString() != "") { if (remember.isChecked) { - if (authError) + if (authError) { authenticationDao.update( Authentication( (resourceURL + realm), @@ -1338,7 +1359,7 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi password.text.toString() ) ) - else + } else { authenticationDao.insert( Authentication( (resourceURL + realm), @@ -1346,15 +1367,18 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi password.text.toString() ) ) + } } handler.proceed(username.text.toString(), password.text.toString()) - } else AlertDialog.Builder(this) - .setTitle(commonR.string.auth_cancel) - .setMessage(commonR.string.auth_error_message) - .setPositiveButton(android.R.string.ok) { _, _ -> - authenticationDialog(handler, host, realm, authError) - } - .show() + } else { + AlertDialog.Builder(this) + .setTitle(commonR.string.auth_cancel) + .setMessage(commonR.string.auth_error_message) + .setPositiveButton(android.R.string.ok) { _, _ -> + authenticationDialog(handler, host, realm, authError) + } + .show() + } } .setNeutralButton(android.R.string.cancel) { _, _ -> Toast.makeText(applicationContext, commonR.string.auth_cancel, Toast.LENGTH_SHORT) @@ -1510,7 +1534,9 @@ class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webvi """, null ) - } else Log.d(TAG, "User is in the Home Assistant config. Will not show first view of the default dashboard.") + } else { + Log.d(TAG, "User is in the Home Assistant config. Will not show first view of the default dashboard.") + } } } diff --git a/app/src/main/java/io/homeassistant/companion/android/webview/WebViewPresenterImpl.kt b/app/src/main/java/io/homeassistant/companion/android/webview/WebViewPresenterImpl.kt index 20d9b310698..d69d6178a33 100644 --- a/app/src/main/java/io/homeassistant/companion/android/webview/WebViewPresenterImpl.kt +++ b/app/src/main/java/io/homeassistant/companion/android/webview/WebViewPresenterImpl.kt @@ -240,7 +240,9 @@ class WebViewPresenterImpl @Inject constructor( Log.w(TAG, "Cannot determine app locked state") false } - } else false + } else { + false + } } override fun setAppActive(active: Boolean) = runBlocking { @@ -313,7 +315,9 @@ class WebViewPresenterImpl @Inject constructor( m.group(2).toInt(), m.group(3).toInt() ) - } else Color.parseColor(colorString) + } else { + Color.parseColor(colorString) + } } override fun appCanCommissionMatterDevice(): Boolean = matterUseCase.appSupportsCommissioning() @@ -368,8 +372,11 @@ class WebViewPresenterImpl @Inject constructor( } else -> { // Any errors will have been shown in the UI provided by Play Services - if (result.resultCode == Activity.RESULT_OK) Log.d(TAG, "Matter commissioning returned success") - else Log.d(TAG, "Matter commissioning returned with non-OK code ${result.resultCode}") + if (result.resultCode == Activity.RESULT_OK) { + Log.d(TAG, "Matter commissioning returned success") + } else { + Log.d(TAG, "Matter commissioning returned with non-OK code ${result.resultCode}") + } } } } diff --git a/app/src/main/java/io/homeassistant/companion/android/widgets/BaseWidgetConfigureActivity.kt b/app/src/main/java/io/homeassistant/companion/android/widgets/BaseWidgetConfigureActivity.kt index 21a70a056f2..318f9c0e353 100644 --- a/app/src/main/java/io/homeassistant/companion/android/widgets/BaseWidgetConfigureActivity.kt +++ b/app/src/main/java/io/homeassistant/companion/android/widgets/BaseWidgetConfigureActivity.kt @@ -33,8 +33,11 @@ abstract class BaseWidgetConfigureActivity : BaseActivity() { serverSelectList.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, servers.map { it.friendlyName }) serverSelectList.setSelection( - if (widgetServerId != null) servers.indexOfFirst { it.id == widgetServerId } - else servers.indexOfFirst { it.id == activeServerId } + if (widgetServerId != null) { + servers.indexOfFirst { it.id == widgetServerId } + } else { + servers.indexOfFirst { it.id == activeServerId } + } ) if ( diff --git a/app/src/main/java/io/homeassistant/companion/android/widgets/BaseWidgetProvider.kt b/app/src/main/java/io/homeassistant/companion/android/widgets/BaseWidgetProvider.kt index d3da4e940cc..e193b261ad9 100644 --- a/app/src/main/java/io/homeassistant/companion/android/widgets/BaseWidgetProvider.kt +++ b/app/src/main/java/io/homeassistant/companion/android/widgets/BaseWidgetProvider.kt @@ -107,7 +107,9 @@ abstract class BaseWidgetProvider : AppWidgetProvider() { val entityUpdates = if (serverManager.getServer(serverId) != null) { serverManager.integrationRepository(serverId).getEntityUpdates(entities) - } else null + } else { + null + } if (entityUpdates != null) { widgetEntities[id] = entities widgetJobs[id] = widgetScope!!.launch { @@ -175,6 +177,7 @@ abstract class BaseWidgetProvider : AppWidgetProvider() { abstract fun getWidgetProvider(context: Context): ComponentName abstract suspend fun getWidgetRemoteViews(context: Context, appWidgetId: Int, suggestedEntity: Entity>? = null): RemoteViews + // A map of widget IDs to [server ID, list of entity IDs] abstract suspend fun getAllWidgetIdsWithEntities(context: Context): Map>> abstract fun saveEntityConfiguration(context: Context, extras: Bundle?, appWidgetId: Int) diff --git a/app/src/main/java/io/homeassistant/companion/android/widgets/button/ButtonWidget.kt b/app/src/main/java/io/homeassistant/companion/android/widgets/button/ButtonWidget.kt index 71543bc4213..c38ff1e264b 100644 --- a/app/src/main/java/io/homeassistant/companion/android/widgets/button/ButtonWidget.kt +++ b/app/src/main/java/io/homeassistant/companion/android/widgets/button/ButtonWidget.kt @@ -299,7 +299,6 @@ class ButtonWidget : AppWidgetProvider() { } else { // If everything loaded correctly, package the service data and attempt the call try { - // Convert JSON to HashMap val serviceDataMap: HashMap = jacksonObjectMapper().readValue(serviceDataJson) diff --git a/app/src/main/java/io/homeassistant/companion/android/widgets/button/ButtonWidgetConfigureActivity.kt b/app/src/main/java/io/homeassistant/companion/android/widgets/button/ButtonWidgetConfigureActivity.kt index a979fc1161c..c1734531cf1 100644 --- a/app/src/main/java/io/homeassistant/companion/android/widgets/button/ButtonWidgetConfigureActivity.kt +++ b/app/src/main/java/io/homeassistant/companion/android/widgets/button/ButtonWidgetConfigureActivity.kt @@ -144,10 +144,11 @@ class ButtonWidgetConfigureActivity : BaseWidgetConfigureActivity(), IconDialog. // Insert a dynamic layout // IDs get priority and go at the top, since the other fields // are usually optional but the ID is required - if (fieldKey.contains("_id")) + if (fieldKey.contains("_id")) { dynamicFields.add(0, ServiceFieldBinder(serviceText, fieldKey)) - else + } else { dynamicFields.add(ServiceFieldBinder(serviceText, fieldKey)) + } } dynamicFieldAdapter.notifyDataSetChanged() @@ -183,10 +184,12 @@ class ButtonWidgetConfigureActivity : BaseWidgetConfigureActivity(), IconDialog. val extras = intent.extras if (extras != null) { appWidgetId = extras.getInt( - AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID + AppWidgetManager.EXTRA_APPWIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID ) requestLauncherSetup = extras.getBoolean( - ManageWidgetsViewModel.CONFIGURE_REQUEST_LAUNCHER, false + ManageWidgetsViewModel.CONFIGURE_REQUEST_LAUNCHER, + false ) } @@ -203,8 +206,9 @@ class ButtonWidgetConfigureActivity : BaseWidgetConfigureActivity(), IconDialog. getString(commonR.string.widget_background_type_daynight), getString(commonR.string.widget_background_type_transparent) ) - if (DynamicColors.isDynamicColorAvailable()) + if (DynamicColors.isDynamicColorAvailable()) { backgroundTypeValues.add(0, getString(commonR.string.widget_background_type_dynamiccolor)) + } binding.backgroundType.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, backgroundTypeValues) if (buttonWidget != null) { @@ -280,8 +284,11 @@ class ButtonWidgetConfigureActivity : BaseWidgetConfigureActivity(), IconDialog. binding.backgroundType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { binding.textColor.visibility = - if (parent?.adapter?.getItem(position) == getString(commonR.string.widget_background_type_transparent)) View.VISIBLE - else View.GONE + if (parent?.adapter?.getItem(position) == getString(commonR.string.widget_background_type_transparent)) { + View.VISIBLE + } else { + View.GONE + } } override fun onNothingSelected(parent: AdapterView<*>?) { @@ -310,7 +317,9 @@ class ButtonWidgetConfigureActivity : BaseWidgetConfigureActivity(), IconDialog. PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE ) ) - } else showAddWidgetError() + } else { + showAddWidgetError() + } } else { onAddWidget() } @@ -341,7 +350,8 @@ class ButtonWidgetConfigureActivity : BaseWidgetConfigureActivity(), IconDialog. super.onNewIntent(intent) if (intent != null && intent.extras != null && intent.hasExtra(PIN_WIDGET_CALLBACK)) { appWidgetId = intent.extras!!.getInt( - AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID + AppWidgetManager.EXTRA_APPWIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID ) onAddWidget() } @@ -466,9 +476,11 @@ class ButtonWidgetConfigureActivity : BaseWidgetConfigureActivity(), IconDialog. intent.putExtra( ButtonWidget.EXTRA_TEXT_COLOR, - if (binding.backgroundType.selectedItem as String? == getString(commonR.string.widget_background_type_transparent)) + if (binding.backgroundType.selectedItem as String? == getString(commonR.string.widget_background_type_transparent)) { getHexForColor(if (binding.textColorWhite.isChecked) android.R.color.white else commonR.color.colorWidgetButtonLabelBlack) - else null + } else { + null + } ) intent.putExtra(ButtonWidget.EXTRA_REQUIRE_AUTHENTICATION, binding.widgetCheckboxRequireAuthentication.isChecked) diff --git a/app/src/main/java/io/homeassistant/companion/android/widgets/camera/CameraWidget.kt b/app/src/main/java/io/homeassistant/companion/android/widgets/camera/CameraWidget.kt index d5d6d13739e..d1f677853f7 100755 --- a/app/src/main/java/io/homeassistant/companion/android/widgets/camera/CameraWidget.kt +++ b/app/src/main/java/io/homeassistant/companion/android/widgets/camera/CameraWidget.kt @@ -149,8 +149,9 @@ class CameraWidget : AppWidgetProvider() { Log.d(TAG, "Fetching camera image") Handler(Looper.getMainLooper()).post { val picasso = Picasso.get() - if (BuildConfig.DEBUG) + if (BuildConfig.DEBUG) { picasso.isLoggingEnabled = true + } try { picasso.invalidate(url) picasso.load(url).resize(1024, 600).into( diff --git a/app/src/main/java/io/homeassistant/companion/android/widgets/camera/CameraWidgetConfigureActivity.kt b/app/src/main/java/io/homeassistant/companion/android/widgets/camera/CameraWidgetConfigureActivity.kt index 2b31e7137fb..c518c63be47 100755 --- a/app/src/main/java/io/homeassistant/companion/android/widgets/camera/CameraWidgetConfigureActivity.kt +++ b/app/src/main/java/io/homeassistant/companion/android/widgets/camera/CameraWidgetConfigureActivity.kt @@ -77,7 +77,9 @@ class CameraWidgetConfigureActivity : BaseWidgetConfigureActivity() { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE ) ) - } else showAddWidgetError() + } else { + showAddWidgetError() + } } else { onAddWidget() } @@ -88,10 +90,12 @@ class CameraWidgetConfigureActivity : BaseWidgetConfigureActivity() { val extras = intent.extras if (extras != null) { appWidgetId = extras.getInt( - AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID + AppWidgetManager.EXTRA_APPWIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID ) requestLauncherSetup = extras.getBoolean( - ManageWidgetsViewModel.CONFIGURE_REQUEST_LAUNCHER, false + ManageWidgetsViewModel.CONFIGURE_REQUEST_LAUNCHER, + false ) } @@ -214,7 +218,8 @@ class CameraWidgetConfigureActivity : BaseWidgetConfigureActivity() { super.onNewIntent(intent) if (intent != null && intent.extras != null && intent.hasExtra(PIN_WIDGET_CALLBACK)) { appWidgetId = intent.extras!!.getInt( - AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID + AppWidgetManager.EXTRA_APPWIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID ) onAddWidget() } diff --git a/app/src/main/java/io/homeassistant/companion/android/widgets/common/WidgetDynamicFieldAdapter.kt b/app/src/main/java/io/homeassistant/companion/android/widgets/common/WidgetDynamicFieldAdapter.kt index b9db3757b33..de2a0414db4 100644 --- a/app/src/main/java/io/homeassistant/companion/android/widgets/common/WidgetDynamicFieldAdapter.kt +++ b/app/src/main/java/io/homeassistant/companion/android/widgets/common/WidgetDynamicFieldAdapter.kt @@ -54,8 +54,11 @@ class WidgetDynamicFieldAdapter( // Reformat text to "Capital Words" instead of "capital_words" binding.dynamicAutocompleteLabel.text = fieldKey.split("_").map { - if (it == "id") it.toUpperCase() - else it.capitalize() + if (it == "id") { + it.toUpperCase() + } else { + it.capitalize() + } }.joinToString(" ") // If the field has an example, use it as a hint diff --git a/app/src/main/java/io/homeassistant/companion/android/widgets/entity/EntityWidgetConfigureActivity.kt b/app/src/main/java/io/homeassistant/companion/android/widgets/entity/EntityWidgetConfigureActivity.kt index 942bc15e9ed..1a12216a97a 100644 --- a/app/src/main/java/io/homeassistant/companion/android/widgets/entity/EntityWidgetConfigureActivity.kt +++ b/app/src/main/java/io/homeassistant/companion/android/widgets/entity/EntityWidgetConfigureActivity.kt @@ -92,7 +92,9 @@ class EntityWidgetConfigureActivity : BaseWidgetConfigureActivity() { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE ) ) - } else showAddWidgetError() + } else { + showAddWidgetError() + } } else { onAddWidget() } @@ -103,10 +105,12 @@ class EntityWidgetConfigureActivity : BaseWidgetConfigureActivity() { val extras = intent.extras if (extras != null) { appWidgetId = extras.getInt( - AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID + AppWidgetManager.EXTRA_APPWIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID ) requestLauncherSetup = extras.getBoolean( - ManageWidgetsViewModel.CONFIGURE_REQUEST_LAUNCHER, false + ManageWidgetsViewModel.CONFIGURE_REQUEST_LAUNCHER, + false ) } @@ -122,8 +126,9 @@ class EntityWidgetConfigureActivity : BaseWidgetConfigureActivity() { getString(commonR.string.widget_background_type_daynight), getString(commonR.string.widget_background_type_transparent) ) - if (DynamicColors.isDynamicColorAvailable()) + if (DynamicColors.isDynamicColorAvailable()) { backgroundTypeValues.add(0, getString(commonR.string.widget_background_type_dynamiccolor)) + } binding.backgroundType.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, backgroundTypeValues) if (staticWidget != null) { @@ -198,8 +203,11 @@ class EntityWidgetConfigureActivity : BaseWidgetConfigureActivity() { binding.backgroundType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { binding.textColor.visibility = - if (parent?.adapter?.getItem(position) == getString(commonR.string.widget_background_type_transparent)) View.VISIBLE - else View.GONE + if (parent?.adapter?.getItem(position) == getString(commonR.string.widget_background_type_transparent)) { + View.VISIBLE + } else { + View.GONE + } } override fun onNothingSelected(parent: AdapterView<*>?) { @@ -288,10 +296,11 @@ class EntityWidgetConfigureActivity : BaseWidgetConfigureActivity() { selectedServerId!! ) - val entity = if (selectedEntity == null) + val entity = if (selectedEntity == null) { binding.widgetTextConfigEntityId.text.toString() - else + } else { selectedEntity!!.entityId + } if (entity !in entities[selectedServerId].orEmpty().map { it.entityId }) { showAddWidgetError() return @@ -317,10 +326,11 @@ class EntityWidgetConfigureActivity : BaseWidgetConfigureActivity() { ) if (appendAttributes) { - val attributes = if (selectedAttributeIds.isNullOrEmpty()) + val attributes = if (selectedAttributeIds.isNullOrEmpty()) { binding.widgetTextConfigAttribute.text.toString() - else + } else { selectedAttributeIds + } intent.putExtra( EntityWidget.EXTRA_ATTRIBUTE_IDS, attributes @@ -343,9 +353,11 @@ class EntityWidgetConfigureActivity : BaseWidgetConfigureActivity() { intent.putExtra( EntityWidget.EXTRA_TEXT_COLOR, - if (binding.backgroundType.selectedItem as String? == getString(commonR.string.widget_background_type_transparent)) + if (binding.backgroundType.selectedItem as String? == getString(commonR.string.widget_background_type_transparent)) { getHexForColor(if (binding.textColorWhite.isChecked) android.R.color.white else commonR.color.colorWidgetButtonLabelBlack) - else null + } else { + null + } ) context.sendBroadcast(intent) @@ -366,7 +378,8 @@ class EntityWidgetConfigureActivity : BaseWidgetConfigureActivity() { super.onNewIntent(intent) if (intent != null && intent.extras != null && intent.hasExtra(PIN_WIDGET_CALLBACK)) { appWidgetId = intent.extras!!.getInt( - AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID + AppWidgetManager.EXTRA_APPWIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID ) onAddWidget() } diff --git a/app/src/main/java/io/homeassistant/companion/android/widgets/media_player_controls/MediaPlayerControlsWidget.kt b/app/src/main/java/io/homeassistant/companion/android/widgets/mediaplayer/MediaPlayerControlsWidget.kt similarity index 98% rename from app/src/main/java/io/homeassistant/companion/android/widgets/media_player_controls/MediaPlayerControlsWidget.kt rename to app/src/main/java/io/homeassistant/companion/android/widgets/mediaplayer/MediaPlayerControlsWidget.kt index d6adb63d46c..a0670bc3be0 100644 --- a/app/src/main/java/io/homeassistant/companion/android/widgets/media_player_controls/MediaPlayerControlsWidget.kt +++ b/app/src/main/java/io/homeassistant/companion/android/widgets/mediaplayer/MediaPlayerControlsWidget.kt @@ -1,4 +1,4 @@ -package io.homeassistant.companion.android.widgets.media_player_controls +package io.homeassistant.companion.android.widgets.mediaplayer import android.app.PendingIntent import android.appwidget.AppWidgetManager @@ -231,8 +231,9 @@ class MediaPlayerControlsWidget : BaseWidgetProvider() { var iconBitmap = IconicsDrawable(context, CommunityMaterial.Icon.cmd_cast).toBitmap() if (icon?.startsWith("mdi") == true && icon.substringAfter(":").isNotBlank()) { val iconDrawable = IconicsDrawable(context, "cmd-${icon.substringAfter(":")}") - if (iconDrawable.icon != null) + if (iconDrawable.icon != null) { iconBitmap = iconDrawable.toBitmap() + } } setImageViewBitmap( @@ -421,8 +422,9 @@ class MediaPlayerControlsWidget : BaseWidgetProvider() { } } catch (e: Exception) { Log.d(TAG, "Failed to fetch entity or entity does not exist") - if (lastIntent == UPDATE_MEDIA_IMAGE) + if (lastIntent == UPDATE_MEDIA_IMAGE) { Toast.makeText(context, commonR.string.widget_entity_fetch_error, Toast.LENGTH_LONG).show() + } return null } @@ -560,8 +562,9 @@ class MediaPlayerControlsWidget : BaseWidgetProvider() { } if (currentEntityInfo == null) { Log.d(TAG, "Failed to fetch entity or entity does not exist") - if (lastIntent != Intent.ACTION_SCREEN_ON) + if (lastIntent != Intent.ACTION_SCREEN_ON) { Toast.makeText(context, commonR.string.widget_entity_fetch_error, Toast.LENGTH_LONG).show() + } return@launch } @@ -643,8 +646,9 @@ class MediaPlayerControlsWidget : BaseWidgetProvider() { } if (currentEntityInfo == null) { Log.d(TAG, "Failed to fetch entity or entity does not exist") - if (lastIntent != Intent.ACTION_SCREEN_ON) + if (lastIntent != Intent.ACTION_SCREEN_ON) { Toast.makeText(context, commonR.string.widget_entity_fetch_error, Toast.LENGTH_LONG).show() + } return@launch } diff --git a/app/src/main/java/io/homeassistant/companion/android/widgets/media_player_controls/MediaPlayerControlsWidgetConfigureActivity.kt b/app/src/main/java/io/homeassistant/companion/android/widgets/mediaplayer/MediaPlayerControlsWidgetConfigureActivity.kt similarity index 96% rename from app/src/main/java/io/homeassistant/companion/android/widgets/media_player_controls/MediaPlayerControlsWidgetConfigureActivity.kt rename to app/src/main/java/io/homeassistant/companion/android/widgets/mediaplayer/MediaPlayerControlsWidgetConfigureActivity.kt index d0480004b2b..baa318596b1 100644 --- a/app/src/main/java/io/homeassistant/companion/android/widgets/media_player_controls/MediaPlayerControlsWidgetConfigureActivity.kt +++ b/app/src/main/java/io/homeassistant/companion/android/widgets/mediaplayer/MediaPlayerControlsWidgetConfigureActivity.kt @@ -1,4 +1,4 @@ -package io.homeassistant.companion.android.widgets.media_player_controls +package io.homeassistant.companion.android.widgets.mediaplayer import android.app.PendingIntent import android.appwidget.AppWidgetManager @@ -87,7 +87,9 @@ class MediaPlayerControlsWidgetConfigureActivity : BaseWidgetConfigureActivity() PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE ) ) - } else showAddWidgetError() + } else { + showAddWidgetError() + } } else { onAddWidget() } @@ -98,10 +100,12 @@ class MediaPlayerControlsWidgetConfigureActivity : BaseWidgetConfigureActivity() val extras = intent.extras if (extras != null) { appWidgetId = extras.getInt( - AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID + AppWidgetManager.EXTRA_APPWIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID ) requestLauncherSetup = extras.getBoolean( - ManageWidgetsViewModel.CONFIGURE_REQUEST_LAUNCHER, false + ManageWidgetsViewModel.CONFIGURE_REQUEST_LAUNCHER, + false ) } @@ -152,8 +156,9 @@ class MediaPlayerControlsWidgetConfigureActivity : BaseWidgetConfigureActivity() backgroundTypeValues.indexOf(getString(commonR.string.widget_background_type_daynight)) } ) - if (entities != null) + if (entities != null) { selectedEntities.addAll(entities) + } binding.addButton.setText(commonR.string.update_widget) } entityAdapter = SingleItemArrayAdapter(this) { it?.entityId ?: "" } @@ -279,7 +284,8 @@ class MediaPlayerControlsWidgetConfigureActivity : BaseWidgetConfigureActivity() super.onNewIntent(intent) if (intent != null && intent.extras != null && intent.hasExtra(PIN_WIDGET_CALLBACK)) { appWidgetId = intent.extras!!.getInt( - AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID + AppWidgetManager.EXTRA_APPWIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID ) onAddWidget() } diff --git a/app/src/main/java/io/homeassistant/companion/android/widgets/template/TemplateWidget.kt b/app/src/main/java/io/homeassistant/companion/android/widgets/template/TemplateWidget.kt index 0410bc14d94..89f95a76f4a 100644 --- a/app/src/main/java/io/homeassistant/companion/android/widgets/template/TemplateWidget.kt +++ b/app/src/main/java/io/homeassistant/companion/android/widgets/template/TemplateWidget.kt @@ -142,7 +142,9 @@ class TemplateWidget : AppWidgetProvider() { val templateUpdates = if (serverManager.getServer(widget.serverId) != null) { serverManager.integrationRepository(widget.serverId).getTemplateUpdates(widget.template) - } else null + } else { + null + } if (templateUpdates != null) { widgetTemplates[widget.id] = widget.template widgetJobs[widget.id] = widgetScope!!.launch { diff --git a/app/src/main/java/io/homeassistant/companion/android/widgets/template/TemplateWidgetConfigureActivity.kt b/app/src/main/java/io/homeassistant/companion/android/widgets/template/TemplateWidgetConfigureActivity.kt index c9f448eb2a2..181f820ac49 100644 --- a/app/src/main/java/io/homeassistant/companion/android/widgets/template/TemplateWidgetConfigureActivity.kt +++ b/app/src/main/java/io/homeassistant/companion/android/widgets/template/TemplateWidgetConfigureActivity.kt @@ -69,10 +69,12 @@ class TemplateWidgetConfigureActivity : BaseWidgetConfigureActivity() { val extras = intent.extras if (extras != null) { appWidgetId = extras.getInt( - AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID + AppWidgetManager.EXTRA_APPWIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID ) requestLauncherSetup = extras.getBoolean( - ManageWidgetsViewModel.CONFIGURE_REQUEST_LAUNCHER, false + ManageWidgetsViewModel.CONFIGURE_REQUEST_LAUNCHER, + false ) } @@ -88,8 +90,9 @@ class TemplateWidgetConfigureActivity : BaseWidgetConfigureActivity() { getString(commonR.string.widget_background_type_daynight), getString(commonR.string.widget_background_type_transparent) ) - if (DynamicColors.isDynamicColorAvailable()) + if (DynamicColors.isDynamicColorAvailable()) { backgroundTypeValues.add(0, getString(commonR.string.widget_background_type_dynamiccolor)) + } binding.backgroundType.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, backgroundTypeValues) setupServerSelect(templateWidget?.serverId) @@ -98,9 +101,9 @@ class TemplateWidgetConfigureActivity : BaseWidgetConfigureActivity() { binding.templateText.setText(templateWidget.template) binding.textSize.setText(templateWidget.textSize.toInt().toString()) binding.addButton.setText(commonR.string.update_widget) - if (templateWidget.template.isNotEmpty()) + if (templateWidget.template.isNotEmpty()) { renderTemplateText(templateWidget.template) - else { + } else { binding.renderedTemplate.text = getString(commonR.string.empty_template) binding.addButton.isEnabled = false } @@ -152,7 +155,9 @@ class TemplateWidgetConfigureActivity : BaseWidgetConfigureActivity() { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE ) ) - } else showAddWidgetError() // this shouldn't be possible + } else { + showAddWidgetError() // this shouldn't be possible + } } else { onAddWidget() } @@ -194,9 +199,11 @@ class TemplateWidgetConfigureActivity : BaseWidgetConfigureActivity() { ) putExtra( TemplateWidget.EXTRA_TEXT_COLOR, - if (binding.backgroundType.selectedItem as String? == getString(commonR.string.widget_background_type_transparent)) + if (binding.backgroundType.selectedItem as String? == getString(commonR.string.widget_background_type_transparent)) { getHexForColor(if (binding.textColorWhite.isChecked) android.R.color.white else commonR.color.colorWidgetButtonLabelBlack) - else null + } else { + null + } ) } applicationContext.sendBroadcast(createIntent) @@ -212,7 +219,8 @@ class TemplateWidgetConfigureActivity : BaseWidgetConfigureActivity() { super.onNewIntent(intent) if (intent != null && intent.extras != null && intent.hasExtra(PIN_WIDGET_CALLBACK)) { appWidgetId = intent.extras!!.getInt( - AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID + AppWidgetManager.EXTRA_APPWIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID ) onAddWidget() } @@ -230,8 +238,11 @@ class TemplateWidgetConfigureActivity : BaseWidgetConfigureActivity() { Log.e(TAG, "Exception while rendering template", e) // JsonMappingException suggests that template is not a String (= error) templateText = getString( - if (e.cause is JsonMappingException) commonR.string.template_error - else commonR.string.template_render_error + if (e.cause is JsonMappingException) { + commonR.string.template_error + } else { + commonR.string.template_render_error + } ) enabled = false } diff --git a/app/src/main/res/xml/media_player_control_widget_info.xml b/app/src/main/res/xml/media_player_control_widget_info.xml index 8ff7fe48261..8d6f5f380b0 100644 --- a/app/src/main/res/xml/media_player_control_widget_info.xml +++ b/app/src/main/res/xml/media_player_control_widget_info.xml @@ -1,6 +1,6 @@ ) { sharedPreferences.edit().putStringSet(key, value).apply() diff --git a/common/src/main/java/io/homeassistant/companion/android/common/bluetooth/BluetoothUtils.kt b/common/src/main/java/io/homeassistant/companion/android/common/bluetooth/BluetoothUtils.kt index 433cede8476..d980ced08f2 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/bluetooth/BluetoothUtils.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/bluetooth/BluetoothUtils.kt @@ -16,7 +16,6 @@ object BluetoothUtils { context.applicationContext.getSystemService()!! if (bluetoothManager.adapter != null) { - val adapter = bluetoothManager.adapter val isBtOn = adapter.isEnabled diff --git a/common/src/main/java/io/homeassistant/companion/android/common/bluetooth/ble/IBeaconMonitor.kt b/common/src/main/java/io/homeassistant/companion/android/common/bluetooth/ble/IBeaconMonitor.kt index 4c139d173c3..77d79b6367d 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/bluetooth/ble/IBeaconMonitor.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/bluetooth/ble/IBeaconMonitor.kt @@ -15,7 +15,7 @@ data class IBeacon( override val minor: String, val distance: Double, val rssi: Double, - var skippedUpdated: Int, + var skippedUpdated: Int ) : IBeaconNameFormat class IBeaconMonitor { @@ -31,10 +31,11 @@ class IBeaconMonitor { private fun ignoreBeacon(uuid: String): Boolean { val inList = uuidFilter.contains(uuid) - return if (uuidFilterExclude) + return if (uuidFilterExclude) { inList // exclude filter, keep those not in list - else + } else { !(inList || uuidFilter.isEmpty()) // include filter, keep those in list (or all if the list is empty) + } } fun setBeacons(context: Context, newBeacons: Collection) { diff --git a/common/src/main/java/io/homeassistant/companion/android/common/bluetooth/ble/TransmitterManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/bluetooth/ble/TransmitterManager.kt index 57b8ff98b9b..1ccba16cc41 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/bluetooth/ble/TransmitterManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/bluetooth/ble/TransmitterManager.kt @@ -33,8 +33,9 @@ object TransmitterManager { private fun validateInputs(haTransmitter: IBeaconTransmitter): Boolean { try { UUID.fromString(haTransmitter.uuid) - if (haTransmitter.major.toInt() < 0 || haTransmitter.major.toInt() > 65535 || haTransmitter.minor.toInt() < 0 || haTransmitter.minor.toInt() > 65535 || haTransmitter.measuredPowerSetting >= 0) + if (haTransmitter.major.toInt() < 0 || haTransmitter.major.toInt() > 65535 || haTransmitter.minor.toInt() < 0 || haTransmitter.minor.toInt() > 65535 || haTransmitter.measuredPowerSetting >= 0) { throw IllegalArgumentException("Invalid Major or Minor") + } } catch (e: IllegalArgumentException) { stopTransmitting(haTransmitter) haTransmitter.state = "Invalid parameters, check UUID, Major and Minor, and Measured Power settings." @@ -108,8 +109,9 @@ object TransmitterManager { fun stopTransmitting(haTransmitter: IBeaconTransmitter) { if (haTransmitter.transmitting && this::physicalTransmitter.isInitialized) { - if (physicalTransmitter.isStarted) + if (physicalTransmitter.isStarted) { physicalTransmitter.stopAdvertising() + } } haTransmitter.transmitting = false haTransmitter.state = "Stopped" diff --git a/common/src/main/java/io/homeassistant/companion/android/common/data/authentication/SessionState.kt b/common/src/main/java/io/homeassistant/companion/android/common/data/authentication/SessionState.kt index 48e8cabec6f..3f28377f6e5 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/data/authentication/SessionState.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/data/authentication/SessionState.kt @@ -2,5 +2,5 @@ package io.homeassistant.companion.android.common.data.authentication enum class SessionState { ANONYMOUS, - CONNECTED, + CONNECTED } diff --git a/common/src/main/java/io/homeassistant/companion/android/common/data/integration/Entity.kt b/common/src/main/java/io/homeassistant/companion/android/common/data/integration/Entity.kt index f3c58efc022..4fa4337e372 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/data/integration/Entity.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/data/integration/Entity.kt @@ -94,7 +94,9 @@ fun Entity.getCoverPosition(): EntityPosition? { if ( domain != "cover" || (attributes as Map<*, *>)["current_position"] == null - ) return null + ) { + return null + } val minValue = 0f val maxValue = 100f @@ -276,26 +278,29 @@ fun Entity.getIcon(context: Context): IIcon? { "group" -> CommunityMaterial.Icon2.cmd_google_circles_communities "homeassistant" -> CommunityMaterial.Icon2.cmd_home_assistant "homekit" -> CommunityMaterial.Icon2.cmd_home_automation - "humidifier" -> if (compareState == "off") + "humidifier" -> if (compareState == "off") { CommunityMaterial.Icon.cmd_air_humidifier_off - else + } else { CommunityMaterial.Icon.cmd_air_humidifier + } "image_processing" -> CommunityMaterial.Icon2.cmd_image_filter_frames "input_boolean" -> if (!entityId.endsWith(".ha_android_placeholder")) { - if (compareState == "on") + if (compareState == "on") { CommunityMaterial.Icon.cmd_check_circle_outline - else + } else { CommunityMaterial.Icon.cmd_close_circle_outline + } } else { // For SimplifiedEntity without state, use a more generic icon CommunityMaterial.Icon3.cmd_toggle_switch_outline } "input_button" -> CommunityMaterial.Icon2.cmd_gesture_tap_button - "input_datetime" -> if (attributes["has_date"] == false) + "input_datetime" -> if (attributes["has_date"] == false) { CommunityMaterial.Icon.cmd_clock - else if (attributes["has_time"] == false) + } else if (attributes["has_time"] == false) { CommunityMaterial.Icon.cmd_calendar - else + } else { CommunityMaterial.Icon.cmd_calendar_clock + } "input_select" -> CommunityMaterial.Icon2.cmd_form_dropdown "input_text" -> CommunityMaterial.Icon2.cmd_form_textbox "light" -> CommunityMaterial.Icon2.cmd_lightbulb @@ -342,10 +347,11 @@ fun Entity.getIcon(context: Context): IIcon? { "sensor" -> CommunityMaterial.Icon.cmd_eye "siren" -> CommunityMaterial.Icon.cmd_bullhorn "simple_alarm" -> CommunityMaterial.Icon.cmd_bell - "sun" -> if (compareState == "above_horizon") + "sun" -> if (compareState == "above_horizon") { CommunityMaterial.Icon3.cmd_white_balance_sunny - else + } else { CommunityMaterial.Icon3.cmd_weather_night + } "switch" -> if (!entityId.endsWith(".ha_android_placeholder")) { when (attributes["device_class"]) { "outlet" -> if (compareState == "on") CommunityMaterial.Icon3.cmd_power_plug else CommunityMaterial.Icon3.cmd_power_plug_off diff --git a/common/src/main/java/io/homeassistant/companion/android/common/data/integration/impl/IntegrationRepositoryImpl.kt b/common/src/main/java/io/homeassistant/companion/android/common/data/integration/impl/IntegrationRepositoryImpl.kt index 627560a9e2b..e1099059d7b 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/data/integration/impl/IntegrationRepositoryImpl.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/data/integration/impl/IntegrationRepositoryImpl.kt @@ -126,8 +126,11 @@ class IntegrationRepositoryImpl @AssistedInject constructor( } } - if (causeException != null) throw IntegrationException(causeException) - else throw IntegrationException("Error calling integration request update_registration") + if (causeException != null) { + throw IntegrationException(causeException) + } else { + throw IntegrationException("Error calling integration request update_registration") + } } override suspend fun getRegistration(): DeviceRegistration { @@ -139,12 +142,15 @@ class IntegrationRepositoryImpl @AssistedInject constructor( } private suspend fun persistDeviceRegistration(deviceRegistration: DeviceRegistration) { - if (deviceRegistration.appVersion != null) + if (deviceRegistration.appVersion != null) { localStorage.putString(PREF_APP_VERSION, deviceRegistration.appVersion) - if (deviceRegistration.deviceName != null) + } + if (deviceRegistration.deviceName != null) { serverManager.updateServer(server.copy(deviceName = deviceRegistration.deviceName)) - if (deviceRegistration.pushToken != null) + } + if (deviceRegistration.pushToken != null) { localStorage.putString(PREF_PUSH_TOKEN, deviceRegistration.pushToken) + } } override suspend fun deletePreferences() { @@ -176,8 +182,11 @@ class IntegrationRepositoryImpl @AssistedInject constructor( } } - if (causeException != null) throw IntegrationException(causeException) - else throw IntegrationException("Error calling integration request render_template") + if (causeException != null) { + throw IntegrationException(causeException) + } else { + throw IntegrationException("Error calling integration request render_template") + } } override suspend fun getTemplateUpdates(template: String): Flow? { @@ -204,12 +213,16 @@ class IntegrationRepositoryImpl @AssistedInject constructor( // Ignore failure until we are out of URLS to try, but use the first exception as cause exception } // if we had a successful call we can return - if (wasSuccess) + if (wasSuccess) { return + } } - if (causeException != null) throw IntegrationException(causeException) - else throw IntegrationException("Error calling integration request update_location") + if (causeException != null) { + throw IntegrationException(causeException) + } else { + throw IntegrationException("Error calling integration request update_location") + } } override suspend fun callService( @@ -242,12 +255,16 @@ class IntegrationRepositoryImpl @AssistedInject constructor( // Ignore failure until we are out of URLS to try, but use the first exception as cause exception } // if we had a successful call we can return - if (wasSuccess) + if (wasSuccess) { return + } } - if (causeException != null) throw IntegrationException(causeException) - else throw IntegrationException("Error calling integration request call_service") + if (causeException != null) { + throw IntegrationException(causeException) + } else { + throw IntegrationException("Error calling integration request call_service") + } } override suspend fun scanTag(data: HashMap) { @@ -269,12 +286,16 @@ class IntegrationRepositoryImpl @AssistedInject constructor( // Ignore failure until we are out of URLS to try, but use the first exception as cause exception } // if we had a successful call we can return - if (wasSuccess) + if (wasSuccess) { return + } } - if (causeException != null) throw IntegrationException(causeException) - else throw IntegrationException("Error calling integration request scan_tag") + if (causeException != null) { + throw IntegrationException(causeException) + } else { + throw IntegrationException("Error calling integration request scan_tag") + } } override suspend fun fireEvent(eventType: String, eventData: Map) { @@ -301,12 +322,16 @@ class IntegrationRepositoryImpl @AssistedInject constructor( // Ignore failure until we are out of URLS to try, but use the first exception as cause exception } // if we had a successful call we can return - if (wasSuccess) + if (wasSuccess) { return + } } - if (causeException != null) throw IntegrationException(causeException) - else throw IntegrationException("Error calling integration request fire_event") + if (causeException != null) { + throw IntegrationException(causeException) + } else { + throw IntegrationException("Error calling integration request fire_event") + } } override suspend fun getZones(): Array> { @@ -330,8 +355,11 @@ class IntegrationRepositoryImpl @AssistedInject constructor( } } - if (causeException != null) throw IntegrationException(causeException) - else throw IntegrationException("Error calling integration request get_zones") + if (causeException != null) { + throw IntegrationException(causeException) + } else { + throw IntegrationException("Error calling integration request get_zones") + } } override suspend fun isAppLocked(): Boolean { @@ -379,19 +407,24 @@ class IntegrationRepositoryImpl @AssistedInject constructor( causeException = e Log.e(TAG, "Unable to get notification rate limits", e) } - if (checkRateLimits != null) + if (checkRateLimits != null) { return checkRateLimits + } - if (causeException != null) throw IntegrationException(causeException) - else throw IntegrationException("Error calling checkRateLimits") + if (causeException != null) { + throw IntegrationException(causeException) + } else { + throw IntegrationException("Error calling checkRateLimits") + } } override suspend fun getHomeAssistantVersion(): String { val current = System.currentTimeMillis() val next = localStorage.getLong("${serverId}_$PREF_CHECK_SENSOR_REGISTRATION_NEXT") ?: 0 - if (current <= next) + if (current <= next) { return server._version ?: "" // Skip checking HA version as it has not been 4 hours yet + } return try { getConfig().let { response -> @@ -447,8 +480,11 @@ class IntegrationRepositoryImpl @AssistedInject constructor( } } - if (causeException != null) throw IntegrationException(causeException) - else throw IntegrationException("Error calling integration request get_config") + if (causeException != null) { + throw IntegrationException(causeException) + } else { + throw IntegrationException("Error calling integration request get_config") + } } /** @@ -564,9 +600,13 @@ class IntegrationRepositoryImpl @AssistedInject constructor( "register_sensor", SensorRequest( sensorRegistration.uniqueId, - if (canRegisterEntityDisabledState && sensorRegistration.disabled) null - else if (sensorRegistration.state is String) sensorRegistration.state.ifBlank { null } - else sensorRegistration.state, + if (canRegisterEntityDisabledState && sensorRegistration.disabled) { + null + } else if (sensorRegistration.state is String) { + sensorRegistration.state.ifBlank { null } + } else { + sensorRegistration.state + }, sensorRegistration.type, sensorRegistration.icon, sensorRegistration.attributes, @@ -596,8 +636,11 @@ class IntegrationRepositoryImpl @AssistedInject constructor( // Ignore failure until we are out of URLS to try, but use the first exception as cause exception } } - if (causeException != null) throw IntegrationException(causeException) - else throw IntegrationException("Error calling integration request register_sensor") + if (causeException != null) { + throw IntegrationException(causeException) + } else { + throw IntegrationException("Error calling integration request register_sensor") + } } override suspend fun updateSensors(sensors: Array>): Boolean { @@ -631,8 +674,11 @@ class IntegrationRepositoryImpl @AssistedInject constructor( } } - if (causeException != null) throw IntegrationException(causeException) - else throw IntegrationException("Error calling integration update_sensor_states") + if (causeException != null) { + throw IntegrationException(causeException) + } else { + throw IntegrationException("Error calling integration update_sensor_states") + } } override suspend fun shouldNotifySecurityWarning(): Boolean { diff --git a/common/src/main/java/io/homeassistant/companion/android/common/data/servers/ServerManagerImpl.kt b/common/src/main/java/io/homeassistant/companion/android/common/data/servers/ServerManagerImpl.kt index 0da491444f6..aee39d6ce27 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/data/servers/ServerManagerImpl.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/data/servers/ServerManagerImpl.kt @@ -103,8 +103,11 @@ class ServerManagerImpl @Inject constructor( private fun activeServerId(): Int? = runBlocking { val pref = localStorage.getInt(PREF_ACTIVE_SERVER) - if (pref != null && _servers[pref] != null) pref - else _servers.keys.maxOfOrNull { it } + if (pref != null && _servers[pref] != null) { + pref + } else { + _servers.keys.maxOfOrNull { it } + } } override fun getServer(id: Int): Server? { diff --git a/common/src/main/java/io/homeassistant/companion/android/common/data/websocket/impl/WebSocketRepositoryImpl.kt b/common/src/main/java/io/homeassistant/companion/android/common/data/websocket/impl/WebSocketRepositoryImpl.kt index b63df3e3b96..e6ef37453cc 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/data/websocket/impl/WebSocketRepositoryImpl.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/data/websocket/impl/WebSocketRepositoryImpl.kt @@ -141,7 +141,6 @@ class WebSocketRepositoryImpl @AssistedInject constructor( } override suspend fun getAreaRegistry(): List? { - val socketResponse = sendMessage( mapOf( "type" to "config/area_registry/list" @@ -152,7 +151,6 @@ class WebSocketRepositoryImpl @AssistedInject constructor( } override suspend fun getDeviceRegistry(): List? { - val socketResponse = sendMessage( mapOf( "type" to "config/device_registry/list" @@ -163,7 +161,6 @@ class WebSocketRepositoryImpl @AssistedInject constructor( } override suspend fun getEntityRegistry(): List? { - val socketResponse = sendMessage( mapOf( "type" to "config/entity_registry/list" @@ -364,7 +361,9 @@ class WebSocketRepositoryImpl @AssistedInject constructor( response.error.get("code").let { if (it.isNumber) it.asInt() else null } - } else null + } else { + null + } ) } } @@ -392,7 +391,9 @@ class WebSocketRepositoryImpl @AssistedInject constructor( response.error.get("code").let { if (it.isNumber) it.asInt() else null } - } else null + } else { + null + } ) } } @@ -409,7 +410,9 @@ class WebSocketRepositoryImpl @AssistedInject constructor( ) return if (response?.success == true && response.result?.contains("datasets") == true) { mapper.convertValue(response.result["datasets"]!!) - } else null + } else { + null + } } /** @@ -648,8 +651,9 @@ class WebSocketRepositoryImpl @AssistedInject constructor( connected = CompletableDeferred() connection = null connectionHaVersion = null - if (connectionState != WebSocketState.CLOSED_AUTH) + if (connectionState != WebSocketState.CLOSED_AUTH) { connectionState = WebSocketState.CLOSED_OTHER + } synchronized(activeMessages) { activeMessages .filterValues { it.eventFlow == null } diff --git a/common/src/main/java/io/homeassistant/companion/android/common/data/websocket/impl/entities/CompressedEntity.kt b/common/src/main/java/io/homeassistant/companion/android/common/data/websocket/impl/entities/CompressedEntity.kt index a0e2d50b475..bc8cf048fd6 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/data/websocket/impl/entities/CompressedEntity.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/data/websocket/impl/entities/CompressedEntity.kt @@ -61,12 +61,18 @@ data class CompressedEntityState( lastChanged = Calendar.getInstance().apply { timeInMillis = round(lastChanged!! * 1000).toLong() }, lastUpdated = Calendar.getInstance().apply { timeInMillis = - if (lastUpdated != null) round(lastUpdated * 1000).toLong() - else round(lastChanged!! * 1000).toLong() + if (lastUpdated != null) { + round(lastUpdated * 1000).toLong() + } else { + round(lastChanged!! * 1000).toLong() + } }, context = - if (context is String) mapOf("id" to context, "parent_id" to null, "user_id" to null) - else context as? Map + if (context is String) { + mapOf("id" to context, "parent_id" to null, "user_id" to null) + } else { + context as? Map + } ) } } diff --git a/common/src/main/java/io/homeassistant/companion/android/common/data/wifi/WifiHelper.kt b/common/src/main/java/io/homeassistant/companion/android/common/data/wifi/WifiHelper.kt index 15ed1d13ca8..017dbac39a9 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/data/wifi/WifiHelper.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/data/wifi/WifiHelper.kt @@ -9,6 +9,7 @@ interface WifiHelper { /** Returns if the active data connection is using Wi-Fi */ fun isUsingWifi(): Boolean + /** Returns if the active data connection is using one of the provided Wi-Fi networks */ fun isUsingSpecificWifi(networks: List): Boolean fun getWifiSsid(): String? diff --git a/common/src/main/java/io/homeassistant/companion/android/common/notifications/DeviceCommands.kt b/common/src/main/java/io/homeassistant/companion/android/common/notifications/DeviceCommands.kt index 41e108a9737..3b0bda683af 100755 --- a/common/src/main/java/io/homeassistant/companion/android/common/notifications/DeviceCommands.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/notifications/DeviceCommands.kt @@ -40,7 +40,10 @@ object DeviceCommandData { const val BLE_TRANSMIT = "ble_transmit" val BLE_COMMANDS = listOf( - BLE_SET_ADVERTISE_MODE, BLE_SET_TRANSMIT_POWER, BLE_SET_UUID, BLE_SET_MAJOR, + BLE_SET_ADVERTISE_MODE, + BLE_SET_TRANSMIT_POWER, + BLE_SET_UUID, + BLE_SET_MAJOR, BLE_SET_MINOR ) val BLE_TRANSMIT_COMMANDS = @@ -86,10 +89,12 @@ fun commandBeaconMonitor( } val command = data[NotificationData.COMMAND] Log.d(TAG, "Processing command: ${data[NotificationData.MESSAGE]}") - if (command == DeviceCommandData.TURN_OFF) + if (command == DeviceCommandData.TURN_OFF) { BluetoothSensorManager.enableDisableBeaconMonitor(context, false) - if (command == DeviceCommandData.TURN_ON) + } + if (command == DeviceCommandData.TURN_ON) { BluetoothSensorManager.enableDisableBeaconMonitor(context, true) + } return true } @@ -108,10 +113,12 @@ fun commandBleTransmitter( } val command = data[NotificationData.COMMAND] Log.d(TAG, "Processing command: ${data[NotificationData.MESSAGE]}") - if (command == DeviceCommandData.TURN_OFF) + if (command == DeviceCommandData.TURN_OFF) { BluetoothSensorManager.enableDisableBLETransmitter(context, false) - if (command == DeviceCommandData.TURN_ON) + } + if (command == DeviceCommandData.TURN_ON) { BluetoothSensorManager.enableDisableBLETransmitter(context, true) + } if (command in DeviceCommandData.BLE_COMMANDS) { sensorDao.updateSettingValue( BluetoothSensorManager.bleTransmitter.id, diff --git a/common/src/main/java/io/homeassistant/companion/android/common/notifications/NotificationFunctions.kt b/common/src/main/java/io/homeassistant/companion/android/common/notifications/NotificationFunctions.kt index b9129973df2..67a3a25fcbd 100755 --- a/common/src/main/java/io/homeassistant/companion/android/common/notifications/NotificationFunctions.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/notifications/NotificationFunctions.kt @@ -81,8 +81,9 @@ fun handleChannel( handleImportance(data) ) - if (channelName == NotificationData.ALARM_STREAM) + if (channelName == NotificationData.ALARM_STREAM) { handleChannelSound(context, channel) + } setChannelLedColor(context, data, channel) setChannelVibrationPattern(data, channel) @@ -95,7 +96,6 @@ fun handleChannel( fun handleImportance( data: Map ): Int { - when (data[NotificationData.IMPORTANCE]) { "high" -> { return NotificationManager.IMPORTANCE_HIGH @@ -210,12 +210,14 @@ fun handleSmallIcon( val iconName = notificationIcon.split(":")[1] val iconDrawable = IconicsDrawable(context, "cmd-$iconName") - if (iconDrawable.icon != null) + if (iconDrawable.icon != null) { builder.setSmallIcon(iconDrawable.toAndroidIconCompat()) - else + } else { builder.setSmallIcon(R.drawable.ic_stat_ic_notification) - } else + } + } else { builder.setSmallIcon(R.drawable.ic_stat_ic_notification) + } } fun getGroupNotificationBuilder( @@ -224,7 +226,6 @@ fun getGroupNotificationBuilder( group: String, data: Map ): NotificationCompat.Builder { - val groupNotificationBuilder = NotificationCompat.Builder(context, channelId) .setStyle( NotificationCompat.BigTextStyle() @@ -235,8 +236,9 @@ fun getGroupNotificationBuilder( .setGroup(group) .setGroupSummary(true) - if (data[NotificationData.ALERT_ONCE].toBoolean()) + if (data[NotificationData.ALERT_ONCE].toBoolean()) { groupNotificationBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN) + } handleColor(context, groupNotificationBuilder, data) handleSmallIcon(context, groupNotificationBuilder, data) return groupNotificationBuilder diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/AppSensorManagerBase.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/AppSensorManagerBase.kt index 923296fd6f2..e213fa34c8b 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/AppSensorManagerBase.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/AppSensorManagerBase.kt @@ -101,12 +101,21 @@ abstract class AppSensorManagerBase : SensorManager { return when { (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) -> listOf( - currentVersion, app_rx_gb, app_tx_gb, app_memory, app_inactive, - app_standby_bucket, app_importance + currentVersion, + app_rx_gb, + app_tx_gb, + app_memory, + app_inactive, + app_standby_bucket, + app_importance ) (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) -> listOf( - currentVersion, app_rx_gb, app_tx_gb, app_memory, app_inactive, + currentVersion, + app_rx_gb, + app_tx_gb, + app_memory, + app_inactive, app_importance ) else -> listOf(currentVersion, app_rx_gb, app_tx_gb, app_memory, app_importance) @@ -129,17 +138,18 @@ abstract class AppSensorManagerBase : SensorManager { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val usageStatsManager = context.getSystemService()!! updateAppInactive(context, usageStatsManager) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { updateAppStandbyBucket(context, usageStatsManager) + } } } abstract fun getCurrentVersion(): String private fun updateCurrentVersion(context: Context) { - - if (!isEnabled(context, currentVersion)) + if (!isEnabled(context, currentVersion)) { return + } val state = getCurrentVersion() @@ -153,9 +163,9 @@ abstract class AppSensorManagerBase : SensorManager { } private fun updateAppRxGb(context: Context, appUid: Int) { - - if (!isEnabled(context, app_rx_gb)) + if (!isEnabled(context, app_rx_gb)) { return + } val appRx = try { TrafficStats.getUidRxBytes(appUid).toFloat() / GB @@ -174,9 +184,9 @@ abstract class AppSensorManagerBase : SensorManager { } private fun updateAppTxGb(context: Context, appUid: Int) { - - if (!isEnabled(context, app_tx_gb)) + if (!isEnabled(context, app_tx_gb)) { return + } val appTx = try { TrafficStats.getUidTxBytes(appUid).toFloat() / GB @@ -195,9 +205,9 @@ abstract class AppSensorManagerBase : SensorManager { } private fun updateAppMemory(context: Context) { - - if (!isEnabled(context, app_memory)) + if (!isEnabled(context, app_memory)) { return + } val runTime = Runtime.getRuntime() val freeSize = runTime.freeMemory().toFloat() / GB @@ -218,8 +228,9 @@ abstract class AppSensorManagerBase : SensorManager { @RequiresApi(Build.VERSION_CODES.M) private fun updateAppInactive(context: Context, usageStatsManager: UsageStatsManager) { - if (!isEnabled(context, app_inactive)) + if (!isEnabled(context, app_inactive)) { return + } val isAppInactive = usageStatsManager.isAppInactive(context.packageName) @@ -236,8 +247,9 @@ abstract class AppSensorManagerBase : SensorManager { @RequiresApi(Build.VERSION_CODES.P) private fun updateAppStandbyBucket(context: Context, usageStatsManager: UsageStatsManager) { - if (!isEnabled(context, app_standby_bucket)) + if (!isEnabled(context, app_standby_bucket)) { return + } val appStandbyBucket = when (usageStatsManager.appStandbyBucket) { UsageStatsManager.STANDBY_BUCKET_ACTIVE -> "active" @@ -258,8 +270,9 @@ abstract class AppSensorManagerBase : SensorManager { } private fun updateImportanceCheck(context: Context) { - if (!isEnabled(context, app_importance)) + if (!isEnabled(context, app_importance)) { return + } val appManager = context.getSystemService()!! val currentProcess = appManager.runningAppProcesses diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/AudioSensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/AudioSensorManager.kt index 0a6778ecdfe..3b172fb5f92 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/AudioSensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/AudioSensorManager.kt @@ -42,8 +42,11 @@ class AudioSensorManager : SensorManager { commonR.string.sensor_description_mic_muted, "mdi:microphone-off", updateType = - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) SensorManager.BasicSensor.UpdateType.INTENT - else SensorManager.BasicSensor.UpdateType.WORKER + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + SensorManager.BasicSensor.UpdateType.INTENT + } else { + SensorManager.BasicSensor.UpdateType.WORKER + } ) private val musicActive = SensorManager.BasicSensor( "music_active", @@ -59,8 +62,11 @@ class AudioSensorManager : SensorManager { commonR.string.sensor_description_speakerphone, "mdi:volume-high", updateType = - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) SensorManager.BasicSensor.UpdateType.INTENT - else SensorManager.BasicSensor.UpdateType.WORKER + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + SensorManager.BasicSensor.UpdateType.INTENT + } else { + SensorManager.BasicSensor.UpdateType.WORKER + } ) private val volAlarm = SensorManager.BasicSensor( "volume_alarm", @@ -141,10 +147,11 @@ class AudioSensorManager : SensorManager { musicActive, volAlarm, volCall, volMusic, volRing, volNotification, volSystem, volDTMF ) - return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { allSupportedSensors.plus(volAccessibility) - else + } else { allSupportedSensors + } } override fun requiredPermissions(sensorId: String): Array { @@ -166,13 +173,15 @@ class AudioSensorManager : SensorManager { updateVolumeNotification(context, audioManager) updateVolumeSystem(context, audioManager) updateVolumeDTMF(context, audioManager) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { updateVolumeAccessibility(context, audioManager) + } } private fun updateAudioSensor(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, audioSensor)) + if (!isEnabled(context, audioSensor)) { return + } val ringerMode = when (audioManager.ringerMode) { AudioManager.RINGER_MODE_NORMAL -> "normal" @@ -198,8 +207,9 @@ class AudioSensorManager : SensorManager { } private fun updateAudioState(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, audioState)) + if (!isEnabled(context, audioState)) { return + } val audioMode = when (audioManager.mode) { AudioManager.MODE_NORMAL -> "normal" AudioManager.MODE_RINGTONE -> "ringing" @@ -228,15 +238,17 @@ class AudioSensorManager : SensorManager { } private fun updateHeadphoneState(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, headphoneState)) + if (!isEnabled(context, headphoneState)) { return + } var isHeadphones = false if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val audioDevices = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS) for (deviceInfo in audioDevices) { - if (deviceInfo.type == AudioDeviceInfo.TYPE_WIRED_HEADPHONES || deviceInfo.type == AudioDeviceInfo.TYPE_WIRED_HEADSET || deviceInfo.type == AudioDeviceInfo.TYPE_USB_HEADSET) + if (deviceInfo.type == AudioDeviceInfo.TYPE_WIRED_HEADPHONES || deviceInfo.type == AudioDeviceInfo.TYPE_WIRED_HEADSET || deviceInfo.type == AudioDeviceInfo.TYPE_USB_HEADSET) { isHeadphones = true + } } } else { // Use deprecated method as getDevices is API 23 and up only and we support API 21 @@ -255,8 +267,9 @@ class AudioSensorManager : SensorManager { } private fun updateMicMuted(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, micMuted)) + if (!isEnabled(context, micMuted)) { return + } val isMicMuted = audioManager.isMicrophoneMute @@ -272,8 +285,9 @@ class AudioSensorManager : SensorManager { } private fun updateMusicActive(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, musicActive)) + if (!isEnabled(context, musicActive)) { return + } val isMusicActive = audioManager.isMusicActive @@ -289,8 +303,9 @@ class AudioSensorManager : SensorManager { } private fun updateSpeakerphoneState(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, speakerphoneState)) + if (!isEnabled(context, speakerphoneState)) { return + } val isSpeakerOn = audioManager.isSpeakerphoneOn @@ -306,8 +321,9 @@ class AudioSensorManager : SensorManager { } private fun updateVolumeAlarm(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, volAlarm)) + if (!isEnabled(context, volAlarm)) { return + } val volumeLevelAlarm = audioManager.getStreamVolume(AudioManager.STREAM_ALARM) onSensorUpdated( @@ -320,8 +336,9 @@ class AudioSensorManager : SensorManager { } private fun updateVolumeCall(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, volCall)) + if (!isEnabled(context, volCall)) { return + } val volumeLevelCall = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL) @@ -335,8 +352,9 @@ class AudioSensorManager : SensorManager { } private fun updateVolumeMusic(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, volMusic)) + if (!isEnabled(context, volMusic)) { return + } val volumeLevelMusic = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) @@ -350,8 +368,9 @@ class AudioSensorManager : SensorManager { } private fun updateVolumeRing(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, volRing)) + if (!isEnabled(context, volRing)) { return + } val volumeLevelRing = audioManager.getStreamVolume(AudioManager.STREAM_RING) @@ -365,8 +384,9 @@ class AudioSensorManager : SensorManager { } private fun updateVolumeNotification(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, volNotification)) + if (!isEnabled(context, volNotification)) { return + } val volumeLevelNotification = audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) @@ -380,8 +400,9 @@ class AudioSensorManager : SensorManager { } private fun updateVolumeSystem(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, volSystem)) + if (!isEnabled(context, volSystem)) { return + } val volumeLevelSystem = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM) @@ -396,8 +417,9 @@ class AudioSensorManager : SensorManager { @RequiresApi(Build.VERSION_CODES.O) private fun updateVolumeAccessibility(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, volAccessibility)) + if (!isEnabled(context, volAccessibility)) { return + } val volumeLevelAccessibility = audioManager.getStreamVolume(AudioManager.STREAM_ACCESSIBILITY) @@ -411,8 +433,9 @@ class AudioSensorManager : SensorManager { } private fun updateVolumeDTMF(context: Context, audioManager: AudioManager) { - if (!isEnabled(context, volDTMF)) + if (!isEnabled(context, volDTMF)) { return + } val volumeLevelDTMF = audioManager.getStreamVolume(AudioManager.STREAM_DTMF) diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/BatterySensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/BatterySensorManager.kt index faeca2a10a8..400d6cd6ed9 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/BatterySensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/BatterySensorManager.kt @@ -141,8 +141,9 @@ class BatterySensorManager : SensorManager { } private fun updateBatteryLevel(context: Context, intent: Intent) { - if (!isEnabled(context, batteryLevel)) + if (!isEnabled(context, batteryLevel)) { return + } val percentage = getBatteryPercentage(intent) val baseIcon = when (getChargingStatus(intent)) { @@ -172,8 +173,9 @@ class BatterySensorManager : SensorManager { } private fun updateBatteryState(context: Context, intent: Intent) { - if (!isEnabled(context, batteryState)) + if (!isEnabled(context, batteryState)) { return + } val chargingStatus = getChargingStatus(intent) @@ -194,8 +196,9 @@ class BatterySensorManager : SensorManager { } private fun updateIsCharging(context: Context, intent: Intent) { - if (!isEnabled(context, isChargingState)) + if (!isEnabled(context, isChargingState)) { return + } val isCharging = getIsCharging(intent) @@ -210,8 +213,9 @@ class BatterySensorManager : SensorManager { } private fun updateChargerType(context: Context, intent: Intent) { - if (!isEnabled(context, chargerTypeState)) + if (!isEnabled(context, chargerTypeState)) { return + } val chargerType = getChargerType(intent) @@ -231,8 +235,9 @@ class BatterySensorManager : SensorManager { } private fun updateBatteryHealth(context: Context, intent: Intent) { - if (!isEnabled(context, batteryHealthState)) + if (!isEnabled(context, batteryHealthState)) { return + } val batteryHealth = getBatteryHealth(intent) @@ -250,8 +255,9 @@ class BatterySensorManager : SensorManager { } private fun updateBatteryTemperature(context: Context, intent: Intent) { - if (!isEnabled(context, batteryTemperature)) + if (!isEnabled(context, batteryTemperature)) { return + } val batteryTemp = getBatteryTemperature(intent) @@ -265,8 +271,9 @@ class BatterySensorManager : SensorManager { } private fun updateBatteryPower(context: Context, intent: Intent) { - if (!isEnabled(context, batteryPower)) + if (!isEnabled(context, batteryPower)) { return + } val voltage = getBatteryVolts(intent) val batteryManager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/BluetoothSensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/BluetoothSensorManager.kt index 29e882829d8..58b8ec118f7 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/BluetoothSensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/BluetoothSensorManager.kt @@ -104,8 +104,9 @@ class BluetoothSensorManager : SensorManager { fun enableDisableBLETransmitter(context: Context, transmitEnabled: Boolean) { val sensorDao = AppDatabase.getInstance(context).sensorDao() val sensorEntity = sensorDao.get(bleTransmitter.id) - if (sensorEntity.none { it.enabled }) + if (sensorEntity.none { it.enabled }) { return + } TransmitterManager.stopTransmitting(bleTransmitterDevice) // stop in all instances, clean up state if start required if (transmitEnabled) { @@ -117,8 +118,9 @@ class BluetoothSensorManager : SensorManager { fun enableDisableBeaconMonitor(context: Context, monitorEnabled: Boolean) { val sensorDao = AppDatabase.getInstance(context).sensorDao() val sensorEntity = sensorDao.get(beaconMonitor.id) - if (sensorEntity.none { it.enabled }) + if (sensorEntity.none { it.enabled }) { return + } if (monitorEnabled) { monitoringManager.startMonitoring(context, beaconMonitoringDevice) @@ -154,7 +156,7 @@ class BluetoothSensorManager : SensorManager { Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION, - Manifest.permission.ACCESS_COARSE_LOCATION, + Manifest.permission.ACCESS_COARSE_LOCATION ) } (sensorId == beaconMonitor.id && Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) -> { @@ -163,7 +165,7 @@ class BluetoothSensorManager : SensorManager { Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION, - Manifest.permission.ACCESS_COARSE_LOCATION, + Manifest.permission.ACCESS_COARSE_LOCATION ) } (sensorId == beaconMonitor.id && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) -> { @@ -172,7 +174,7 @@ class BluetoothSensorManager : SensorManager { Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION, - Manifest.permission.ACCESS_COARSE_LOCATION, + Manifest.permission.ACCESS_COARSE_LOCATION ) } (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) -> { @@ -195,8 +197,9 @@ class BluetoothSensorManager : SensorManager { } private fun updateBluetoothConnectionSensor(context: Context) { - if (!isEnabled(context, bluetoothConnection)) + if (!isEnabled(context, bluetoothConnection)) { return + } var totalConnectedDevices = 0 var connectedPairedDevices: List = ArrayList() @@ -204,7 +207,6 @@ class BluetoothSensorManager : SensorManager { var pairedDevices: List = ArrayList() if (checkPermission(context, bluetoothConnection.id)) { - val bluetoothDevices = BluetoothUtils.getBluetoothDevices(context) pairedDevices = bluetoothDevices.filter { b -> b.paired }.map { checkNameAddress(it) } connectedPairedDevices = bluetoothDevices.filter { b -> b.paired && b.connected }.map { checkNameAddress(it) } @@ -233,8 +235,9 @@ class BluetoothSensorManager : SensorManager { } private fun updateBluetoothState(context: Context) { - if (!isEnabled(context, bluetoothState)) + if (!isEnabled(context, bluetoothState)) { return + } val icon = if (isBtOn(context)) "mdi:bluetooth" else "mdi:bluetooth-off" onSensorUpdated( context, @@ -257,7 +260,10 @@ class BluetoothSensorManager : SensorManager { settingName = SETTING_BLE_TRANSMIT_POWER, settingType = SensorSettingType.LIST, entries = listOf( - BLE_TRANSMIT_ULTRA_LOW, BLE_TRANSMIT_LOW, BLE_TRANSMIT_MEDIUM, BLE_TRANSMIT_HIGH + BLE_TRANSMIT_ULTRA_LOW, + BLE_TRANSMIT_LOW, + BLE_TRANSMIT_MEDIUM, + BLE_TRANSMIT_HIGH ), default = DEFAULT_BLE_TRANSMIT_POWER ) @@ -267,7 +273,9 @@ class BluetoothSensorManager : SensorManager { settingName = SETTING_BLE_ADVERTISE_MODE, settingType = SensorSettingType.LIST, entries = listOf( - BLE_ADVERTISE_LOW_POWER, BLE_ADVERTISE_BALANCED, BLE_ADVERTISE_LOW_LATENCY + BLE_ADVERTISE_LOW_POWER, + BLE_ADVERTISE_BALANCED, + BLE_ADVERTISE_LOW_LATENCY ), default = DEFAULT_BLE_ADVERTISE_MODE ) @@ -319,7 +327,7 @@ class BluetoothSensorManager : SensorManager { monitoringManager.scanPeriod = scanPeriod monitoringManager.scanInterval = scanInterval - if (!isEnabled(context, beaconMonitor) || ! monitoringActive || restart) { + if (!isEnabled(context, beaconMonitor) || !monitoringActive || restart) { monitoringManager.stopMonitoring(context, beaconMonitoringDevice) } else { monitoringManager.startMonitoring(context, beaconMonitoringDevice) diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/DNDSensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/DNDSensorManager.kt index c8425700be4..b43357110d8 100755 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/DNDSensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/DNDSensorManager.kt @@ -39,8 +39,9 @@ class DNDSensorManager : SensorManager { } override fun requestSensorUpdate(context: Context) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { updateDNDState(context) + } } @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.M) @@ -49,9 +50,9 @@ class DNDSensorManager : SensorManager { } private fun updateDNDState(context: Context) { - - if (!isEnabled(context, dndSensor)) + if (!isEnabled(context, dndSensor)) { return + } val notificationManager = context.getSystemService() diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/DisplaySensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/DisplaySensorManager.kt index 909d25595ee..09764281b00 100755 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/DisplaySensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/DisplaySensorManager.kt @@ -46,8 +46,9 @@ class DisplaySensorManager : SensorManager { } private fun updateScreenBrightness(context: Context) { - if (!isEnabled(context, screenBrightness)) + if (!isEnabled(context, screenBrightness)) { return + } var brightness = 0 var auto = false @@ -76,8 +77,9 @@ class DisplaySensorManager : SensorManager { } private fun updateScreenTimeout(context: Context) { - if (!isEnabled(context, screenOffTimeout)) + if (!isEnabled(context, screenOffTimeout)) { return + } var timeout = 0 diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/KeyguardSensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/KeyguardSensorManager.kt index 40ec7ef5e83..ddd706d78dc 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/KeyguardSensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/KeyguardSensorManager.kt @@ -67,10 +67,12 @@ class KeyguardSensorManager : SensorManager { context: Context ) { val km = context.getSystemService()!! - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { updateDeviceLocked(context, km) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { updateDeviceSecure(context, km) + } updateKeyguardLocked(context, km) updateKeyguardSecure(context, km) @@ -78,9 +80,9 @@ class KeyguardSensorManager : SensorManager { @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1) private fun updateDeviceLocked(context: Context, km: KeyguardManager) { - - if (!isEnabled(context, deviceLocked)) + if (!isEnabled(context, deviceLocked)) { return + } val isLocked = km.isDeviceLocked val icon = if (isLocked) "mdi:cellphone-lock" else "mdi:cellphone" @@ -96,9 +98,9 @@ class KeyguardSensorManager : SensorManager { @RequiresApi(Build.VERSION_CODES.M) private fun updateDeviceSecure(context: Context, km: KeyguardManager) { - - if (!isEnabled(context, deviceSecure)) + if (!isEnabled(context, deviceSecure)) { return + } val isSecure = km.isDeviceSecure val icon = if (isSecure) "mdi:cellphone-key" else "mdi:cellphone" @@ -113,9 +115,9 @@ class KeyguardSensorManager : SensorManager { } private fun updateKeyguardLocked(context: Context, km: KeyguardManager) { - - if (!isEnabled(context, keyguardLocked)) + if (!isEnabled(context, keyguardLocked)) { return + } val isLocked = km.isKeyguardLocked val icon = if (isLocked) "mdi:cellphone-lock" else "mdi:cellphone" @@ -130,9 +132,9 @@ class KeyguardSensorManager : SensorManager { } private fun updateKeyguardSecure(context: Context, km: KeyguardManager) { - - if (!isEnabled(context, keyguardSecure)) + if (!isEnabled(context, keyguardSecure)) { return + } val isSecure = km.isKeyguardSecure val icon = if (isSecure) "mdi:cellphone-key" else "mdi:cellphone" diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/LastRebootSensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/LastRebootSensorManager.kt index 0ad12bdb60b..00f0cc62d1a 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/LastRebootSensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/LastRebootSensorManager.kt @@ -56,8 +56,9 @@ class LastRebootSensorManager : SensorManager { @SuppressLint("SimpleDateFormat") private fun updateLastReboot(context: Context) { - if (!isEnabled(context, lastRebootSensor)) + if (!isEnabled(context, lastRebootSensor)) { return + } var timeInMillis = 0L var local = "" @@ -72,8 +73,9 @@ class LastRebootSensorManager : SensorManager { try { timeInMillis = System.currentTimeMillis() - SystemClock.elapsedRealtime() val diffMillis = (timeInMillis - lastTimeMillis).absoluteValue - if (lastTimeMillis != 0L && settingDeadband > diffMillis) + if (lastTimeMillis != 0L && settingDeadband > diffMillis) { return + } val cal: Calendar = GregorianCalendar() cal.timeInMillis = timeInMillis local = cal.time.toString() diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/LastUpdateManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/LastUpdateManager.kt index f9db22f7f1b..0cf6fc5b672 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/LastUpdateManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/LastUpdateManager.kt @@ -45,12 +45,13 @@ class LastUpdateManager : SensorManager { } fun sendLastUpdate(context: Context, intentAction: String?) { - - if (!isEnabled(context, lastUpdate)) + if (!isEnabled(context, lastUpdate)) { return + } - if (intentAction.isNullOrEmpty()) + if (intentAction.isNullOrEmpty()) { return + } Log.d(TAG, "Last update is $intentAction") diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/LightSensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/LightSensorManager.kt index 0a550ac9b6f..5bfc631b355 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/LightSensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/LightSensorManager.kt @@ -59,8 +59,9 @@ class LightSensorManager : SensorManager, SensorEventListener { } private fun updateLightSensor() { - if (!isEnabled(latestContext, lightSensor)) + if (!isEnabled(latestContext, lightSensor)) { return + } val now = System.currentTimeMillis() if (listenerLastRegistered + SensorManager.SENSOR_LISTENER_TIMEOUT < now && isListenerRegistered) { diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/MobileDataManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/MobileDataManager.kt index 8212f565bc6..04d115d138a 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/MobileDataManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/MobileDataManager.kt @@ -42,9 +42,11 @@ class MobileDataManager : SensorManager { } override fun requiredPermissions(sensorId: String): Array { - return if (sensorId == mobileDataRoaming.id) + return if (sensorId == mobileDataRoaming.id) { arrayOf(Manifest.permission.READ_PHONE_STATE) - else arrayOf() + } else { + arrayOf() + } } override fun hasSensor(context: Context): Boolean { @@ -64,15 +66,16 @@ class MobileDataManager : SensorManager { settingKey: String, icon: String ) { - if (!isEnabled(context, sensor)) + if (!isEnabled(context, sensor)) { return + } var enabled = false val telephonyManager = context.applicationContext.getSystemService() if (telephonyManager?.simState == TelephonyManager.SIM_STATE_READY) { - enabled = if (sensor.id == mobileDataRoaming.id && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) + enabled = if (sensor.id == mobileDataRoaming.id && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { telephonyManager.isDataRoamingEnabled - else { + } else { getInt(context.contentResolver, settingKey, 0) == 1 } } diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/NetworkSensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/NetworkSensorManager.kt index a3d5630dcfa..5e929a5f877 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/NetworkSensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/NetworkSensorManager.kt @@ -135,10 +135,11 @@ class NetworkSensorManager : SensorManager { wifiSignalStrength, publicIp ) - return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { list.plus(networkType) - else + } else { list + } } override fun requiredPermissions(sensorId: String): Array { @@ -175,8 +176,9 @@ class NetworkSensorManager : SensorManager { } private fun updateWifiConnectionSensor(context: Context) { - if (!isEnabled(context, wifiConnection)) + if (!isEnabled(context, wifiConnection)) { return + } var conInfo: WifiInfo? = null var ssid = "Unknown" @@ -216,8 +218,9 @@ class NetworkSensorManager : SensorManager { } private fun updateBSSIDSensor(context: Context) { - if (!isEnabled(context, bssidState)) + if (!isEnabled(context, bssidState)) { return + } var conInfo: WifiInfo? = null @@ -240,10 +243,11 @@ class NetworkSensorManager : SensorManager { sensorDao.add(SensorSetting(bssidState.id, settingName, bssid, SensorSettingType.STRING)) } } else { - if (currentSetting != "") + if (currentSetting != "") { bssid = currentSetting - else + } else { sensorDao.removeSetting(bssidState.id, settingName) + } sensorDao.add(SensorSetting(bssidState.id, SETTING_GET_CURRENT_BSSID, "false", SensorSettingType.TOGGLE)) } @@ -259,8 +263,9 @@ class NetworkSensorManager : SensorManager { } private fun updateWifiIPSensor(context: Context) { - if (!isEnabled(context, wifiIp)) + if (!isEnabled(context, wifiIp)) { return + } var deviceIp = "Unknown" @@ -286,8 +291,9 @@ class NetworkSensorManager : SensorManager { } private fun updateWifiLinkSpeedSensor(context: Context) { - if (!isEnabled(context, wifiLinkSpeed)) + if (!isEnabled(context, wifiLinkSpeed)) { return + } var linkSpeed = 0 var rssi = -1 @@ -329,8 +335,9 @@ class NetworkSensorManager : SensorManager { } private fun updateWifiSensor(context: Context) { - if (!isEnabled(context, wifiState)) + if (!isEnabled(context, wifiState)) { return + } var wifiEnabled = false @@ -352,8 +359,9 @@ class NetworkSensorManager : SensorManager { } private fun updateWifiFrequencySensor(context: Context) { - if (!isEnabled(context, wifiFrequency)) + if (!isEnabled(context, wifiFrequency)) { return + } var frequency = 0 @@ -379,8 +387,9 @@ class NetworkSensorManager : SensorManager { } private fun updateWifiSignalStrengthSensor(context: Context) { - if (!isEnabled(context, wifiSignalStrength)) + if (!isEnabled(context, wifiSignalStrength)) { return + } var rssi = -1 @@ -422,8 +431,9 @@ class NetworkSensorManager : SensorManager { } private fun updatePublicIpSensor(context: Context) { - if (!isEnabled(context, publicIp)) + if (!isEnabled(context, publicIp)) { return + } var ip = "unknown" val client = OkHttpClient() @@ -457,8 +467,9 @@ class NetworkSensorManager : SensorManager { @SuppressLint("MissingPermission") @RequiresApi(Build.VERSION_CODES.M) private fun updateNetworkType(context: Context) { - if (!isEnabled(context, networkType)) + if (!isEnabled(context, networkType)) { return + } val connectivityManager = context.getSystemService() val activeNetwork = connectivityManager?.activeNetwork diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/NextAlarmManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/NextAlarmManager.kt index 5062d02604b..2ee0c97b706 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/NextAlarmManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/NextAlarmManager.kt @@ -51,9 +51,9 @@ class NextAlarmManager : SensorManager { } private fun updateNextAlarm(context: Context) { - - if (!isEnabled(context, nextAlarm)) + if (!isEnabled(context, nextAlarm)) { return + } var triggerTime = 0L var local = "" @@ -92,8 +92,9 @@ class NextAlarmManager : SensorManager { val sdf = SimpleDateFormat(dateFormat) sdf.timeZone = TimeZone.getTimeZone("UTC") utc = sdf.format(Date(triggerTime)) - } else + } else { Log.d(TAG, "No alarm is scheduled, sending unavailable") + } } catch (e: Exception) { Log.e(TAG, "Error getting the next alarm info", e) } diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/PhoneStateSensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/PhoneStateSensorManager.kt index 78d6f5d0f69..f1fbc93ce8c 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/PhoneStateSensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/PhoneStateSensorManager.kt @@ -55,9 +55,11 @@ class PhoneStateSensorManager : SensorManager { return context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) } override suspend fun getAvailableSensors(context: Context): List { - return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { listOf(phoneState, sim_1, sim_2) - else listOf(phoneState) + } else { + listOf(phoneState) + } } override fun requiredPermissions(sensorId: String): Array { @@ -94,8 +96,9 @@ class PhoneStateSensorManager : SensorManager { private fun updatePhoneStateSensor(context: Context, state: String) { var phoneIcon = "mdi:phone" - if (state == "ringing" || state == "offhook") + if (state == "ringing" || state == "offhook") { phoneIcon += "-in-talk" + } onSensorUpdated( context, @@ -112,8 +115,9 @@ class PhoneStateSensorManager : SensorManager { 1 -> sim_2 else -> throw IllegalArgumentException("Invalid sim slot: $slotIndex") } - if (!isEnabled(context, basicSimSensor)) + if (!isEnabled(context, basicSimSensor)) { return + } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { var displayName = "Unavailable" val attrs = mutableMapOf() diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/PowerSensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/PowerSensorManager.kt index db0e3f90fad..9f9c0f3951a 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/PowerSensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/PowerSensorManager.kt @@ -71,9 +71,9 @@ class PowerSensorManager : SensorManager { } private fun updateInteractive(context: Context, powerManager: PowerManager) { - - if (!isEnabled(context, interactiveDevice)) + if (!isEnabled(context, interactiveDevice)) { return + } val interactiveState = powerManager.isInteractive val icon = if (interactiveState) "mdi:cellphone" else "mdi:cellphone-off" @@ -89,9 +89,9 @@ class PowerSensorManager : SensorManager { @RequiresApi(Build.VERSION_CODES.M) private fun updateDoze(context: Context, powerManager: PowerManager) { - - if (!isEnabled(context, doze)) + if (!isEnabled(context, doze)) { return + } val dozeState = powerManager.isDeviceIdleMode val icon = if (dozeState) "mdi:sleep" else "mdi:sleep-off" @@ -110,9 +110,9 @@ class PowerSensorManager : SensorManager { } private fun updatePowerSave(context: Context, powerManager: PowerManager) { - - if (!isEnabled(context, powerSave)) + if (!isEnabled(context, powerSave)) { return + } val powerSaveState = powerManager.isPowerSaveMode diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/PressureSensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/PressureSensorManager.kt index fd4bc8b0227..910f6577e81 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/PressureSensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/PressureSensorManager.kt @@ -58,8 +58,9 @@ class PressureSensorManager : SensorManager, SensorEventListener { } private fun updatePressureSensor() { - if (!isEnabled(latestContext, pressureSensor)) + if (!isEnabled(latestContext, pressureSensor)) { return + } val now = System.currentTimeMillis() if (listenerLastRegistered + SensorManager.SENSOR_LISTENER_TIMEOUT < now && isListenerRegistered) { diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/ProximitySensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/ProximitySensorManager.kt index 497844d8cf9..da9ea28c55e 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/ProximitySensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/ProximitySensorManager.kt @@ -57,8 +57,9 @@ class ProximitySensorManager : SensorManager, SensorEventListener { } private fun updateProximitySensor() { - if (!isEnabled(latestContext, proximitySensor)) + if (!isEnabled(latestContext, proximitySensor)) { return + } val now = System.currentTimeMillis() if (listenerLastRegistered + SensorManager.SENSOR_LISTENER_TIMEOUT < now && isListenerRegistered) { diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/SensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/SensorManager.kt index d007825b13c..d5ac9c8a8ad 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/SensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/SensorManager.kt @@ -66,9 +66,9 @@ interface SensorManager { fun checkPermission(context: Context, sensorId: String): Boolean { return requiredPermissions(sensorId).all { - if (sensorId != "last_used_app") + if (sensorId != "last_used_app") { context.checkPermission(it, myPid(), myUid()) == PackageManager.PERMISSION_GRANTED - else { + } else { checkUsageStatsPermission(context) } } @@ -198,15 +198,16 @@ interface SensorManager { settingType: SensorSettingType, default: String, enabled: Boolean = true, - entries: List = arrayListOf(), + entries: List = arrayListOf() ): String { val sensorDao = AppDatabase.getInstance(context).sensorDao() val setting = sensorDao .getSettings(sensor.id) .firstOrNull { it.name == settingName } ?.value - if (setting == null) + if (setting == null) { sensorDao.add(SensorSetting(sensor.id, settingName, default, settingType, enabled, entries = entries)) + } return setting ?: default } @@ -217,7 +218,7 @@ interface SensorManager { state: Any, mdiIcon: String, attributes: Map, - forceUpdate: Boolean = false, + forceUpdate: Boolean = false ) { val sensorDao = AppDatabase.getInstance(context).sensorDao() val sensors = sensorDao.get(basicSensor.id) @@ -241,7 +242,7 @@ interface SensorManager { stateClass = basicSensor.stateClass, entityCategory = basicSensor.entityCategory, lastSentState = if (forceUpdate) null else it.lastSentState, - lastSentIcon = if (forceUpdate) null else it.lastSentIcon, + lastSentIcon = if (forceUpdate) null else it.lastSentIcon ) sensorDao.update(sensor) } diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/SensorReceiverBase.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/SensorReceiverBase.kt index 645a8067f3b..cb9803fd098 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/SensorReceiverBase.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/SensorReceiverBase.kt @@ -91,8 +91,7 @@ abstract class SensorReceiverBase : BroadcastReceiver() { if (!isSensorEnabled(sensor!!)) { Log.d( tag, - String.format - ( + String.format( "Sensor %s corresponding to received event %s is disabled, skipping sensors update", sensor, intent.action @@ -168,8 +167,9 @@ abstract class SensorReceiverBase : BroadcastReceiver() { managers.forEach { manager -> // Since we don't have this manager injected it doesn't fulfil its injects, manually // inject for now I guess? - if (manager is LocationSensorManagerBase) + if (manager is LocationSensorManagerBase) { manager.serverManager = serverManager + } val hasSensor = manager.hasSensor(context) if (hasSensor) { @@ -330,8 +330,11 @@ abstract class SensorReceiverBase : BroadcastReceiver() { // Don't trigger re-registration when the server is down or job was cancelled val exceptionOk = e is IntegrationException && (e.cause is IOException || e.cause is CancellationException) - if (exceptionOk) Log.w(tag, "Exception while updating sensors: ${e::class.java.simpleName}: ${e.cause?.let { it::class.java.name } }") - else Log.e(tag, "Exception while updating sensors.", e) + if (exceptionOk) { + Log.w(tag, "Exception while updating sensors: ${e::class.java.simpleName}: ${e.cause?.let { it::class.java.name } }") + } else { + Log.e(tag, "Exception while updating sensors.", e) + } exceptionOk } @@ -347,7 +350,9 @@ abstract class SensorReceiverBase : BroadcastReceiver() { } } } - } else Log.d(tag, "Nothing to update for server ${server.id} (${server.friendlyName})") + } else { + Log.d(tag, "Nothing to update for server ${server.id} (${server.friendlyName})") + } return success } @@ -406,7 +411,9 @@ abstract class SensorReceiverBase : BroadcastReceiver() { notificationManager.getNotificationChannel(sensorCoreSyncChannel) if (notificationChannel == null) { notificationChannel = NotificationChannel( - sensorCoreSyncChannel, sensorCoreSyncChannel, NotificationManager.IMPORTANCE_DEFAULT + sensorCoreSyncChannel, + sensorCoreSyncChannel, + NotificationManager.IMPORTANCE_DEFAULT ) notificationManager.createNotificationChannel(notificationChannel) } diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/SensorWorkerBase.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/SensorWorkerBase.kt index d4ea1226bbb..69117eedc5d 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/SensorWorkerBase.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/SensorWorkerBase.kt @@ -75,7 +75,9 @@ abstract class SensorWorkerBase( notificationManager.getNotificationChannel(sensorWorkerChannel) if (notificationChannel == null) { notificationChannel = NotificationChannel( - sensorWorkerChannel, TAG, NotificationManager.IMPORTANCE_LOW + sensorWorkerChannel, + TAG, + NotificationManager.IMPORTANCE_LOW ) notificationManager.createNotificationChannel(notificationChannel) } diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/StepsSensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/StepsSensorManager.kt index 112cf9bf8ba..68b55f936c9 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/StepsSensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/StepsSensorManager.kt @@ -65,8 +65,9 @@ class StepsSensorManager : SensorManager, SensorEventListener { } private fun updateStepsSensor() { - if (!isEnabled(latestContext, stepsSensor)) + if (!isEnabled(latestContext, stepsSensor)) { return + } if (checkPermission(latestContext, stepsSensor.id)) { val now = System.currentTimeMillis() diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/StorageSensorManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/StorageSensorManager.kt index e3e31852341..fa3979bec08 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/StorageSensorManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/StorageSensorManager.kt @@ -79,8 +79,9 @@ class StorageSensorManager : SensorManager { } private fun updateInternalStorageSensor(context: Context) { - if (!isEnabled(context, storageSensor)) + if (!isEnabled(context, storageSensor)) { return + } val path = Environment.getDataDirectory() val internalStorageStats = getStorageStats(path) @@ -98,8 +99,9 @@ class StorageSensorManager : SensorManager { } private fun updateExternalStorageSensor(context: Context) { - if (!isEnabled(context, externalStorage)) + if (!isEnabled(context, externalStorage)) { return + } val externalStoragePath = getExternalStoragePathIfAvailable(context) val externalStorageStats = externalStoragePath?.let { diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/TimeZoneManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/TimeZoneManager.kt index 3cf277d68f2..eed641d5024 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/TimeZoneManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/TimeZoneManager.kt @@ -41,9 +41,9 @@ class TimeZoneManager : SensorManager { } private fun updateTimeZone(context: Context) { - - if (!isEnabled(context, currentTimeZone)) + if (!isEnabled(context, currentTimeZone)) { return + } val timeZone: TimeZone = TimeZone.getDefault() val currentlyInDst = timeZone.inDaylightTime(Date()) diff --git a/common/src/main/java/io/homeassistant/companion/android/common/sensors/TrafficStatsManager.kt b/common/src/main/java/io/homeassistant/companion/android/common/sensors/TrafficStatsManager.kt index 5b6668047bc..184c4c37393 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/sensors/TrafficStatsManager.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/sensors/TrafficStatsManager.kt @@ -67,7 +67,9 @@ class TrafficStatsManager : SensorManager { override suspend fun getAvailableSensors(context: Context): List { return if (hasCellular) { listOf(rxBytesMobile, txBytesMobile, rxBytesTotal, txBytesTotal) - } else listOf(rxBytesTotal, txBytesTotal) + } else { + listOf(rxBytesTotal, txBytesTotal) + } } override fun requiredPermissions(sensorId: String): Array { @@ -80,8 +82,9 @@ class TrafficStatsManager : SensorManager { var networkCapabilities: NetworkCapabilities? for (item in networkInfo) { networkCapabilities = cm.getNetworkCapabilities(item) - if (!hasCellular) + if (!hasCellular) { hasCellular = networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ?: false + } } return true } @@ -95,9 +98,9 @@ class TrafficStatsManager : SensorManager { } private fun updateMobileRxBytes(context: Context) { - - if (!isEnabled(context, rxBytesMobile)) + if (!isEnabled(context, rxBytesMobile)) { return + } val mobileRx = try { TrafficStats.getMobileRxBytes().toFloat() / GB @@ -116,9 +119,9 @@ class TrafficStatsManager : SensorManager { } private fun updateMobileTxBytes(context: Context) { - - if (!isEnabled(context, txBytesMobile)) + if (!isEnabled(context, txBytesMobile)) { return + } val mobileTx = try { TrafficStats.getMobileTxBytes().toFloat() / GB @@ -136,9 +139,9 @@ class TrafficStatsManager : SensorManager { ) } private fun updateTotalRxBytes(context: Context) { - - if (!isEnabled(context, rxBytesTotal)) + if (!isEnabled(context, rxBytesTotal)) { return + } val totalRx = try { TrafficStats.getTotalRxBytes().toFloat().absoluteValue / GB @@ -157,9 +160,9 @@ class TrafficStatsManager : SensorManager { } private fun updateTotalTxBytes(context: Context) { - - if (!isEnabled(context, txBytesTotal)) + if (!isEnabled(context, txBytesTotal)) { return + } val totalTx = try { TrafficStats.getTotalTxBytes().toFloat().absoluteValue / GB diff --git a/common/src/main/java/io/homeassistant/companion/android/common/util/DisabledLocationHandler.kt b/common/src/main/java/io/homeassistant/companion/android/common/util/DisabledLocationHandler.kt index 6c23f5efff3..2874913faaa 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/util/DisabledLocationHandler.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/util/DisabledLocationHandler.kt @@ -46,8 +46,11 @@ object DisabledLocationHandler { return if (fineLocation == null) { containsFineLocation && containsCoarseLocation } else { - if (fineLocation) containsFineLocation - else containsCoarseLocation + if (fineLocation) { + containsFineLocation + } else { + containsCoarseLocation + } } } @@ -81,15 +84,16 @@ object DisabledLocationHandler { if ((!withDisableOption || callback == null) && showAsNotification) { val notificationManager = NotificationManagerCompat.from(context) if (notificationManager.getActiveNotification(DISABLED_LOCATION_WARN_ID, DISABLED_LOCATION_WARN_ID.hashCode()) == null) { - if (VERSION.SDK_INT >= VERSION_CODES.O) { val channel = NotificationChannel(locationDisabledChannel, context.applicationContext.getString(commonR.string.location_warn_channel), NotificationManager.IMPORTANCE_DEFAULT) notificationManager.createNotificationChannel(channel) } val pendingIntent = PendingIntent.getActivity( - context, 0, - intent, PendingIntent.FLAG_IMMUTABLE + context, + 0, + intent, + PendingIntent.FLAG_IMMUTABLE ) val notificationBuilder = NotificationCompat.Builder(context, locationDisabledChannel) diff --git a/common/src/main/java/io/homeassistant/companion/android/common/util/LocationPermissionInfoHandler.kt b/common/src/main/java/io/homeassistant/companion/android/common/util/LocationPermissionInfoHandler.kt index 3d4655ad6fd..2a1351a1bcb 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/util/LocationPermissionInfoHandler.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/util/LocationPermissionInfoHandler.kt @@ -24,6 +24,8 @@ object LocationPermissionInfoHandler { if (continueNoCallback != null) continueNoCallback() } .show() - } else continueYesCallback() + } else { + continueYesCallback() + } } } diff --git a/common/src/main/java/io/homeassistant/companion/android/common/util/NotificationManagerExtensions.kt b/common/src/main/java/io/homeassistant/companion/android/common/util/NotificationManagerExtensions.kt index b345dad1a56..3ad1d123ec7 100644 --- a/common/src/main/java/io/homeassistant/companion/android/common/util/NotificationManagerExtensions.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/util/NotificationManagerExtensions.kt @@ -45,15 +45,17 @@ fun NotificationManagerCompat.cancelGroupIfNeeded(tag: String?, id: Int): Boolea // Check if the group is the auto group of android ("ranker_group") if (!groupKey.endsWith("|g:ranker_group")) { - // Nope it is a custom group. Get notifications of the group... val groupNotifications = currentActiveNotifications.filter { s -> s.groupKey == groupKey } // Is the notification which should be deleted a group summary val isGroupSummary = statusBarNotification.notification.flags and FLAG_GROUP_SUMMARY != 0 - if (isGroupSummary) Log.d(TAG, "Notification is the group summary.") - else Log.d(TAG, "Notification is NOT the group summary.") + if (isGroupSummary) { + Log.d(TAG, "Notification is the group summary.") + } else { + Log.d(TAG, "Notification is NOT the group summary.") + } // If the notification which should be delete is NOT a group summary AND // If there are only two left notifications, then this means only the current to be @@ -69,8 +71,11 @@ fun NotificationManagerCompat.cancelGroupIfNeeded(tag: String?, id: Int): Boolea ) { val group = groupNotifications[0].notification.group - if (isGroupSummary) Log.d(TAG, "Notification is the group summary \"$group\" with no notifications inside. Try to cancel this group summary notification...") - else Log.d(TAG, "Notification is inside of group \"$group\", but is the last one in the group. Try to cancel the group notification....") + if (isGroupSummary) { + Log.d(TAG, "Notification is the group summary \"$group\" with no notifications inside. Try to cancel this group summary notification...") + } else { + Log.d(TAG, "Notification is inside of group \"$group\", but is the last one in the group. Try to cancel the group notification....") + } // If group is null, the group is a group which is generate by the system. // This group can't be canceled, but it will be canceled by canceling the last notification inside of the group // If the group isn't null, cancel the group @@ -84,21 +89,25 @@ fun NotificationManagerCompat.cancelGroupIfNeeded(tag: String?, id: Int): Boolea false } } else { - if (isGroupSummary && groupNotifications.size != 1) Log.d( - TAG, - "Notification is the group summary, but the group has more than or no notifications inside (" + groupNotifications.size + "). Cancel notification" - ) - else if (!isGroupSummary && groupNotifications.size != 2) Log.d( - TAG, - "Notification is in a group, but the group has more/less than 2 notifications inside (" + groupNotifications.size + "). Cancel notification" - ) + if (isGroupSummary && groupNotifications.size != 1) { + Log.d( + TAG, + "Notification is the group summary, but the group has more than or no notifications inside (" + groupNotifications.size + "). Cancel notification" + ) + } else if (!isGroupSummary && groupNotifications.size != 2) { + Log.d( + TAG, + "Notification is in a group, but the group has more/less than 2 notifications inside (" + groupNotifications.size + "). Cancel notification" + ) + } } } else { Log.d(TAG, "Notification is in a group ($groupKey), but it is in the auto group. Cancel notification") } } else { - if (statusBarNotification == null) Log.d(TAG, "Notification is not in a group. Cancel notification...") - else if (groupKey.isNullOrBlank()) Log.d(TAG, "Notification is in a group but has no group key. Cancel notification") + if (statusBarNotification == null) { + Log.d(TAG, "Notification is not in a group. Cancel notification...") + } else if (groupKey.isNullOrBlank()) Log.d(TAG, "Notification is in a group but has no group key. Cancel notification") } } return false diff --git a/common/src/main/java/io/homeassistant/companion/android/common/util/TextToSpeech.kt b/common/src/main/java/io/homeassistant/companion/android/common/util/TextToSpeech.kt index aa6b172d5a5..12023ff52f0 100755 --- a/common/src/main/java/io/homeassistant/companion/android/common/util/TextToSpeech.kt +++ b/common/src/main/java/io/homeassistant/companion/android/common/util/TextToSpeech.kt @@ -32,52 +32,57 @@ fun speakText( val audioManager = context.getSystemService() val currentAlarmVolume = audioManager?.getStreamVolume(AudioManager.STREAM_ALARM) val maxAlarmVolume = audioManager?.getStreamMaxVolume(AudioManager.STREAM_ALARM) - if (tts.isNullOrEmpty()) + if (tts.isNullOrEmpty()) { tts = context.getString(R.string.tts_no_text) + } textToSpeech = TextToSpeech( context ) { if (it == TextToSpeech.SUCCESS) { val listener = object : UtteranceProgressListener() { override fun onStart(p0: String?) { - if (data[NotificationData.MEDIA_STREAM] == NotificationData.ALARM_STREAM_MAX) + if (data[NotificationData.MEDIA_STREAM] == NotificationData.ALARM_STREAM_MAX) { audioManager?.setStreamVolume( AudioManager.STREAM_ALARM, maxAlarmVolume!!, 0 ) + } } override fun onDone(p0: String?) { textToSpeech?.stop() textToSpeech?.shutdown() - if (data[NotificationData.MEDIA_STREAM] == NotificationData.ALARM_STREAM_MAX) + if (data[NotificationData.MEDIA_STREAM] == NotificationData.ALARM_STREAM_MAX) { audioManager?.setStreamVolume( AudioManager.STREAM_ALARM, currentAlarmVolume!!, 0 ) + } } @Deprecated("Deprecated in Java") override fun onError(p0: String?) { textToSpeech?.stop() textToSpeech?.shutdown() - if (data[NotificationData.MEDIA_STREAM] == NotificationData.ALARM_STREAM_MAX) + if (data[NotificationData.MEDIA_STREAM] == NotificationData.ALARM_STREAM_MAX) { audioManager?.setStreamVolume( AudioManager.STREAM_ALARM, currentAlarmVolume!!, 0 ) + } } override fun onStop(utteranceId: String?, interrupted: Boolean) { - if (data[NotificationData.MEDIA_STREAM] == NotificationData.ALARM_STREAM_MAX) + if (data[NotificationData.MEDIA_STREAM] == NotificationData.ALARM_STREAM_MAX) { audioManager?.setStreamVolume( AudioManager.STREAM_ALARM, currentAlarmVolume!!, 0 ) + } } } textToSpeech?.setOnUtteranceProgressListener(listener) diff --git a/common/src/main/java/io/homeassistant/companion/android/database/AppDatabase.kt b/common/src/main/java/io/homeassistant/companion/android/database/AppDatabase.kt index 742f70e2eda..1847a673426 100644 --- a/common/src/main/java/io/homeassistant/companion/android/database/AppDatabase.kt +++ b/common/src/main/java/io/homeassistant/companion/android/database/AppDatabase.kt @@ -102,7 +102,7 @@ import io.homeassistant.companion.android.common.R as commonR AutoMigration(from = 34, to = 35), AutoMigration(from = 35, to = 36), AutoMigration(from = 36, to = 37, spec = AppDatabase.Companion.Migration36to37::class), - AutoMigration(from = 37, to = 38, spec = AppDatabase.Companion.Migration37to38::class), + AutoMigration(from = 37, to = 38, spec = AppDatabase.Companion.Migration37to38::class) ] ) @TypeConverters( @@ -282,8 +282,9 @@ abstract class AppDatabase : RoomDatabase() { database.insert("sensors", OnConflictStrategy.REPLACE, it) } } - if (migrationFailed) + if (migrationFailed) { notifyMigrationFailed() + } database.execSQL("CREATE TABLE IF NOT EXISTS `sensor_attributes` (`sensor_id` TEXT NOT NULL, `name` TEXT NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`sensor_id`, `name`))") } @@ -341,8 +342,9 @@ abstract class AppDatabase : RoomDatabase() { database.insert("sensors", OnConflictStrategy.REPLACE, it) } } - if (migrationFailed) + if (migrationFailed) { notifyMigrationFailed() + } } } @@ -385,7 +387,6 @@ abstract class AppDatabase : RoomDatabase() { private val MIGRATION_16_17 = object : Migration(16, 17) { override fun migrate(database: SupportSQLiteDatabase) { - val cursor = database.query("SELECT * FROM sensor_settings") val sensorSettings = mutableListOf() var migrationSuccessful = false @@ -393,10 +394,8 @@ abstract class AppDatabase : RoomDatabase() { try { if (cursor.moveToFirst()) { while (cursor.moveToNext()) { - sensorSettings.add( ContentValues().also { - val currentSensorId = cursor.getString(cursor.getColumnIndex("sensor_id")) val currentSensorSettingName = cursor.getString(cursor.getColumnIndex("name")) var entries: String = "" @@ -485,8 +484,9 @@ abstract class AppDatabase : RoomDatabase() { database.insert("sensor_settings", OnConflictStrategy.REPLACE, it) } } - if (migrationFailed) + if (migrationFailed) { notifyMigrationFailed() + } } } @@ -817,7 +817,9 @@ abstract class AppDatabase : RoomDatabase() { notificationManager.getNotificationChannel(databaseChannel) if (notificationChannel == null) { notificationChannel = NotificationChannel( - databaseChannel, TAG, NotificationManager.IMPORTANCE_HIGH + databaseChannel, + TAG, + NotificationManager.IMPORTANCE_HIGH ) notificationManager.createNotificationChannel(notificationChannel) } diff --git a/common/src/main/java/io/homeassistant/companion/android/database/sensor/SensorSetting.kt b/common/src/main/java/io/homeassistant/companion/android/database/sensor/SensorSetting.kt index 00daa671256..a6f376f966a 100644 --- a/common/src/main/java/io/homeassistant/companion/android/database/sensor/SensorSetting.kt +++ b/common/src/main/java/io/homeassistant/companion/android/database/sensor/SensorSetting.kt @@ -12,7 +12,7 @@ enum class SensorSettingType(val string: String, val listType: Boolean = false) LIST_APPS("list-apps", listType = true), LIST_BLUETOOTH("list-bluetooth", listType = true), LIST_ZONES("list-zones", listType = true), - LIST_BEACONS("list-beacons", listType = true), + LIST_BEACONS("list-beacons", listType = true) } @Entity(tableName = "sensor_settings", primaryKeys = ["sensor_id", "name"]) @@ -29,7 +29,7 @@ data class SensorSetting( @ColumnInfo(name = "enabled") val enabled: Boolean = true, @ColumnInfo(name = "entries") - val entries: List = arrayListOf(), + val entries: List = arrayListOf() ) class EntriesTypeConverter { diff --git a/common/src/main/java/io/homeassistant/companion/android/database/settings/SensorUpdateFrequencySetting.kt b/common/src/main/java/io/homeassistant/companion/android/database/settings/SensorUpdateFrequencySetting.kt index 9521394fab2..573fabe9046 100755 --- a/common/src/main/java/io/homeassistant/companion/android/database/settings/SensorUpdateFrequencySetting.kt +++ b/common/src/main/java/io/homeassistant/companion/android/database/settings/SensorUpdateFrequencySetting.kt @@ -11,6 +11,7 @@ enum class SensorUpdateFrequencySetting { class LocalSensorSettingConverter { @TypeConverter fun toLocalSensorSetting(setting: String): SensorUpdateFrequencySetting = SensorUpdateFrequencySetting.valueOf(setting) + @TypeConverter fun fromLocalSensorSetting(setting: SensorUpdateFrequencySetting): String = setting.name } diff --git a/common/src/main/java/io/homeassistant/companion/android/database/settings/WebsocketSetting.kt b/common/src/main/java/io/homeassistant/companion/android/database/settings/WebsocketSetting.kt index 7521dd94a9c..8d02b189874 100644 --- a/common/src/main/java/io/homeassistant/companion/android/database/settings/WebsocketSetting.kt +++ b/common/src/main/java/io/homeassistant/companion/android/database/settings/WebsocketSetting.kt @@ -12,6 +12,7 @@ enum class WebsocketSetting { class LocalNotificationSettingConverter { @TypeConverter fun toLocalNotificationSetting(setting: String): WebsocketSetting = WebsocketSetting.valueOf(setting) + @TypeConverter fun fromLocalNotificationSetting(setting: WebsocketSetting): String = setting.name } diff --git a/common/src/main/java/io/homeassistant/companion/android/database/widget/ThemeableWidgetEntity.kt b/common/src/main/java/io/homeassistant/companion/android/database/widget/ThemeableWidgetEntity.kt index e31caf33bea..d640b2eb89a 100644 --- a/common/src/main/java/io/homeassistant/companion/android/database/widget/ThemeableWidgetEntity.kt +++ b/common/src/main/java/io/homeassistant/companion/android/database/widget/ThemeableWidgetEntity.kt @@ -14,6 +14,7 @@ enum class WidgetBackgroundType { class WidgetBackgroundTypeConverter { @TypeConverter fun toWidgetBackgroundType(setting: String): WidgetBackgroundType = WidgetBackgroundType.valueOf(setting) + @TypeConverter fun fromWidgetBackgroundType(setting: WidgetBackgroundType): String = setting.name } diff --git a/common/src/main/java/io/homeassistant/companion/android/util/UrlUtil.kt b/common/src/main/java/io/homeassistant/companion/android/util/UrlUtil.kt index 2a2e9753993..a92c2a14a3e 100644 --- a/common/src/main/java/io/homeassistant/companion/android/util/UrlUtil.kt +++ b/common/src/main/java/io/homeassistant/companion/android/util/UrlUtil.kt @@ -8,17 +8,21 @@ import okhttp3.HttpUrl.Companion.toHttpUrlOrNull object UrlUtil { fun formattedUrlString(url: String): String { - return if (url == "") throw MalformedHttpUrlException() else try { - val httpUrl = url.toHttpUrl() - HttpUrl.Builder() - .scheme(httpUrl.scheme) - .host(httpUrl.host) - .port(httpUrl.port) - .toString() - } catch (e: IllegalArgumentException) { - throw MalformedHttpUrlException( - e.message - ) + return if (url == "") { + throw MalformedHttpUrlException() + } else { + try { + val httpUrl = url.toHttpUrl() + HttpUrl.Builder() + .scheme(httpUrl.scheme) + .host(httpUrl.host) + .port(httpUrl.port) + .toString() + } catch (e: IllegalArgumentException) { + throw MalformedHttpUrlException( + e.message + ) + } } } diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index eeab76e88ed..1e6b32cf984 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -72,7 +72,7 @@ - + diff --git a/wear/src/main/java/io/homeassistant/companion/android/complications/AssistDataSourceService.kt b/wear/src/main/java/io/homeassistant/companion/android/complications/AssistDataSourceService.kt index 1db4ec3d686..03006f14824 100755 --- a/wear/src/main/java/io/homeassistant/companion/android/complications/AssistDataSourceService.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/complications/AssistDataSourceService.kt @@ -22,8 +22,9 @@ class AssistDataSourceService : ComplicationDataSourceService() { } override fun onComplicationRequest(request: ComplicationRequest, listener: ComplicationRequestListener) { - if (request.complicationType != ComplicationType.MONOCHROMATIC_IMAGE) + if (request.complicationType != ComplicationType.MONOCHROMATIC_IMAGE) { return + } listener.onComplicationData( MonochromaticImageComplicationData.Builder( diff --git a/wear/src/main/java/io/homeassistant/companion/android/complications/EntityStateDataSourceService.kt b/wear/src/main/java/io/homeassistant/companion/android/complications/EntityStateDataSourceService.kt index 6edae7aff23..5c24d2cdb50 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/complications/EntityStateDataSourceService.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/complications/EntityStateDataSourceService.kt @@ -25,6 +25,7 @@ class EntityStateDataSourceService : SuspendingComplicationDataSourceService() { @Inject lateinit var serverManager: ServerManager + @Inject lateinit var entityStateComplicationsDao: EntityStateComplicationsDao @@ -33,8 +34,9 @@ class EntityStateDataSourceService : SuspendingComplicationDataSourceService() { } override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? { - if (request.complicationType != ComplicationType.SHORT_TEXT) + if (request.complicationType != ComplicationType.SHORT_TEXT) { return null + } val id = request.complicationInstanceId @@ -82,9 +84,9 @@ class EntityStateDataSourceService : SuspendingComplicationDataSourceService() { MonochromaticImage.Builder( Icon.createWithResource( this, - io.homeassistant.companion.android.R.drawable.ic_lightbulb, - ), - ).build(), + io.homeassistant.companion.android.R.drawable.ic_lightbulb + ) + ).build() ) .setTitle(PlainComplicationText.Builder(getText(R.string.entity)).build()) .build() diff --git a/wear/src/main/java/io/homeassistant/companion/android/complications/views/ComplicationConfigMainView.kt b/wear/src/main/java/io/homeassistant/companion/android/complications/views/ComplicationConfigMainView.kt index cf154aa83c5..01f5cdf899d 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/complications/views/ComplicationConfigMainView.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/complications/views/ComplicationConfigMainView.kt @@ -108,10 +108,11 @@ fun MainConfigView( }, secondaryLabel = { Text( - if (loaded) + if (loaded) { entity?.friendlyName ?: "" - else + } else { stringResource(R.string.loading) + } ) }, enabled = loaded, diff --git a/wear/src/main/java/io/homeassistant/companion/android/conversation/ConversationViewModel.kt b/wear/src/main/java/io/homeassistant/companion/android/conversation/ConversationViewModel.kt index b252bc779b5..32d7b21fd2a 100755 --- a/wear/src/main/java/io/homeassistant/companion/android/conversation/ConversationViewModel.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/conversation/ConversationViewModel.kt @@ -40,8 +40,11 @@ class ConversationViewModel @Inject constructor( fun getConversation() { viewModelScope.launch { conversationResult = - if (serverManager.isRegistered()) serverManager.integrationRepository().getConversation(speechResult) ?: "" - else "" + if (serverManager.isRegistered()) { + serverManager.integrationRepository().getConversation(speechResult) ?: "" + } else { + "" + } } } diff --git a/wear/src/main/java/io/homeassistant/companion/android/conversation/views/ConversationView.kt b/wear/src/main/java/io/homeassistant/companion/android/conversation/views/ConversationView.kt index 3478ddddf29..ab237f5ea16 100755 --- a/wear/src/main/java/io/homeassistant/companion/android/conversation/views/ConversationView.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/conversation/views/ConversationView.kt @@ -35,14 +35,14 @@ import io.homeassistant.companion.android.theme.WearAppTheme fun ConversationResultView( conversationViewModel: ConversationViewModel ) { - val scrollState = rememberScalingLazyListState() WearAppTheme { Scaffold( positionIndicator = { - if (scrollState.isScrollInProgress) + if (scrollState.isScrollInProgress) { PositionIndicator(scalingLazyListState = scrollState) + } }, timeText = { TimeText(visible = !scrollState.isScrollInProgress) } ) { @@ -67,7 +67,7 @@ fun ConversationResultView( Spacer(Modifier.padding(4.dp)) } } - if (conversationViewModel.conversationResult.isNotEmpty()) + if (conversationViewModel.conversationResult.isNotEmpty()) { item { if (conversationViewModel.isHapticEnabled.value) { val haptic = LocalHapticFeedback.current @@ -82,6 +82,7 @@ fun ConversationResultView( true ) } + } } } } @@ -101,10 +102,11 @@ fun SpeechBubble(text: String, isResponse: Boolean) { Box( modifier = Modifier .background( - if (isResponse) + if (isResponse) { colorResource(R.color.colorAccent) - else - colorResource(R.color.colorSpeechText), + } else { + colorResource(R.color.colorSpeechText) + }, AbsoluteRoundedCornerShape( topLeftPercent = 30, topRightPercent = 30, @@ -116,10 +118,11 @@ fun SpeechBubble(text: String, isResponse: Boolean) { ) { Text( text = text, - color = if (isResponse) + color = if (isResponse) { Color.White - else - Color.Black, + } else { + Color.Black + }, modifier = Modifier .padding(2.dp) ) diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/HomeActivity.kt b/wear/src/main/java/io/homeassistant/companion/android/home/HomeActivity.kt index 15f182a5155..938c14fe078 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/HomeActivity.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/HomeActivity.kt @@ -72,8 +72,9 @@ class HomeActivity : ComponentActivity(), HomeView { mainViewModel.initAllSensors() lifecycleScope.launch { - if (mainViewModel.loadingState.value == MainViewModel.LoadingState.READY) + if (mainViewModel.loadingState.value == MainViewModel.LoadingState.READY) { mainViewModel.updateUI() + } } } diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/HomePresenterImpl.kt b/wear/src/main/java/io/homeassistant/companion/android/home/HomePresenterImpl.kt index 0b641634cfc..d231d5f3a49 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/HomePresenterImpl.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/HomePresenterImpl.kt @@ -91,10 +91,11 @@ class HomePresenterImpl @Inject constructor( "button", "input_button" -> "press" "lock" -> { // Defaults to locking, to be save - if (state == "locked") + if (state == "locked") { "unlock" - else + } else { "lock" + } } in toggleDomains -> "toggle" else -> "turn_on" diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/MainViewModel.kt b/wear/src/main/java/io/homeassistant/companion/android/home/MainViewModel.kt index 8b3a3002af4..1c25f344ee2 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/MainViewModel.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/MainViewModel.kt @@ -195,23 +195,27 @@ class MainViewModel @Inject constructor( entities.clear() it.forEach { state -> updateEntityStates(state) } } - if (!isFavoritesOnly) + if (!isFavoritesOnly) { updateEntityDomains() + } } suspend fun entityUpdates() { - if (!homePresenter.isConnected()) + if (!homePresenter.isConnected()) { return + } homePresenter.getEntityUpdates(supportedEntities.value)?.collect { updateEntityStates(it) - if (!isFavoritesOnly) + if (!isFavoritesOnly) { updateEntityDomains() + } } } suspend fun areaUpdates() { - if (!homePresenter.isConnected() || isFavoritesOnly) + if (!homePresenter.isConnected() || isFavoritesOnly) { return + } homePresenter.getAreaRegistryUpdates()?.collect { areaRegistry = homePresenter.getAreaRegistry() areas.clear() @@ -223,8 +227,9 @@ class MainViewModel @Inject constructor( } suspend fun deviceUpdates() { - if (!homePresenter.isConnected() || isFavoritesOnly) + if (!homePresenter.isConnected() || isFavoritesOnly) { return + } homePresenter.getDeviceRegistryUpdates()?.collect { deviceRegistry = homePresenter.getDeviceRegistry() updateEntityDomains() @@ -232,8 +237,9 @@ class MainViewModel @Inject constructor( } suspend fun entityRegistryUpdates() { - if (!homePresenter.isConnected()) + if (!homePresenter.isConnected()) { return + } homePresenter.getEntityRegistryUpdates()?.collect { entityRegistry = homePresenter.getEntityRegistry() _supportedEntities.value = getSupportedEntities() @@ -319,10 +325,12 @@ class MainViewModel @Inject constructor( .first { basicSensor -> basicSensor.id == sensorId } updateSensorEntity(sensorsDao, basicSensor, isEnabled) - if (isEnabled) try { - sensorManager.requestSensorUpdate(getApplication()) - } catch (e: Exception) { - Log.e(TAG, "Exception while requesting update for sensor $sensorId", e) + if (isEnabled) { + try { + sensorManager.requestSensorUpdate(getApplication()) + } catch (e: Exception) { + Log.e(TAG, "Exception while requesting update for sensor $sensorId", e) + } } } } diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/views/DetailsPanelView.kt b/wear/src/main/java/io/homeassistant/companion/android/home/views/DetailsPanelView.kt index 8c0cf289269..2dc82bbf2ce 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/views/DetailsPanelView.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/views/DetailsPanelView.kt @@ -92,10 +92,11 @@ fun DetailsPanelView( ) { Icon( imageVector = ToggleChipDefaults.switchIcon(isChecked), - contentDescription = if (isChecked) + contentDescription = if (isChecked) { stringResource(R.string.enabled) - else + } else { stringResource(R.string.disabled) + } ) } } @@ -278,10 +279,12 @@ fun ColorTempSlider( val minValue = (attributes["min_mireds"] as? Number)?.toFloat() ?: 0f val maxValue = (attributes["max_mireds"] as? Number)?.toFloat() ?: 0f var currentValue = (attributes["color_temp"] as? Number)?.toFloat() ?: 0f - if (currentValue < minValue) + if (currentValue < minValue) { currentValue = minValue - if (currentValue > maxValue) + } + if (currentValue > maxValue) { currentValue = maxValue + } Column { Text( @@ -336,8 +339,11 @@ private fun onSliderChangedFeedback( haptic: HapticFeedback ) { val fullMessage = - if (increase) context.getString(R.string.slider_increased, sliderName) - else context.getString(R.string.slider_decreased, sliderName) + if (increase) { + context.getString(R.string.slider_increased, sliderName) + } else { + context.getString(R.string.slider_decreased, sliderName) + } onEntityFeedback( isToastEnabled, isHapticEnabled, @@ -353,7 +359,7 @@ private fun PreviewDetailsPaneView() { CompositionLocalProvider { DetailsPanelView( entity = previewEntity1, - onEntityToggled = { _, _, -> }, + onEntityToggled = { _, _ -> }, onFanSpeedChanged = {}, onBrightnessChanged = {}, onColorTempChanged = {}, diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/views/EntityUi.kt b/wear/src/main/java/io/homeassistant/companion/android/home/views/EntityUi.kt index 12482f862de..64452a21d35 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/views/EntityUi.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/views/EntityUi.kt @@ -90,10 +90,11 @@ fun EntityUi( toggleControl = { Icon( imageVector = ToggleChipDefaults.switchIcon(isChecked), - contentDescription = if (isChecked) + contentDescription = if (isChecked) { stringResource(R.string.enabled) - else + } else { stringResource(R.string.disabled) + } ) }, colors = WearToggleChip.entityToggleChipBackgroundColors(entity, isChecked) diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/views/HomeView.kt b/wear/src/main/java/io/homeassistant/companion/android/home/views/HomeView.kt index f53503e260d..16b8532ba6d 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/views/HomeView.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/views/HomeView.kt @@ -233,7 +233,7 @@ fun LoadHomePage( SensorManagerUi( allSensors = mainViewModel.sensors.value, allAvailSensors = mainViewModel.availableSensors, - sensorManager = sensorManager, + sensorManager = sensorManager ) { sensorId, isEnabled -> mainViewModel.enableDisableSensor(sensorManager, sensorId, isEnabled) } diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/views/MainView.kt b/wear/src/main/java/io/homeassistant/companion/android/home/views/MainView.kt index f696b0a31cb..532d3a9ec19 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/views/MainView.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/views/MainView.kt @@ -68,8 +68,9 @@ fun MainView( WearAppTheme { Scaffold( positionIndicator = { - if (scalingLazyListState.isScrollInProgress) + if (scalingLazyListState.isScrollInProgress) { PositionIndicator(scalingLazyListState = scalingLazyListState) + } }, timeText = { TimeText(!scalingLazyListState.isScrollInProgress) } ) { @@ -137,8 +138,11 @@ fun MainView( } item { val minHeight = - if (favoriteEntityIds.isEmpty()) LocalConfiguration.current.screenHeightDp - 64 - else 0 + if (favoriteEntityIds.isEmpty()) { + LocalConfiguration.current.screenHeightDp - 64 + } else { + 0 + } Column( modifier = Modifier .heightIn(min = minHeight.dp) @@ -329,10 +333,11 @@ fun MainView( } } - if (mainViewModel.isFavoritesOnly) + if (mainViewModel.isFavoritesOnly) { item { Spacer(Modifier.padding(32.dp)) } + } // Settings item { diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/views/SensorManagerUi.kt b/wear/src/main/java/io/homeassistant/companion/android/home/views/SensorManagerUi.kt index 75a8d9d3119..7e08859eebd 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/views/SensorManagerUi.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/views/SensorManagerUi.kt @@ -30,14 +30,15 @@ fun SensorManagerUi( allSensors: List?, allAvailSensors: List?, sensorManager: SensorManager, - onSensorClicked: (String, Boolean) -> Unit, + onSensorClicked: (String, Boolean) -> Unit ) { val scalingLazyListState: ScalingLazyListState = rememberScalingLazyListState() WearAppTheme { Scaffold( positionIndicator = { - if (scalingLazyListState.isScrollInProgress) + if (scalingLazyListState.isScrollInProgress) { PositionIndicator(scalingLazyListState = scalingLazyListState) + } }, timeText = { TimeText(!scalingLazyListState.isScrollInProgress) } ) { @@ -76,7 +77,7 @@ fun SensorManagerUi( SensorUi( sensor = sensor, manager = sensorManager, - basicSensor = basicSensor, + basicSensor = basicSensor ) { sensorId, enabled -> onSensorClicked(sensorId, enabled) } } } diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/views/SensorUi.kt b/wear/src/main/java/io/homeassistant/companion/android/home/views/SensorUi.kt index 3a804683820..d3aa44c9010 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/views/SensorUi.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/views/SensorUi.kt @@ -28,7 +28,7 @@ fun SensorUi( sensor: Sensor?, manager: SensorManager, basicSensor: SensorManager.BasicSensor, - onSensorClicked: (String, Boolean) -> Unit, + onSensorClicked: (String, Boolean) -> Unit ) { val checked = sensor?.enabled == true @@ -50,8 +50,9 @@ fun SensorUi( backgroundRequest.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION) return@forEach } - if (!it.value) + if (!it.value) { allGranted = false + } } onSensorClicked(basicSensor.id, allGranted) } @@ -62,16 +63,18 @@ fun SensorUi( (sensor?.enabled == true && perm), onCheckedChange = { enabled -> val permissions = manager.requiredPermissions(basicSensor.id) - if (perm || !enabled) + if (perm || !enabled) { onSensorClicked(basicSensor.id, enabled) - else + } else { permissionLaunch.launch( - if (permissions.size == 1 && permissions[0] == Manifest.permission.ACCESS_BACKGROUND_LOCATION) + if (permissions.size == 1 && permissions[0] == Manifest.permission.ACCESS_BACKGROUND_LOCATION) { permissions - else + } else { permissions.toSet().minus(Manifest.permission.ACCESS_BACKGROUND_LOCATION) .toTypedArray() + } ) + } }, modifier = Modifier .fillMaxWidth(), @@ -85,10 +88,11 @@ fun SensorUi( toggleControl = { Icon( imageVector = ToggleChipDefaults.switchIcon(checked), - contentDescription = if (checked) + contentDescription = if (checked) { stringResource(R.string.enabled) - else + } else { stringResource(R.string.disabled) + } ) } ) diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/views/SensorsView.kt b/wear/src/main/java/io/homeassistant/companion/android/home/views/SensorsView.kt index c28b62e3393..03194ce4cae 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/views/SensorsView.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/views/SensorsView.kt @@ -32,8 +32,9 @@ fun SensorsView( WearAppTheme { Scaffold( positionIndicator = { - if (scalingLazyListState.isScrollInProgress) + if (scalingLazyListState.isScrollInProgress) { PositionIndicator(scalingLazyListState = scalingLazyListState) + } }, timeText = { TimeText(!scalingLazyListState.isScrollInProgress) } ) { diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/views/SetFavoriteView.kt b/wear/src/main/java/io/homeassistant/companion/android/home/views/SetFavoriteView.kt index c523a858e76..f8373eba375 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/views/SetFavoriteView.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/views/SetFavoriteView.kt @@ -43,8 +43,9 @@ fun SetFavoritesView( WearAppTheme { Scaffold( positionIndicator = { - if (scalingLazyListState.isScrollInProgress) + if (scalingLazyListState.isScrollInProgress) { PositionIndicator(scalingLazyListState = scalingLazyListState) + } }, timeText = { TimeText(!scalingLazyListState.isScrollInProgress) } ) { @@ -114,10 +115,11 @@ private fun FavoriteToggleChip( toggleControl = { Icon( imageVector = ToggleChipDefaults.switchIcon(checked), - contentDescription = if (checked) + contentDescription = if (checked) { stringResource(commonR.string.enabled) - else + } else { stringResource(commonR.string.disabled) + } ) } ) diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/views/SetTileShortcutsView.kt b/wear/src/main/java/io/homeassistant/companion/android/home/views/SetTileShortcutsView.kt index fffdf15790b..7874a0c18fd 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/views/SetTileShortcutsView.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/views/SetTileShortcutsView.kt @@ -38,7 +38,6 @@ fun SetTileShortcutsView( isShowShortcutTextEnabled: Boolean, onShowShortcutTextEnabled: (Boolean) -> Unit ) { - WearAppTheme { ThemeLazyColumn { item { @@ -55,20 +54,22 @@ fun SetTileShortcutsView( appIcon = { Image( asset = - if (isShowShortcutTextEnabled) + if (isShowShortcutTextEnabled) { CommunityMaterial.Icon.cmd_alphabetical - else - CommunityMaterial.Icon.cmd_alphabetical_off, + } else { + CommunityMaterial.Icon.cmd_alphabetical_off + }, colorFilter = ColorFilter.tint(wearColorPalette.onSurface) ) }, toggleControl = { Icon( imageVector = ToggleChipDefaults.checkboxIcon(isShowShortcutTextEnabled), - contentDescription = if (isShowShortcutTextEnabled) + contentDescription = if (isShowShortcutTextEnabled) { stringResource(commonR.string.show) - else + } else { stringResource(commonR.string.hide) + } ) } ) diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/views/SettingsView.kt b/wear/src/main/java/io/homeassistant/companion/android/home/views/SettingsView.kt index e864bd7fd64..72fee3eeba3 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/views/SettingsView.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/views/SettingsView.kt @@ -80,8 +80,9 @@ fun SettingsView( WearAppTheme { Scaffold( positionIndicator = { - if (scalingLazyListState.isScrollInProgress) + if (scalingLazyListState.isScrollInProgress) { PositionIndicator(scalingLazyListState = scalingLazyListState) + } }, timeText = { TimeText(!scalingLazyListState.isScrollInProgress) } ) { @@ -118,10 +119,11 @@ fun SettingsView( toggleControl = { Icon( imageVector = ToggleChipDefaults.switchIcon(isFavoritesOnly), - contentDescription = if (isFavoritesOnly) + contentDescription = if (isFavoritesOnly) { stringResource(commonR.string.enabled) - else + } else { stringResource(commonR.string.disabled) + } ) }, appIcon = { @@ -152,20 +154,22 @@ fun SettingsView( appIcon = { Image( asset = - if (isHapticEnabled) + if (isHapticEnabled) { CommunityMaterial.Icon3.cmd_watch_vibrate - else - CommunityMaterial.Icon3.cmd_watch_vibrate_off, + } else { + CommunityMaterial.Icon3.cmd_watch_vibrate_off + }, colorFilter = ColorFilter.tint(wearColorPalette.onSurface) ) }, toggleControl = { Icon( imageVector = ToggleChipDefaults.checkboxIcon(isHapticEnabled), - contentDescription = if (isHapticEnabled) + contentDescription = if (isHapticEnabled) { stringResource(commonR.string.enabled) - else + } else { stringResource(commonR.string.disabled) + } ) } ) @@ -181,20 +185,22 @@ fun SettingsView( appIcon = { Image( asset = - if (isToastEnabled) + if (isToastEnabled) { CommunityMaterial.Icon3.cmd_message - else - CommunityMaterial.Icon3.cmd_message_off, + } else { + CommunityMaterial.Icon3.cmd_message_off + }, colorFilter = ColorFilter.tint(wearColorPalette.onSurface) ) }, toggleControl = { Icon( imageVector = ToggleChipDefaults.checkboxIcon(isToastEnabled), - contentDescription = if (isHapticEnabled) + contentDescription = if (isHapticEnabled) { stringResource(commonR.string.enabled) - else + } else { stringResource(commonR.string.disabled) + } ) } ) diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/views/TemplateTileSettingsView.kt b/wear/src/main/java/io/homeassistant/companion/android/home/views/TemplateTileSettingsView.kt index 92fb01d8b26..b3065d939d2 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/views/TemplateTileSettingsView.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/views/TemplateTileSettingsView.kt @@ -27,7 +27,6 @@ fun TemplateTileSettingsView( refreshInterval: Int, onClickRefreshInterval: () -> Unit ) { - ThemeLazyColumn { item { ListHeader(id = R.string.template_tile) diff --git a/wear/src/main/java/io/homeassistant/companion/android/home/views/TimeText.kt b/wear/src/main/java/io/homeassistant/companion/android/home/views/TimeText.kt index eb57505e994..e2278f47f92 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/home/views/TimeText.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/home/views/TimeText.kt @@ -16,7 +16,7 @@ fun TimeText( AnimatedVisibility( visible = visible, enter = slideInVertically(), - exit = slideOutVertically(), + exit = slideOutVertically() ) { TimeText() } diff --git a/wear/src/main/java/io/homeassistant/companion/android/notifications/MessagingManager.kt b/wear/src/main/java/io/homeassistant/companion/android/notifications/MessagingManager.kt index be00992360d..25737aa7a69 100755 --- a/wear/src/main/java/io/homeassistant/companion/android/notifications/MessagingManager.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/notifications/MessagingManager.kt @@ -32,7 +32,7 @@ import javax.inject.Inject class MessagingManager @Inject constructor( @ApplicationContext val context: Context, private val serverManager: ServerManager, - private val sensorDao: SensorDao, + private val sensorDao: SensorDao ) { companion object { @@ -42,7 +42,6 @@ class MessagingManager @Inject constructor( private val mainScope: CoroutineScope = CoroutineScope(Dispatchers.Main + Job()) fun handleMessage(notificationData: Map, source: String) { - val notificationDao = AppDatabase.getInstance(context).notificationDao() val now = System.currentTimeMillis() diff --git a/wear/src/main/java/io/homeassistant/companion/android/onboarding/OnboardingActivity.kt b/wear/src/main/java/io/homeassistant/companion/android/onboarding/OnboardingActivity.kt index cb5b79eab23..1b653b1ec89 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/onboarding/OnboardingActivity.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/onboarding/OnboardingActivity.kt @@ -21,7 +21,7 @@ import com.google.android.gms.wearable.Wearable import dagger.hilt.android.AndroidEntryPoint import io.homeassistant.companion.android.R import io.homeassistant.companion.android.onboarding.integration.MobileAppIntegrationActivity -import io.homeassistant.companion.android.onboarding.manual_setup.ManualSetupActivity +import io.homeassistant.companion.android.onboarding.manual.ManualSetupActivity import io.homeassistant.companion.android.util.LoadingView import kotlinx.coroutines.guava.await import kotlinx.coroutines.launch @@ -59,12 +59,18 @@ class OnboardingActivity : AppCompatActivity(), OnboardingView { adapter = ServerListAdapter(ArrayList()) adapter.onInstanceClicked = { instance -> - if (phoneSignInAvailable) startPhoneSignIn(instance) - else presenter.onInstanceClickedWithoutApp(this, instance.url.toString()) + if (phoneSignInAvailable) { + startPhoneSignIn(instance) + } else { + presenter.onInstanceClickedWithoutApp(this, instance.url.toString()) + } } adapter.onManualSetupClicked = { - if (phoneSignInAvailable) startPhoneSignIn(null) - else startManualSetup() + if (phoneSignInAvailable) { + startPhoneSignIn(null) + } else { + startManualSetup() + } } capabilityClient = Wearable.getCapabilityClient(this) diff --git a/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupActivity.kt b/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupActivity.kt similarity index 97% rename from wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupActivity.kt rename to wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupActivity.kt index 60225659986..1f44fb5c728 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupActivity.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupActivity.kt @@ -1,4 +1,4 @@ -package io.homeassistant.companion.android.onboarding.manual_setup +package io.homeassistant.companion.android.onboarding.manual import android.content.Context import android.content.Intent diff --git a/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupModule.kt b/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupModule.kt similarity index 82% rename from wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupModule.kt rename to wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupModule.kt index 09f8fce0431..1dd3bd93c69 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupModule.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupModule.kt @@ -1,4 +1,4 @@ -package io.homeassistant.companion.android.onboarding.manual_setup +package io.homeassistant.companion.android.onboarding.manual import dagger.Binds import dagger.Module diff --git a/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupPresenter.kt b/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupPresenter.kt similarity index 67% rename from wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupPresenter.kt rename to wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupPresenter.kt index 723205036c4..4db4ec3b45d 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupPresenter.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupPresenter.kt @@ -1,4 +1,4 @@ -package io.homeassistant.companion.android.onboarding.manual_setup +package io.homeassistant.companion.android.onboarding.manual import android.content.Context diff --git a/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupPresenterImpl.kt b/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupPresenterImpl.kt similarity index 98% rename from wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupPresenterImpl.kt rename to wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupPresenterImpl.kt index 3fa391efc0a..13ade7386c7 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupPresenterImpl.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupPresenterImpl.kt @@ -1,4 +1,4 @@ -package io.homeassistant.companion.android.onboarding.manual_setup +package io.homeassistant.companion.android.onboarding.manual import android.content.Context import android.net.Uri diff --git a/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupView.kt b/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupView.kt similarity index 75% rename from wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupView.kt rename to wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupView.kt index 2e6d151bc61..56c9cec0a77 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual_setup/ManualSetupView.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/onboarding/manual/ManualSetupView.kt @@ -1,4 +1,4 @@ -package io.homeassistant.companion.android.onboarding.manual_setup +package io.homeassistant.companion.android.onboarding.manual import androidx.annotation.StringRes diff --git a/wear/src/main/java/io/homeassistant/companion/android/sensors/BedtimeModeSensorManager.kt b/wear/src/main/java/io/homeassistant/companion/android/sensors/BedtimeModeSensorManager.kt index 8242ba85a68..b5f9ba9c444 100755 --- a/wear/src/main/java/io/homeassistant/companion/android/sensors/BedtimeModeSensorManager.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/sensors/BedtimeModeSensorManager.kt @@ -45,9 +45,9 @@ class BedtimeModeSensorManager : SensorManager { } private fun updateBedtimeMode(context: Context) { - - if (!isEnabled(context, bedtimeMode)) + if (!isEnabled(context, bedtimeMode)) { return + } val state = try { Settings.Global.getInt(context.contentResolver, if (Build.MANUFACTURER == "samsung") "setting_bedtime_mode_running_state" else "bedtime_mode") == 1 diff --git a/wear/src/main/java/io/homeassistant/companion/android/sensors/HealthServicesSensorManager.kt b/wear/src/main/java/io/homeassistant/companion/android/sensors/HealthServicesSensorManager.kt index dc0b1977580..04c12165c51 100755 --- a/wear/src/main/java/io/homeassistant/companion/android/sensors/HealthServicesSensorManager.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/sensors/HealthServicesSensorManager.kt @@ -102,10 +102,12 @@ class HealthServicesSensorManager : SensorManager { override suspend fun getAvailableSensors(context: Context): List { latestContext = context - if (healthClient == null) + if (healthClient == null) { healthClient = HealthServices.getClient(latestContext) - if (passiveMonitoringClient == null) + } + if (passiveMonitoringClient == null) { passiveMonitoringClient = healthClient?.passiveMonitoringClient + } if (passiveMonitoringCapabilities == null) { passiveMonitoringCapabilities = passiveMonitoringClient?.getCapabilitiesAsync()?.await() Log.d(TAG, "Supported capabilities: $passiveMonitoringCapabilities") @@ -113,14 +115,18 @@ class HealthServicesSensorManager : SensorManager { val supportedSensors = mutableListOf(userActivityState) - if (passiveMonitoringCapabilities?.supportedDataTypesPassiveMonitoring?.contains(DataType.FLOORS_DAILY) == true) + if (passiveMonitoringCapabilities?.supportedDataTypesPassiveMonitoring?.contains(DataType.FLOORS_DAILY) == true) { supportedSensors += dailyFloors - if (passiveMonitoringCapabilities?.supportedDataTypesPassiveMonitoring?.contains(DataType.DISTANCE_DAILY) == true) + } + if (passiveMonitoringCapabilities?.supportedDataTypesPassiveMonitoring?.contains(DataType.DISTANCE_DAILY) == true) { supportedSensors += dailyDistance - if (passiveMonitoringCapabilities?.supportedDataTypesPassiveMonitoring?.contains(DataType.CALORIES_DAILY) == true) + } + if (passiveMonitoringCapabilities?.supportedDataTypesPassiveMonitoring?.contains(DataType.CALORIES_DAILY) == true) { supportedSensors += dailyCalories - if (passiveMonitoringCapabilities?.supportedDataTypesPassiveMonitoring?.contains(DataType.STEPS_DAILY) == true) + } + if (passiveMonitoringCapabilities?.supportedDataTypesPassiveMonitoring?.contains(DataType.STEPS_DAILY) == true) { supportedSensors += dailySteps + } return supportedSensors } @@ -156,14 +162,18 @@ class HealthServicesSensorManager : SensorManager { if (passiveMonitoringClient == null) passiveMonitoringClient = healthClient?.passiveMonitoringClient val dataTypes = mutableSetOf>() - if (dailyFloorEnabled) + if (dailyFloorEnabled) { dataTypes += DataType.FLOORS_DAILY - if (dailyDistanceEnabled) + } + if (dailyDistanceEnabled) { dataTypes += DataType.DISTANCE_DAILY - if (dailyCaloriesEnabled) + } + if (dailyCaloriesEnabled) { dataTypes += DataType.CALORIES_DAILY - if (dailyStepsEnabled) + } + if (dailyStepsEnabled) { dataTypes += DataType.STEPS_DAILY + } passiveListenerConfig = PassiveListenerConfig.builder() .setShouldUserActivityInfoBeRequested(activityStateEnabled) @@ -201,8 +211,9 @@ class HealthServicesSensorManager : SensorManager { val sensorDao = AppDatabase.getInstance(latestContext).sensorDao() val sensorData = sensorDao.get(userActivityState.id) - if (sensorData.any { it.state != it.lastSentState } || forceUpdate) + if (sensorData.any { it.state != it.lastSentState } || forceUpdate) { SensorReceiver.updateAllSensors(latestContext) + } } override fun onNewDataPointsReceived(dataPoints: DataPointContainer) { diff --git a/wear/src/main/java/io/homeassistant/companion/android/sensors/HeartRateSensorManager.kt b/wear/src/main/java/io/homeassistant/companion/android/sensors/HeartRateSensorManager.kt index 7e634650944..019bee9e41f 100755 --- a/wear/src/main/java/io/homeassistant/companion/android/sensors/HeartRateSensorManager.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/sensors/HeartRateSensorManager.kt @@ -71,8 +71,9 @@ class HeartRateSensorManager : SensorManager, SensorEventListener { } private fun updateHeartRate() { - if (!isEnabled(latestContext, heartRate)) + if (!isEnabled(latestContext, heartRate)) { return + } val now = System.currentTimeMillis() if (listenerLastRegistered + 60000 < now && isListenerRegistered) { @@ -105,8 +106,9 @@ class HeartRateSensorManager : SensorManager, SensorEventListener { event.values[0].roundToInt() >= 0 if (event?.sensor?.type == Sensor.TYPE_HEART_RATE) { Log.d(TAG, "HR event received with accuracy: ${getAccuracy(event.accuracy)} and value: ${event.values[0]} with event count: $eventCount") - } else + } else { Log.d(TAG, "No HR event received") + } if (event != null && validReading) { onSensorUpdated( latestContext, diff --git a/wear/src/main/java/io/homeassistant/companion/android/sensors/OnBodySensorManager.kt b/wear/src/main/java/io/homeassistant/companion/android/sensors/OnBodySensorManager.kt index de1dbda406f..d9a9f4b5cfc 100755 --- a/wear/src/main/java/io/homeassistant/companion/android/sensors/OnBodySensorManager.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/sensors/OnBodySensorManager.kt @@ -56,8 +56,9 @@ class OnBodySensorManager : SensorManager, SensorEventListener { } private fun updateOnBodySensor() { - if (!isEnabled(latestContext, onBodySensor)) + if (!isEnabled(latestContext, onBodySensor)) { return + } mySensorManager = latestContext.getSystemService()!! diff --git a/wear/src/main/java/io/homeassistant/companion/android/sensors/SensorReceiver.kt b/wear/src/main/java/io/homeassistant/companion/android/sensors/SensorReceiver.kt index 978b424ad5c..c2b3ee8f417 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/sensors/SensorReceiver.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/sensors/SensorReceiver.kt @@ -81,10 +81,11 @@ class SensorReceiver : SensorReceiverBase() { TrafficStatsManager(), WetModeSensorManager() ) - val MANAGERS = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) + val MANAGERS = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { allManager.plus(HealthServicesSensorManager()) - else + } else { allManager + } const val ACTION_REQUEST_SENSORS_UPDATE = "io.homeassistant.companion.android.background.REQUEST_SENSORS_UPDATE" diff --git a/wear/src/main/java/io/homeassistant/companion/android/sensors/TheaterModeSensorManager.kt b/wear/src/main/java/io/homeassistant/companion/android/sensors/TheaterModeSensorManager.kt index 5a8ad29df5c..701f0d83849 100755 --- a/wear/src/main/java/io/homeassistant/companion/android/sensors/TheaterModeSensorManager.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/sensors/TheaterModeSensorManager.kt @@ -41,9 +41,9 @@ class TheaterModeSensorManager : SensorManager { } private fun updateTheaterMode(context: Context) { - - if (!isEnabled(context, theaterMode)) + if (!isEnabled(context, theaterMode)) { return + } val state = try { Settings.Global.getInt(context.contentResolver, if (Build.MANUFACTURER == "samsung") "setting_theater_mode_on" else "theater_mode_on") == 1 diff --git a/wear/src/main/java/io/homeassistant/companion/android/sensors/WetModeSensorManager.kt b/wear/src/main/java/io/homeassistant/companion/android/sensors/WetModeSensorManager.kt index 5e2a8ccff10..0919e673d94 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/sensors/WetModeSensorManager.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/sensors/WetModeSensorManager.kt @@ -57,8 +57,9 @@ class WetModeSensorManager : SensorManager { } private fun updateWetMode(context: Context) { - if (!isEnabled(context, wetModeSensor)) + if (!isEnabled(context, wetModeSensor)) { return + } onSensorUpdated( context, diff --git a/wear/src/main/java/io/homeassistant/companion/android/tiles/TemplateTile.kt b/wear/src/main/java/io/homeassistant/companion/android/tiles/TemplateTile.kt index 874b6be8c2d..b8b0964ea26 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/tiles/TemplateTile.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/tiles/TemplateTile.kt @@ -75,13 +75,19 @@ class TemplateTile : TileService() { val template = wearPrefsRepository.getTemplateTileContent() val renderedText = try { - if (serverManager.isRegistered()) serverManager.integrationRepository().renderTemplate(template, mapOf()).toString() - else "" + if (serverManager.isRegistered()) { + serverManager.integrationRepository().renderTemplate(template, mapOf()).toString() + } else { + "" + } } catch (e: Exception) { Log.e("TemplateTile", "Exception while rendering template", e) // JsonMappingException suggests that template is not a String (= error) - if (e.cause is JsonMappingException) getString(commonR.string.template_error) - else getString(commonR.string.template_render_error) + if (e.cause is JsonMappingException) { + getString(commonR.string.template_error) + } else { + getString(commonR.string.template_render_error) + } } Tile.Builder() diff --git a/wear/src/main/java/io/homeassistant/companion/android/tiles/TileActionReceiver.kt b/wear/src/main/java/io/homeassistant/companion/android/tiles/TileActionReceiver.kt index 98e2e41449f..c241155cd9f 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/tiles/TileActionReceiver.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/tiles/TileActionReceiver.kt @@ -54,10 +54,11 @@ class TileActionReceiver : BroadcastReceiver() { } catch (e: Exception) { null } - if (lockEntity?.state == "locked") + if (lockEntity?.state == "locked") { "unlock" - else + } else { "lock" + } } in HomePresenterImpl.toggleDomains -> "toggle" else -> "turn_on" diff --git a/wear/src/main/java/io/homeassistant/companion/android/util/CommonFunctions.kt b/wear/src/main/java/io/homeassistant/companion/android/util/CommonFunctions.kt index ccb37f55723..2bca7681f56 100755 --- a/wear/src/main/java/io/homeassistant/companion/android/util/CommonFunctions.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/util/CommonFunctions.kt @@ -48,8 +48,10 @@ fun onEntityClickedFeedback(isToastEnabled: Boolean, isHapticEnabled: Boolean, c } fun onEntityFeedback(isToastEnabled: Boolean, isHapticEnabled: Boolean, message: String, context: Context, haptic: HapticFeedback) { - if (isToastEnabled) + if (isToastEnabled) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() - if (isHapticEnabled) + } + if (isHapticEnabled) { haptic.performHapticFeedback(HapticFeedbackType.LongPress) + } } diff --git a/wear/src/main/java/io/homeassistant/companion/android/util/WearToggleChip.kt b/wear/src/main/java/io/homeassistant/companion/android/util/WearToggleChip.kt index 38da5c8be3c..a7326b81cd8 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/util/WearToggleChip.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/util/WearToggleChip.kt @@ -208,7 +208,7 @@ object WearToggleChip { ) disabledCheckedBackgroundColors = listOf( checkedEndBackgroundColor.copy(alpha = ContentAlpha.disabled), - checkedStartBackgroundColor.copy(alpha = ContentAlpha.disabled), + checkedStartBackgroundColor.copy(alpha = ContentAlpha.disabled) ) } val uncheckedBackgroundColors: List @@ -229,7 +229,7 @@ object WearToggleChip { ) disabledUncheckedBackgroundColors = listOf( uncheckedEndBackgroundColor.copy(alpha = ContentAlpha.disabled), - uncheckedStartBackgroundColor.copy(alpha = ContentAlpha.disabled), + uncheckedStartBackgroundColor.copy(alpha = ContentAlpha.disabled) ) } @@ -290,7 +290,7 @@ class WearToggleChipColors( var disabledUncheckedBackgroundPainter: Painter, var disabledUncheckedContentColor: Color, var disabledUncheckedSecondaryContentColor: Color, - var disabledUncheckedIconColor: Color, + var disabledUncheckedIconColor: Color ) : ToggleChipColors { @Composable @@ -299,8 +299,11 @@ class WearToggleChipColors( if (enabled) { if (checked) checkedBackgroundPainter else uncheckedBackgroundPainter } else { - if (checked) disabledCheckedBackgroundPainter else + if (checked) { + disabledCheckedBackgroundPainter + } else { disabledUncheckedBackgroundPainter + } } ) } @@ -322,8 +325,11 @@ class WearToggleChipColors( if (enabled) { if (checked) checkedSecondaryContentColor else uncheckedSecondaryContentColor } else { - if (checked) disabledCheckedSecondaryContentColor else + if (checked) { + disabledCheckedSecondaryContentColor + } else { disabledUncheckedSecondaryContentColor + } } ) } @@ -359,15 +365,21 @@ class WearToggleChipColors( if (disabledCheckedIconColor != other.disabledCheckedIconColor) return false if (disabledCheckedSecondaryContentColor != other.disabledCheckedSecondaryContentColor - ) return false + ) { + return false + } if (disabledUncheckedBackgroundPainter != other.disabledUncheckedBackgroundPainter - ) return false + ) { + return false + } if (disabledUncheckedContentColor != other.disabledUncheckedContentColor) return false if (disabledUncheckedIconColor != other.disabledUncheckedIconColor) return false if (disabledUncheckedSecondaryContentColor != other.disabledUncheckedSecondaryContentColor - ) return false + ) { + return false + } return true } diff --git a/wear/src/main/java/io/homeassistant/companion/android/views/ExpandableListHeader.kt b/wear/src/main/java/io/homeassistant/companion/android/views/ExpandableListHeader.kt index d8e653da081..76230cb1a45 100644 --- a/wear/src/main/java/io/homeassistant/companion/android/views/ExpandableListHeader.kt +++ b/wear/src/main/java/io/homeassistant/companion/android/views/ExpandableListHeader.kt @@ -30,7 +30,9 @@ fun rememberExpandedStates( ): SnapshotStateMap { val defaultExpanded = if (initialKeys is Collection) { initialKeys.size == 1 - } else false + } else { + false + } return remember { mutableStateMapOf().apply { initialKeys.forEach { key ->