diff --git a/.editorconfig b/.editorconfig
index 054437f601..78b7fa3b32 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -12,6 +12,7 @@ insert_final_newline = true
[*.{java,kt,xml}]
max_line_length = 120
+ktlint_code_style = android_studio
[*.yml]
indent_size = 2
diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml
index 902fce96b0..cd165e646c 100644
--- a/.idea/codeStyles/Project.xml
+++ b/.idea/codeStyles/Project.xml
@@ -12,8 +12,6 @@
-
-
diff --git a/mobile/src/foss/java/org/openhab/habdroid/ui/MapViewHelper.kt b/mobile/src/foss/java/org/openhab/habdroid/ui/MapViewHelper.kt
index 1a3df864ee..e91b4f1e2f 100644
--- a/mobile/src/foss/java/org/openhab/habdroid/ui/MapViewHelper.kt
+++ b/mobile/src/foss/java/org/openhab/habdroid/ui/MapViewHelper.kt
@@ -67,16 +67,18 @@ object MapViewHelper {
setMultiTouchControls(false)
setDestroyMode(false)
overlays.add(CopyrightOverlay(itemView.context))
- overlays.add(MapEventsOverlay(object : MapEventsReceiver {
- override fun singleTapConfirmedHelper(p: GeoPoint): Boolean {
- openPopup()
- return true
- }
+ overlays.add(
+ MapEventsOverlay(object : MapEventsReceiver {
+ override fun singleTapConfirmedHelper(p: GeoPoint): Boolean {
+ openPopup()
+ return true
+ }
- override fun longPressHelper(p: GeoPoint): Boolean {
- return false
- }
- }))
+ override fun longPressHelper(p: GeoPoint): Boolean {
+ return false
+ }
+ })
+ )
mapOverlay.setColorFilter(if (context.isDarkModeActive()) TilesOverlay.INVERT_COLORS else null)
}
}
diff --git a/mobile/src/full/java/org/openhab/habdroid/core/CloudMessagingHelper.kt b/mobile/src/full/java/org/openhab/habdroid/core/CloudMessagingHelper.kt
index c78d339a21..0295a9557a 100644
--- a/mobile/src/full/java/org/openhab/habdroid/core/CloudMessagingHelper.kt
+++ b/mobile/src/full/java/org/openhab/habdroid/core/CloudMessagingHelper.kt
@@ -41,8 +41,7 @@ object CloudMessagingHelper {
}
fun onNotificationSelected(context: Context, intent: Intent) {
- val notificationId = intent.getIntExtra(
- NotificationHelper.EXTRA_NOTIFICATION_ID, -1)
+ val notificationId = intent.getIntExtra(NotificationHelper.EXTRA_NOTIFICATION_ID, -1)
if (notificationId >= 0) {
FcmRegistrationWorker.scheduleHideNotification(context, notificationId)
}
@@ -64,15 +63,15 @@ object CloudMessagingHelper {
val cloudFailure = cloudConnectionResult?.failureReason
return when {
// No remote server is configured
- prefs.getRemoteUrl(prefs.getPrimaryServerId()).isEmpty() ->
- PushNotificationStatus(
- context.getString(R.string.push_notification_status_no_remote_configured),
- R.drawable.ic_bell_off_outline_grey_24dp,
- false
- )
+ prefs.getRemoteUrl(prefs.getPrimaryServerId()).isEmpty() -> PushNotificationStatus(
+ context.getString(R.string.push_notification_status_no_remote_configured),
+ R.drawable.ic_bell_off_outline_grey_24dp,
+ false
+ )
// Cloud connection failed
cloudFailure != null && cloudFailure !is NotACloudServerException -> {
- val message = context.getString(R.string.push_notification_status_http_error,
+ val message = context.getString(
+ R.string.push_notification_status_http_error,
context.getHumanReadableErrorMessage(
if (cloudFailure is HttpClient.HttpException) cloudFailure.originalUrl else "",
if (cloudFailure is HttpClient.HttpException) cloudFailure.statusCode else 0,
@@ -90,12 +89,11 @@ object CloudMessagingHelper {
false
)
// Registration isn't done yet
- !registrationDone ->
- PushNotificationStatus(
- context.getString(R.string.info_openhab_gcm_in_progress),
- R.drawable.ic_bell_outline_grey_24dp,
- false
- )
+ !registrationDone -> PushNotificationStatus(
+ context.getString(R.string.info_openhab_gcm_in_progress),
+ R.drawable.ic_bell_outline_grey_24dp,
+ false
+ )
// Registration failed
registrationFailureReason != null -> {
val gaa = GoogleApiAvailability.getInstance()
@@ -115,12 +113,11 @@ object CloudMessagingHelper {
}
}
// Push notifications are working
- else ->
- PushNotificationStatus(
- context.getString(R.string.info_openhab_gcm_connected),
- R.drawable.ic_bell_ring_outline_grey_24dp,
- false
- )
+ else -> PushNotificationStatus(
+ context.getString(R.string.info_openhab_gcm_connected),
+ R.drawable.ic_bell_ring_outline_grey_24dp,
+ false
+ )
}
}
}
diff --git a/mobile/src/full/java/org/openhab/habdroid/core/FcmRegistrationWorker.kt b/mobile/src/full/java/org/openhab/habdroid/core/FcmRegistrationWorker.kt
index e16abb77ca..c9ce94afd5 100644
--- a/mobile/src/full/java/org/openhab/habdroid/core/FcmRegistrationWorker.kt
+++ b/mobile/src/full/java/org/openhab/habdroid/core/FcmRegistrationWorker.kt
@@ -53,8 +53,11 @@ class FcmRegistrationWorker(private val context: Context, params: WorkerParamete
val manufacturer = Build.MANUFACTURER
val model = Build.MODEL
- val actualModel = if (model.lowercase(Locale.ROOT).startsWith(manufacturer.lowercase(Locale.ROOT)))
- model else "$manufacturer $model"
+ val actualModel = if (model.lowercase(Locale.ROOT).startsWith(manufacturer.lowercase(Locale.ROOT))) {
+ model
+ } else {
+ "$manufacturer $model"
+ }
// Capitalize returned value
val first = actualModel.elementAtOrNull(0)
@@ -103,7 +106,6 @@ class FcmRegistrationWorker(private val context: Context, params: WorkerParamete
sendHideNotificationRequest(id, connection.messagingSenderId)
return Result.success()
}
-
}
else -> Log.e(TAG, "Invalid action '$action'")
}
@@ -119,15 +121,21 @@ class FcmRegistrationWorker(private val context: Context, params: WorkerParamete
// HttpException is thrown by our HTTP code, IOException can be thrown by FCM
@Throws(HttpClient.HttpException::class, IOException::class)
private suspend fun registerFcm(connection: CloudConnection) {
- val token = FirebaseInstanceId.getInstance().getToken(connection.messagingSenderId,
- FirebaseMessaging.INSTANCE_ID_SCOPE)
+ val token = FirebaseInstanceId.getInstance().getToken(
+ connection.messagingSenderId,
+ FirebaseMessaging.INSTANCE_ID_SCOPE
+ )
val deviceName = deviceName + if (Util.isFlavorBeta) " (${context.getString(R.string.beta)})" else ""
val deviceId = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID) +
- if (Util.isFlavorBeta) "-beta" else ""
+ if (Util.isFlavorBeta) "-beta" else ""
- val regUrl = String.format(Locale.US,
- "addAndroidRegistration?deviceId=%s&deviceModel=%s®Id=%s",
- deviceId, URLEncoder.encode(deviceName, "UTF-8"), token)
+ val regUrl = String.format(
+ Locale.US,
+ "addAndroidRegistration?deviceId=%s&deviceModel=%s®Id=%s",
+ deviceId,
+ URLEncoder.encode(deviceName, "UTF-8"),
+ token
+ )
Log.d(TAG, "Register device at openHAB-cloud with URL: $regUrl")
connection.httpClient.get(regUrl).close()
@@ -137,9 +145,9 @@ class FcmRegistrationWorker(private val context: Context, params: WorkerParamete
private fun sendHideNotificationRequest(notificationId: Int, senderId: String) {
val fcm = FirebaseMessaging.getInstance()
val message = RemoteMessage.Builder("$senderId@gcm.googleapis.com")
- .addData("type", "hideNotification")
- .addData("notificationId", notificationId.toString())
- .build()
+ .addData("type", "hideNotification")
+ .addData("notificationId", notificationId.toString())
+ .build()
fcm.send(message)
}
@@ -158,7 +166,7 @@ class FcmRegistrationWorker(private val context: Context, params: WorkerParamete
companion object {
internal fun wrap(context: Context, intent: Intent, id: Int): PendingIntent {
val wrapped = Intent(context, ProxyReceiver::class.java)
- .putExtra("intent", intent)
+ .putExtra("intent", intent)
return PendingIntent.getBroadcast(
context,
id,
@@ -209,8 +217,11 @@ class FcmRegistrationWorker(private val context: Context, params: WorkerParamete
val workRequest = OneTimeWorkRequest.Builder(FcmRegistrationWorker::class.java)
.setConstraints(constraints)
- .setBackoffCriteria(BackoffPolicy.LINEAR,
- WorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
+ .setBackoffCriteria(
+ BackoffPolicy.LINEAR,
+ WorkRequest.MIN_BACKOFF_MILLIS,
+ TimeUnit.MILLISECONDS
+ )
.setInputData(data)
.build()
diff --git a/mobile/src/full/java/org/openhab/habdroid/ui/MapViewHelper.kt b/mobile/src/full/java/org/openhab/habdroid/ui/MapViewHelper.kt
index 90a14b532e..b4be07b1ca 100644
--- a/mobile/src/full/java/org/openhab/habdroid/ui/MapViewHelper.kt
+++ b/mobile/src/full/java/org/openhab/habdroid/ui/MapViewHelper.kt
@@ -126,9 +126,9 @@ fun GoogleMap.applyPositionAndLabel(widget: Widget, zoomLevel: Float, allowDrag:
fun GoogleMap.setMarker(position: LatLng, item: Item, label: CharSequence?, canDrag: Boolean) {
val marker = MarkerOptions()
- .draggable(canDrag)
- .position(position)
- .title(label?.toString())
+ .draggable(canDrag)
+ .position(position)
+ .title(label?.toString())
addMarker(marker)?.tag = item
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/BackgroundTasksManager.kt b/mobile/src/main/java/org/openhab/habdroid/background/BackgroundTasksManager.kt
index f05172e48c..918e223f52 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/BackgroundTasksManager.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/BackgroundTasksManager.kt
@@ -198,7 +198,8 @@ class BackgroundTasksManager : BroadcastReceiver() {
}
}
ACTION_VOICE_RESULT -> {
- val voiceCommand = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)?.elementAtOrNull(0)
+ val voiceCommand = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
+ ?.elementAtOrNull(0)
?: return
Log.i(TAG, "Recognized text: $voiceCommand")
@@ -281,6 +282,7 @@ class BackgroundTasksManager : BroadcastReceiver() {
const val WORKER_TAG_PREFIX_TILE = "tile-"
const val WORKER_TAG_PREFIX_TILE_ID = "tile_id-"
const val WORKER_TAG_VOICE_COMMAND = "voiceCommand"
+
fun buildWorkerTagForServer(id: Int) = "server-id-$id"
private const val GADGETBRIDGE_ACTION_PREFIX = "nodomain.freeyourgadget.gadgetbridge."
@@ -306,6 +308,7 @@ class BackgroundTasksManager : BroadcastReceiver() {
PrefKeys.SEND_WIFI_SSID,
PrefKeys.SEND_DND_MODE
)
+
// These package names must be added to the manifest as well
private val IGNORED_PACKAGES_FOR_ALARM = listOf(
"net.dinglisch.android.taskerm",
@@ -337,7 +340,8 @@ class BackgroundTasksManager : BroadcastReceiver() {
// These broadcasts are already defined in the manifest, so we only need them on Android 8+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (prefs.isItemUpdatePrefEnabled(PrefKeys.SEND_BATTERY_LEVEL) ||
- prefs.isItemUpdatePrefEnabled(PrefKeys.SEND_CHARGING_STATE)) {
+ prefs.isItemUpdatePrefEnabled(PrefKeys.SEND_CHARGING_STATE)
+ ) {
addAction(Intent.ACTION_POWER_CONNECTED)
addAction(Intent.ACTION_POWER_DISCONNECTED)
addAction(Intent.ACTION_BATTERY_LOW)
@@ -354,7 +358,8 @@ class BackgroundTasksManager : BroadcastReceiver() {
}
// This broadcast is only sent to registered receivers, so we need that in any case
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
- prefs.isItemUpdatePrefEnabled(PrefKeys.SEND_DND_MODE)) {
+ prefs.isItemUpdatePrefEnabled(PrefKeys.SEND_DND_MODE)
+ ) {
addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED)
}
}
@@ -494,12 +499,19 @@ class BackgroundTasksManager : BroadcastReceiver() {
PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS
)
- Log.d(TAG, "Scheduling periodic workers with $repeatInterval repeat interval. Currently running:" +
- " notCharging $isNotChargingWorkerRunning, charging $isChargingWorkerRunning")
+ Log.d(
+ TAG,
+ "Scheduling periodic workers with $repeatInterval repeat interval. Currently running:" +
+ " notCharging $isNotChargingWorkerRunning, charging $isChargingWorkerRunning"
+ )
- val notChargingWorkRequest = PeriodicWorkRequest.Builder(PeriodicItemUpdateWorker::class.java,
- repeatInterval, TimeUnit.MILLISECONDS,
- flexInterval, TimeUnit.MILLISECONDS)
+ val notChargingWorkRequest = PeriodicWorkRequest.Builder(
+ PeriodicItemUpdateWorker::class.java,
+ repeatInterval,
+ TimeUnit.MILLISECONDS,
+ flexInterval,
+ TimeUnit.MILLISECONDS
+ )
.setConstraints(Constraints(requiredNetworkType = NetworkType.CONNECTED))
.addTag(WORKER_TAG_PERIODIC_TRIGGER)
.addTag(WORKER_TAG_PERIODIC_TRIGGER_NOT_CHARGING)
@@ -511,9 +523,13 @@ class BackgroundTasksManager : BroadcastReceiver() {
requiresCharging = true
)
- val chargingWorkRequest = PeriodicWorkRequest.Builder(PeriodicItemUpdateWorker::class.java,
- PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, TimeUnit.MILLISECONDS,
- PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS, TimeUnit.MILLISECONDS)
+ val chargingWorkRequest = PeriodicWorkRequest.Builder(
+ PeriodicItemUpdateWorker::class.java,
+ PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
+ TimeUnit.MILLISECONDS,
+ PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS,
+ TimeUnit.MILLISECONDS
+ )
.setConstraints(chargingConstraints)
.addTag(WORKER_TAG_PERIODIC_TRIGGER)
.addTag(WORKER_TAG_PERIODIC_TRIGGER_CHARGING)
@@ -605,10 +621,7 @@ class BackgroundTasksManager : BroadcastReceiver() {
.setSmallIcon(R.drawable.ic_openhab_appicon_white_24dp)
.setContentTitle(context.getString(R.string.send_device_info_to_server_short))
.setContentText(debugInfo)
- .setStyle(
- NotificationCompat.BigTextStyle()
- .bigText(debugInfo)
- )
+ .setStyle(NotificationCompat.BigTextStyle().bigText(debugInfo))
.setWhen(System.currentTimeMillis())
.setShowWhen(true)
.setColor(ContextCompat.getColor(context, R.color.openhab_orange))
@@ -661,8 +674,11 @@ class BackgroundTasksManager : BroadcastReceiver() {
)
val workRequest = OneTimeWorkRequest.Builder(ItemUpdateWorker::class.java)
.setConstraints(constraints)
- .setBackoffCriteria(if (isImportant) BackoffPolicy.LINEAR else BackoffPolicy.EXPONENTIAL,
- WorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
+ .setBackoffCriteria(
+ if (isImportant) BackoffPolicy.LINEAR else BackoffPolicy.EXPONENTIAL,
+ WorkRequest.MIN_BACKOFF_MILLIS,
+ TimeUnit.MILLISECONDS
+ )
.addTag(primaryTag)
.addTag(WORKER_TAG_ITEM_UPLOADS)
.addTag(
@@ -756,25 +772,29 @@ class BackgroundTasksManager : BroadcastReceiver() {
val status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
val plugged = batteryStatus?.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
Log.d(TAG, "EXTRA_STATUS is $status, EXTRA_PLUGGED is $plugged")
- val state = if (status == BatteryManager.BATTERY_STATUS_CHARGING ||
- status == BatteryManager.BATTERY_STATUS_FULL) {
- when (plugged) {
- BatteryManager.BATTERY_PLUGGED_USB -> "USB"
- BatteryManager.BATTERY_PLUGGED_AC -> "AC"
- BatteryManager.BATTERY_PLUGGED_WIRELESS -> "WIRELESS"
- else -> "UNKNOWN_CHARGER"
+ val state =
+ if (status == BatteryManager.BATTERY_STATUS_CHARGING ||
+ status == BatteryManager.BATTERY_STATUS_FULL
+ ) {
+ when (plugged) {
+ BatteryManager.BATTERY_PLUGGED_USB -> "USB"
+ BatteryManager.BATTERY_PLUGGED_AC -> "AC"
+ BatteryManager.BATTERY_PLUGGED_WIRELESS -> "WIRELESS"
+ else -> "UNKNOWN_CHARGER"
+ }
+ } else {
+ "UNDEF"
}
- } else {
- "UNDEF"
- }
ItemUpdateWorker.ValueWithInfo(state, type = ItemUpdateWorker.ValueType.MapUndefToOffForSwitchItems)
}
VALUE_GETTER_MAP[PrefKeys.SEND_WIFI_SSID] = { context, _ ->
val wifiManager = context.getWifiManager(OpenHabApplication.DATA_ACCESS_TAG_SEND_DEV_INFO)
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val requiredPermissions = getRequiredPermissionsForTask(PrefKeys.SEND_WIFI_SSID)
+
// TODO: Replace deprecated function
- @Suppress("DEPRECATION") val ssidToSend = wifiManager.connectionInfo.let { info ->
+ @Suppress("DEPRECATION")
+ val ssidToSend = wifiManager.connectionInfo.let { info ->
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
!LocationManagerCompat.isLocationEnabled(locationManager) -> {
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/EventListenerService.kt b/mobile/src/main/java/org/openhab/habdroid/background/EventListenerService.kt
index 6c8c93b30a..b07bce9c0f 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/EventListenerService.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/EventListenerService.kt
@@ -64,12 +64,18 @@ class EventListenerService : Service() {
getString(R.string.send_device_info_foreground_service_running_summary_one, titlesOfItems[0])
}
titlesOfItems.size == 2 -> {
- getString(R.string.send_device_info_foreground_service_running_summary_two,
- titlesOfItems[0], titlesOfItems[1])
+ getString(
+ R.string.send_device_info_foreground_service_running_summary_two,
+ titlesOfItems[0],
+ titlesOfItems[1]
+ )
}
else -> {
- getString(R.string.send_device_info_foreground_service_running_summary_more,
- titlesOfItems[0], titlesOfItems[1])
+ getString(
+ R.string.send_device_info_foreground_service_running_summary_more,
+ titlesOfItems[0],
+ titlesOfItems[1]
+ )
}
}
val title = getString(R.string.send_device_info_foreground_service_title)
@@ -105,6 +111,7 @@ class EventListenerService : Service() {
companion object {
private val TAG = EventListenerService::class.java.simpleName
+
@VisibleForTesting val KNOWN_EVENT_LISTENER_KEYS = listOf(
PrefKeys.SEND_BATTERY_LEVEL,
PrefKeys.SEND_CHARGING_STATE,
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/ItemUpdateWorker.kt b/mobile/src/main/java/org/openhab/habdroid/background/ItemUpdateWorker.kt
index bb188bcd95..67c30f7fd1 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/ItemUpdateWorker.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/ItemUpdateWorker.kt
@@ -292,23 +292,23 @@ class ItemUpdateWorker(context: Context, params: WorkerParameters) : CoroutineWo
value: String,
mappedValue: String
): String = when (value) {
- "ON" -> context.getString(R.string.item_update_success_message_on, label)
- "OFF" -> context.getString(R.string.item_update_success_message_off, label)
- "UP" -> context.getString(R.string.item_update_success_message_up, label)
- "DOWN" -> context.getString(R.string.item_update_success_message_down, label)
- "MOVE" -> context.getString(R.string.item_update_success_message_move, label)
- "STOP" -> context.getString(R.string.item_update_success_message_stop, label)
- "INCREASE" -> context.getString(R.string.item_update_success_message_increase, label)
- "DECREASE" -> context.getString(R.string.item_update_success_message_decrease, label)
- "UNDEF" -> context.getString(R.string.item_update_success_message_undefined, label)
- "" -> context.getString(R.string.item_update_success_message_empty_string, label)
- "PLAY" -> context.getString(R.string.item_update_success_message_play, label)
- "PAUSE" -> context.getString(R.string.item_update_success_message_pause, label)
- "NEXT" -> context.getString(R.string.item_update_success_message_next, label)
- "PREVIOUS" -> context.getString(R.string.item_update_success_message_previous, label)
- "REWIND" -> context.getString(R.string.item_update_success_message_rewind, label)
- "FASTFORWARD" -> context.getString(R.string.item_update_success_message_fastforward, label)
- else -> context.getString(R.string.item_update_success_message_generic, label, mappedValue)
+ "ON" -> context.getString(R.string.item_update_success_message_on, label)
+ "OFF" -> context.getString(R.string.item_update_success_message_off, label)
+ "UP" -> context.getString(R.string.item_update_success_message_up, label)
+ "DOWN" -> context.getString(R.string.item_update_success_message_down, label)
+ "MOVE" -> context.getString(R.string.item_update_success_message_move, label)
+ "STOP" -> context.getString(R.string.item_update_success_message_stop, label)
+ "INCREASE" -> context.getString(R.string.item_update_success_message_increase, label)
+ "DECREASE" -> context.getString(R.string.item_update_success_message_decrease, label)
+ "UNDEF" -> context.getString(R.string.item_update_success_message_undefined, label)
+ "" -> context.getString(R.string.item_update_success_message_empty_string, label)
+ "PLAY" -> context.getString(R.string.item_update_success_message_play, label)
+ "PAUSE" -> context.getString(R.string.item_update_success_message_pause, label)
+ "NEXT" -> context.getString(R.string.item_update_success_message_next, label)
+ "PREVIOUS" -> context.getString(R.string.item_update_success_message_previous, label)
+ "REWIND" -> context.getString(R.string.item_update_success_message_rewind, label)
+ "FASTFORWARD" -> context.getString(R.string.item_update_success_message_fastforward, label)
+ else -> context.getString(R.string.item_update_success_message_generic, label, mappedValue)
}
companion object {
@@ -359,10 +359,7 @@ class ItemUpdateWorker(context: Context, params: WorkerParameters) : CoroutineWo
.build()
}
- fun getShortItemUpdateSuccessMessage(
- context: Context,
- value: String
- ): String = when (value) {
+ fun getShortItemUpdateSuccessMessage(context: Context, value: String): String = when (value) {
"ON" -> context.getString(R.string.item_update_short_success_message_on)
"OFF" -> context.getString(R.string.item_update_short_success_message_off)
"UP" -> context.getString(R.string.item_update_short_success_message_up)
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/ItemsControlsProviderService.kt b/mobile/src/main/java/org/openhab/habdroid/background/ItemsControlsProviderService.kt
index abf05c880b..5dd5759302 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/ItemsControlsProviderService.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/ItemsControlsProviderService.kt
@@ -311,11 +311,12 @@ class ItemsControlsProviderService : ControlsProviderService() {
item.name,
ControlButton(item.state?.asBoolean ?: false, context.getString(R.string.nfc_action_toggle))
)
- item.isOfTypeOrGroupType(Item.Type.Dimmer) || item.isOfTypeOrGroupType(Item.Type.Color) -> ToggleRangeTemplate(
- "${item.name}_toggle",
- ControlButton(item.state?.asBoolean ?: false, context.getString(R.string.nfc_action_toggle)),
- createRangeTemplate(item, "%.0f%%")
- )
+ item.isOfTypeOrGroupType(Item.Type.Dimmer) || item.isOfTypeOrGroupType(Item.Type.Color) ->
+ ToggleRangeTemplate(
+ "${item.name}_toggle",
+ ControlButton(item.state?.asBoolean ?: false, context.getString(R.string.nfc_action_toggle)),
+ createRangeTemplate(item, "%.0f%%")
+ )
item.isOfTypeOrGroupType(Item.Type.Rollershutter) -> createRangeTemplate(item, "%.0f%%")
item.isOfTypeOrGroupType(Item.Type.Number) -> createRangeTemplate(
item,
@@ -333,11 +334,7 @@ class ItemsControlsProviderService : ControlsProviderService() {
val currentValue = item.state?.asNumber?.value ?: 0F
val minimum = min(currentValue, item.minimum ?: 0F)
val maximum = max(currentValue, item.maximum ?: 100F)
- return RangeTemplate(
- item.name, minimum, maximum,
- currentValue, item.step ?: 1F,
- format
- )
+ return RangeTemplate(item.name, minimum, maximum, currentValue, item.step ?: 1F, format)
}
private fun getItemTagLabel(item: Item, type: Item.Tag): String? {
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/NotificationUpdateObserver.kt b/mobile/src/main/java/org/openhab/habdroid/background/NotificationUpdateObserver.kt
index 98d2a70884..3a3d98f47a 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/NotificationUpdateObserver.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/NotificationUpdateObserver.kt
@@ -117,29 +117,40 @@ internal class NotificationUpdateObserver(context: Context) : Observer,
retryInfoList: ArrayList
): Notification {
- val text = context.resources.getQuantityString(R.plurals.item_update_error_title,
- errors.size, errors.size)
+ val text = context.resources.getQuantityString(
+ R.plurals.item_update_error_title,
+ errors.size,
+ errors.size
+ )
val prefs = context.getPrefs()
val nb = createBaseBuilder(context, CHANNEL_ID_BACKGROUND_ERROR)
.setContentTitle(text)
@@ -273,9 +287,11 @@ internal class NotificationUpdateObserver(context: Context) : Observer= Build.VERSION_CODES.Q) {
val workManager = WorkManager.getInstance(applicationContext)
val infoLiveData =
- workManager.getWorkInfosByTagLiveData(BackgroundTasksManager.WORKER_TAG_PREFIX_TILE_ID + ID)
+ workManager.getWorkInfosByTagLiveData(BackgroundTasksManager.WORKER_TAG_PREFIX_TILE_ID + id)
infoLiveData.observe(lifeCycleOwner) {
updateTileSubtitle()
}
@@ -109,13 +110,13 @@ abstract class AbstractTileService : TileService() {
override fun onClick() {
Log.d(TAG, "onClick()")
- val data = getPrefs().getTileData(ID)
+ val data = getPrefs().getTileData(id)
if (data?.item?.isNotEmpty() == true && data.state.isNotEmpty()) {
lifeCycleOwner.startListening()
if (data.requireUnlock && isLocked) {
- unlockAndRun { BackgroundTasksManager.enqueueTileUpdate(this, data, ID) }
+ unlockAndRun { BackgroundTasksManager.enqueueTileUpdate(this, data, id) }
} else {
- BackgroundTasksManager.enqueueTileUpdate(this, data, ID)
+ BackgroundTasksManager.enqueueTileUpdate(this, data, id)
}
} else {
Intent(this, PreferencesActivity::class.java).apply {
@@ -128,11 +129,11 @@ abstract class AbstractTileService : TileService() {
private fun updateTile(tile: Tile) {
Log.d(TAG, "updateTile()")
- val data = getPrefs().getTileData(ID)
+ val data = getPrefs().getTileData(id)
tile.apply {
state = Tile.STATE_INACTIVE
- label = data?.tileLabel ?: getString(R.string.tile_number, ID)
+ label = data?.tileLabel ?: getString(R.string.tile_number, id)
icon = Icon.createWithResource(this@AbstractTileService, getIconRes(applicationContext, data?.icon))
updateTile()
}
@@ -144,7 +145,7 @@ abstract class AbstractTileService : TileService() {
val lastInfo = WorkManager
.getInstance(applicationContext)
- .getWorkInfosByTag(BackgroundTasksManager.WORKER_TAG_PREFIX_TILE_ID + ID)
+ .getWorkInfosByTag(BackgroundTasksManager.WORKER_TAG_PREFIX_TILE_ID + id)
.get()
.lastOrNull()
var lastWorkInfoState = lastInfo?.state
@@ -240,12 +241,12 @@ abstract class AbstractTileService : TileService() {
fun requestTileUpdate(context: Context, id: Int) {
val data = context.getPrefs().getTileData(id)
- val tileService = ComponentName(
- context,
- getClassNameForId(id)
- )
- val tileServiceState = if (data != null) PackageManager.COMPONENT_ENABLED_STATE_ENABLED
- else PackageManager.COMPONENT_ENABLED_STATE_DISABLED
+ val tileService = ComponentName(context, getClassNameForId(id))
+ val tileServiceState = if (data != null) {
+ PackageManager.COMPONENT_ENABLED_STATE_ENABLED
+ } else {
+ PackageManager.COMPONENT_ENABLED_STATE_DISABLED
+ }
context.packageManager.setComponentEnabledSetting(
tileService,
tileServiceState,
@@ -262,6 +263,7 @@ abstract class AbstractTileService : TileService() {
}
@VisibleForTesting fun getClassNameForId(id: Int) = "org.openhab.habdroid.background.tiles.TileService$id"
+
fun getIdFromClassName(className: String) =
className.substringAfter("org.openhab.habdroid.background.tiles.TileService").toInt()
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService1.kt b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService1.kt
index ec515a1701..f64197187d 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService1.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService1.kt
@@ -18,5 +18,5 @@ import androidx.annotation.RequiresApi
@RequiresApi(Build.VERSION_CODES.N)
class TileService1 : AbstractTileService() {
- override val ID = 1
+ override val id = 1
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService10.kt b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService10.kt
index d1d0dcf590..0bce01643b 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService10.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService10.kt
@@ -18,5 +18,5 @@ import androidx.annotation.RequiresApi
@RequiresApi(Build.VERSION_CODES.N)
class TileService10 : AbstractTileService() {
- override val ID = 10
+ override val id = 10
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService11.kt b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService11.kt
index e034b63735..adca508bef 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService11.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService11.kt
@@ -18,5 +18,5 @@ import androidx.annotation.RequiresApi
@RequiresApi(Build.VERSION_CODES.N)
class TileService11 : AbstractTileService() {
- override val ID = 11
+ override val id = 11
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService12.kt b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService12.kt
index e7a3c54e2a..d246147693 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService12.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService12.kt
@@ -18,5 +18,5 @@ import androidx.annotation.RequiresApi
@RequiresApi(Build.VERSION_CODES.N)
class TileService12 : AbstractTileService() {
- override val ID = 12
+ override val id = 12
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService2.kt b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService2.kt
index 5a1355bd50..77bead2640 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService2.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService2.kt
@@ -18,5 +18,5 @@ import androidx.annotation.RequiresApi
@RequiresApi(Build.VERSION_CODES.N)
class TileService2 : AbstractTileService() {
- override val ID = 2
+ override val id = 2
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService3.kt b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService3.kt
index 2a921e916e..614cc81293 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService3.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService3.kt
@@ -18,5 +18,5 @@ import androidx.annotation.RequiresApi
@RequiresApi(Build.VERSION_CODES.N)
class TileService3 : AbstractTileService() {
- override val ID = 3
+ override val id = 3
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService4.kt b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService4.kt
index 97f4488f3e..ee6e02b025 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService4.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService4.kt
@@ -18,5 +18,5 @@ import androidx.annotation.RequiresApi
@RequiresApi(Build.VERSION_CODES.N)
class TileService4 : AbstractTileService() {
- override val ID = 4
+ override val id = 4
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService5.kt b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService5.kt
index 5b0e687d59..5373d3734c 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService5.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService5.kt
@@ -18,5 +18,5 @@ import androidx.annotation.RequiresApi
@RequiresApi(Build.VERSION_CODES.N)
class TileService5 : AbstractTileService() {
- override val ID = 5
+ override val id = 5
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService6.kt b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService6.kt
index e94d25603a..7416957eff 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService6.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService6.kt
@@ -18,5 +18,5 @@ import androidx.annotation.RequiresApi
@RequiresApi(Build.VERSION_CODES.N)
class TileService6 : AbstractTileService() {
- override val ID = 6
+ override val id = 6
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService7.kt b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService7.kt
index 34ae600bc4..952a8323a4 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService7.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService7.kt
@@ -18,5 +18,5 @@ import androidx.annotation.RequiresApi
@RequiresApi(Build.VERSION_CODES.N)
class TileService7 : AbstractTileService() {
- override val ID = 7
+ override val id = 7
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService8.kt b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService8.kt
index 155be25c23..7d03355834 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService8.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService8.kt
@@ -18,5 +18,5 @@ import androidx.annotation.RequiresApi
@RequiresApi(Build.VERSION_CODES.N)
class TileService8 : AbstractTileService() {
- override val ID = 8
+ override val id = 8
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService9.kt b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService9.kt
index d948b4fbfb..bfd0d8e5b6 100644
--- a/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService9.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/background/tiles/TileService9.kt
@@ -18,5 +18,5 @@ import androidx.annotation.RequiresApi
@RequiresApi(Build.VERSION_CODES.N)
class TileService9 : AbstractTileService() {
- override val ID = 9
+ override val id = 9
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/core/NotificationHelper.kt b/mobile/src/main/java/org/openhab/habdroid/core/NotificationHelper.kt
index 5152660316..eebb85e864 100644
--- a/mobile/src/main/java/org/openhab/habdroid/core/NotificationHelper.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/core/NotificationHelper.kt
@@ -53,11 +53,7 @@ class NotificationHelper(private val context: Context) {
) {
createChannelForSeverity(message.severity)
- val n = makeNotification(
- message,
- notificationId,
- deleteIntent
- )
+ val n = makeNotification(message, notificationId, deleteIntent)
notificationManager.notify(notificationId, n)
@@ -127,9 +123,7 @@ class NotificationHelper(private val context: Context) {
val contentIntent = makeNotificationClickIntent(message.id, notificationId)
val channelId = getChannelId(message.severity)
- val publicText = context.resources.getQuantityString(
- R.plurals.summary_notification_text, 1, 1
- )
+ val publicText = context.resources.getQuantityString(R.plurals.summary_notification_text, 1, 1)
val publicVersion = makeNotificationBuilder(channelId, message.createdTimestamp)
.setContentText(publicText)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
@@ -196,7 +190,8 @@ class NotificationHelper(private val context: Context) {
): Notification {
val text = context.resources.getQuantityString(
R.plurals.summary_notification_text,
- subNotificationCount, subNotificationCount
+ subNotificationCount,
+ subNotificationCount
)
val clickIntent = makeNotificationClickIntent(null, SUMMARY_NOTIFICATION_ID)
val publicVersion = makeNotificationBuilder(
@@ -219,10 +214,7 @@ class NotificationHelper(private val context: Context) {
.build()
}
- private fun makeNotificationClickIntent(
- persistedId: String?,
- notificationId: Int
- ): PendingIntent {
+ private fun makeNotificationClickIntent(persistedId: String?, notificationId: Int): PendingIntent {
val contentIntent = Intent(context, MainActivity::class.java).apply {
action = MainActivity.ACTION_NOTIFICATION_SELECTED
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
@@ -237,23 +229,25 @@ class NotificationHelper(private val context: Context) {
)
}
- private fun makeNotificationBuilder(
- channelId: String,
- timestamp: Long
- ) = NotificationCompat.Builder(context, channelId)
- .setSmallIcon(R.drawable.ic_openhab_appicon_white_24dp)
- .setWhen(timestamp)
- .setShowWhen(timestamp != 0L)
- .setColor(ContextCompat.getColor(context, R.color.openhab_orange))
- .setAutoCancel(true)
- .setLights(ContextCompat.getColor(context, R.color.openhab_orange), 3000, 3000)
- .setVibrate(context.getPrefs().getNotificationVibrationPattern(context))
- .setGroup("gcm")
+ private fun makeNotificationBuilder(channelId: String, timestamp: Long) =
+ NotificationCompat.Builder(context, channelId)
+ .setSmallIcon(R.drawable.ic_openhab_appicon_white_24dp)
+ .setWhen(timestamp)
+ .setShowWhen(timestamp != 0L)
+ .setColor(ContextCompat.getColor(context, R.color.openhab_orange))
+ .setAutoCancel(true)
+ .setLights(ContextCompat.getColor(context, R.color.openhab_orange), 3000, 3000)
+ .setVibrate(context.getPrefs().getNotificationVibrationPattern(context))
+ .setGroup("gcm")
companion object {
private val TAG = NotificationHelper::class.java.simpleName
- private fun getChannelId(severity: String?) = if (severity.isNullOrEmpty())
- NotificationUpdateObserver.CHANNEL_ID_MESSAGE_DEFAULT else "severity-$severity"
+
+ private fun getChannelId(severity: String?) = if (severity.isNullOrEmpty()) {
+ NotificationUpdateObserver.CHANNEL_ID_MESSAGE_DEFAULT
+ } else {
+ "severity-$severity"
+ }
@Suppress("MemberVisibilityCanBePrivate") // Used in full flavor
internal const val EXTRA_NOTIFICATION_ID = "notificationId"
diff --git a/mobile/src/main/java/org/openhab/habdroid/core/connection/AbstractConnection.kt b/mobile/src/main/java/org/openhab/habdroid/core/connection/AbstractConnection.kt
index 2a47416537..74c68c487a 100644
--- a/mobile/src/main/java/org/openhab/habdroid/core/connection/AbstractConnection.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/core/connection/AbstractConnection.kt
@@ -28,21 +28,13 @@ abstract class AbstractConnection : Connection {
protected val baseUrl: String
private val socketFactory = object : SocketFactory() {
- override fun createSocket(): Socket {
- return prepareSocket(Socket())
- }
- override fun createSocket(host: String?, port: Int): Socket {
- return prepareSocket(Socket(host, port))
- }
- override fun createSocket(host: String?, port: Int, clientAddress: InetAddress?, clientPort: Int): Socket {
- return prepareSocket(Socket(host, port, clientAddress, clientPort))
- }
- override fun createSocket(host: InetAddress?, port: Int): Socket {
- return prepareSocket(Socket(host, port))
- }
- override fun createSocket(host: InetAddress?, port: Int, clientAddress: InetAddress?, clientPort: Int): Socket {
- return prepareSocket(Socket(host, port, clientAddress, clientPort))
- }
+ override fun createSocket() = prepareSocket(Socket())
+ override fun createSocket(host: String?, port: Int) = prepareSocket(Socket(host, port))
+ override fun createSocket(host: String?, port: Int, clientAddress: InetAddress?, clientPort: Int) =
+ prepareSocket(Socket(host, port, clientAddress, clientPort))
+ override fun createSocket(host: InetAddress?, port: Int) = prepareSocket(Socket(host, port))
+ override fun createSocket(host: InetAddress?, port: Int, clientAddress: InetAddress?, clientPort: Int) =
+ prepareSocket(Socket(host, port, clientAddress, clientPort))
}
internal constructor(
diff --git a/mobile/src/main/java/org/openhab/habdroid/core/connection/Connection.kt b/mobile/src/main/java/org/openhab/habdroid/core/connection/Connection.kt
index 8c267a1139..4c8b953055 100644
--- a/mobile/src/main/java/org/openhab/habdroid/core/connection/Connection.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/core/connection/Connection.kt
@@ -45,6 +45,7 @@ interface Connection {
* connected to.
*/
const val TYPE_LOCAL = 0
+
/**
* Represents a connection to an openHAB instance, which may or may not be available from the
* public internet. This is most likely the instance configured in the "remote" settings of
@@ -52,6 +53,7 @@ interface Connection {
* currently connected to.
*/
const val TYPE_REMOTE = 1
+
/**
* Represents a connection that is guaranteed to provide functionality implemented in the
* openHAB cloud product (like notifications).
diff --git a/mobile/src/main/java/org/openhab/habdroid/core/connection/ConnectionFactory.kt b/mobile/src/main/java/org/openhab/habdroid/core/connection/ConnectionFactory.kt
index e2344d6fd4..b82a5a93f7 100644
--- a/mobile/src/main/java/org/openhab/habdroid/core/connection/ConnectionFactory.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/core/connection/ConnectionFactory.kt
@@ -89,26 +89,33 @@ class ConnectionFactory internal constructor(
val local: Connection?,
val remote: AbstractConnection?
)
+
data class ConnectionResult(
val connection: Connection?,
val failureReason: ConnectionException?
)
+
data class CloudConnectionResult(
val connection: CloudConnection?,
val failureReason: Exception?
)
+
private data class StateHolder(
val primary: ConnectionResult?,
val active: ConnectionResult?,
val primaryCloud: CloudConnectionResult?,
val activeCloud: CloudConnectionResult?
)
+
private val stateChannel = ConflatedBroadcastChannel(StateHolder(null, null, null, null))
interface UpdateListener {
fun onActiveConnectionChanged()
+
fun onPrimaryConnectionChanged()
+
fun onActiveCloudConnectionChanged(connection: CloudConnection?)
+
fun onPrimaryCloudConnectionChanged(connection: CloudConnection?)
}
@@ -163,10 +170,7 @@ class ConnectionFactory internal constructor(
// changed since we went to background
val (_, active, _, _) = stateChannel.value
val local = active?.connection === activeConn?.local ||
- (
- active?.failureReason is NoUrlInformationException &&
- active.failureReason.wouldHaveUsedLocalConnection()
- )
+ (active?.failureReason as? NoUrlInformationException)?.wouldHaveUsedLocalConnection() == true
if (local) {
triggerConnectionUpdateIfNeeded()
}
@@ -186,10 +190,12 @@ class ConnectionFactory internal constructor(
}
if (key in UPDATE_TRIGGERING_KEYS ||
UPDATE_TRIGGERING_PREFIXES.any { prefix -> key == PrefKeys.buildServerKey(serverId, prefix) }
- ) launch {
- // if the active server changed, we need to invalidate the old connection immediately,
- // as we don't want the user to see old server data while we're validating the new one
- updateConnections(key == PrefKeys.ACTIVE_SERVER_ID)
+ ) {
+ launch {
+ // if the active server changed, we need to invalidate the old connection immediately,
+ // as we don't want the user to see old server data while we're validating the new one
+ updateConnections(key == PrefKeys.ACTIVE_SERVER_ID)
+ }
}
}
@@ -247,8 +253,11 @@ class ConnectionFactory internal constructor(
} else {
prefs.getStringOrNull(PrefKeys.buildServerKey(prefs.getActiveServerId(), PrefKeys.SSL_CLIENT_CERT_PREFIX))
}
- val keyManagers = if (clientCertAlias != null)
- arrayOf(ClientKeyManager(context, clientCertAlias)) else null
+ val keyManagers = if (clientCertAlias != null) {
+ arrayOf(ClientKeyManager(context, clientCertAlias))
+ } else {
+ null
+ }
// Updating the SSL socket factory is an expensive call;
// make sure to only do this if really needed.
@@ -285,7 +294,10 @@ class ConnectionFactory internal constructor(
val newState = StateHolder(primary, active, primaryCloud, activeCloud)
stateChannel.trySend(newState)
.onClosed { throw it ?: ClosedSendChannelException("Channel was closed normally") }
- if (callListenersOnChange) launch {
+ if (!callListenersOnChange) {
+ return
+ }
+ launch {
if (newState.active?.failureReason != null ||
prevState.active?.connection !== newState.active?.connection
) {
@@ -397,15 +409,16 @@ class ConnectionFactory internal constructor(
}
private suspend fun checkAvailableConnection(local: Connection?, remote: Connection?): Connection {
- val available = connectionHelper.currentConnections
- .sortedBy { type -> when (type) {
+ val available = connectionHelper.currentConnections.sortedBy { type ->
+ when (type) {
is ConnectionManagerHelper.ConnectionType.Vpn -> 1
is ConnectionManagerHelper.ConnectionType.Ethernet -> 2
is ConnectionManagerHelper.ConnectionType.Wifi -> 3
is ConnectionManagerHelper.ConnectionType.Bluetooth -> 4
is ConnectionManagerHelper.ConnectionType.Mobile -> 5
is ConnectionManagerHelper.ConnectionType.Unknown -> 6
- } }
+ }
+ }
Log.d(TAG, "checkAvailableConnection: found types $available")
if (available.isEmpty()) {
@@ -416,13 +429,12 @@ class ConnectionFactory internal constructor(
var hasWrongWifi = false
if (local != null && local is DefaultConnection) {
- val localCandidates = available
- .filter { type ->
- type is ConnectionManagerHelper.ConnectionType.Wifi ||
- type is ConnectionManagerHelper.ConnectionType.Bluetooth ||
- type is ConnectionManagerHelper.ConnectionType.Ethernet ||
- type is ConnectionManagerHelper.ConnectionType.Vpn
- }
+ val localCandidates = available.filter { type ->
+ type is ConnectionManagerHelper.ConnectionType.Wifi ||
+ type is ConnectionManagerHelper.ConnectionType.Bluetooth ||
+ type is ConnectionManagerHelper.ConnectionType.Ethernet ||
+ type is ConnectionManagerHelper.ConnectionType.Vpn
+ }
for (type in localCandidates) {
if (type is ConnectionManagerHelper.ConnectionType.Wifi && !serverMayUseWifi()) {
Log.d(TAG, "Don't use current Wi-Fi because server is restricted to other Wi-Fis")
@@ -537,7 +549,9 @@ class ConnectionFactory internal constructor(
companion object {
private val TAG = ConnectionFactory::class.java.simpleName
private val UPDATE_TRIGGERING_KEYS = listOf(
- PrefKeys.DEMO_MODE, PrefKeys.ACTIVE_SERVER_ID, PrefKeys.PRIMARY_SERVER_ID
+ PrefKeys.DEMO_MODE,
+ PrefKeys.ACTIVE_SERVER_ID,
+ PrefKeys.PRIMARY_SERVER_ID
)
private val UPDATE_TRIGGERING_PREFIXES = listOf(
PrefKeys.LOCAL_URL_PREFIX,
diff --git a/mobile/src/main/java/org/openhab/habdroid/core/connection/ConnectionManagerHelper.kt b/mobile/src/main/java/org/openhab/habdroid/core/connection/ConnectionManagerHelper.kt
index 8b7ac14740..06349017bd 100644
--- a/mobile/src/main/java/org/openhab/habdroid/core/connection/ConnectionManagerHelper.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/core/connection/ConnectionManagerHelper.kt
@@ -40,6 +40,7 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
typealias ConnectionChangedCallback = () -> Unit
+
interface ConnectionManagerHelper {
val currentConnections: List
var changeCallback: ConnectionChangedCallback?
@@ -48,10 +49,15 @@ interface ConnectionManagerHelper {
sealed class ConnectionType(val network: Network, val caps: NetworkCapabilities) {
class Bluetooth(network: Network, caps: NetworkCapabilities) : ConnectionType(network, caps)
+
class Ethernet(network: Network, caps: NetworkCapabilities) : ConnectionType(network, caps)
+
class Mobile(network: Network, caps: NetworkCapabilities) : ConnectionType(network, caps)
+
class Unknown(network: Network, caps: NetworkCapabilities) : ConnectionType(network, caps)
+
class Vpn(network: Network, caps: NetworkCapabilities) : ConnectionType(network, caps)
+
class Wifi(network: Network, caps: NetworkCapabilities) : ConnectionType(network, caps)
override fun toString(): String {
diff --git a/mobile/src/main/java/org/openhab/habdroid/model/CloudNotification.kt b/mobile/src/main/java/org/openhab/habdroid/model/CloudNotification.kt
index 0d1f78d87d..c71de81caa 100644
--- a/mobile/src/main/java/org/openhab/habdroid/model/CloudNotification.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/model/CloudNotification.kt
@@ -50,5 +50,6 @@ fun JSONObject.toCloudNotification(): CloudNotification {
getString("message"),
created,
optStringOrNull("icon").toOH2IconResource(),
- optStringOrNull("severity"))
+ optStringOrNull("severity")
+ )
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/model/IconResource.kt b/mobile/src/main/java/org/openhab/habdroid/model/IconResource.kt
index 9171d8da0b..309bb98bc9 100644
--- a/mobile/src/main/java/org/openhab/habdroid/model/IconResource.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/model/IconResource.kt
@@ -20,6 +20,7 @@ import android.net.Uri
import android.os.Parcelable
import androidx.annotation.VisibleForTesting
import java.util.Locale
+import kotlin.text.replace
import kotlinx.parcelize.Parcelize
import org.json.JSONException
import org.json.JSONObject
@@ -28,7 +29,6 @@ import org.openhab.habdroid.util.appendQueryParameter
import org.openhab.habdroid.util.getIconFormat
import org.openhab.habdroid.util.getPrefs
import org.openhab.habdroid.util.getStringOrNull
-import kotlin.text.replace
@Parcelize
data class IconResource internal constructor(
@@ -104,10 +104,10 @@ data class IconResource internal constructor(
}
builder.path("icon")
- .appendPath(iconName)
- .appendQueryParameter("format", suffix)
- .appendQueryParameter("anyFormat", true)
- .appendQueryParameter("iconset", iconSet)
+ .appendPath(iconName)
+ .appendQueryParameter("format", suffix)
+ .appendQueryParameter("anyFormat", true)
+ .appendQueryParameter("iconset", iconSet)
if (customState.isNotEmpty() && includeState) {
builder.appendQueryParameter("state", customState)
@@ -173,7 +173,7 @@ internal fun String?.toOH2WidgetIconResource(
// For NULL states, we send 'null' as state when fetching the icon (BasicUI set a predecent for doing so)
item.state == null -> "null"
// Number items need to follow the format "" or " "
- item.isOfTypeOrGroupType(Item.Type.Number) || item.isOfTypeOrGroupType(Item.Type.NumberWithDimension)-> {
+ item.isOfTypeOrGroupType(Item.Type.Number) || item.isOfTypeOrGroupType(Item.Type.NumberWithDimension) -> {
item.state.asNumber?.let { numberState ->
val unitSuffix = numberState.unit?.let { " $it" } ?: ""
"${numberState.formatValue()}$unitSuffix"
diff --git a/mobile/src/main/java/org/openhab/habdroid/model/LabeledValue.kt b/mobile/src/main/java/org/openhab/habdroid/model/LabeledValue.kt
index ccef31e128..134e9d64a0 100644
--- a/mobile/src/main/java/org/openhab/habdroid/model/LabeledValue.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/model/LabeledValue.kt
@@ -14,7 +14,6 @@
package org.openhab.habdroid.model
import android.os.Parcelable
-
import kotlinx.parcelize.Parcelize
import org.json.JSONException
import org.json.JSONObject
diff --git a/mobile/src/main/java/org/openhab/habdroid/model/LinkedPage.kt b/mobile/src/main/java/org/openhab/habdroid/model/LinkedPage.kt
index 19295be2e6..98ddbe914e 100644
--- a/mobile/src/main/java/org/openhab/habdroid/model/LinkedPage.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/model/LinkedPage.kt
@@ -14,7 +14,6 @@
package org.openhab.habdroid.model
import android.os.Parcelable
-
import kotlinx.parcelize.Parcelize
import org.json.JSONObject
import org.openhab.habdroid.util.forEach
@@ -33,14 +32,12 @@ data class LinkedPage(
val link: String
) : Parcelable {
companion object {
- internal fun build(
- id: String,
- title: String?,
- icon: IconResource?,
- link: String
- ): LinkedPage {
- val actualTitle = if (title != null && title.indexOf('[') > 0)
- title.substring(0, title.indexOf('[')) else title
+ internal fun build(id: String, title: String?, icon: IconResource?, link: String): LinkedPage {
+ val actualTitle = if (title != null && title.indexOf('[') > 0) {
+ title.substring(0, title.indexOf('['))
+ } else {
+ title
+ }
return LinkedPage(id, actualTitle.orEmpty(), icon, link)
}
}
@@ -75,5 +72,6 @@ fun JSONObject?.toLinkedPage(): LinkedPage? {
getString("id"),
optStringOrNull("title"),
icon.toOH2IconResource(),
- getString("link"))
+ getString("link")
+ )
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/model/NfcTag.kt b/mobile/src/main/java/org/openhab/habdroid/model/NfcTag.kt
index d661bf924b..52f180d674 100644
--- a/mobile/src/main/java/org/openhab/habdroid/model/NfcTag.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/model/NfcTag.kt
@@ -39,15 +39,17 @@ fun Uri.toTagData(): NfcTag? {
if (isOpaque || scheme != NfcTag.SCHEME) {
return null
}
- val item = if (NfcTag.DEPRECATED_QUERY_PARAMETER_ITEM_NAME in queryParameterNames)
+ val item = if (NfcTag.DEPRECATED_QUERY_PARAMETER_ITEM_NAME in queryParameterNames) {
getQueryParameter(NfcTag.DEPRECATED_QUERY_PARAMETER_ITEM_NAME)
- else
+ } else {
getQueryParameter(NfcTag.QUERY_PARAMETER_ITEM_NAME)
+ }
- val state = if (NfcTag.DEPRECATED_QUERY_PARAMETER_STATE in queryParameterNames)
+ val state = if (NfcTag.DEPRECATED_QUERY_PARAMETER_STATE in queryParameterNames) {
getQueryParameter(NfcTag.DEPRECATED_QUERY_PARAMETER_STATE)
- else
+ } else {
getQueryParameter(NfcTag.QUERY_PARAMETER_STATE)
+ }
val label = getQueryParameter(NfcTag.QUERY_PARAMETER_ITEM_LABEL)
val mappedState = getQueryParameter(NfcTag.QUERY_PARAMETER_MAPPED_STATE)
diff --git a/mobile/src/main/java/org/openhab/habdroid/model/ParsedState.kt b/mobile/src/main/java/org/openhab/habdroid/model/ParsedState.kt
index f71a2dfdef..288836338e 100644
--- a/mobile/src/main/java/org/openhab/habdroid/model/ParsedState.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/model/ParsedState.kt
@@ -145,10 +145,10 @@ data class ParsedState internal constructor(
}
val stateAsFloat = state.toFloatOrNull() ?: return null
return when (stateAsFloat) {
- in 1f .. 100f, 0f -> {
+ in 1f..100f, 0f -> {
stateAsFloat.toInt()
}
- in 0f .. 1f -> {
+ in 0f..1f -> {
1
}
else -> null
@@ -216,7 +216,8 @@ fun String?.toParsedState(formatPattern: String? = null): ParsedState? {
if (this == null) {
return null
}
- return ParsedState(this,
+ return ParsedState(
+ this,
ParsedState.parseAsBoolean(this),
ParsedState.parseAsNumber(this, formatPattern),
ParsedState.parseAsHsv(this),
diff --git a/mobile/src/main/java/org/openhab/habdroid/model/ServerConfiguration.kt b/mobile/src/main/java/org/openhab/habdroid/model/ServerConfiguration.kt
index 3f79b1ffc7..4470c4d233 100644
--- a/mobile/src/main/java/org/openhab/habdroid/model/ServerConfiguration.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/model/ServerConfiguration.kt
@@ -136,7 +136,7 @@ data class ServerConfiguration(
return ServerPath(
path.url,
if (path.userName.isNullOrEmpty()) "" else "",
- if (path.password.isNullOrEmpty()) "" else "",
+ if (path.password.isNullOrEmpty()) "" else ""
)
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/model/ServerProperties.kt b/mobile/src/main/java/org/openhab/habdroid/model/ServerProperties.kt
index cbe1080d42..74a8b34c34 100644
--- a/mobile/src/main/java/org/openhab/habdroid/model/ServerProperties.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/model/ServerProperties.kt
@@ -61,11 +61,15 @@ data class ServerProperties(val flags: Int, val sitemaps: List) : Parce
const val SERVER_FLAG_TRANSPARENT_CHARTS = 1 shl 8
private sealed interface FlagsResult
+
private class FlagsSuccess(val flags: Int) : FlagsResult
+
private class FlagsFailure(val request: Request, val httpStatusCode: Int, val error: Throwable) : FlagsResult
sealed interface PropsResult
+
class PropsSuccess(val props: ServerProperties) : PropsResult
+
class PropsFailure(val request: Request, val httpStatusCode: Int, val error: Throwable) : PropsResult
suspend fun updateSitemaps(props: ServerProperties, connection: Connection): PropsResult {
diff --git a/mobile/src/main/java/org/openhab/habdroid/model/Sitemap.kt b/mobile/src/main/java/org/openhab/habdroid/model/Sitemap.kt
index 34f2b0aca4..46e31d9e0f 100644
--- a/mobile/src/main/java/org/openhab/habdroid/model/Sitemap.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/model/Sitemap.kt
@@ -15,7 +15,6 @@ package org.openhab.habdroid.model
import android.os.Parcelable
import android.util.Log
-
import kotlinx.parcelize.Parcelize
import org.json.JSONArray
import org.json.JSONException
@@ -44,11 +43,12 @@ fun Node.toSitemap(): Sitemap? {
"name" -> name = node.textContent
"label" -> label = node.textContent
"icon" -> icon = node.textContent
- "homepage" -> node.childNodes.forEach { pageNode ->
- if (pageNode.nodeName == "link") {
- homepageLink = pageNode.textContent
+ "homepage" ->
+ node.childNodes.forEach { pageNode ->
+ if (pageNode.nodeName == "link") {
+ homepageLink = pageNode.textContent
+ }
}
- }
}
}
@@ -88,11 +88,13 @@ fun JSONArray.toSitemapList(): List {
fun List.sortedWithDefaultName(defaultSitemapName: String): List {
// Sort by site name label, the default sitemap should be the first one
- return sortedWith(Comparator { lhs, rhs ->
- when (defaultSitemapName) {
- lhs.name -> -1
- rhs.name -> 1
- else -> lhs.label.compareTo(rhs.label, true)
+ return sortedWith(
+ Comparator { lhs, rhs ->
+ when (defaultSitemapName) {
+ lhs.name -> -1
+ rhs.name -> 1
+ else -> lhs.label.compareTo(rhs.label, true)
+ }
}
- })
+ )
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/model/Widget.kt b/mobile/src/main/java/org/openhab/habdroid/model/Widget.kt
index f61338ddb9..4293e153de 100644
--- a/mobile/src/main/java/org/openhab/habdroid/model/Widget.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/model/Widget.kt
@@ -155,7 +155,10 @@ data class Widget(
val chartUrl = Uri.Builder()
.path("chart")
- .appendQueryParameter(if (item.type === Item.Type.Group && !forceAsItem) "groups" else "items", item.name)
+ .appendQueryParameter(
+ if (item.type === Item.Type.Group && !forceAsItem) "groups" else "items",
+ item.name
+ )
.appendQueryParameter("dpi", actualDensity.toInt() / resDivider)
.appendQueryParameter("period", forcedPeriod)
@@ -216,6 +219,7 @@ data class Widget(
}
internal fun sanitizeRefreshRate(refresh: Int) = if (refresh in 1..99) 100 else refresh
+
internal fun sanitizePeriod(period: String?) = if (period.isNullOrEmpty()) "D" else period
internal fun determineWidgetState(state: String?, item: Item?): ParsedState? = when {
@@ -339,11 +343,13 @@ fun Node.collectWidgets(parent: Widget?): List {
period = Widget.sanitizePeriod(period),
service = service,
legend = null,
- forceAsItem = false, // forceAsItem was added in openHAB 3, so no support for openHAB 1 required.
+ // forceAsItem was added in openHAB 3, so no support for openHAB 1 required.
+ forceAsItem = false,
yAxisDecimalPattern = null,
switchSupport = switchSupport,
height = height,
- rawInputHint = null, // inputHint was added in openHAB 4, so no support for openHAB 1 required.
+ // inputHint was added in openHAB 4, so no support for openHAB 1 required.
+ rawInputHint = null,
visibility = true
)
val childWidgets = childWidgetNodes.map { node -> node.collectWidgets(widget) }.flatten()
diff --git a/mobile/src/main/java/org/openhab/habdroid/model/WidgetDataSource.kt b/mobile/src/main/java/org/openhab/habdroid/model/WidgetDataSource.kt
index cf689636bd..a85498ceb5 100644
--- a/mobile/src/main/java/org/openhab/habdroid/model/WidgetDataSource.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/model/WidgetDataSource.kt
@@ -31,10 +31,10 @@ class WidgetDataSource() {
private set
var id: String? = null
private set
- var icon: String? = null
- private set
var link: String? = null
private set
+ var icon: String? = null
+ private set
val widgets: List get() {
val firstLevelWidgetIds = allWidgets
@@ -66,8 +66,8 @@ class WidgetDataSource() {
return
}
try {
- jsonObject.getJSONArray("widgets").forEach {
- obj -> allWidgets.addAll(obj.collectWidgets(null))
+ jsonObject.getJSONArray("widgets").forEach { obj ->
+ allWidgets.addAll(obj.collectWidgets(null))
}
id = jsonObject.optStringOrNull("id")
title = jsonObject.optString("title", id.orEmpty())
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/AboutActivity.kt b/mobile/src/main/java/org/openhab/habdroid/ui/AboutActivity.kt
index 461e676d98..826b0b1d00 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/AboutActivity.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/AboutActivity.kt
@@ -91,91 +91,122 @@ class AboutActivity : AbstractBaseActivity(), FragmentManager.OnBackStackChanged
val year = SimpleDateFormat("yyyy", Locale.US).format(Calendar.getInstance().time)
val appCard = MaterialAboutCard.Builder()
- appCard.addItem(MaterialAboutTitleItem.Builder()
- .text(R.string.app_name)
- .desc(context.getString(R.string.about_copyright, year))
- .icon(R.mipmap.icon)
- .build())
- if (Util.isFlavorStable) {
- appCard.addItem(MaterialAboutActionItem.Builder()
- .text(R.string.about_rate_this_app)
- .icon(R.drawable.ic_star_border_grey_24dp)
- .setOnClickAction { context.openInAppStore(context.packageName) }
+ appCard.addItem(
+ MaterialAboutTitleItem.Builder()
+ .text(R.string.app_name)
+ .desc(context.getString(R.string.about_copyright, year))
+ .icon(R.mipmap.icon)
.build()
+ )
+ if (Util.isFlavorStable) {
+ appCard.addItem(
+ MaterialAboutActionItem.Builder()
+ .text(R.string.about_rate_this_app)
+ .icon(R.drawable.ic_star_border_grey_24dp)
+ .setOnClickAction { context.openInAppStore(context.packageName) }
+ .build()
)
}
- appCard.addItem(MaterialAboutActionItem.Builder()
- .text(R.string.version)
- .subText(BuildConfig.VERSION_NAME)
- .icon(R.drawable.ic_update_grey_24dp)
- .build())
- appCard.addItem(MaterialAboutActionItem.Builder()
- .text(R.string.about_changelog)
- .icon(R.drawable.ic_track_changes_grey_24dp)
- .setOnClickAction(makeClickRedirect(context, "$URL_TO_GITHUB/releases"))
- .build())
- appCard.addItem(MaterialAboutActionItem.Builder()
- .text(R.string.about_source_code)
- .icon(R.drawable.ic_github_grey_24dp)
- .setOnClickAction(makeClickRedirect(context, URL_TO_GITHUB))
- .build())
- appCard.addItem(MaterialAboutActionItem.Builder()
- .text(R.string.about_issues)
- .icon(R.drawable.ic_bug_outline_grey_24dp)
- .setOnClickAction(makeClickRedirect(context, "$URL_TO_GITHUB/issues"))
- .build())
- appCard.addItem(MaterialAboutActionItem.Builder()
- .text(R.string.about_license_title)
- .subText(R.string.about_license)
- .icon(R.drawable.ic_account_balance_grey_24dp)
- .setOnClickAction(makeClickRedirect(context, "$URL_TO_GITHUB/blob/main/LICENSE"))
- .build())
- appCard.addItem(MaterialAboutActionItem.Builder()
- .text(R.string.title_activity_libraries)
- .icon(R.drawable.ic_code_braces_grey_24dp)
- .setOnClickAction {
- val f = LibsBuilder()
- .withLicenseShown(true)
- .withAboutIconShown(false)
- .withAboutVersionShown(false)
- .withAboutVersionShownCode(false)
- .supportFragment()
- parentFragmentManager.commit {
- setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left,
- R.anim.slide_in_left, R.anim.slide_out_right)
- replace(R.id.activity_content, f)
- addToBackStack(null)
+ appCard.addItem(
+ MaterialAboutActionItem.Builder()
+ .text(R.string.version)
+ .subText(BuildConfig.VERSION_NAME)
+ .icon(R.drawable.ic_update_grey_24dp)
+ .build()
+ )
+ appCard.addItem(
+ MaterialAboutActionItem.Builder()
+ .text(R.string.about_changelog)
+ .icon(R.drawable.ic_track_changes_grey_24dp)
+ .setOnClickAction(makeClickRedirect(context, "$URL_TO_GITHUB/releases"))
+ .build()
+ )
+ appCard.addItem(
+ MaterialAboutActionItem.Builder()
+ .text(R.string.about_source_code)
+ .icon(R.drawable.ic_github_grey_24dp)
+ .setOnClickAction(makeClickRedirect(context, URL_TO_GITHUB))
+ .build()
+ )
+ appCard.addItem(
+ MaterialAboutActionItem.Builder()
+ .text(R.string.about_issues)
+ .icon(R.drawable.ic_bug_outline_grey_24dp)
+ .setOnClickAction(makeClickRedirect(context, "$URL_TO_GITHUB/issues"))
+ .build()
+ )
+ appCard.addItem(
+ MaterialAboutActionItem.Builder()
+ .text(R.string.about_license_title)
+ .subText(R.string.about_license)
+ .icon(R.drawable.ic_account_balance_grey_24dp)
+ .setOnClickAction(makeClickRedirect(context, "$URL_TO_GITHUB/blob/main/LICENSE"))
+ .build()
+ )
+ appCard.addItem(
+ MaterialAboutActionItem.Builder()
+ .text(R.string.title_activity_libraries)
+ .icon(R.drawable.ic_code_braces_grey_24dp)
+ .setOnClickAction {
+ val f = LibsBuilder()
+ .withLicenseShown(true)
+ .withAboutIconShown(false)
+ .withAboutVersionShown(false)
+ .withAboutVersionShownCode(false)
+ .supportFragment()
+ parentFragmentManager.commit {
+ setCustomAnimations(
+ R.anim.slide_in_right,
+ R.anim.slide_out_left,
+ R.anim.slide_in_left,
+ R.anim.slide_out_right
+ )
+ replace(R.id.activity_content, f)
+ addToBackStack(null)
+ }
}
- }
- .build())
- appCard.addItem(MaterialAboutActionItem.Builder()
- .text(R.string.about_privacy_policy)
- .icon(R.drawable.ic_security_grey_24dp)
- .setOnClickAction(makeClickRedirect(context, "https://www.openhabfoundation.org/privacy.html#android-app"))
- .build())
+ .build()
+ )
+ appCard.addItem(
+ MaterialAboutActionItem.Builder()
+ .text(R.string.about_privacy_policy)
+ .icon(R.drawable.ic_security_grey_24dp)
+ .setOnClickAction(
+ makeClickRedirect(context, "https://www.openhabfoundation.org/privacy.html#android-app")
+ )
+ .build()
+ )
val ohCommunityCard = MaterialAboutCard.Builder()
.title(R.string.about_community)
- ohCommunityCard.addItem(MaterialAboutActionItem.Builder()
- .text(R.string.about_docs)
- .icon(R.drawable.ic_file_document_box_multiple_outline_grey_24dp)
- .setOnClickAction(makeClickRedirect(context, "https://www.openhab.org/docs/apps/android.html"))
- .build())
- ohCommunityCard.addItem(MaterialAboutActionItem.Builder()
- .text(R.string.about_community_forum)
- .icon(R.drawable.ic_forum_outline_grey_24dp)
- .setOnClickAction(makeClickRedirect(context, "https://community.openhab.org/"))
- .build())
- ohCommunityCard.addItem(MaterialAboutActionItem.Builder()
- .text(R.string.about_translation)
- .icon(R.drawable.ic_translate_grey_24dp)
- .setOnClickAction(makeClickRedirect(context, "https://crowdin.com/profile/openhab-bot"))
- .build())
- ohCommunityCard.addItem(MaterialAboutActionItem.Builder()
- .text(R.string.about_foundation)
- .icon(R.drawable.ic_people_outline_grey_24dp)
- .setOnClickAction(makeClickRedirect(context, "https://www.openhabfoundation.org/"))
- .build())
+ ohCommunityCard.addItem(
+ MaterialAboutActionItem.Builder()
+ .text(R.string.about_docs)
+ .icon(R.drawable.ic_file_document_box_multiple_outline_grey_24dp)
+ .setOnClickAction(makeClickRedirect(context, "https://www.openhab.org/docs/apps/android.html"))
+ .build()
+ )
+ ohCommunityCard.addItem(
+ MaterialAboutActionItem.Builder()
+ .text(R.string.about_community_forum)
+ .icon(R.drawable.ic_forum_outline_grey_24dp)
+ .setOnClickAction(makeClickRedirect(context, "https://community.openhab.org/"))
+ .build()
+ )
+ ohCommunityCard.addItem(
+ MaterialAboutActionItem.Builder()
+ .text(R.string.about_translation)
+ .icon(R.drawable.ic_translate_grey_24dp)
+ .setOnClickAction(makeClickRedirect(context, "https://crowdin.com/profile/openhab-bot"))
+ .build()
+ )
+ ohCommunityCard.addItem(
+ MaterialAboutActionItem.Builder()
+ .text(R.string.about_foundation)
+ .icon(R.drawable.ic_people_outline_grey_24dp)
+ .setOnClickAction(makeClickRedirect(context, "https://www.openhabfoundation.org/"))
+ .build()
+ )
return MaterialAboutList.Builder()
.addCard(appCard.build())
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/AbstractBaseActivity.kt b/mobile/src/main/java/org/openhab/habdroid/ui/AbstractBaseActivity.kt
index a0f8fa0031..092525b0e7 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/AbstractBaseActivity.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/AbstractBaseActivity.kt
@@ -172,9 +172,10 @@ abstract class AbstractBaseActivity : AppCompatActivity(), CoroutineScope {
val insets = if (Build.VERSION.SDK_INT < 30 && isFullscreenEnabled) {
Insets.NONE
} else {
- val insetsType = WindowInsetsCompat.Type.statusBars() or
- WindowInsetsCompat.Type.navigationBars() or
- WindowInsetsCompat.Type.displayCutout()
+ val insetsType =
+ WindowInsetsCompat.Type.statusBars() or
+ WindowInsetsCompat.Type.navigationBars() or
+ WindowInsetsCompat.Type.displayCutout()
lastInsets?.getInsets(insetsType) ?: Insets.NONE
}
// AppBarLayout uses its own insets calculations, which doesn't factor in status bar visibility on API < 30
@@ -189,15 +190,15 @@ abstract class AbstractBaseActivity : AppCompatActivity(), CoroutineScope {
private fun setNavigationBarColor() {
val currentNightMode = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
+
@ColorInt val black = ContextCompat.getColor(this, R.color.black)
- @ColorInt val windowColor = if (currentNightMode == Configuration.UI_MODE_NIGHT_YES) {
- resolveThemedColor(android.R.attr.windowBackground, black)
- } else {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+
+ @ColorInt val windowColor = when {
+ currentNightMode == Configuration.UI_MODE_NIGHT_YES ->
resolveThemedColor(android.R.attr.windowBackground, black)
- } else {
- black
- }
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ->
+ resolveThemedColor(android.R.attr.windowBackground, black)
+ else -> black
}
window.navigationBarColor = windowColor
@@ -242,20 +243,22 @@ abstract class AbstractBaseActivity : AppCompatActivity(), CoroutineScope {
snackbar.setAction(actionResId) { onClickListener() }
}
snackbar.view.tag = tag
- snackbar.addCallback(object : BaseTransientBottomBar.BaseCallback() {
- override fun onShown(transientBottomBar: Snackbar?) {
- super.onShown(transientBottomBar)
- Log.d(TAG, "Show snackbar with tag $tag")
- }
+ snackbar.addCallback(
+ object : BaseTransientBottomBar.BaseCallback() {
+ override fun onShown(transientBottomBar: Snackbar?) {
+ super.onShown(transientBottomBar)
+ Log.d(TAG, "Show snackbar with tag $tag")
+ }
- override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
- super.onDismissed(transientBottomBar, event)
- if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {
- onDismissListener?.invoke()
+ override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
+ super.onDismissed(transientBottomBar, event)
+ if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {
+ onDismissListener?.invoke()
+ }
+ showNextSnackbar()
}
- showNextSnackbar()
}
- })
+ )
hideSnackbar(tag)
Log.d(TAG, "Queue snackbar with tag $tag")
snackbarQueue.add(snackbar)
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/AbstractItemPickerActivity.kt b/mobile/src/main/java/org/openhab/habdroid/ui/AbstractItemPickerActivity.kt
index c2ab6f730f..f58def8da8 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/AbstractItemPickerActivity.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/AbstractItemPickerActivity.kt
@@ -40,7 +40,6 @@ import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
-import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.Job
@@ -58,8 +57,11 @@ import org.openhab.habdroid.util.getPrefs
import org.openhab.habdroid.util.parcelable
import org.openhab.habdroid.util.parcelableArrayList
-abstract class AbstractItemPickerActivity : AbstractBaseActivity(), SwipeRefreshLayout.OnRefreshListener,
- ItemPickerAdapter.ItemClickListener, SearchView.OnQueryTextListener {
+abstract class AbstractItemPickerActivity :
+ AbstractBaseActivity(),
+ SwipeRefreshLayout.OnRefreshListener,
+ ItemPickerAdapter.ItemClickListener,
+ SearchView.OnQueryTextListener {
override val forceNonFullscreen = true
private var requestJob: Job? = null
@@ -285,11 +287,13 @@ abstract class AbstractItemPickerActivity : AbstractBaseActivity(), SwipeRefresh
toolbarExtension?.isGone = showEmpty
emptyView.isVisible = showEmpty
swipeLayout.isRefreshing = loading
- emptyMessage.setText(when {
- loadError -> R.string.item_picker_list_error
- showHint -> hintMessageId
- else -> R.string.item_picker_list_empty
- })
+ emptyMessage.setText(
+ when {
+ loadError -> R.string.item_picker_list_error
+ showHint -> hintMessageId
+ else -> R.string.item_picker_list_empty
+ }
+ )
watermark.setImageResource(if (showHint) hintIconId else R.drawable.ic_connection_error)
retryButton.setText(if (showHint) hintButtonMessageId else R.string.try_again_button)
retryButton.isVisible = loadError || showHint
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/BasicItemPickerActivity.kt b/mobile/src/main/java/org/openhab/habdroid/ui/BasicItemPickerActivity.kt
index 53eb131bec..e1a95e6386 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/BasicItemPickerActivity.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/BasicItemPickerActivity.kt
@@ -15,7 +15,6 @@ package org.openhab.habdroid.ui
import android.content.Intent
import android.os.Bundle
-import androidx.annotation.LayoutRes
import org.openhab.habdroid.R
import org.openhab.habdroid.model.Item
import org.openhab.habdroid.util.SuggestedCommandsFactory
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/CloudNotificationAdapter.kt b/mobile/src/main/java/org/openhab/habdroid/ui/CloudNotificationAdapter.kt
index 394e48eb28..5226216313 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/CloudNotificationAdapter.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/CloudNotificationAdapter.kt
@@ -102,9 +102,13 @@ class CloudNotificationAdapter(context: Context, private val loadMoreListener: (
private val severityView: TextView = itemView.findViewById(R.id.notificationSeverity)
fun bind(notification: CloudNotification) {
- createdView.text = DateUtils.getRelativeDateTimeString(itemView.context,
+ createdView.text = DateUtils.getRelativeDateTimeString(
+ itemView.context,
notification.createdTimestamp,
- DateUtils.MINUTE_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0)
+ DateUtils.MINUTE_IN_MILLIS,
+ DateUtils.WEEK_IN_MILLIS,
+ 0
+ )
messageView.text = notification.message
val conn = ConnectionFactory.activeCloudConnection?.connection
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/CloudNotificationListFragment.kt b/mobile/src/main/java/org/openhab/habdroid/ui/CloudNotificationListFragment.kt
index d92c33b9e4..91d2c1399a 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/CloudNotificationListFragment.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/CloudNotificationListFragment.kt
@@ -174,9 +174,11 @@ class CloudNotificationListFragment : Fragment(), View.OnClickListener, SwipeRef
emptyView.isVisible = showEmpty
swipeLayout.isRefreshing = loading
emptyMessage.setText(
- if (loadError) R.string.notification_list_error else R.string.notification_list_empty)
+ if (loadError) R.string.notification_list_error else R.string.notification_list_empty
+ )
emptyWatermark.setImageResource(
- if (loadError) R.drawable.ic_connection_error else R.drawable.ic_no_notifications)
+ if (loadError) R.drawable.ic_connection_error else R.drawable.ic_no_notifications
+ )
retryButton.isVisible = loadError
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/ConnectionWebViewClient.kt b/mobile/src/main/java/org/openhab/habdroid/ui/ConnectionWebViewClient.kt
index 6bbeaaee4c..7296e839c8 100755
--- a/mobile/src/main/java/org/openhab/habdroid/ui/ConnectionWebViewClient.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/ConnectionWebViewClient.kt
@@ -46,7 +46,6 @@ import org.openhab.habdroid.util.openInBrowser
open class ConnectionWebViewClient(
private val connection: Connection
) : WebViewClient() {
-
override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
handler.proceed(connection.username, connection.password)
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/ImageWidgetActivity.kt b/mobile/src/main/java/org/openhab/habdroid/ui/ImageWidgetActivity.kt
index 3dcbf30bb1..4000588fd3 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/ImageWidgetActivity.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/ImageWidgetActivity.kt
@@ -123,7 +123,6 @@ class ImageWidgetActivity : AbstractBaseActivity() {
Log.d(TAG, "Failed to load image", e)
return finish()
}
-
} else {
val link = intent.getStringExtra(WIDGET_LINK)!!
val widgetState = JSONObject(
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/IntroActivity.kt b/mobile/src/main/java/org/openhab/habdroid/ui/IntroActivity.kt
index 532c2885ab..90e4314b8a 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/IntroActivity.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/IntroActivity.kt
@@ -72,13 +72,11 @@ class IntroActivity : AppIntro(), CoroutineScope {
R.string.tiles_for_quick_settings,
R.string.intro_quick_tile_description,
R.drawable.ic_twotone_library_books_themed_340dp
-
)
addSlide(
R.string.intro_send_device_info,
R.string.intro_send_device_info_description,
R.drawable.ic_twotone_access_alarm_themed_340dp
-
)
if (getPrefs().getConfiguredServerIds().isEmpty()) {
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/ItemPickerAdapter.kt b/mobile/src/main/java/org/openhab/habdroid/ui/ItemPickerAdapter.kt
index d8d6b72ac6..6377004a85 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/ItemPickerAdapter.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/ItemPickerAdapter.kt
@@ -29,7 +29,6 @@ import org.openhab.habdroid.util.determineDataUsagePolicy
class ItemPickerAdapter(context: Context, private val itemClickListener: ItemClickListener?) :
RecyclerView.Adapter(), View.OnClickListener {
-
private val filteredItems = ArrayList- ()
private val allItems = ArrayList
- ()
private val inflater = LayoutInflater.from(context)
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/LogActivity.kt b/mobile/src/main/java/org/openhab/habdroid/ui/LogActivity.kt
index 0cb5eb2f84..19a9f3d838 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/LogActivity.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/LogActivity.kt
@@ -238,10 +238,10 @@ class LogActivity : AbstractBaseActivity(), SwipeRefreshLayout.OnRefreshListener
"Product: ${Build.PRODUCT}\n" +
"OS: ${Build.VERSION.RELEASE}\n" +
"Display: ${displayMetrics.widthPixels}x${displayMetrics.heightPixels}, " +
- "${displayMetrics.density} density\n" +
+ "${displayMetrics.density} density\n" +
"Data usage policy: ${determineDataUsagePolicy()}, " +
- "data saver: ${(applicationContext as OpenHabApplication).systemDataSaverStatus}, " +
- "battery saver: ${(applicationContext as OpenHabApplication).batterySaverActive}\n"
+ "data saver: ${(applicationContext as OpenHabApplication).systemDataSaverStatus}, " +
+ "battery saver: ${(applicationContext as OpenHabApplication).batterySaverActive}\n"
}
private fun redactHost(text: String, url: String?, replacement: String): String {
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/MainActivity.kt b/mobile/src/main/java/org/openhab/habdroid/ui/MainActivity.kt
index 17d6503d2f..9b02fd2ba9 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/MainActivity.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/MainActivity.kt
@@ -461,11 +461,10 @@ class MainActivity : AbstractBaseActivity(), ConnectionFactory.UpdateListener {
drawerLayout.isDrawerOpen(findViewById(R.id.left_drawer)) -> drawerLayout.closeDrawers()
controller.canGoBack() -> controller.goBack()
isFullscreenEnabled -> when {
- lastSnackbar?.isShown != true ->
- showSnackbar(
- SNACKBAR_TAG_PRESS_AGAIN_EXIT,
- R.string.press_back_to_exit
- )
+ lastSnackbar?.isShown != true -> showSnackbar(
+ SNACKBAR_TAG_PRESS_AGAIN_EXIT,
+ R.string.press_back_to_exit
+ )
lastSnackbar?.view?.tag?.toString() == SNACKBAR_TAG_PRESS_AGAIN_EXIT -> {
isEnabled = false
onBackPressedDispatcher.onBackPressed()
@@ -532,9 +531,11 @@ class MainActivity : AbstractBaseActivity(), ConnectionFactory.UpdateListener {
handleServiceResolveResult(resolver.resolve())
serviceResolveJob = null
}
- controller.updateConnection(null,
+ controller.updateConnection(
+ null,
getString(R.string.resolving_openhab),
- R.drawable.ic_home_search_outline_grey_340dp)
+ R.drawable.ic_home_search_outline_grey_340dp
+ )
}
} else {
val officialServer = !failureReason.wouldHaveUsedLocalConnection() &&
@@ -618,8 +619,7 @@ class MainActivity : AbstractBaseActivity(), ConnectionFactory.UpdateListener {
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
}
}
- Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ->
- arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION)
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION)
else -> null
}
@@ -633,7 +633,7 @@ class MainActivity : AbstractBaseActivity(), ConnectionFactory.UpdateListener {
Log.d(TAG, "Cannot auto select server: Location off")
showSnackbar(
SNACKBAR_TAG_SWITCHED_SERVER,
- R.string.settings_multi_server_wifi_ssid_location_off,
+ R.string.settings_multi_server_wifi_ssid_location_off
)
return -1
}
@@ -731,8 +731,11 @@ class MainActivity : AbstractBaseActivity(), ConnectionFactory.UpdateListener {
val wifiManager = getWifiManager(OpenHabApplication.DATA_ACCESS_TAG_SUGGEST_TURN_ON_WIFI)
@Suppress("DEPRECATION")
wifiManager.isWifiEnabled = true
- controller.updateConnection(null, getString(R.string.waiting_for_wifi),
- R.drawable.ic_wifi_strength_outline_grey_24dp)
+ controller.updateConnection(
+ null,
+ getString(R.string.waiting_for_wifi),
+ R.drawable.ic_wifi_strength_outline_grey_24dp
+ )
}
}
@@ -872,36 +875,43 @@ class MainActivity : AbstractBaseActivity(), ConnectionFactory.UpdateListener {
private fun setupDrawer() {
drawerLayout = findViewById(R.id.drawer_container)
layoutForSnackbar = drawerLayout
- drawerToggle = ActionBarDrawerToggle(this, drawerLayout,
- R.string.drawer_open, R.string.drawer_close)
+ drawerToggle = ActionBarDrawerToggle(
+ this,
+ drawerLayout,
+ R.string.drawer_open,
+ R.string.drawer_close
+ )
drawerLayout.addDrawerListener(drawerToggle)
- drawerLayout.addDrawerListener(object : DrawerLayout.SimpleDrawerListener() {
- override fun onDrawerOpened(drawerView: View) {
- val loadedProperties = serverProperties ?: return
- val connection = connection ?: return
- if (propsRequestJob?.isActive == true) {
- return
- }
- propsRequestJob = launch {
- val result = withContext(Dispatchers.IO) {
- ServerProperties.updateSitemaps(loadedProperties, connection)
+ drawerLayout.addDrawerListener(
+ object : DrawerLayout.SimpleDrawerListener() {
+ override fun onDrawerOpened(drawerView: View) {
+ val loadedProperties = serverProperties ?: return
+ val connection = connection ?: return
+ if (propsRequestJob?.isActive == true) {
+ return
}
- when (result) {
- is ServerProperties.Companion.PropsSuccess -> {
- serverProperties = result.props
- updateSitemapDrawerEntries()
+ propsRequestJob = launch {
+ val result = withContext(Dispatchers.IO) {
+ ServerProperties.updateSitemaps(loadedProperties, connection)
}
- is ServerProperties.Companion.PropsFailure -> {
- handlePropertyFetchFailure(result)
+ when (result) {
+ is ServerProperties.Companion.PropsSuccess -> {
+ serverProperties = result.props
+ updateSitemapDrawerEntries()
+ }
+ is ServerProperties.Companion.PropsFailure -> {
+ handlePropertyFetchFailure(result)
+ }
}
}
}
+
+ override fun onDrawerClosed(drawerView: View) {
+ super.onDrawerClosed(drawerView)
+ updateDrawerMode(false)
+ }
}
- override fun onDrawerClosed(drawerView: View) {
- super.onDrawerClosed(drawerView)
- updateDrawerMode(false)
- }
- })
+ )
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START)
// Ensure drawer layout uses the same background as the app bar layout,
// even if the toolbar is currently hidden
@@ -1127,9 +1137,8 @@ class MainActivity : AbstractBaseActivity(), ConnectionFactory.UpdateListener {
launch {
val context = this@MainActivity
try {
- item.icon = conn.httpClient.get(
- sitemap.icon.toUrl(context, context.determineDataUsagePolicy(conn).loadIconsWithState)
- )
+ item.icon = conn.httpClient
+ .get(sitemap.icon.toUrl(context, context.determineDataUsagePolicy(conn).loadIconsWithState))
.asBitmap(
defaultIcon!!.intrinsicWidth,
getIconFallbackColor(IconBackground.APP_THEME),
@@ -1379,8 +1388,10 @@ class MainActivity : AbstractBaseActivity(), ConnectionFactory.UpdateListener {
val authHeader = result.request.header("Authorization")
if (authHeader?.startsWith("Basic") == true) {
val base64Credentials = authHeader.substring("Basic".length).trim()
- val credentials = String(Base64.decode(base64Credentials, Base64.DEFAULT),
- Charset.forName("UTF-8"))
+ val credentials = String(
+ Base64.decode(base64Credentials, Base64.DEFAULT),
+ Charset.forName("UTF-8")
+ )
append("\nUsername: ")
append(credentials.substring(0, credentials.indexOf(":")))
}
@@ -1419,7 +1430,8 @@ class MainActivity : AbstractBaseActivity(), ConnectionFactory.UpdateListener {
.filter { !hasPermissions(arrayOf(it)) }
.toMutableList()
- val length = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
+ val length = if (
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
!hasPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS))
) {
missingPermissions.add(Manifest.permission.POST_NOTIFICATIONS)
@@ -1466,7 +1478,7 @@ class MainActivity : AbstractBaseActivity(), ConnectionFactory.UpdateListener {
}
}
- private fun setupUiCommandItem () {
+ private fun setupUiCommandItem() {
uiCommandItemJob?.cancel()
val setting = prefs.getStringOrNull(PrefKeys.UI_COMMAND_ITEM).toItemUpdatePrefValue()
if (setting.first) {
@@ -1552,22 +1564,36 @@ class MainActivity : AbstractBaseActivity(), ConnectionFactory.UpdateListener {
}
private fun manageHabPanelShortcut(visible: Boolean) {
- manageShortcut(visible, "habpanel", ACTION_HABPANEL_SELECTED,
- R.string.mainmenu_openhab_habpanel, R.mipmap.ic_shortcut_habpanel,
- R.string.app_shortcut_disabled_habpanel)
+ manageShortcut(
+ visible,
+ "habpanel",
+ ACTION_HABPANEL_SELECTED,
+ R.string.mainmenu_openhab_habpanel,
+ R.mipmap.ic_shortcut_habpanel,
+ R.string.app_shortcut_disabled_habpanel
+ )
}
private fun manageNotificationShortcut(visible: Boolean) {
- manageShortcut(visible, "notification", ACTION_NOTIFICATION_SELECTED,
- R.string.app_notifications, R.mipmap.ic_shortcut_notifications,
- R.string.app_shortcut_disabled_notifications)
+ manageShortcut(
+ visible,
+ "notification",
+ ACTION_NOTIFICATION_SELECTED,
+ R.string.app_notifications,
+ R.mipmap.ic_shortcut_notifications,
+ R.string.app_shortcut_disabled_notifications
+ )
}
private fun manageVoiceRecognitionShortcut(visible: Boolean) {
- manageShortcut(visible, "voice_recognition", ACTION_VOICE_RECOGNITION_SELECTED,
+ manageShortcut(
+ visible,
+ "voice_recognition",
+ ACTION_VOICE_RECOGNITION_SELECTED,
R.string.mainmenu_openhab_voice_recognition,
R.mipmap.ic_shortcut_voice_recognition,
- R.string.app_shortcut_disabled_voice_recognition)
+ R.string.app_shortcut_disabled_voice_recognition
+ )
}
private fun manageShortcut(
@@ -1601,18 +1627,23 @@ class MainActivity : AbstractBaseActivity(), ConnectionFactory.UpdateListener {
private fun setVoiceWidgetComponentEnabledSetting(component: Class<*>, isSpeechRecognizerAvailable: Boolean) {
val voiceWidget = ComponentName(this, component)
- val newState = if (isSpeechRecognizerAvailable)
+ val newState = if (isSpeechRecognizerAvailable) {
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
- else
+ } else {
PackageManager.COMPONENT_ENABLED_STATE_DISABLED
+ }
packageManager.setComponentEnabledSetting(voiceWidget, newState, PackageManager.DONT_KILL_APP)
}
private sealed class PendingAction {
class ChooseSitemap : PendingAction()
+
class OpenSitemapUrl(val url: String, val serverId: Int) : PendingAction()
+
class OpenWebViewUi(val ui: WebViewUi, val serverId: Int, val subpage: String?) : PendingAction()
+
class LaunchVoiceRecognition : PendingAction()
+
class OpenNotification(val notificationId: String, val primary: Boolean) : PendingAction()
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/NfcItemPickerActivity.kt b/mobile/src/main/java/org/openhab/habdroid/ui/NfcItemPickerActivity.kt
index 49a50d3924..3f52388638 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/NfcItemPickerActivity.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/NfcItemPickerActivity.kt
@@ -55,11 +55,13 @@ class NfcItemPickerActivity(
) {
val deviceId = getPrefs().getStringOrEmpty(PrefKeys.DEV_ID)
if (deviceId.isNotEmpty() && suggestedCommands.shouldShowCustom) {
- entries.add(CommandEntry(
- deviceId,
- getString(R.string.device_identifier_suggested_command_nfc_tag, deviceId),
- "isDeviceId"
- ))
+ entries.add(
+ CommandEntry(
+ deviceId,
+ getString(R.string.device_identifier_suggested_command_nfc_tag, deviceId),
+ "isDeviceId"
+ )
+ )
}
}
@@ -68,7 +70,15 @@ class NfcItemPickerActivity(
return
}
val deviceId = tag == "isDeviceId"
- startActivity(WriteTagActivity.createItemUpdateIntent(
- this, item.name, state, mappedState, item.label, deviceId))
+ startActivity(
+ WriteTagActivity.createItemUpdateIntent(
+ this,
+ item.name,
+ state,
+ mappedState,
+ item.label,
+ deviceId
+ )
+ )
}
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/SelectionItemActivity.kt b/mobile/src/main/java/org/openhab/habdroid/ui/SelectionItemActivity.kt
index 1cab7a1690..0d49ee0512 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/SelectionItemActivity.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/SelectionItemActivity.kt
@@ -18,11 +18,8 @@ import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MenuItem
-import android.view.View
import android.view.ViewGroup
-import android.widget.LinearLayout
import android.widget.RadioButton
-import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.openhab.habdroid.R
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/TaskerItemPickerActivity.kt b/mobile/src/main/java/org/openhab/habdroid/ui/TaskerItemPickerActivity.kt
index 6208463469..16f0a16bb8 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/TaskerItemPickerActivity.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/TaskerItemPickerActivity.kt
@@ -122,7 +122,8 @@ class TaskerItemPickerActivity(
}
if (TaskerPlugin.Setting.hostSupportsOnFireVariableReplacement(this)) {
- TaskerPlugin.Setting.setVariableReplaceKeys(resultBundle,
+ TaskerPlugin.Setting.setVariableReplaceKeys(
+ resultBundle,
arrayOf(EXTRA_ITEM_STATE, EXTRA_ITEM_MAPPED_STATE)
)
}
@@ -132,8 +133,10 @@ class TaskerItemPickerActivity(
}
if (TaskerPlugin.hostSupportsRelevantVariables(intent.extras)) {
- TaskerPlugin.addRelevantVariableList(resultIntent,
- arrayOf("$VAR_HTTP_CODE\nHTTP code\nHTTP code returned by the server"))
+ TaskerPlugin.addRelevantVariableList(
+ resultIntent,
+ arrayOf("$VAR_HTTP_CODE\nHTTP code\nHTTP code returned by the server")
+ )
}
setResult(RESULT_OK, resultIntent)
@@ -148,6 +151,7 @@ class TaskerItemPickerActivity(
const val RESULT_CODE_PLUGIN_DISABLED = TaskerPlugin.Setting.RESULT_CODE_FAILED_PLUGIN_FIRST
const val RESULT_CODE_NO_CONNECTION = TaskerPlugin.Setting.RESULT_CODE_FAILED_PLUGIN_FIRST + 1
+
fun getResultCodeForHttpFailure(httpCode: Int): Int {
return 1000 + httpCode
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/ViewExtensions.kt b/mobile/src/main/java/org/openhab/habdroid/ui/ViewExtensions.kt
index 3b9e74f9f6..fb0783daaa 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/ViewExtensions.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/ViewExtensions.kt
@@ -55,11 +55,7 @@ fun SwipeRefreshLayout.applyColors() {
setColorSchemeColors(*colors)
}
-fun WebView.setUpForConnection(
- connection: Connection,
- url: HttpUrl,
- avoidAuthentication: Boolean = false
-) {
+fun WebView.setUpForConnection(connection: Connection, url: HttpUrl, avoidAuthentication: Boolean = false) {
when {
avoidAuthentication -> { /* Don't add authentication */ }
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/WidgetAdapter.kt b/mobile/src/main/java/org/openhab/habdroid/ui/WidgetAdapter.kt
index 0e1af4048b..62f6971894 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/WidgetAdapter.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/WidgetAdapter.kt
@@ -141,8 +141,10 @@ class WidgetAdapter(
interface ItemClickListener {
fun onItemClicked(widget: Widget): Boolean // returns whether click was handled
}
+
interface FragmentPresenter {
fun showBottomSheet(sheet: AbstractWidgetBottomSheet, widget: Widget)
+
fun showSelectionFragment(fragment: DialogFragment, widget: Widget)
}
@@ -386,12 +388,14 @@ class WidgetAdapter(
protected val fragmentPresenter get() = requireHolderContext().fragmentPresenter
abstract fun bind(widget: Widget)
+
fun start() {
if (!started) {
onStart()
started = true
}
}
+
fun stop(): Boolean {
if (!started) {
return false
@@ -400,17 +404,22 @@ class WidgetAdapter(
started = false
return true
}
+
fun attach() {
start()
scope = CoroutineScope(Dispatchers.Main + Job())
}
+
fun detach() {
stop()
scope?.cancel()
scope = null
}
+
open fun onStart() {}
+
open fun onStop() {}
+
open fun handleRowClick() {}
protected fun requireHolderContext() = vhc ?: throw IllegalStateException("Holder not bound")
@@ -469,8 +478,8 @@ class WidgetAdapter(
override fun bind(widget: Widget) {
super.bind(widget)
- val showLabelAndIcon = widget.label.isNotEmpty()
- && widget.labelSource == Widget.LabelSource.SitemapDefinition
+ val showLabelAndIcon = widget.label.isNotEmpty() &&
+ widget.labelSource == Widget.LabelSource.SitemapDefinition
labelView.isVisible = showLabelAndIcon
iconView.isVisible = showLabelAndIcon
if (!showDataSaverPlaceholderIfNeeded(widget, canBindWithoutDataTransfer(widget))) {
@@ -524,6 +533,7 @@ class WidgetAdapter(
}
internal abstract fun bindAfterDataSaverCheck(widget: Widget)
+
internal open fun canBindWithoutDataTransfer(widget: Widget): Boolean = false
}
@@ -541,7 +551,6 @@ class WidgetAdapter(
class InvisibleWidgetViewHolder internal constructor(initData: ViewHolderInitData) :
ViewHolder(initData, R.layout.widgetlist_invisibleitem) {
-
override fun bind(widget: Widget) {
}
}
@@ -811,8 +820,8 @@ class WidgetAdapter(
override fun bind(widget: Widget) {
super.bind(widget)
- val showLabelAndIcon = widget.label.isNotEmpty()
- && widget.labelSource == Widget.LabelSource.SitemapDefinition
+ val showLabelAndIcon = widget.label.isNotEmpty() &&
+ widget.labelSource == Widget.LabelSource.SitemapDefinition
labelView.isVisible = showLabelAndIcon
iconView.isVisible = showLabelAndIcon
@@ -824,8 +833,8 @@ class WidgetAdapter(
table.columnCount = min(mappings.maxOfOrNull { it.column } ?: 0, maxColumns)
(0 until table.rowCount).forEach { row ->
(0 until table.columnCount).forEach { column ->
- val buttonView = spareViews.removeFirstOrNull() ?:
- initData.inflater.inflate(R.layout.widgetlist_sectionswitchitem_button, table, false)
+ val buttonView = spareViews.removeFirstOrNull()
+ ?: initData.inflater.inflate(R.layout.widgetlist_sectionswitchitem_button, table, false)
as MaterialButton
// Rows and columns start with 1 in Sitemap definition, thus decrement them here
val mapping = mappings.firstOrNull { it.row - 1 == row && it.column - 1 == column }
@@ -1144,6 +1153,7 @@ class WidgetAdapter(
View.OnLongClickListener {
private val upButton = itemView.findViewById(R.id.up_button)
private val downButton = itemView.findViewById(R.id.down_button)
+
data class UpDownButtonState(val item: Item?, val command: String, var inLongPress: Boolean = false)
init {
@@ -1464,6 +1474,7 @@ class WidgetAdapter(
View.OnLongClickListener {
private val upButton = itemView.findViewById(R.id.up_button)
private val downButton = itemView.findViewById(R.id.down_button)
+
data class UpDownButtonState(
val item: Item?,
val shortCommand: String,
@@ -1565,6 +1576,7 @@ class WidgetAdapter(
openPopup()
}
}
+
protected abstract fun openPopup()
}
@@ -1636,6 +1648,7 @@ class WidgetAdapter(
private fun toInternalViewType(viewType: Int, compactMode: Boolean): Int {
return viewType or (if (compactMode) 0x100 else 0)
}
+
private fun fromInternalViewType(viewType: Int): Pair {
val compactMode = (viewType and 0x100) != 0
return Pair(viewType and 0xff, compactMode)
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/WidgetDetailBottomSheets.kt b/mobile/src/main/java/org/openhab/habdroid/ui/WidgetDetailBottomSheets.kt
index e6ff61c1d0..19d7ee85db 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/WidgetDetailBottomSheets.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/WidgetDetailBottomSheets.kt
@@ -13,7 +13,6 @@
package org.openhab.habdroid.ui
-import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
@@ -56,6 +55,7 @@ open class AbstractWidgetBottomSheet : BottomSheetDialogFragment() {
}
super.onViewCreated(view, savedInstanceState)
}
+
companion object {
fun createArguments(widget: Widget): Bundle {
return bundleOf("widget" to widget)
@@ -69,6 +69,7 @@ open class AbstractWidgetBottomSheet : BottomSheetDialogFragment() {
class SliderBottomSheet : AbstractWidgetBottomSheet(), WidgetSlider.UpdateListener {
private var updateJob: Job? = null
+
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.bottom_sheet_setpoint, container, false)
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/WidgetListFragment.kt b/mobile/src/main/java/org/openhab/habdroid/ui/WidgetListFragment.kt
index dddb8d8066..9e27182455 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/WidgetListFragment.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/WidgetListFragment.kt
@@ -97,6 +97,7 @@ class WidgetListFragment :
private lateinit var layoutManager: LinearLayoutManager
private var adapter: WidgetAdapter? = null
private var lastContextMenu: ContextMenu? = null
+
// parent activity
private var titleOverride: String? = null
private var highlightedPageLink: String? = null
@@ -245,8 +246,11 @@ class WidgetListFragment :
override fun onContextItemSelected(item: MenuItem): Boolean {
val context = context
val info = item.menuInfo
- val widget = if (info is ContextMenuAwareRecyclerView.RecyclerContextMenuInfo)
- adapter?.getItemForContextMenu(info) else null
+ val widget = if (info is ContextMenuAwareRecyclerView.RecyclerContextMenuInfo) {
+ adapter?.getItemForContextMenu(info)
+ } else {
+ null
+ }
if (widget != null && context != null) {
when (item.itemId) {
CONTEXT_MENU_ID_WRITE_SITEMAP_TAG -> {
@@ -291,7 +295,6 @@ class WidgetListFragment :
return@setOnMenuItemClickListener true
}
-
val widgetMenu = menu.addSubMenu(
Menu.NONE,
CONTEXT_MENU_ID_CREATE_HOME_SCREEN_WIDGET,
@@ -323,7 +326,8 @@ class WidgetListFragment :
if (widget.linkedPage != null && ShortcutManagerCompat.isRequestPinShortcutSupported(activity)) {
val shortcutMenu = menu.addSubMenu(
- Menu.NONE, CONTEXT_MENU_ID_PIN_HOME_MENU,
+ Menu.NONE,
+ CONTEXT_MENU_ID_PIN_HOME_MENU,
Menu.NONE,
R.string.home_shortcut_pin_to_home
)
@@ -351,7 +355,8 @@ class WidgetListFragment :
if (hasCommandOptions && nfcSupported) {
val nfcMenu = menu.addSubMenu(
- Menu.NONE, CONTEXT_MENU_ID_WRITE_ITEM_TAG,
+ Menu.NONE,
+ CONTEXT_MENU_ID_WRITE_ITEM_TAG,
Menu.NONE,
R.string.nfc_action_write_command_tag
)
@@ -419,10 +424,11 @@ class WidgetListFragment :
.setNegativeButton(android.R.string.cancel, null)
.show()
input.setOnFocusChangeListener { _, hasFocus ->
- val mode = if (hasFocus)
+ val mode = if (hasFocus) {
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
- else
+ } else {
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
+ }
customDialog.window?.setSoftInputMode(mode)
}
return true
@@ -447,7 +453,10 @@ class WidgetListFragment :
val deviceId = context.getPrefs().getStringOrEmpty(PrefKeys.DEV_ID)
if (showDeviceId && deviceId.isNotEmpty()) {
- menu.add(Menu.NONE, CONTEXT_MENU_ID_WRITE_DEVICE_ID, Menu.NONE,
+ menu.add(
+ Menu.NONE,
+ CONTEXT_MENU_ID_WRITE_DEVICE_ID,
+ Menu.NONE,
getString(R.string.device_identifier_suggested_command_nfc_tag, deviceId)
).setOnMenuItemClickListener(listener)
}
@@ -570,85 +579,84 @@ class WidgetListFragment :
}
}
- private fun createShortcut(
- activity: AbstractBaseActivity,
- linkedPage: LinkedPage,
- whiteBackground: Boolean
- ) = activity.launch {
- val connection = ConnectionFactory.activeUsableConnection?.connection ?: return@launch
- /**
- * Icon size is defined in {@link AdaptiveIconDrawable}. Foreground size of
- * 46dp instead of 72dp adds enough border to the icon.
- * 46dp foreground + 2 * 31dp border = 108dp
- **/
- val foregroundSize = activity.resources.dpToPixel(46F).toInt()
- val iconBitmap = if (linkedPage.icon != null) {
- try {
- val iconFallbackColor = activity.getIconFallbackColor(
- if (whiteBackground) IconBackground.LIGHT else IconBackground.DARK
- )
- connection.httpClient
- .get(linkedPage.icon.toUrl(activity, true))
- .asBitmap(foregroundSize, iconFallbackColor, ImageConversionPolicy.ForceTargetSize)
- .response
- } catch (e: HttpClient.HttpException) {
+ private fun createShortcut(activity: AbstractBaseActivity, linkedPage: LinkedPage, whiteBackground: Boolean) =
+ activity.launch {
+ val connection = ConnectionFactory.activeUsableConnection?.connection ?: return@launch
+
+ /**
+ * Icon size is defined in {@link AdaptiveIconDrawable}. Foreground size of
+ * 46dp instead of 72dp adds enough border to the icon.
+ * 46dp foreground + 2 * 31dp border = 108dp
+ **/
+ val foregroundSize = activity.resources.dpToPixel(46F).toInt()
+ val iconBitmap = if (linkedPage.icon != null) {
+ try {
+ val iconFallbackColor = activity.getIconFallbackColor(
+ if (whiteBackground) IconBackground.LIGHT else IconBackground.DARK
+ )
+ connection.httpClient
+ .get(linkedPage.icon.toUrl(activity, true))
+ .asBitmap(foregroundSize, iconFallbackColor, ImageConversionPolicy.ForceTargetSize)
+ .response
+ } catch (e: HttpClient.HttpException) {
+ null
+ }
+ } else {
null
}
- } else {
- null
- }
- val icon = if (iconBitmap != null) {
- val borderSize = activity.resources.dpToPixel(31F)
- val totalFrameWidth = (borderSize * 2).toInt()
- val bitmapWithBackground = Bitmap.createBitmap(
- iconBitmap.width + totalFrameWidth,
- iconBitmap.height + totalFrameWidth,
- iconBitmap.config)
- with(Canvas(bitmapWithBackground)) {
- drawColor(if (whiteBackground) Color.WHITE else Color.DKGRAY)
- drawBitmap(iconBitmap, borderSize, borderSize, null)
+ val icon = if (iconBitmap != null) {
+ val borderSize = activity.resources.dpToPixel(31F)
+ val totalFrameWidth = (borderSize * 2).toInt()
+ val bitmapWithBackground = Bitmap.createBitmap(
+ iconBitmap.width + totalFrameWidth,
+ iconBitmap.height + totalFrameWidth,
+ iconBitmap.config
+ )
+ with(Canvas(bitmapWithBackground)) {
+ drawColor(if (whiteBackground) Color.WHITE else Color.DKGRAY)
+ drawBitmap(iconBitmap, borderSize, borderSize, null)
+ }
+ IconCompat.createWithAdaptiveBitmap(bitmapWithBackground)
+ } else {
+ // Fall back to openHAB icon
+ IconCompat.createWithResource(activity, R.mipmap.icon)
}
- IconCompat.createWithAdaptiveBitmap(bitmapWithBackground)
- } else {
- // Fall back to openHAB icon
- IconCompat.createWithResource(activity, R.mipmap.icon)
- }
- val sitemapUri = linkedPage.link.toUri()
- val shortSitemapUri = sitemapUri.path?.substring(14).orEmpty()
+ val sitemapUri = linkedPage.link.toUri()
+ val shortSitemapUri = sitemapUri.path?.substring(14).orEmpty()
- val startIntent = Intent(activity, MainActivity::class.java).apply {
- action = MainActivity.ACTION_SITEMAP_SELECTED
- putExtra(MainActivity.EXTRA_SITEMAP_URL, shortSitemapUri)
- putExtra(MainActivity.EXTRA_SERVER_ID, activity.getPrefs().getActiveServerId())
- }
+ val startIntent = Intent(activity, MainActivity::class.java).apply {
+ action = MainActivity.ACTION_SITEMAP_SELECTED
+ putExtra(MainActivity.EXTRA_SITEMAP_URL, shortSitemapUri)
+ putExtra(MainActivity.EXTRA_SERVER_ID, activity.getPrefs().getActiveServerId())
+ }
- val name = if (linkedPage.title.isEmpty()) activity.getString(R.string.app_name) else linkedPage.title
- val shortcutInfo = ShortcutInfoCompat.Builder(activity, shortSitemapUri + '-' + System.currentTimeMillis())
- .setShortLabel(name)
- .setIcon(icon)
- .setIntent(startIntent)
- .setAlwaysBadged()
- .build()
-
- val success = ShortcutManagerCompat.requestPinShortcut(activity, shortcutInfo, null)
- withContext(Dispatchers.Main) {
- if (success) {
- (activity as? MainActivity)?.showSnackbar(
- MainActivity.SNACKBAR_TAG_SHORTCUT_INFO,
- R.string.home_shortcut_success_pinning,
- Snackbar.LENGTH_SHORT
- )
- } else {
- (activity as? MainActivity)?.showSnackbar(
- MainActivity.SNACKBAR_TAG_SHORTCUT_INFO,
- R.string.home_shortcut_error_pinning,
- Snackbar.LENGTH_LONG
- )
+ val name = if (linkedPage.title.isEmpty()) activity.getString(R.string.app_name) else linkedPage.title
+ val shortcutInfo = ShortcutInfoCompat.Builder(activity, shortSitemapUri + '-' + System.currentTimeMillis())
+ .setShortLabel(name)
+ .setIcon(icon)
+ .setIntent(startIntent)
+ .setAlwaysBadged()
+ .build()
+
+ val success = ShortcutManagerCompat.requestPinShortcut(activity, shortcutInfo, null)
+ withContext(Dispatchers.Main) {
+ if (success) {
+ (activity as? MainActivity)?.showSnackbar(
+ MainActivity.SNACKBAR_TAG_SHORTCUT_INFO,
+ R.string.home_shortcut_success_pinning,
+ Snackbar.LENGTH_SHORT
+ )
+ } else {
+ (activity as? MainActivity)?.showSnackbar(
+ MainActivity.SNACKBAR_TAG_SHORTCUT_INFO,
+ R.string.home_shortcut_error_pinning,
+ Snackbar.LENGTH_LONG
+ )
+ }
}
}
- }
override fun toString(): String {
return "${super.toString()} [url=$displayPageUrl, title=$title]"
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/activity/AbstractWebViewFragment.kt b/mobile/src/main/java/org/openhab/habdroid/ui/activity/AbstractWebViewFragment.kt
index 71dc146ee4..02d930fe43 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/activity/AbstractWebViewFragment.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/activity/AbstractWebViewFragment.kt
@@ -461,6 +461,7 @@ abstract class AbstractWebViewFragment : Fragment(), ConnectionFactory.UpdateLis
android.Manifest.permission.CAMERA
)
)
+
private fun permsToWebResources(androidPermissions: Array) = PERMISSION_REQUEST_MAPPING
.filter { (_, perms) -> perms.all { perm -> androidPermissions.contains(perm) } }
.keys
@@ -473,6 +474,7 @@ abstract class AbstractWebViewFragment : Fragment(), ConnectionFactory.UpdateLis
interface ParentCallback {
fun closeFragment()
+
fun updateActionBarState()
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/activity/ContentController.kt b/mobile/src/main/java/org/openhab/habdroid/ui/activity/ContentController.kt
index eca1eff67e..3ba3781bc5 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/activity/ContentController.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/activity/ContentController.kt
@@ -349,8 +349,8 @@ abstract class ContentController protected constructor(private val activity: Mai
if (noConnectionFragment is CommunicationFailureFragment) {
noConnectionFragment = null
resetState()
- updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
activity.updateTitle()
+ updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
}
}
@@ -363,8 +363,11 @@ abstract class ContentController protected constructor(private val activity: Mai
*/
fun updateConnection(connection: Connection?, progressMessage: CharSequence?, @DrawableRes icon: Int) {
CrashReportingHelper.d(TAG, "Update to connection $connection (message $progressMessage)")
- noConnectionFragment = if (connection == null)
- ProgressFragment.newInstance(progressMessage, icon) else null
+ noConnectionFragment = if (connection == null) {
+ ProgressFragment.newInstance(progressMessage, icon)
+ } else {
+ null
+ }
resetState()
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
// Make sure dropped fragments are destroyed immediately to get their views recycled
@@ -482,8 +485,13 @@ abstract class ContentController protected constructor(private val activity: Mai
if (pendingDataLoadUrls.remove(pageUrl) && pendingDataLoadUrls.isEmpty()) {
activity.setProgressIndicatorVisible(false)
activity.updateTitle()
- updateFragmentState(if (pageStack.isEmpty())
- FragmentUpdateReason.PAGE_UPDATE else FragmentUpdateReason.PAGE_ENTER)
+ updateFragmentState(
+ if (pageStack.isEmpty()) {
+ FragmentUpdateReason.PAGE_UPDATE
+ } else {
+ FragmentUpdateReason.PAGE_ENTER
+ }
+ )
}
}
@@ -497,12 +505,12 @@ abstract class ContentController protected constructor(private val activity: Mai
override fun onLoadFailure(error: HttpClient.HttpException) {
val url = error.request.url.toString()
- val errorMessage = activity.getHumanReadableErrorMessage(url, error.statusCode, error, false)
- .toString()
+ val errorMessage = activity.getHumanReadableErrorMessage(url, error.statusCode, error, false).toString()
CrashReportingHelper.d(TAG, "onLoadFailure() with message $errorMessage")
noConnectionFragment = CommunicationFailureFragment.newInstance(
- activity.getString(R.string.error_sitemap_generic_load_error, errorMessage))
+ activity.getString(R.string.error_sitemap_generic_load_error, errorMessage)
+ )
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
activity.updateTitle()
if (pendingDataLoadUrls.remove(error.originalUrl) && pendingDataLoadUrls.isEmpty()) {
@@ -635,8 +643,12 @@ abstract class ContentController protected constructor(private val activity: Mai
companion object {
fun newInstance(message: CharSequence): NoNetworkFragment {
val f = NoNetworkFragment()
- f.arguments = buildArgs(message, R.string.try_again_button,
- R.drawable.ic_network_strength_off_outline_black_24dp, false)
+ f.arguments = buildArgs(
+ message,
+ R.string.try_again_button,
+ R.drawable.ic_network_strength_off_outline_black_24dp,
+ false
+ )
return f
}
}
@@ -650,8 +662,12 @@ abstract class ContentController protected constructor(private val activity: Mai
companion object {
fun newInstance(message: CharSequence): EnableWifiNetworkFragment {
val f = EnableWifiNetworkFragment()
- f.arguments = buildArgs(message, R.string.enable_wifi_button,
- R.drawable.ic_wifi_strength_off_outline_grey_24dp, false)
+ f.arguments = buildArgs(
+ message,
+ R.string.enable_wifi_button,
+ R.drawable.ic_wifi_strength_off_outline_grey_24dp,
+ false
+ )
return f
}
}
@@ -672,15 +688,16 @@ abstract class ContentController protected constructor(private val activity: Mai
}
companion object {
- fun newInstance(
- message: CharSequence
- ): WrongWifiFragment {
+ fun newInstance(message: CharSequence): WrongWifiFragment {
val f = WrongWifiFragment()
val args = buildArgs(
message = message,
button1TextResId = R.string.go_to_settings_button,
- button2TextResId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
- R.string.switch_wifi_button else 0,
+ button2TextResId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ R.string.switch_wifi_button
+ } else {
+ 0
+ },
drawableResId = R.drawable.ic_wifi_strength_off_outline_grey_24dp,
showProgress = false
)
@@ -692,33 +709,37 @@ abstract class ContentController protected constructor(private val activity: Mai
internal class MissingConfigurationFragment : StatusFragment() {
override fun onClick(view: View) {
- if (view.id == R.id.button1) when {
- arguments?.getBoolean(KEY_RESOLVE_ATTEMPTED) == true -> {
- // If we attempted resolving, primary button opens settings
- val preferencesIntent = Intent(activity, PreferencesActivity::class.java)
- startActivity(preferencesIntent)
- }
- arguments?.getBoolean(KEY_WIFI_ENABLED) == true -> {
- // If Wifi is enabled, primary button suggests retrying
- ConnectionFactory.restartNetworkCheck()
- activity?.recreate()
- }
- else -> {
- // If Wifi is disabled, primary button suggests enabling Wifi
- (activity as MainActivity?)?.enableWifiAndIndicateStartup()
+ if (view.id == R.id.button1) {
+ when {
+ arguments?.getBoolean(KEY_RESOLVE_ATTEMPTED) == true -> {
+ // If we attempted resolving, primary button opens settings
+ val preferencesIntent = Intent(activity, PreferencesActivity::class.java)
+ startActivity(preferencesIntent)
+ }
+ arguments?.getBoolean(KEY_WIFI_ENABLED) == true -> {
+ // If Wifi is enabled, primary button suggests retrying
+ ConnectionFactory.restartNetworkCheck()
+ activity?.recreate()
+ }
+ else -> {
+ // If Wifi is disabled, primary button suggests enabling Wifi
+ (activity as MainActivity?)?.enableWifiAndIndicateStartup()
+ }
}
- } else when {
- arguments?.getBoolean(KEY_RESOLVE_ATTEMPTED) == true -> {
- // If we attempted resolving, secondary button enables demo mode
- context?.apply {
- getPrefs().edit {
- putBoolean(PrefKeys.DEMO_MODE, true)
+ } else {
+ when {
+ arguments?.getBoolean(KEY_RESOLVE_ATTEMPTED) == true -> {
+ // If we attempted resolving, secondary button enables demo mode
+ context?.apply {
+ getPrefs().edit {
+ putBoolean(PrefKeys.DEMO_MODE, true)
+ }
}
}
- }
- else -> {
- // If connection issue, secondary button suggests opening status.openhab.org
- "https://status.openhab.org".toUri().openInBrowser(requireContext())
+ else -> {
+ // If connection issue, secondary button suggests opening status.openhab.org
+ "https://status.openhab.org".toUri().openInBrowser(requireContext())
+ }
}
}
}
@@ -732,17 +753,27 @@ abstract class ContentController protected constructor(private val activity: Mai
): MissingConfigurationFragment {
val f = MissingConfigurationFragment()
val args = when {
- resolveAttempted -> buildArgs(context.getString(R.string.configuration_missing),
- R.string.go_to_settings_button, R.string.enable_demo_mode_button,
- R.drawable.ic_home_search_outline_grey_340dp, false)
- hasWifiEnabled -> buildArgs(context.getString(R.string.no_remote_server),
+ resolveAttempted -> buildArgs(
+ context.getString(R.string.configuration_missing),
+ R.string.go_to_settings_button,
+ R.string.enable_demo_mode_button,
+ R.drawable.ic_home_search_outline_grey_340dp,
+ false
+ )
+ hasWifiEnabled -> buildArgs(
+ context.getString(R.string.no_remote_server),
R.string.try_again_button,
if (wouldHaveUsedOfficialServer) R.string.visit_status_openhab_org else 0,
- R.drawable.ic_network_strength_off_outline_black_24dp, false)
- else -> buildArgs(context.getString(R.string.no_remote_server),
+ R.drawable.ic_network_strength_off_outline_black_24dp,
+ false
+ )
+ else -> buildArgs(
+ context.getString(R.string.no_remote_server),
R.string.enable_wifi_button,
if (wouldHaveUsedOfficialServer) R.string.visit_status_openhab_org else 0,
- R.drawable.ic_wifi_strength_off_outline_grey_24dp, false)
+ R.drawable.ic_wifi_strength_off_outline_grey_24dp,
+ false
+ )
}
args.putBoolean(KEY_RESOLVE_ATTEMPTED, resolveAttempted)
args.putBoolean(KEY_WIFI_ENABLED, hasWifiEnabled)
@@ -765,12 +796,14 @@ abstract class ContentController protected constructor(private val activity: Mai
view.findViewById(R.id.progress).isVisible = arguments.getBoolean(KEY_PROGRESS)
val watermark = view.findViewById(R.id.image)
+
@DrawableRes val drawableResId = arguments.getInt(KEY_DRAWABLE)
if (drawableResId != 0) {
val drawable = ContextCompat.getDrawable(view.context, drawableResId)
drawable?.colorFilter = PorterDuffColorFilter(
view.context.resolveThemedColor(R.attr.colorOnSurfaceVariant),
- PorterDuff.Mode.SRC_IN)
+ PorterDuff.Mode.SRC_IN
+ )
watermark.setImageDrawable(drawable)
} else {
watermark.isVisible = false
@@ -805,8 +838,13 @@ abstract class ContentController protected constructor(private val activity: Mai
@DrawableRes drawableResId: Int,
showProgress: Boolean
): Bundle {
- return buildArgs(message, buttonTextResId,
- 0, drawableResId, showProgress)
+ return buildArgs(
+ message,
+ buttonTextResId,
+ 0,
+ drawableResId,
+ showProgress
+ )
}
internal fun buildArgs(
@@ -848,6 +886,7 @@ abstract class ContentController protected constructor(private val activity: Mai
private const val STATE_KEY_PROGRESS_FRAGMENT = "progressFragment"
private const val STATE_KEY_ERROR_FRAGMENT = "errorFragment"
private const val STATE_KEY_TEMPORARY_PAGE = "temporaryPage"
+
private fun makeStateKeyForPage(page: LinkedPage) = "pageFragment-${page.link}"
@AnimRes
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/activity/PageConnectionHolderFragment.kt b/mobile/src/main/java/org/openhab/habdroid/ui/activity/PageConnectionHolderFragment.kt
index 07dd4eff96..4a2ba48ef5 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/activity/PageConnectionHolderFragment.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/activity/PageConnectionHolderFragment.kt
@@ -219,8 +219,14 @@ class PageConnectionHolderFragment : Fragment(), CoroutineScope {
val sitemap = segments[segments.size - 2]
val pageId = segments[segments.size - 1]
Log.d(TAG, "Creating new SSE helper for sitemap $sitemap, page $pageId")
- eventHelper = EventHelper(scope, httpClient, sitemap, pageId,
- this::handleUpdateEvent, this::handleSseSubscriptionFailure)
+ eventHelper = EventHelper(
+ scope,
+ httpClient,
+ sitemap,
+ pageId,
+ this::handleUpdateEvent,
+ this::handleSseSubscriptionFailure
+ )
}
}
}
@@ -311,8 +317,11 @@ class PageConnectionHolderFragment : Fragment(), CoroutineScope {
}
val dataSource = WidgetDataSource()
- val hasUpdate = if (callback.serverProperties?.hasJsonApi() == true)
- parseResponseJson(dataSource, response) else parseResponseXml(dataSource, response)
+ val hasUpdate = if (callback.serverProperties?.hasJsonApi() == true) {
+ parseResponseJson(dataSource, response)
+ } else {
+ parseResponseXml(dataSource, response)
+ }
if (hasUpdate) {
// Remove frame widgets with no label text
@@ -465,8 +474,11 @@ class PageConnectionHolderFragment : Fragment(), CoroutineScope {
subscribeJob = scope.launch {
try {
- val response = client.post("/rest/sitemaps/events/subscribe",
- "{}", "application/json").asText()
+ val response = client.post(
+ "/rest/sitemaps/events/subscribe",
+ "{}",
+ "application/json"
+ ).asText()
val result = JSONObject(response.response)
val status = result.getString("status")
if (status != "CREATED") {
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/homescreenwidget/ItemUpdateWidget.kt b/mobile/src/main/java/org/openhab/habdroid/ui/homescreenwidget/ItemUpdateWidget.kt
index d624364aed..f27ce9efaa 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/homescreenwidget/ItemUpdateWidget.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/homescreenwidget/ItemUpdateWidget.kt
@@ -93,8 +93,7 @@ open class ItemUpdateWidget : AppWidgetProvider() {
if (id != AppWidgetManager.INVALID_APPWIDGET_ID) {
when (intent.action) {
ACTION_CREATE_WIDGET -> {
- val data = intent
- .getBundleExtra(EXTRA_BUNDLE)
+ val data = intent.getBundleExtra(EXTRA_BUNDLE)
?.parcelable(EXTRA_DATA)
?: return
saveInfoForWidget(context, data, id)
@@ -220,6 +219,7 @@ open class ItemUpdateWidget : AppWidgetProvider() {
height *= 0.5F
}
val sizeInDp = min(height, width)
+
@Px val size = context.resources.dpToPixel(sizeInDp).toInt()
Log.d(TAG, "Icon size: $size")
val widgetBackground = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
@@ -311,11 +311,7 @@ open class ItemUpdateWidget : AppWidgetProvider() {
return ItemUpdateWidgetData(item, command, label, widgetLabel, mappedState, icon, showState)
}
- fun saveInfoForWidget(
- context: Context,
- data: ItemUpdateWidgetData,
- id: Int
- ) {
+ fun saveInfoForWidget(context: Context, data: ItemUpdateWidgetData, id: Int) {
getPrefsForWidget(context, id).edit {
putString(PreferencesActivity.ITEM_UPDATE_WIDGET_ITEM, data.item)
putString(PreferencesActivity.ITEM_UPDATE_WIDGET_COMMAND, data.command)
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/homescreenwidget/VoiceWidgetWithIcon.kt b/mobile/src/main/java/org/openhab/habdroid/ui/homescreenwidget/VoiceWidgetWithIcon.kt
index 2e758cdcf2..8b61483b2a 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/homescreenwidget/VoiceWidgetWithIcon.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/homescreenwidget/VoiceWidgetWithIcon.kt
@@ -18,7 +18,6 @@ import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
import androidx.annotation.LayoutRes
-
import org.openhab.habdroid.R
import org.openhab.habdroid.ui.MainActivity
import org.openhab.habdroid.util.PendingIntent_Immutable
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/preference/PreferencesActivity.kt b/mobile/src/main/java/org/openhab/habdroid/ui/preference/PreferencesActivity.kt
index c60d282012..b1b5aff9c6 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/preference/PreferencesActivity.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/preference/PreferencesActivity.kt
@@ -150,6 +150,7 @@ class PreferencesActivity : AbstractBaseActivity() {
class ConfirmLeaveDialogFragment : DialogFragment() {
interface Callback {
fun onLeaveAndSave()
+
fun onLeaveAndDiscard()
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/ConnectionSettingsFragment.kt b/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/ConnectionSettingsFragment.kt
index e44cec2d89..4f4f1f326f 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/ConnectionSettingsFragment.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/ConnectionSettingsFragment.kt
@@ -52,11 +52,7 @@ class ConnectionSettingsFragment : AbstractSettingsFragment() {
getString(requireArguments().getInt("urlsummary"), actualValue)
}
- userNamePreference = initEditor(
- "username",
- path.userName,
- R.drawable.ic_person_outline_grey_24dp
- ) { value ->
+ userNamePreference = initEditor("username", path.userName, R.drawable.ic_person_outline_grey_24dp) { value ->
if (!value.isNullOrEmpty()) value else getString(R.string.info_not_set)
}
passwordPreference = initEditor(
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/MainSettingsFragment.kt b/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/MainSettingsFragment.kt
index 8038f14092..e10c61e100 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/MainSettingsFragment.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/MainSettingsFragment.kt
@@ -226,10 +226,11 @@ class MainSettingsFragment : AbstractSettingsFragment(), ConnectionFactory.Updat
launcherPref.setOnPreferenceChangeListener { pref, newValue ->
val context = pref.context
val launcherAlias = ComponentName(context, "${context.packageName}.ui.LauncherActivityAlias")
- val newState = if (newValue as Boolean)
+ val newState = if (newValue as Boolean) {
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
- else
+ } else {
PackageManager.COMPONENT_ENABLED_STATE_DISABLED
+ }
context.packageManager.setComponentEnabledSetting(launcherAlias, newState, PackageManager.DONT_KILL_APP)
true
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/ServerEditorFragment.kt b/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/ServerEditorFragment.kt
index d0c9e5fb39..8d4aa29862 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/ServerEditorFragment.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/ServerEditorFragment.kt
@@ -66,7 +66,10 @@ class ServerEditorFragment :
val backCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (initialConfig != config) {
- PreferencesActivity.ConfirmLeaveDialogFragment().show(childFragmentManager, "dialog_confirm_leave")
+ PreferencesActivity.ConfirmLeaveDialogFragment().show(
+ childFragmentManager,
+ "dialog_confirm_leave"
+ )
} else {
isEnabled = false
parentActivity.onBackPressedDispatcher.onBackPressed()
@@ -225,7 +228,8 @@ class ServerEditorFragment :
handleNoDefaultSitemap(clearDefaultSitemapPref)
} else {
clearDefaultSitemapPref.summary = getString(
- R.string.settings_current_default_sitemap, config.defaultSitemap?.label.orEmpty()
+ R.string.settings_current_default_sitemap,
+ config.defaultSitemap?.label.orEmpty()
)
}
clearDefaultSitemapPref.setOnPreferenceClickListener { preference ->
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/TileSettingsFragment.kt b/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/TileSettingsFragment.kt
index dc48c6a520..7b7204bd8e 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/TileSettingsFragment.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/preference/fragments/TileSettingsFragment.kt
@@ -136,7 +136,10 @@ class TileSettingsFragment :
val backCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (prefs.getTileData(tileId) != getCurrentPrefsAsTileData()) {
- PreferencesActivity.ConfirmLeaveDialogFragment().show(childFragmentManager, "dialog_confirm_leave")
+ PreferencesActivity.ConfirmLeaveDialogFragment().show(
+ childFragmentManager,
+ "dialog_confirm_leave"
+ )
} else {
isEnabled = false
parentActivity.onBackPressedDispatcher.onBackPressed()
@@ -193,11 +196,10 @@ class TileSettingsFragment :
private fun updateIconPrefIcon(newIcon: String = iconPref.value) {
val context = iconPref.context
- iconPref.icon =
- ContextCompat.getDrawable(context, AbstractTileService.getIconRes(context, newIcon))?.apply {
- mutate()
- setTint(context.getColor(R.color.pref_icon_grey))
- }
+ iconPref.icon = ContextCompat.getDrawable(context, AbstractTileService.getIconRes(context, newIcon))?.apply {
+ mutate()
+ setTint(context.getColor(R.color.pref_icon_grey))
+ }
}
private fun getCurrentPrefsAsTileData(): TileData? {
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/ChartScalingPreference.kt b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/ChartScalingPreference.kt
index 7cb1e7f59d..aa616f9c00 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/ChartScalingPreference.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/ChartScalingPreference.kt
@@ -21,7 +21,6 @@ import androidx.preference.Preference
import androidx.preference.PreferenceViewHolder
import com.google.android.material.slider.Slider
import kotlin.math.max
-
import org.openhab.habdroid.R
class ChartScalingPreference(context: Context, attrs: AttributeSet) :
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/CustomInputTypePreference.kt b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/CustomInputTypePreference.kt
index 25b86efc31..b63145a038 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/CustomInputTypePreference.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/CustomInputTypePreference.kt
@@ -192,4 +192,3 @@ open class CustomInputTypePreference(context: Context, attrs: AttributeSet) :
WARN
}
}
-
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/DeviceIdentifierPreference.kt b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/DeviceIdentifierPreference.kt
index bb4a5b883a..844ebfa62f 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/DeviceIdentifierPreference.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/DeviceIdentifierPreference.kt
@@ -34,7 +34,8 @@ import org.openhab.habdroid.R
import org.openhab.habdroid.ui.preference.CustomDialogPreference
import org.openhab.habdroid.util.PrefKeys
-class DeviceIdentifierPreference(context: Context, attrs: AttributeSet) : DialogPreference(context, attrs),
+class DeviceIdentifierPreference(context: Context, attrs: AttributeSet) :
+ DialogPreference(context, attrs),
CustomDialogPreference {
private var value: String? = null
@@ -154,10 +155,7 @@ class DeviceIdentifierPreference(context: Context, attrs: AttributeSet) : Dialog
companion object {
private const val KEY_TITLE = "title"
- fun newInstance(
- key: String,
- title: CharSequence?
- ): PrefFragment {
+ fun newInstance(key: String, title: CharSequence?): PrefFragment {
val f = PrefFragment()
f.arguments = bundleOf(ARG_KEY to key, KEY_TITLE to title)
return f
@@ -165,4 +163,3 @@ class DeviceIdentifierPreference(context: Context, attrs: AttributeSet) : Dialog
}
}
}
-
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/ItemAndTogglePreference.kt b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/ItemAndTogglePreference.kt
index 1772fb29de..e52e9d2839 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/ItemAndTogglePreference.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/ItemAndTogglePreference.kt
@@ -41,7 +41,8 @@ import org.openhab.habdroid.ui.preference.CustomDialogPreference
import org.openhab.habdroid.ui.setupHelpIcon
import org.openhab.habdroid.util.hasPermissions
-open class ItemAndTogglePreference(context: Context, attrs: AttributeSet?) : DialogPreference(context, attrs),
+open class ItemAndTogglePreference(context: Context, attrs: AttributeSet?) :
+ DialogPreference(context, attrs),
CustomDialogPreference {
private val howtoUrl: String?
protected var summaryOn: String?
@@ -102,6 +103,7 @@ open class ItemAndTogglePreference(context: Context, attrs: AttributeSet?) : Dia
summaryOn = summary
updateSummaryAndIcon()
}
+
open fun updateSummaryAndIcon() {
val value = value ?: return
val summary = if (value.first) summaryOn else summaryOff
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/ItemUpdatingPreference.kt b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/ItemUpdatingPreference.kt
index d659d9a392..bfafc02307 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/ItemUpdatingPreference.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/ItemUpdatingPreference.kt
@@ -24,7 +24,8 @@ import org.openhab.habdroid.ui.preference.CustomDialogPreference
import org.openhab.habdroid.util.getPrefixForBgTasks
import org.openhab.habdroid.util.getPrefs
-class ItemUpdatingPreference(context: Context, attrs: AttributeSet?) : ItemAndTogglePreference(context, attrs),
+class ItemUpdatingPreference(context: Context, attrs: AttributeSet?) :
+ ItemAndTogglePreference(context, attrs),
CustomDialogPreference {
fun startObserving(lifecycleOwner: LifecycleOwner) {
val infoLiveData = workManager.getWorkInfosByTagLiveData(key)
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/UrlInputPreference.kt b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/UrlInputPreference.kt
index 39d1c29d89..ecbc65adb4 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/UrlInputPreference.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/UrlInputPreference.kt
@@ -33,7 +33,6 @@ import org.openhab.habdroid.R
class UrlInputPreference(context: Context, attrs: AttributeSet) :
CustomInputTypePreference(context, attrs) {
-
private val isForRemoteServer: Boolean
init {
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/WifiSsidInputPreference.kt b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/WifiSsidInputPreference.kt
index da11d58709..c62d62aff7 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/WifiSsidInputPreference.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/preference/widgets/WifiSsidInputPreference.kt
@@ -117,10 +117,7 @@ class WifiSsidInputPreference(context: Context, attrs: AttributeSet) :
companion object {
private const val KEY_TITLE = "title"
- fun newInstance(
- key: String,
- title: CharSequence?
- ): PrefFragment {
+ fun newInstance(key: String, title: CharSequence?): PrefFragment {
val f = PrefFragment()
f.arguments = bundleOf(
ARG_KEY to key,
@@ -131,4 +128,3 @@ class WifiSsidInputPreference(context: Context, attrs: AttributeSet) :
}
}
}
-
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/widget/RecyclerViewSwipeRefreshLayout.kt b/mobile/src/main/java/org/openhab/habdroid/ui/widget/RecyclerViewSwipeRefreshLayout.kt
index b8fd4019c5..ab63d3da11 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/widget/RecyclerViewSwipeRefreshLayout.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/widget/RecyclerViewSwipeRefreshLayout.kt
@@ -108,8 +108,13 @@ class RecyclerViewSwipeRefreshLayout(context: Context, attrs: AttributeSet) : Sw
dyUnconsumed: Int,
offsetInWindow: IntArray?
): Boolean {
- return nestedScrollingChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed,
- dxUnconsumed, dyUnconsumed, offsetInWindow)
+ return nestedScrollingChildHelper.dispatchNestedScroll(
+ dxConsumed,
+ dyConsumed,
+ dxUnconsumed,
+ dyUnconsumed,
+ offsetInWindow
+ )
}
override fun dispatchNestedPreScroll(dx: Int, dy: Int, consumed: IntArray?, offsetInWindow: IntArray?): Boolean {
@@ -124,16 +129,15 @@ class RecyclerViewSwipeRefreshLayout(context: Context, attrs: AttributeSet) : Sw
return nestedScrollingChildHelper.dispatchNestedPreFling(velocityX, velocityY)
}
- override fun onNestedScroll(
- target: View,
- dxConsumed: Int,
- dyConsumed: Int,
- dxUnconsumed: Int,
- dyUnconsumed: Int
- ) {
+ override fun onNestedScroll(target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int) {
if (shouldPreventRefresh()) {
- dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed,
- parentOffsetInWindow)
+ dispatchNestedScroll(
+ dxConsumed,
+ dyConsumed,
+ dxUnconsumed,
+ dyUnconsumed,
+ parentOffsetInWindow
+ )
} else {
super.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed)
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/widget/WidgetImageView.kt b/mobile/src/main/java/org/openhab/habdroid/ui/widget/WidgetImageView.kt
index e4a163892d..21297b3e99 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/widget/WidgetImageView.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/widget/WidgetImageView.kt
@@ -343,10 +343,11 @@ class WidgetImageView(context: Context, attrs: AttributeSet?) : AppCompatImageVi
}
Log.i(TAG, "Refreshing image at $url, avoidCache $avoidCache")
- val cachingMode = if (avoidCache)
+ val cachingMode = if (avoidCache) {
HttpClient.CachingMode.AVOID_CACHE
- else
+ } else {
HttpClient.CachingMode.FORCE_CACHE_IF_POSSIBLE
+ }
val actualUrl = if (addRandomnessToUrl) {
if (avoidCache) {
@@ -365,13 +366,9 @@ class WidgetImageView(context: Context, attrs: AttributeSet?) : AppCompatImageVi
else -> ImageConversionPolicy.PreferSourceSize
}
val fallbackColor = context.getIconFallbackColor(IconBackground.APP_THEME)
- val bitmap = client.get(actualUrl.toString(),
- timeoutMillis = timeoutMillis, caching = cachingMode)
- .asBitmap(
- size,
- fallbackColor,
- conversionPolicy
- )
+ val bitmap = client
+ .get(actualUrl.toString(), timeoutMillis = timeoutMillis, caching = cachingMode)
+ .asBitmap(size, fallbackColor, conversionPolicy)
.response
CacheManager.getInstance(context).cacheBitmap(url, bitmap, fallbackColor)
applyLoadedBitmap(bitmap)
@@ -406,12 +403,14 @@ class WidgetImageView(context: Context, attrs: AttributeSet?) : AppCompatImageVi
}
abstract class PendingRequest
+
data class PendingHttpRequest(
val client: HttpClient,
val url: HttpUrl,
val timeoutMillis: Long,
val forceLoad: Boolean
) : PendingRequest()
+
data class PendingBase64Request(val bitmap: Bitmap) : PendingRequest()
enum class ImageScalingType {
diff --git a/mobile/src/main/java/org/openhab/habdroid/ui/widget/WidgetSlider.kt b/mobile/src/main/java/org/openhab/habdroid/ui/widget/WidgetSlider.kt
index 62399e33f9..dc0f97d0e8 100644
--- a/mobile/src/main/java/org/openhab/habdroid/ui/widget/WidgetSlider.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/ui/widget/WidgetSlider.kt
@@ -35,7 +35,6 @@ class WidgetSlider(context: Context, attrs: AttributeSet?) :
LabelFormatter,
Slider.OnChangeListener,
Slider.OnSliderTouchListener {
-
interface UpdateListener {
suspend fun onValueUpdate(value: Float)
}
@@ -57,8 +56,11 @@ class WidgetSlider(context: Context, attrs: AttributeSet?) :
val from = (if (isColor) 0F else widget.minValue).toBigDecimal()
val to = (if (isColor) 100F else widget.maxValue).toBigDecimal()
val step = (if (isColor) 1F else widget.step).toBigDecimal()
- val widgetValue = (if (isColor) widget.state?.asBrightness?.toBigDecimal() else widget.state?.asNumber?.value?.toBigDecimal())
- ?: from
+ val widgetValue = if (isColor) {
+ widget.state?.asBrightness?.toBigDecimal()
+ } else {
+ widget.state?.asNumber?.value?.toBigDecimal()
+ } ?: from
updateJob?.cancel()
this.updateOnMove = updateOnMove
@@ -139,4 +141,3 @@ class WidgetSlider(context: Context, attrs: AttributeSet?) :
private val TAG = WidgetSlider::class.java.simpleName
}
}
-
diff --git a/mobile/src/main/java/org/openhab/habdroid/util/AsyncServiceResolver.kt b/mobile/src/main/java/org/openhab/habdroid/util/AsyncServiceResolver.kt
index 0b6f6cb46f..82a79f15a0 100644
--- a/mobile/src/main/java/org/openhab/habdroid/util/AsyncServiceResolver.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/util/AsyncServiceResolver.kt
@@ -42,6 +42,7 @@ class AsyncServiceResolver(
) : ServiceListener {
// Multicast lock for mDNS
private val multicastLock: MulticastLock
+
// mDNS service
private var jmDns: JmDNS? = null
private val serviceInfoChannel = Channel(0)
diff --git a/mobile/src/main/java/org/openhab/habdroid/util/ExtensionFuncs.kt b/mobile/src/main/java/org/openhab/habdroid/util/ExtensionFuncs.kt
index b0a4af0dec..677503d7ce 100644
--- a/mobile/src/main/java/org/openhab/habdroid/util/ExtensionFuncs.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/util/ExtensionFuncs.kt
@@ -272,8 +272,7 @@ fun InputStream.svgToBitmap(
}
}
-fun NodeList.forEach(action: (Node) -> Unit) =
- (0 until length).forEach { index -> action(item(index)) }
+fun NodeList.forEach(action: (Node) -> Unit) = (0 until length).forEach { index -> action(item(index)) }
fun JSONArray.forEach(action: (JSONObject) -> Unit) =
(0 until length()).forEach { index -> action(getJSONObject(index)) }
@@ -337,14 +336,17 @@ fun Context.hasPermissions(permissions: Array) = permissions.firstOrNull
fun Context.getHumanReadableErrorMessage(url: String, httpCode: Int, error: Throwable?, short: Boolean): CharSequence {
return if (error.hasCause(UnknownHostException::class.java)) {
getString(
- if (short) R.string.error_short_unable_to_resolve_hostname else R.string.error_unable_to_resolve_hostname)
+ if (short) R.string.error_short_unable_to_resolve_hostname else R.string.error_unable_to_resolve_hostname
+ )
} else if (error.hasCause(CertificateExpiredException::class.java)) {
getString(if (short) R.string.error_short_certificate_expired else R.string.error_certificate_expired)
} else if (error.hasCause(CertificateNotYetValidException::class.java)) {
getString(
- if (short) R.string.error_short_certificate_not_valid_yet else R.string.error_certificate_not_valid_yet)
+ if (short) R.string.error_short_certificate_not_valid_yet else R.string.error_certificate_not_valid_yet
+ )
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N &&
- error.hasCause(CertificateRevokedException::class.java)) {
+ error.hasCause(CertificateRevokedException::class.java)
+ ) {
getString(if (short) R.string.error_short_certificate_revoked else R.string.error_certificate_revoked)
} else if (error.hasCause(SSLPeerUnverifiedException::class.java)) {
getString(
@@ -354,8 +356,13 @@ fun Context.getHumanReadableErrorMessage(url: String, httpCode: Int, error: Thro
} else if (error.hasCause(CertPathValidatorException::class.java)) {
getString(if (short) R.string.error_short_certificate_not_trusted else R.string.error_certificate_not_trusted)
} else if (error.hasCause(SSLException::class.java) || error.hasCause(SSLHandshakeException::class.java)) {
- getString(if (short) R.string.error_short_connection_sslhandshake_failed else
- R.string.error_connection_sslhandshake_failed)
+ getString(
+ if (short) {
+ R.string.error_short_connection_sslhandshake_failed
+ } else {
+ R.string.error_connection_sslhandshake_failed
+ }
+ )
} else if (error.hasCause(ConnectException::class.java) || error.hasCause(SocketTimeoutException::class.java)) {
getString(if (short) R.string.error_short_connection_failed else R.string.error_connection_failed)
} else if (error.hasCause(IOException::class.java) && error.hasCause(EOFException::class.java)) {
@@ -478,16 +485,18 @@ enum class IconBackground {
LIGHT,
DARK
}
+
@ColorInt
fun Context.getIconFallbackColor(iconBackground: IconBackground) = when (iconBackground) {
IconBackground.APP_THEME -> resolveThemedColor(R.attr.colorOnBackground)
IconBackground.OS_THEME -> {
val currentNightMode = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
val isDark = currentNightMode != Configuration.UI_MODE_NIGHT_NO
- val colorRes = if (isDark)
+ val colorRes = if (isDark) {
R.color.on_background_default_theme_dark
- else
+ } else {
R.color.on_background_default_theme_light
+ }
ContextCompat.getColor(this, colorRes)
}
IconBackground.LIGHT -> ContextCompat.getColor(this, R.color.on_background_default_theme_light)
@@ -628,7 +637,9 @@ inline fun Intent.parcelable(key: String): T? {
setExtrasClassLoader(T::class.java.classLoader)
return when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> getParcelableExtra(key, T::class.java)
- else -> @Suppress("DEPRECATION") getParcelableExtra(key) as? T
+ else ->
+ @Suppress("DEPRECATION")
+ getParcelableExtra(key) as? T
}
}
@@ -636,16 +647,22 @@ inline fun Intent.parcelableArrayList(key: String): List? {
setExtrasClassLoader(T::class.java.classLoader)
return when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> getParcelableArrayListExtra(key, T::class.java)
- else -> @Suppress("DEPRECATION") getParcelableArrayListExtra(key)
+ else ->
+ @Suppress("DEPRECATION")
+ getParcelableArrayListExtra(key)
}
}
inline fun Bundle.parcelable(key: String): T? = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> getParcelable(key, T::class.java)
- else -> @Suppress("DEPRECATION") getParcelable(key) as? T
+ else ->
+ @Suppress("DEPRECATION")
+ getParcelable(key) as? T
}
inline fun Bundle.parcelableArrayList(key: String): List? = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> getParcelableArrayList(key, T::class.java)
- else -> @Suppress("DEPRECATION") getParcelableArrayList(key)
+ else ->
+ @Suppress("DEPRECATION")
+ getParcelableArrayList(key)
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/util/HttpClient.kt b/mobile/src/main/java/org/openhab/habdroid/util/HttpClient.kt
index bb428c5d25..d82ba314ea 100644
--- a/mobile/src/main/java/org/openhab/habdroid/util/HttpClient.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/util/HttpClient.kt
@@ -46,8 +46,12 @@ import okhttp3.sse.EventSources
class HttpClient(client: OkHttpClient, baseUrl: String?, username: String?, password: String?) {
private val client: OkHttpClient
private val baseUrl: HttpUrl? = baseUrl?.toHttpUrlOrNull()
- @VisibleForTesting val authHeader: String? = if (!username.isNullOrEmpty())
- Credentials.basic(username, password.orEmpty(), StandardCharsets.UTF_8) else null
+
+ @VisibleForTesting val authHeader: String? = if (!username.isNullOrEmpty()) {
+ Credentials.basic(username, password.orEmpty(), StandardCharsets.UTF_8)
+ } else {
+ null
+ }
init {
val clientBuilder = client.newBuilder()
@@ -56,15 +60,18 @@ class HttpClient(client: OkHttpClient, baseUrl: String?, username: String?, pass
clientBuilder.addNetworkInterceptor { chain ->
val request = chain.request()
// Make sure not to send authentication credentials to external servers
- chain.proceed(if (this.baseUrl?.host == request.url.host) {
- request.newBuilder().addHeader("Authorization", authHeader).build()
- } else {
- request
- })
+ chain.proceed(
+ if (this.baseUrl?.host == request.url.host) {
+ request.newBuilder().addHeader("Authorization", authHeader).build()
+ } else {
+ request
+ }
+ )
}
}
this.client = clientBuilder.build()
}
+
enum class CachingMode {
DEFAULT,
AVOID_CACHE,
@@ -113,8 +120,15 @@ class HttpClient(client: OkHttpClient, baseUrl: String?, username: String?, pass
mediaType: String = "text/plain;charset=UTF-8",
headers: Map? = null
): HttpResult {
- return method(url, "POST", headers, requestBody,
- mediaType, DEFAULT_TIMEOUT_MS, CachingMode.AVOID_CACHE)
+ return method(
+ url,
+ "POST",
+ headers,
+ requestBody,
+ mediaType,
+ DEFAULT_TIMEOUT_MS,
+ CachingMode.AVOID_CACHE
+ )
}
@Throws(HttpException::class)
@@ -124,8 +138,15 @@ class HttpClient(client: OkHttpClient, baseUrl: String?, username: String?, pass
mediaType: String = "text/plain;charset=UTF-8",
headers: Map? = null
): HttpResult {
- return method(url, "PUT", headers, requestBody,
- mediaType, DEFAULT_TIMEOUT_MS, CachingMode.AVOID_CACHE)
+ return method(
+ url,
+ "PUT",
+ headers,
+ requestBody,
+ mediaType,
+ DEFAULT_TIMEOUT_MS,
+ CachingMode.AVOID_CACHE
+ )
}
private suspend fun method(
@@ -136,7 +157,7 @@ class HttpClient(client: OkHttpClient, baseUrl: String?, username: String?, pass
mediaType: String?,
timeoutMillis: Long,
caching: CachingMode
- ) = suspendCancellableCoroutine { cont ->
+ ) = suspendCancellableCoroutine { cont ->
val requestBuilder = Request.Builder()
.url(buildUrl(url))
.addHeader("User-Agent", USER_AGENT)
@@ -154,42 +175,47 @@ class HttpClient(client: OkHttpClient, baseUrl: String?, username: String?, pass
CachingMode.FORCE_CACHE_IF_POSSIBLE -> {
requestBuilder.cacheControl(
CacheControl.Builder()
- .maxStale(Integer.MAX_VALUE, TimeUnit.SECONDS)
- .build())
+ .maxStale(Integer.MAX_VALUE, TimeUnit.SECONDS)
+ .build()
+ )
}
else -> {}
}
val request = requestBuilder.build()
- val call = if (timeoutMillis > 0)
+ val call = if (timeoutMillis > 0) {
client.newBuilder().readTimeout(timeoutMillis, TimeUnit.MILLISECONDS).build().newCall(request)
- else
+ } else {
client.newCall(request)
+ }
cont.invokeOnCancellation { call.cancel() }
- call.enqueue(object : Callback {
- override fun onFailure(call: Call, e: IOException) {
- cont.resumeWithException(HttpException(call.request(), url, e))
- }
+ call.enqueue(
+ object : Callback {
+ override fun onFailure(call: Call, e: IOException) {
+ cont.resumeWithException(HttpException(call.request(), url, e))
+ }
- override fun onResponse(call: Call, response: Response) {
- val body = response.body
+ override fun onResponse(call: Call, response: Response) {
+ val body = response.body
- when {
- !response.isSuccessful -> {
- body?.close()
- cont.resumeWithException(
- HttpException(call.request(), url, response.message, response.code))
- }
- body == null -> {
- cont.resumeWithException(HttpException(call.request(), url, "Empty body", 500))
- }
- else -> {
- cont.resume(HttpResult(call.request(), url, body, response.code, response.headers))
+ when {
+ !response.isSuccessful -> {
+ body?.close()
+ cont.resumeWithException(
+ HttpException(call.request(), url, response.message, response.code)
+ )
+ }
+ body == null -> {
+ cont.resumeWithException(HttpException(call.request(), url, "Empty body", 500))
+ }
+ else -> {
+ cont.resume(HttpResult(call.request(), url, body, response.code, response.headers))
+ }
}
}
}
- })
+ )
}
class HttpResult internal constructor(
@@ -236,7 +262,9 @@ class HttpClient(client: OkHttpClient, baseUrl: String?, username: String?, pass
}
class HttpStatusResult internal constructor(val request: Request, val statusCode: Int)
+
class HttpTextResult internal constructor(val request: Request, val response: String, val headers: Headers)
+
class HttpBitmapResult internal constructor(val request: Request, val response: Bitmap)
class HttpException : Exception {
@@ -261,6 +289,7 @@ class HttpClient(client: OkHttpClient, baseUrl: String?, username: String?, pass
internal class SseListener : EventSourceListener() {
val channel = Channel()
+
override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
super.onEvent(eventSource, id, type, data)
runBlocking {
@@ -281,6 +310,7 @@ class HttpClient(client: OkHttpClient, baseUrl: String?, username: String?, pass
suspend fun getNextEvent(): String {
return listener.channel.receive()
}
+
fun cancel() {
listener.channel.close()
source.cancel()
@@ -291,9 +321,10 @@ class HttpClient(client: OkHttpClient, baseUrl: String?, username: String?, pass
const val DEFAULT_TIMEOUT_MS: Long = 30000
// Pretend to be Chrome on Android
- const val USER_AGENT = "Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) " +
- "AppleWebKit/535.19 (KHTML, like Gecko) " +
- "Chrome/18.0.1025.133 Mobile Safari/535.19"
+ const val USER_AGENT =
+ "Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) " +
+ "AppleWebKit/535.19 (KHTML, like Gecko) " +
+ "Chrome/18.0.1025.133 Mobile Safari/535.19"
fun isMyOpenhab(host: String) = host.matches("^(home.)?myopenhab.org$".toRegex())
}
diff --git a/mobile/src/main/java/org/openhab/habdroid/util/MjpegInputStream.kt b/mobile/src/main/java/org/openhab/habdroid/util/MjpegInputStream.kt
index fd30489dc9..5b30630993 100644
--- a/mobile/src/main/java/org/openhab/habdroid/util/MjpegInputStream.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/util/MjpegInputStream.kt
@@ -15,7 +15,6 @@ package org.openhab.habdroid.util
import android.graphics.Bitmap
import android.graphics.BitmapFactory
-
import java.io.BufferedInputStream
import java.io.ByteArrayInputStream
import java.io.DataInputStream
diff --git a/mobile/src/main/java/org/openhab/habdroid/util/PrefKeys.kt b/mobile/src/main/java/org/openhab/habdroid/util/PrefKeys.kt
index d8c7cd50c7..6a4aa08d29 100644
--- a/mobile/src/main/java/org/openhab/habdroid/util/PrefKeys.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/util/PrefKeys.kt
@@ -36,6 +36,7 @@ object PrefKeys {
const val RESTRICT_TO_SSID_PREFIX = "restrict_to_ssid_"
const val FRONTAIL_URL_PREFIX = "frontail_url_"
const val CLEAR_DEFAULT_SITEMAP = "clear_default_sitemap"
+
fun buildServerKey(id: Int, prefix: String) = "$prefix$id"
const val START_PAGE = "start_page"
diff --git a/mobile/src/main/java/org/openhab/habdroid/util/SuggestedCommandsFactory.kt b/mobile/src/main/java/org/openhab/habdroid/util/SuggestedCommandsFactory.kt
index 2c4e37b727..cc476318ea 100644
--- a/mobile/src/main/java/org/openhab/habdroid/util/SuggestedCommandsFactory.kt
+++ b/mobile/src/main/java/org/openhab/habdroid/util/SuggestedCommandsFactory.kt
@@ -185,4 +185,3 @@ class SuggestedCommandsFactory(private val context: Context, private val showUnd
INPUT_TYPE_DECIMAL_NUMBER or InputType.TYPE_NUMBER_FLAG_SIGNED
}
}
-
diff --git a/mobile/src/test/java/org/openhab/habdroid/background/TileServicesTests.kt b/mobile/src/test/java/org/openhab/habdroid/background/TileServicesTests.kt
index 51228d9a8d..d58a2cd46d 100644
--- a/mobile/src/test/java/org/openhab/habdroid/background/TileServicesTests.kt
+++ b/mobile/src/test/java/org/openhab/habdroid/background/TileServicesTests.kt
@@ -61,7 +61,7 @@ class TileServicesTests {
fun checkTileServicesImplementCorrectId() {
GlobalScope.launch(Dispatchers.Main) {
for (tileService in tileServices) {
- val id = (tileService.getDeclaredConstructor().newInstance() as AbstractTileService).ID
+ val id = (tileService.getDeclaredConstructor().newInstance() as AbstractTileService).id
Assert.assertEquals(
"Name of the tile service doesn't match its id",
id,
@@ -75,7 +75,7 @@ class TileServicesTests {
fun checkClassName() {
GlobalScope.launch(Dispatchers.Main) {
for (tileService in tileServices) {
- val id = (tileService.getDeclaredConstructor().newInstance() as AbstractTileService).ID
+ val id = (tileService.getDeclaredConstructor().newInstance() as AbstractTileService).id
Assert.assertEquals(
AbstractTileService.getClassNameForId(id),
tileService.canonicalName
diff --git a/mobile/src/test/java/org/openhab/habdroid/core/connection/ConnectionFactoryTest.kt b/mobile/src/test/java/org/openhab/habdroid/core/connection/ConnectionFactoryTest.kt
index e6d0726f6d..a258b504ee 100644
--- a/mobile/src/test/java/org/openhab/habdroid/core/connection/ConnectionFactoryTest.kt
+++ b/mobile/src/test/java/org/openhab/habdroid/core/connection/ConnectionFactoryTest.kt
@@ -55,19 +55,19 @@ class ConnectionFactoryTest {
companion object {
private val mainThread = newSingleThreadContext("UI thread")
- @BeforeClass
- @JvmStatic
- @Throws(IOException::class)
- fun setupMainThread() {
- Dispatchers.setMain(mainThread)
- }
-
@AfterClass
@JvmStatic
fun tearDownMainThread() {
Dispatchers.resetMain()
mainThread.close()
}
+
+ @BeforeClass
+ @JvmStatic
+ @Throws(IOException::class)
+ fun setupMainThread() {
+ Dispatchers.setMain(mainThread)
+ }
}
@Rule
@@ -172,10 +172,16 @@ class ConnectionFactoryTest {
assertNotNull("Should return a cloud connection if remote url is set.", conn)
assertEquals(CloudConnection::class.java, conn!!.javaClass)
- assertEquals("The connection type of a cloud connection should be TYPE_CLOUD.",
- Connection.TYPE_CLOUD, conn.connectionType)
- assertEquals("The sender ID of the cloud connection should be '12345'",
- "12345", conn.messagingSenderId)
+ assertEquals(
+ "The connection type of a cloud connection should be TYPE_CLOUD.",
+ Connection.TYPE_CLOUD,
+ conn.connectionType
+ )
+ assertEquals(
+ "The sender ID of the cloud connection should be '12345'",
+ "12345",
+ conn.messagingSenderId
+ )
server.shutdown()
}
@@ -271,6 +277,7 @@ class ConnectionFactoryTest {
currentTypes = if (type != null) listOf(type) else emptyList()
changeCallback?.invoke()
}
+
override fun shutdown() {}
}
diff --git a/mobile/src/test/java/org/openhab/habdroid/core/connection/DefaultConnectionTest.kt b/mobile/src/test/java/org/openhab/habdroid/core/connection/DefaultConnectionTest.kt
index b504f14ea3..5ab8e52286 100644
--- a/mobile/src/test/java/org/openhab/habdroid/core/connection/DefaultConnectionTest.kt
+++ b/mobile/src/test/java/org/openhab/habdroid/core/connection/DefaultConnectionTest.kt
@@ -122,7 +122,7 @@ class DefaultConnectionTest {
Triple("user", "", true),
Triple("", "", false),
Triple("", "password", false),
- Triple("user", "äöü", true),
+ Triple("user", "äöü", true)
)
credentials.forEach {
@@ -133,8 +133,11 @@ class DefaultConnectionTest {
)
val httpClient = connection.httpClient
- val expectedCredentials =
- if (it.third) Credentials.basic(it.first, it.second, StandardCharsets.UTF_8) else null
+ val expectedCredentials = if (it.third) {
+ Credentials.basic(it.first, it.second, StandardCharsets.UTF_8)
+ } else {
+ null
+ }
assertEquals("User ${it.first}, password ${it.second}", expectedCredentials, httpClient.authHeader)
}
}
diff --git a/mobile/src/test/java/org/openhab/habdroid/model/IconResourceTest.kt b/mobile/src/test/java/org/openhab/habdroid/model/IconResourceTest.kt
index 30bd2e869b..8f35d1199e 100644
--- a/mobile/src/test/java/org/openhab/habdroid/model/IconResourceTest.kt
+++ b/mobile/src/test/java/org/openhab/habdroid/model/IconResourceTest.kt
@@ -13,14 +13,7 @@
package org.openhab.habdroid.model
-import org.json.JSONException
-import org.json.JSONObject
import org.junit.Assert.assertEquals
-import org.junit.Assert.assertFalse
-import org.junit.Assert.assertNotEquals
-import org.junit.Assert.assertNotNull
-import org.junit.Assert.assertNull
-import org.junit.Assert.assertTrue
import org.junit.Test
class IconResourceTest {
diff --git a/mobile/src/test/java/org/openhab/habdroid/model/ItemTest.kt b/mobile/src/test/java/org/openhab/habdroid/model/ItemTest.kt
index 2e8ab6c2a1..cdac36f072 100644
--- a/mobile/src/test/java/org/openhab/habdroid/model/ItemTest.kt
+++ b/mobile/src/test/java/org/openhab/habdroid/model/ItemTest.kt
@@ -81,7 +81,7 @@ class ItemTest {
@Test
fun isReadOnly() {
- val json = with(JSONObject()) {
+ val json = JSONObject().apply {
put("name", "TestItem")
put("type", "Dummy")
}
@@ -174,52 +174,47 @@ class ItemTest {
private val itemAsJsonObjectWithMembers = JSONObject(
"""
{ 'members': [
- { 'state': '52.5200066,13.4029540', 'type': 'Location', 'name': 'GroupDemoLocation',
- 'label': 'Location 1', 'groupNames': [ 'LocationGroup' ] },
- { 'state': '52.5200066,13.4029540', 'type': 'Location', 'name': 'GroupDemoLocation',
- 'label': 'Location 2 [foo]', 'groupNames': [ 'LocationGroup' ] },
- ], 'state': 'NULL', 'type': 'Group', 'name': 'LocationGroup', 'label': 'Location Group',
- 'tags': [ "Lighting", "Switchable", "Timestamp", "foobar" ] }
+ { 'state': '52.5200066,13.4029540', 'type': 'Location', 'name': 'GroupDemoLocation',
+ 'label': 'Location 1', 'groupNames': [ 'LocationGroup' ] },
+ { 'state': '52.5200066,13.4029540', 'type': 'Location', 'name': 'GroupDemoLocation',
+ 'label': 'Location 2 [foo]', 'groupNames': [ 'LocationGroup' ] },
+ ],
+ 'state': 'NULL', 'type': 'Group', 'name': 'LocationGroup', 'label': 'Location Group',
+ 'tags': [ "Lighting", "Switchable", "Timestamp", "foobar" ]
+ }
""".trimIndent()
)
private val itemAsJsonObject = JSONObject(
"""
- { 'state': 'NULL',
- 'type': 'Group',
- 'name': 'LocationGroup',
- 'label': 'Location Group',
- 'tags': [ "Lighting", "Switchable", "Timestamp", "foobar" ],
- 'category': 'Switch' }
+ { 'state': 'NULL',
+ 'type': 'Group',
+ 'name': 'LocationGroup',
+ 'label': 'Location Group',
+ 'tags': [ "Lighting", "Switchable", "Timestamp", "foobar" ],
+ 'category': 'Switch'
+ }
""".trimIndent()
)
private val itemAsJsonObjectWithoutLabel = JSONObject(
"""
- { 'state': 'NULL',
- 'type': 'Group',
- 'name': 'LocationGroup' }
+ { 'state': 'NULL',
+ 'type': 'Group',
+ 'name': 'LocationGroup'
+ }
""".trimIndent()
)
private val itemWithCommandOptions = JSONObject(
"""
- { 'state': 'NULL',
- 'type': 'Number',
- 'name': 'Foo',
- 'commandDescription': {
- 'commandOptions': [
- {
- 'command': '1',
- 'label': 'One',
- 'icon': 'switch',
- 'row': 1,
- 'column': 2
- },
- {
- 'command': '2',
- 'label': 'Two'
- },
- ]
- }
+ { 'state': 'NULL',
+ 'type': 'Number',
+ 'name': 'Foo',
+ 'commandDescription': {
+ 'commandOptions': [
+ { 'command': '1', 'label': 'One', 'icon': 'switch', 'row': 1, 'column': 2 },
+ { 'command': '2', 'label': 'Two' },
+ ]
}
+ }
""".trimIndent()
)
}
diff --git a/mobile/src/test/java/org/openhab/habdroid/model/SitemapTest.kt b/mobile/src/test/java/org/openhab/habdroid/model/SitemapTest.kt
index 6eac45d692..085921719f 100644
--- a/mobile/src/test/java/org/openhab/habdroid/model/SitemapTest.kt
+++ b/mobile/src/test/java/org/openhab/habdroid/model/SitemapTest.kt
@@ -27,32 +27,53 @@ class SitemapTest {
@Before
@Throws(JSONException::class)
fun initSitemaps() {
- demoSitemapWithLabel = JSONObject("""
- { 'name': 'demo','label': 'Main Menu', 'link': 'http://demo.openhab.org:8080/rest/sitemaps/demo',
- 'homepage': { 'link': 'http://demo.openhab.org:8080/rest/sitemaps/demo/demo', 'leaf': false,
- 'timeout': false,'widgets': [] }}"
- """.trimIndent()).toSitemap()!!
+ demoSitemapWithLabel = JSONObject(
+ """
+ { 'name': 'demo',
+ 'label': 'Main Menu',
+ 'link': 'http://demo.openhab.org:8080/rest/sitemaps/demo',
+ 'homepage': {
+ 'link': 'http://demo.openhab.org:8080/rest/sitemaps/demo/demo', 'leaf': false,
+ 'timeout': false,'widgets': []
+ }
+ }
+ """.trimIndent()
+ ).toSitemap()!!
- homeSitemapWithoutLabel = JSONObject("""
- { 'name': 'home', 'icon': 'home', 'link': 'http://demo.openhab.org:8080/rest/sitemaps/home',
- 'homepage': { 'link': 'http://demo.openhab.org:8080/rest/sitemaps/home/home', 'leaf': true,
- 'timeout': false, 'widgets': [] }}"
- """.trimIndent()).toSitemap()!!
+ homeSitemapWithoutLabel = JSONObject(
+ """
+ { 'name': 'home',
+ 'icon': 'home',
+ 'link': 'http://demo.openhab.org:8080/rest/sitemaps/home',
+ 'homepage': {
+ 'link': 'http://demo.openhab.org:8080/rest/sitemaps/home/home', 'leaf': true,
+ 'timeout': false, 'widgets': []
+ }
+ }
+ """.trimIndent()
+ ).toSitemap()!!
}
@Test
fun sitemapLabelNonNull() {
assertEquals("Main Menu", demoSitemapWithLabel.label)
- assertEquals("Sitemap without explicit label should return name for getLabel",
- "home", homeSitemapWithoutLabel.label)
+ assertEquals(
+ "Sitemap without explicit label should return name for getLabel",
+ "home",
+ homeSitemapWithoutLabel.label
+ )
}
@Test
fun testGetHomepageLink() {
- assertEquals("http://demo.openhab.org:8080/rest/sitemaps/demo/demo",
- demoSitemapWithLabel.homepageLink)
- assertEquals("http://demo.openhab.org:8080/rest/sitemaps/home/home",
- homeSitemapWithoutLabel.homepageLink)
+ assertEquals(
+ "http://demo.openhab.org:8080/rest/sitemaps/demo/demo",
+ demoSitemapWithLabel.homepageLink
+ )
+ assertEquals(
+ "http://demo.openhab.org:8080/rest/sitemaps/home/home",
+ homeSitemapWithoutLabel.homepageLink
+ )
}
@Test
diff --git a/mobile/src/test/java/org/openhab/habdroid/model/WidgetTest.kt b/mobile/src/test/java/org/openhab/habdroid/model/WidgetTest.kt
index 383301f786..f64452caed 100644
--- a/mobile/src/test/java/org/openhab/habdroid/model/WidgetTest.kt
+++ b/mobile/src/test/java/org/openhab/habdroid/model/WidgetTest.kt
@@ -87,7 +87,7 @@ class WidgetTest {
assertEquals(
"If data saver is active, icon paths must not contain a state",
"icon/rollershutter?format=SVG&anyFormat=true&iconset=mdi",
- sut3[3].icon?.toUrl(false, IconFormat.Svg, 64 )
+ sut3[3].icon?.toUrl(false, IconFormat.Svg, 64)
)
}
@@ -113,8 +113,11 @@ class WidgetTest {
@Test
fun testGetRefresh() {
assertEquals(1000, sut1[0].refresh)
- assertEquals("Min refresh is 100, object has set refresh to 10",
- 100, sut2[0].refresh)
+ assertEquals(
+ "Min refresh is 100, object has set refresh to 10",
+ 100,
+ sut2[0].refresh
+ )
assertEquals("Missing refresh should equal 0", 0, sut3[0].refresh)
}
@@ -236,7 +239,8 @@ class WidgetTest {
@Throws(Exception::class)
private fun createXmlNode(): Node {
- val xml = """
+ val xml =
+ """
demo
Group
@@ -276,7 +280,7 @@ class WidgetTest {
Switch
"
- """.trimIndent()
+ """.trimIndent()
val dbf = DocumentBuilderFactory.newInstance()
val builder = dbf.newDocumentBuilder()
val document = builder.parse(InputSource(StringReader(xml)))
@@ -295,7 +299,8 @@ class WidgetTest {
@Throws(Exception::class)
private fun createJsonObject(id: Int): JSONObject {
val json: String = when (id) {
- 1 -> """
+ 1 ->
+ """
{ 'widgetId': 'demo',
'type': 'Group',
'label': 'Group1',
@@ -333,7 +338,8 @@ class WidgetTest {
'widgets': [ { 'widgetId': 'demo11', 'type': 'Switch' } ]
}
"""
- 2 -> """
+ 2 ->
+ """
{
'widgetId': 'demo',
'type': 'Group',
@@ -362,7 +368,8 @@ class WidgetTest {
},
}
"""
- 3 -> """
+ 3 ->
+ """
{
'widgetId': '0202_0',
'type': 'Frame',
diff --git a/mobile/src/test/java/org/openhab/habdroid/util/PreferencesUtilTest.kt b/mobile/src/test/java/org/openhab/habdroid/util/PreferencesUtilTest.kt
index 890b94bb7e..483f102b05 100644
--- a/mobile/src/test/java/org/openhab/habdroid/util/PreferencesUtilTest.kt
+++ b/mobile/src/test/java/org/openhab/habdroid/util/PreferencesUtilTest.kt
@@ -40,8 +40,11 @@ class PreferencesUtilTest {
assertEquals("For an empty string it should return an empty string", "", beautifyUrl(""))
assertEquals("URLs without scheme should treated like one with", "myopenHAB", beautifyUrl("myopenhab.org"))
assertEquals("For myopenhab.org it should return myopenHAB", "myopenHAB", beautifyUrl("https://myopenhab.org"))
- assertEquals("For home.myopenhab.org it should return myopenHAB", "myopenHAB",
- beautifyUrl("https://home.myopenhab.org"))
+ assertEquals(
+ "For home.myopenhab.org it should return myopenHAB",
+ "myopenHAB",
+ beautifyUrl("https://home.myopenhab.org")
+ )
assertEquals("not.myopenhab.org", beautifyUrl("https://not.myopenhab.org"))
assertEquals("notmyopenhab.org", beautifyUrl("https://notmyopenhab.org"))
assertEquals("myopenhab.wrong_tld", beautifyUrl("https://myopenhab.WRONG_TLD"))
diff --git a/mobile/src/test/java/org/openhab/habdroid/util/UtilTest.kt b/mobile/src/test/java/org/openhab/habdroid/util/UtilTest.kt
index 10172ab20a..c3e8edfb32 100644
--- a/mobile/src/test/java/org/openhab/habdroid/util/UtilTest.kt
+++ b/mobile/src/test/java/org/openhab/habdroid/util/UtilTest.kt
@@ -37,7 +37,8 @@ class UtilTest {
private val sitemapOH1Document: Document
@Throws(ParserConfigurationException::class, IOException::class, SAXException::class)
get() {
- val xml = """
+ val xml =
+ """
@@ -141,10 +142,16 @@ class UtilTest {
assertEquals("Empty string should return null", null, "".toNormalizedUrl())
assertEquals("Null should return null", null, null.toNormalizedUrl())
- assertEquals("Url with one slash after the protocol should be fixed",
- "http://localhost/", "http:/localhost/".toNormalizedUrl())
- assertEquals("Url with invalid protocol should return null",
- null, "http//localhost/".toNormalizedUrl())
+ assertEquals(
+ "Url with one slash after the protocol should be fixed",
+ "http://localhost/",
+ "http:/localhost/".toNormalizedUrl()
+ )
+ assertEquals(
+ "Url with invalid protocol should return null",
+ null,
+ "http//localhost/".toNormalizedUrl()
+ )
}
@Test
@@ -222,14 +229,22 @@ class UtilTest {
@Test
fun sitemapExists() {
- assertTrue("Sitemap \"demo\" is a \"normal\" one and exists",
- createJsonArray(1).toSitemapList().any { sitemap -> sitemap.name == "demo" })
- assertFalse("Sitemap \"_default\" exists on the server, but isn't the only one => don't display it in the app.",
- createJsonArray(1).toSitemapList().any { sitemap -> sitemap.name == "_default" })
- assertFalse("Sitemap \"_default\" exists on the server, but isn't the only one => don't display it in the app.",
- createJsonArray(2).toSitemapList().any { sitemap -> sitemap.name == "_default" })
- assertTrue("Sitemap \"_default\" exists on the server and is the only one => display it in the app.",
- createJsonArray(3).toSitemapList().any { sitemap -> sitemap.name == "_default" })
+ assertTrue(
+ "Sitemap \"demo\" is a \"normal\" one and exists",
+ createJsonArray(1).toSitemapList().any { sitemap -> sitemap.name == "demo" }
+ )
+ assertFalse(
+ "Sitemap \"_default\" exists on the server, but isn't the only one => don't display it in the app.",
+ createJsonArray(1).toSitemapList().any { sitemap -> sitemap.name == "_default" }
+ )
+ assertFalse(
+ "Sitemap \"_default\" exists on the server, but isn't the only one => don't display it in the app.",
+ createJsonArray(2).toSitemapList().any { sitemap -> sitemap.name == "_default" }
+ )
+ assertTrue(
+ "Sitemap \"_default\" exists on the server and is the only one => display it in the app.",
+ createJsonArray(3).toSitemapList().any { sitemap -> sitemap.name == "_default" }
+ )
}
/**
@@ -287,10 +302,12 @@ class UtilTest {
assertTrue(
"The exception is caused by CertPathValidatorException, so hasCause() should return true",
- e.hasCause(CertPathValidatorException::class.java))
+ e.hasCause(CertPathValidatorException::class.java)
+ )
assertFalse(
"The exception is not caused by ArrayIndexOutOfBoundsException, so hasCause() should return false",
- e.hasCause(ArrayIndexOutOfBoundsException::class.java))
+ e.hasCause(ArrayIndexOutOfBoundsException::class.java)
+ )
}
@Test
@@ -299,7 +316,9 @@ class UtilTest {
assertEquals("abc", "abc".obfuscate())
assertEquals(
"The function should not throw an exception, when string length is shorter than clearTextCharCount",
- "a", "a".obfuscate(10))
+ "a",
+ "a".obfuscate(10)
+ )
assertEquals("a**", "abc".obfuscate(1))
assertEquals("***", "abc".obfuscate(0))
}