diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/events/model/LocalEcho.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/events/model/LocalEcho.kt index ca75871cda..1dbee475e0 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/events/model/LocalEcho.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/events/model/LocalEcho.kt @@ -16,7 +16,7 @@ package im.vector.matrix.android.api.session.events.model -import java.util.* +import java.util.UUID object LocalEcho { diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DeviceListManager.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DeviceListManager.kt index 7f2a23e4c2..b2002f0916 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DeviceListManager.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DeviceListManager.kt @@ -66,7 +66,7 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM if (':' in userId) { try { synchronized(notReadyToRetryHS) { - res = !notReadyToRetryHS.contains(userId.substring(userId.lastIndexOf(":") + 1)) + res = !notReadyToRetryHS.contains(userId.substringAfterLast(':')) } } catch (e: Exception) { Timber.e(e, "## canRetryKeysDownload() failed") diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/OutgoingRoomKeyRequestManager.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/OutgoingRoomKeyRequestManager.kt index 89a27c9463..86e8a1825c 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/OutgoingRoomKeyRequestManager.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/OutgoingRoomKeyRequestManager.kt @@ -216,7 +216,7 @@ internal class OutgoingRoomKeyRequestManager @Inject constructor( sendMessageToDevices(requestMessage, request.recipients, request.requestId, object : MatrixCallback { private fun onDone(state: OutgoingRoomKeyRequest.RequestState) { if (request.state !== OutgoingRoomKeyRequest.RequestState.UNSENT) { - Timber.v("## sendOutgoingRoomKeyRequest() : Cannot update room key request from UNSENT as it was already updated to " + request.state) + Timber.v("## sendOutgoingRoomKeyRequest() : Cannot update room key request from UNSENT as it was already updated to ${request.state}") } else { request.state = state cryptoStore.updateOutgoingRoomKeyRequest(request) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/verification/DefaultSasVerificationService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/verification/DefaultSasVerificationService.kt index ca1157e583..e0cd47e0e0 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/verification/DefaultSasVerificationService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/verification/DefaultSasVerificationService.kt @@ -43,6 +43,7 @@ import im.vector.matrix.android.internal.util.MatrixCoroutineDispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import timber.log.Timber +import java.lang.Exception import java.util.UUID import javax.inject.Inject import kotlin.collections.HashMap @@ -166,72 +167,59 @@ internal class DefaultSasVerificationService @Inject constructor(private val cre return } // Download device keys prior to everything - checkKeysAreDownloaded( - otherUserId!!, - startReq, - success = { - Timber.v("## SAS onStartRequestReceived ${startReq.transactionID!!}") - val tid = startReq.transactionID!! - val existing = getExistingTransaction(otherUserId, tid) - val existingTxs = getExistingTransactionsForUser(otherUserId) - if (existing != null) { - // should cancel both! - Timber.v("## SAS onStartRequestReceived - Request exist with same if ${startReq.transactionID!!}") - existing.cancel(CancelCode.UnexpectedMessage) - cancelTransaction(tid, otherUserId, startReq.fromDevice!!, CancelCode.UnexpectedMessage) - } else if (existingTxs?.isEmpty() == false) { - Timber.v("## SAS onStartRequestReceived - There is already a transaction with this user ${startReq.transactionID!!}") - // Multiple keyshares between two devices: any two devices may only have at most one key verification in flight at a time. - existingTxs.forEach { - it.cancel(CancelCode.UnexpectedMessage) - } - cancelTransaction(tid, otherUserId, startReq.fromDevice!!, CancelCode.UnexpectedMessage) - } else { - // Ok we can create - if (KeyVerificationStart.VERIF_METHOD_SAS == startReq.method) { - Timber.v("## SAS onStartRequestReceived - request accepted ${startReq.transactionID!!}") - val tx = IncomingSASVerificationTransaction( - this, - setDeviceVerificationAction, - credentials, - cryptoStore, - sendToDeviceTask, - taskExecutor, - myDeviceInfoHolder.get().myDevice.fingerprint()!!, - startReq.transactionID!!, - otherUserId) - addTransaction(tx) - tx.acceptToDeviceEvent(otherUserId, startReq) - } else { - Timber.e("## SAS onStartRequestReceived - unknown method ${startReq.method}") - cancelTransaction(tid, otherUserId, startReq.fromDevice - ?: event.getSenderKey()!!, CancelCode.UnknownMethod) - } - } - }, - error = { - cancelTransaction(startReq.transactionID!!, otherUserId, startReq.fromDevice!!, CancelCode.UnexpectedMessage) - }) + if (checkKeysAreDownloaded(otherUserId!!, startReq) != null) { + Timber.v("## SAS onStartRequestReceived ${startReq.transactionID!!}") + val tid = startReq.transactionID!! + val existing = getExistingTransaction(otherUserId, tid) + val existingTxs = getExistingTransactionsForUser(otherUserId) + if (existing != null) { + // should cancel both! + Timber.v("## SAS onStartRequestReceived - Request exist with same if ${startReq.transactionID!!}") + existing.cancel(CancelCode.UnexpectedMessage) + cancelTransaction(tid, otherUserId, startReq.fromDevice!!, CancelCode.UnexpectedMessage) + } else if (existingTxs?.isEmpty() == false) { + Timber.v("## SAS onStartRequestReceived - There is already a transaction with this user ${startReq.transactionID!!}") + // Multiple keyshares between two devices: any two devices may only have at most one key verification in flight at a time. + existingTxs.forEach { + it.cancel(CancelCode.UnexpectedMessage) + } + cancelTransaction(tid, otherUserId, startReq.fromDevice!!, CancelCode.UnexpectedMessage) + } else { + // Ok we can create + if (KeyVerificationStart.VERIF_METHOD_SAS == startReq.method) { + Timber.v("## SAS onStartRequestReceived - request accepted ${startReq.transactionID!!}") + val tx = IncomingSASVerificationTransaction( + this, + setDeviceVerificationAction, + credentials, + cryptoStore, + sendToDeviceTask, + taskExecutor, + myDeviceInfoHolder.get().myDevice.fingerprint()!!, + startReq.transactionID!!, + otherUserId) + addTransaction(tx) + tx.acceptToDeviceEvent(otherUserId, startReq) + } else { + Timber.e("## SAS onStartRequestReceived - unknown method ${startReq.method}") + cancelTransaction(tid, otherUserId, startReq.fromDevice + ?: event.getSenderKey()!!, CancelCode.UnknownMethod) + } + } + } else { + cancelTransaction(startReq.transactionID!!, otherUserId, startReq.fromDevice!!, CancelCode.UnexpectedMessage) + } } private suspend fun checkKeysAreDownloaded(otherUserId: String, - startReq: KeyVerificationStart, - success: (MXUsersDevicesMap) -> Unit, - error: () -> Unit) { - runCatching { - deviceListManager.downloadKeys(listOf(otherUserId), true) - }.fold( - { - if (it.getUserDeviceIds(otherUserId)?.contains(startReq.fromDevice) == true) { - success(it) - } else { - error() - } - }, - { - error() - } - ) + startReq: KeyVerificationStart): MXUsersDevicesMap? { + return try { + val keys = deviceListManager.downloadKeys(listOf(otherUserId), true) + val deviceIds = keys.getUserDeviceIds(otherUserId) ?: return null + keys.takeIf { deviceIds.contains(startReq.fromDevice) } + } catch (e: Exception) { + null + } } private suspend fun onCancelReceived(event: Event) { @@ -342,10 +330,8 @@ internal class DefaultSasVerificationService @Inject constructor(private val cre private fun addTransaction(tx: VerificationTransaction) { tx.otherUserId.let { otherUserId -> synchronized(txMap) { - if (txMap[otherUserId] == null) { - txMap[otherUserId] = HashMap() - } - txMap[otherUserId]?.set(tx.transactionId, tx) + val txInnerMap = txMap.getOrPut(otherUserId) { HashMap() } + txInnerMap[tx.transactionId] = tx dispatchTxAdded(tx) tx.addListener(this) } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/database/mapper/RoomSummaryMapper.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/database/mapper/RoomSummaryMapper.kt index 5db062b000..0d0143d318 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/database/mapper/RoomSummaryMapper.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/database/mapper/RoomSummaryMapper.kt @@ -22,7 +22,7 @@ import im.vector.matrix.android.api.session.room.model.RoomSummary import im.vector.matrix.android.api.session.room.model.tag.RoomTag import im.vector.matrix.android.internal.crypto.algorithms.olm.OlmDecryptionResult import im.vector.matrix.android.internal.database.model.RoomSummaryEntity -import java.util.* +import java.util.UUID import javax.inject.Inject internal class RoomSummaryMapper @Inject constructor( diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/NetworkConnectivityChecker.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/NetworkConnectivityChecker.kt index bfc37d733d..3d850c223a 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/NetworkConnectivityChecker.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/NetworkConnectivityChecker.kt @@ -22,7 +22,7 @@ import com.novoda.merlin.MerlinsBeard import im.vector.matrix.android.internal.di.MatrixScope import im.vector.matrix.android.internal.util.BackgroundDetectionObserver import timber.log.Timber -import java.util.* +import java.util.Collections import javax.inject.Inject import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/homeserver/DefaultGetHomeServerCapabilitiesTask.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/homeserver/DefaultGetHomeServerCapabilitiesTask.kt index 98ab0b5389..45571286b9 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/homeserver/DefaultGetHomeServerCapabilitiesTask.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/homeserver/DefaultGetHomeServerCapabilitiesTask.kt @@ -23,7 +23,7 @@ import im.vector.matrix.android.internal.database.query.getOrCreate import im.vector.matrix.android.internal.network.executeRequest import im.vector.matrix.android.internal.task.Task import im.vector.matrix.android.internal.util.awaitTransaction -import java.util.* +import java.util.Date import javax.inject.Inject internal interface GetHomeServerCapabilitiesTask : Task diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/pushers/DefaultPusherService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/pushers/DefaultPusherService.kt index 243e4d4b03..8c7e9fb263 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/pushers/DefaultPusherService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/pushers/DefaultPusherService.kt @@ -32,7 +32,7 @@ import im.vector.matrix.android.internal.task.configureWith import im.vector.matrix.android.internal.worker.WorkManagerUtil import im.vector.matrix.android.internal.worker.WorkManagerUtil.matrixOneTimeWorkRequestBuilder import im.vector.matrix.android.internal.worker.WorkerParamsFactory -import java.util.* +import java.util.UUID import java.util.concurrent.TimeUnit import javax.inject.Inject diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/room/send/LocalEchoEventFactory.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/room/send/LocalEchoEventFactory.kt index 49c813ece6..a9406c8bff 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/room/send/LocalEchoEventFactory.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/room/send/LocalEchoEventFactory.kt @@ -39,7 +39,7 @@ import im.vector.matrix.android.internal.session.room.RoomSummaryUpdater import im.vector.matrix.android.internal.util.StringProvider import org.commonmark.parser.Parser import org.commonmark.renderer.html.HtmlRenderer -import java.util.* +import java.util.UUID import javax.inject.Inject /** diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/room/timeline/DefaultTimeline.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/room/timeline/DefaultTimeline.kt index 606c20e8cb..4127e43540 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/room/timeline/DefaultTimeline.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/room/timeline/DefaultTimeline.kt @@ -52,7 +52,8 @@ import io.realm.RealmQuery import io.realm.RealmResults import io.realm.Sort import timber.log.Timber -import java.util.* +import java.util.Collections +import java.util.UUID import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import kotlin.collections.ArrayList diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/securestorage/SecretStoringUtils.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/securestorage/SecretStoringUtils.kt index 260f98d97f..592191975e 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/securestorage/SecretStoringUtils.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/securestorage/SecretStoringUtils.kt @@ -31,7 +31,7 @@ import java.security.KeyPairGenerator import java.security.KeyStore import java.security.KeyStoreException import java.security.SecureRandom -import java.util.* +import java.util.Calendar import javax.crypto.* import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.IvParameterSpec diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/util/CompatUtil.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/util/CompatUtil.kt index 058a862bc8..2df2bd2bf2 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/util/CompatUtil.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/util/CompatUtil.kt @@ -36,7 +36,7 @@ import java.security.* import java.security.cert.CertificateException import java.security.spec.AlgorithmParameterSpec import java.security.spec.RSAKeyGenParameterSpec -import java.util.* +import java.util.Calendar import java.util.zip.GZIPOutputStream import javax.crypto.* import javax.crypto.spec.GCMParameterSpec diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/util/StringUtils.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/util/StringUtils.kt index 4a46a43f03..31da372bbe 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/util/StringUtils.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/util/StringUtils.kt @@ -18,7 +18,7 @@ package im.vector.matrix.android.internal.util import im.vector.matrix.android.api.MatrixPatterns import timber.log.Timber -import java.util.* +import java.util.Locale /** * Convert a string to an UTF8 String diff --git a/vector/src/main/java/im/vector/riotx/VectorApplication.kt b/vector/src/main/java/im/vector/riotx/VectorApplication.kt index b1fd6a8485..20a17e55d4 100644 --- a/vector/src/main/java/im/vector/riotx/VectorApplication.kt +++ b/vector/src/main/java/im/vector/riotx/VectorApplication.kt @@ -55,7 +55,8 @@ import im.vector.riotx.features.version.VersionProvider import im.vector.riotx.push.fcm.FcmHelper import timber.log.Timber import java.text.SimpleDateFormat -import java.util.* +import java.util.Date +import java.util.Locale import javax.inject.Inject class VectorApplication : Application(), HasVectorInjector, MatrixConfiguration.Provider, androidx.work.Configuration.Provider { diff --git a/vector/src/main/java/im/vector/riotx/core/files/FileSaver.kt b/vector/src/main/java/im/vector/riotx/core/files/FileSaver.kt index c1f58306a4..677f7894e8 100644 --- a/vector/src/main/java/im/vector/riotx/core/files/FileSaver.kt +++ b/vector/src/main/java/im/vector/riotx/core/files/FileSaver.kt @@ -30,15 +30,10 @@ import java.io.File */ @WorkerThread fun writeToFile(str: String, file: File): Try { - return Try { - val sink = file.sink() - - val bufferedSink = sink.buffer() - - bufferedSink.writeString(str, Charsets.UTF_8) - - bufferedSink.close() - sink.close() + return Try { + file.sink().buffer().use { + it.writeString(str, Charsets.UTF_8) + } } } @@ -47,15 +42,10 @@ fun writeToFile(str: String, file: File): Try { */ @WorkerThread fun writeToFile(data: ByteArray, file: File): Try { - return Try { - val sink = file.sink() - - val bufferedSink = sink.buffer() - - bufferedSink.write(data) - - bufferedSink.close() - sink.close() + return Try { + file.sink().buffer().use { + it.write(data) + } } } diff --git a/vector/src/main/java/im/vector/riotx/core/images/ImageTools.kt b/vector/src/main/java/im/vector/riotx/core/images/ImageTools.kt index b6ae2be20b..84cba7392f 100644 --- a/vector/src/main/java/im/vector/riotx/core/images/ImageTools.kt +++ b/vector/src/main/java/im/vector/riotx/core/images/ImageTools.kt @@ -17,7 +17,6 @@ package im.vector.riotx.core.images import android.content.Context -import android.database.Cursor import android.net.Uri import android.provider.MediaStore import androidx.exifinterface.media.ExifInterface @@ -37,26 +36,24 @@ class ImageTools @Inject constructor(private val context: Context) { if (uri.scheme == "content") { val proj = arrayOf(MediaStore.Images.Media.DATA) - var cursor: Cursor? = null try { - cursor = context.contentResolver.query(uri, proj, null, null, null) - if (cursor != null && cursor.count > 0) { - cursor.moveToFirst() - val idxData = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) - val path = cursor.getString(idxData) - if (path.isNullOrBlank()) { - Timber.w("Cannot find path in media db for uri $uri") - return orientation + val cursor = context.contentResolver.query(uri, proj, null, null, null) + cursor?.use { + if (it.moveToFirst()) { + val idxData = it.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) + val path = it.getString(idxData) + if (path.isNullOrBlank()) { + Timber.w("Cannot find path in media db for uri $uri") + return orientation + } + val exif = ExifInterface(path) + orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED) } - val exif = ExifInterface(path) - orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED) } } catch (e: Exception) { // eg SecurityException from com.google.android.apps.photos.content.GooglePhotosImageProvider URIs // eg IOException from trying to parse the returned path as a file when it is an http uri. Timber.e(e, "Cannot get orientation for bitmap") - } finally { - cursor?.close() } } else if (uri.scheme == "file") { try { diff --git a/vector/src/main/java/im/vector/riotx/core/intent/Filename.kt b/vector/src/main/java/im/vector/riotx/core/intent/Filename.kt index 9e9f0ae508..2b6740f62f 100644 --- a/vector/src/main/java/im/vector/riotx/core/intent/Filename.kt +++ b/vector/src/main/java/im/vector/riotx/core/intent/Filename.kt @@ -17,28 +17,17 @@ package im.vector.riotx.core.intent import android.content.Context -import android.database.Cursor import android.net.Uri import android.provider.OpenableColumns fun getFilenameFromUri(context: Context?, uri: Uri): String? { - var result: String? = null if (context != null && uri.scheme == "content") { - val cursor: Cursor? = context.contentResolver.query(uri, null, null, null, null) - try { - if (cursor != null && cursor.moveToFirst()) { - result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)) + val cursor = context.contentResolver.query(uri, null, null, null, null) + cursor?.use { + if (it.moveToFirst()) { + return it.getString(it.getColumnIndex(OpenableColumns.DISPLAY_NAME)) } - } finally { - cursor?.close() } } - if (result == null) { - result = uri.path - val cut = result?.lastIndexOf('/') ?: -1 - if (cut != -1) { - result = result?.substring(cut + 1) - } - } - return result + return uri.path?.substringAfterLast('/') } diff --git a/vector/src/main/java/im/vector/riotx/core/linkify/VectorAutoLinkPatterns.kt b/vector/src/main/java/im/vector/riotx/core/linkify/VectorAutoLinkPatterns.kt index e6eb886e02..ae4131b5e9 100644 --- a/vector/src/main/java/im/vector/riotx/core/linkify/VectorAutoLinkPatterns.kt +++ b/vector/src/main/java/im/vector/riotx/core/linkify/VectorAutoLinkPatterns.kt @@ -15,8 +15,6 @@ */ package im.vector.riotx.core.linkify -import java.util.regex.Pattern - /** * Better support for geo URi */ @@ -26,7 +24,7 @@ object VectorAutoLinkPatterns { private const val LAT_OR_LONG_OR_ALT_NUMBER = "-?\\d+(?:\\.\\d+)?" private const val COORDINATE_SYSTEM = ";crs=[\\w-]+" - val GEO_URI: Pattern = Pattern.compile("(?:geo:)?" + + val GEO_URI: Regex = Regex("(?:geo:)?" + "(" + LAT_OR_LONG_OR_ALT_NUMBER + ")" + "," + "(" + LAT_OR_LONG_OR_ALT_NUMBER + ")" + @@ -35,5 +33,5 @@ object VectorAutoLinkPatterns { "(?:" + ";u=\\d+(?:\\.\\d+)?" + ")?" + // uncertainty in meters "(?:" + ";[\\w-]+=(?:[\\w-_.!~*'()]|%[\\da-f][\\da-f])+" + // dafuk - ")*", Pattern.CASE_INSENSITIVE) + ")*", RegexOption.IGNORE_CASE) } diff --git a/vector/src/main/java/im/vector/riotx/core/linkify/VectorLinkify.kt b/vector/src/main/java/im/vector/riotx/core/linkify/VectorLinkify.kt index 358fff6092..99b0316cbe 100644 --- a/vector/src/main/java/im/vector/riotx/core/linkify/VectorLinkify.kt +++ b/vector/src/main/java/im/vector/riotx/core/linkify/VectorLinkify.kt @@ -19,7 +19,6 @@ import android.text.Spannable import android.text.style.URLSpan import android.text.util.Linkify import androidx.core.text.util.LinkifyCompat -import java.util.* object VectorLinkify { /** @@ -95,7 +94,7 @@ object VectorLinkify { createdSpans.add(LinkSpec(URLSpan(urlSpan.url), start, end)) } - LinkifyCompat.addLinks(spannable, VectorAutoLinkPatterns.GEO_URI, "geo:", arrayOf("geo:"), geoMatchFilter, null) + LinkifyCompat.addLinks(spannable, VectorAutoLinkPatterns.GEO_URI.toPattern(), "geo:", arrayOf("geo:"), geoMatchFilter, null) spannable.forEachSpanIndexed { _, urlSpan, start, end -> spannable.removeSpan(urlSpan) createdSpans.add(LinkSpec(URLSpan(urlSpan.url), start, end)) @@ -108,7 +107,7 @@ object VectorLinkify { } private fun pruneOverlaps(links: ArrayList) { - Collections.sort(links, COMPARATOR) + links.sortWith(COMPARATOR) var len = links.size var i = 0 while (i < len - 1) { diff --git a/vector/src/main/java/im/vector/riotx/core/platform/VectorBaseBottomSheetDialogFragment.kt b/vector/src/main/java/im/vector/riotx/core/platform/VectorBaseBottomSheetDialogFragment.kt index 8d40d55a7a..1b07d739b5 100644 --- a/vector/src/main/java/im/vector/riotx/core/platform/VectorBaseBottomSheetDialogFragment.kt +++ b/vector/src/main/java/im/vector/riotx/core/platform/VectorBaseBottomSheetDialogFragment.kt @@ -30,7 +30,7 @@ import com.google.android.material.bottomsheet.BottomSheetDialogFragment import im.vector.riotx.core.di.DaggerScreenComponent import im.vector.riotx.core.di.ScreenComponent import im.vector.riotx.core.utils.DimensionConverter -import java.util.* +import java.util.UUID /** * Add MvRx capabilities to bottomsheetdialog (like BaseMvRxFragment) diff --git a/vector/src/main/java/im/vector/riotx/core/pushers/PushersManager.kt b/vector/src/main/java/im/vector/riotx/core/pushers/PushersManager.kt index 41287d4e38..e2c08a1fe8 100644 --- a/vector/src/main/java/im/vector/riotx/core/pushers/PushersManager.kt +++ b/vector/src/main/java/im/vector/riotx/core/pushers/PushersManager.kt @@ -22,8 +22,9 @@ import im.vector.riotx.core.di.ActiveSessionHolder import im.vector.riotx.core.resources.AppNameProvider import im.vector.riotx.core.resources.LocaleProvider import im.vector.riotx.core.resources.StringProvider -import java.util.* +import java.util.UUID import javax.inject.Inject +import kotlin.math.abs private const val DEFAULT_PUSHER_FILE_TAG = "mobile" @@ -36,7 +37,7 @@ class PushersManager @Inject constructor( fun registerPusherWithFcmKey(pushKey: String): UUID { val currentSession = activeSessionHolder.getActiveSession() - var profileTag = DEFAULT_PUSHER_FILE_TAG + "_" + Math.abs(currentSession.myUserId.hashCode()) + val profileTag = DEFAULT_PUSHER_FILE_TAG + "_" + abs(currentSession.myUserId.hashCode()) return currentSession.addHttpPusher( pushKey, diff --git a/vector/src/main/java/im/vector/riotx/core/resources/LocaleProvider.kt b/vector/src/main/java/im/vector/riotx/core/resources/LocaleProvider.kt index 74861a65cc..c78a5a99b8 100644 --- a/vector/src/main/java/im/vector/riotx/core/resources/LocaleProvider.kt +++ b/vector/src/main/java/im/vector/riotx/core/resources/LocaleProvider.kt @@ -18,7 +18,7 @@ package im.vector.riotx.core.resources import android.content.res.Resources import androidx.core.os.ConfigurationCompat -import java.util.* +import java.util.Locale import javax.inject.Inject class LocaleProvider @Inject constructor(private val resources: Resources) { diff --git a/vector/src/main/java/im/vector/riotx/core/utils/DebouncedClickListener.kt b/vector/src/main/java/im/vector/riotx/core/utils/DebouncedClickListener.kt index 958f642565..230b11f14d 100644 --- a/vector/src/main/java/im/vector/riotx/core/utils/DebouncedClickListener.kt +++ b/vector/src/main/java/im/vector/riotx/core/utils/DebouncedClickListener.kt @@ -16,7 +16,7 @@ package im.vector.riotx.core.utils import android.view.View -import java.util.* +import java.util.WeakHashMap /** * Simple Debounced OnClickListener diff --git a/vector/src/main/java/im/vector/riotx/core/utils/Emoji.kt b/vector/src/main/java/im/vector/riotx/core/utils/Emoji.kt index c65fcafb16..a5babcc885 100644 --- a/vector/src/main/java/im/vector/riotx/core/utils/Emoji.kt +++ b/vector/src/main/java/im/vector/riotx/core/utils/Emoji.kt @@ -59,9 +59,10 @@ fun initKnownEmojiHashSet(context: Context, done: (() -> Unit)? = null) { val jsonAdapter = moshi.adapter(EmojiDataSource.EmojiData::class.java) val inputAsString = input.bufferedReader().use { it.readText() } val source = jsonAdapter.fromJson(inputAsString) - knownEmojiSet = HashSet() - source?.emojis?.values?.forEach { - knownEmojiSet?.add(it.emojiString()) + knownEmojiSet = HashSet().also { + source?.emojis?.mapTo(it) { (_, value) -> + value.emojiString() + } } done?.invoke() } diff --git a/vector/src/main/java/im/vector/riotx/core/utils/ExternalApplicationsUtil.kt b/vector/src/main/java/im/vector/riotx/core/utils/ExternalApplicationsUtil.kt index 9572b07216..78242d58de 100644 --- a/vector/src/main/java/im/vector/riotx/core/utils/ExternalApplicationsUtil.kt +++ b/vector/src/main/java/im/vector/riotx/core/utils/ExternalApplicationsUtil.kt @@ -32,7 +32,8 @@ import im.vector.riotx.R import timber.log.Timber import java.io.File import java.text.SimpleDateFormat -import java.util.* +import java.util.Date +import java.util.Locale /** * Open a url in the internet browser of the system diff --git a/vector/src/main/java/im/vector/riotx/core/utils/SystemUtils.kt b/vector/src/main/java/im/vector/riotx/core/utils/SystemUtils.kt index 12371fe72d..ba0b99762b 100644 --- a/vector/src/main/java/im/vector/riotx/core/utils/SystemUtils.kt +++ b/vector/src/main/java/im/vector/riotx/core/utils/SystemUtils.kt @@ -31,7 +31,7 @@ import im.vector.riotx.R import im.vector.riotx.features.notifications.NotificationUtils import im.vector.riotx.features.settings.VectorLocale import timber.log.Timber -import java.util.* +import java.util.Locale /** * Tells if the application ignores battery optimizations. diff --git a/vector/src/main/java/im/vector/riotx/core/utils/TextUtils.kt b/vector/src/main/java/im/vector/riotx/core/utils/TextUtils.kt index 0b5df0d2e0..75f6893c7c 100644 --- a/vector/src/main/java/im/vector/riotx/core/utils/TextUtils.kt +++ b/vector/src/main/java/im/vector/riotx/core/utils/TextUtils.kt @@ -19,7 +19,7 @@ package im.vector.riotx.core.utils import android.content.Context import android.os.Build import android.text.format.Formatter -import java.util.* +import java.util.TreeMap object TextUtils { diff --git a/vector/src/main/java/im/vector/riotx/features/configuration/VectorConfiguration.kt b/vector/src/main/java/im/vector/riotx/features/configuration/VectorConfiguration.kt index ec8f1c7fa2..adf8421842 100644 --- a/vector/src/main/java/im/vector/riotx/features/configuration/VectorConfiguration.kt +++ b/vector/src/main/java/im/vector/riotx/features/configuration/VectorConfiguration.kt @@ -24,7 +24,7 @@ import im.vector.riotx.features.settings.FontScale import im.vector.riotx.features.settings.VectorLocale import im.vector.riotx.features.themes.ThemeUtils import timber.log.Timber -import java.util.* +import java.util.Locale import javax.inject.Inject /** diff --git a/vector/src/main/java/im/vector/riotx/features/crypto/keys/KeysExporter.kt b/vector/src/main/java/im/vector/riotx/features/crypto/keys/KeysExporter.kt index 54e3a34744..9642c2d8c6 100644 --- a/vector/src/main/java/im/vector/riotx/features/crypto/keys/KeysExporter.kt +++ b/vector/src/main/java/im/vector/riotx/features/crypto/keys/KeysExporter.kt @@ -18,10 +18,10 @@ package im.vector.riotx.features.crypto.keys import android.content.Context import android.os.Environment -import arrow.core.Try import im.vector.matrix.android.api.MatrixCallback import im.vector.matrix.android.api.session.Session import im.vector.matrix.android.internal.extensions.foldToCallback +import im.vector.matrix.android.internal.util.awaitCallback import im.vector.riotx.core.files.addEntryToDownloadManager import im.vector.riotx.core.files.writeToFile import kotlinx.coroutines.Dispatchers @@ -36,28 +36,20 @@ class KeysExporter(private val session: Session) { * Export keys and return the file path with the callback */ fun export(context: Context, password: String, callback: MatrixCallback) { - session.exportRoomKeys(password, object : MatrixCallback { - override fun onSuccess(data: ByteArray) { - GlobalScope.launch(Dispatchers.Main) { - withContext(Dispatchers.IO) { - Try { - val parentDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) - val file = File(parentDir, "riotx-keys-" + System.currentTimeMillis() + ".txt") + GlobalScope.launch(Dispatchers.Main) { + runCatching { + val data = awaitCallback { session.exportRoomKeys(password, it) } + withContext(Dispatchers.IO) { + val parentDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + val file = File(parentDir, "riotx-keys-" + System.currentTimeMillis() + ".txt") - writeToFile(data, file) + writeToFile(data, file) - addEntryToDownloadManager(context, file, "text/plain") + addEntryToDownloadManager(context, file, "text/plain") - file.absolutePath - } - } - .foldToCallback(callback) + file.absolutePath } - } - - override fun onFailure(failure: Throwable) { - callback.onFailure(failure) - } - }) + }.foldToCallback(callback) + } } } diff --git a/vector/src/main/java/im/vector/riotx/features/crypto/keys/KeysImporter.kt b/vector/src/main/java/im/vector/riotx/features/crypto/keys/KeysImporter.kt index 74b2a86bc1..b60e25af04 100644 --- a/vector/src/main/java/im/vector/riotx/features/crypto/keys/KeysImporter.kt +++ b/vector/src/main/java/im/vector/riotx/features/crypto/keys/KeysImporter.kt @@ -18,10 +18,11 @@ package im.vector.riotx.features.crypto.keys import android.content.Context import android.net.Uri -import arrow.core.Try import im.vector.matrix.android.api.MatrixCallback import im.vector.matrix.android.api.session.Session import im.vector.matrix.android.internal.crypto.model.ImportRoomKeysResult +import im.vector.matrix.android.internal.extensions.foldToCallback +import im.vector.matrix.android.internal.util.awaitCallback import im.vector.riotx.core.intent.getMimeTypeFromUri import im.vector.riotx.core.resources.openResource import kotlinx.coroutines.Dispatchers @@ -41,8 +42,8 @@ class KeysImporter(private val session: Session) { password: String, callback: MatrixCallback) { GlobalScope.launch(Dispatchers.Main) { - withContext(Dispatchers.IO) { - Try { + runCatching { + withContext(Dispatchers.IO) { val resource = openResource(context, uri, mimetype ?: getMimeTypeFromUri(context, uri)) if (resource?.mContentStream == null) { @@ -51,33 +52,17 @@ class KeysImporter(private val session: Session) { val data: ByteArray try { - data = ByteArray(resource.mContentStream!!.available()) - resource.mContentStream!!.read(data) - resource.mContentStream!!.close() - - data + data = resource.mContentStream!!.use { it.readBytes() } } catch (e: Exception) { - try { - resource.mContentStream!!.close() - } catch (e2: Exception) { - Timber.e(e2, "## importKeys()") - } - + Timber.e(e, "## importKeys()") throw e } + + awaitCallback { + session.importRoomKeys(data, password, null, it) + } } - } - .fold( - { - callback.onFailure(it) - }, - { byteArray -> - session.importRoomKeys(byteArray, - password, - null, - callback) - } - ) + }.foldToCallback(callback) } } } diff --git a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/settings/KeysBackupSettingsRecyclerViewController.kt b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/settings/KeysBackupSettingsRecyclerViewController.kt index 6b01a7dffa..7b60cb2f9b 100644 --- a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/settings/KeysBackupSettingsRecyclerViewController.kt +++ b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/settings/KeysBackupSettingsRecyclerViewController.kt @@ -31,7 +31,7 @@ import im.vector.riotx.core.epoxy.loadingItem import im.vector.riotx.core.resources.StringProvider import im.vector.riotx.core.ui.list.GenericItem import im.vector.riotx.core.ui.list.genericItem -import java.util.* +import java.util.UUID import javax.inject.Inject class KeysBackupSettingsRecyclerViewController @Inject constructor(private val stringProvider: StringProvider, diff --git a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/setup/KeysBackupSetupStep3Fragment.kt b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/setup/KeysBackupSetupStep3Fragment.kt index 7b61ca2c0f..a5cc0510da 100644 --- a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/setup/KeysBackupSetupStep3Fragment.kt +++ b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/setup/KeysBackupSetupStep3Fragment.kt @@ -170,8 +170,8 @@ class KeysBackupSetupStep3Fragment : VectorBaseFragment() { private fun exportRecoveryKeyToFile(data: String) { GlobalScope.launch(Dispatchers.Main) { - withContext(Dispatchers.IO) { - Try { + Try { + withContext(Dispatchers.IO) { val parentDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) val file = File(parentDir, "recovery-key-" + System.currentTimeMillis() + ".txt") diff --git a/vector/src/main/java/im/vector/riotx/features/home/room/detail/timeline/action/MessageActionsViewModel.kt b/vector/src/main/java/im/vector/riotx/features/home/room/detail/timeline/action/MessageActionsViewModel.kt index 135496264d..63a4919763 100644 --- a/vector/src/main/java/im/vector/riotx/features/home/room/detail/timeline/action/MessageActionsViewModel.kt +++ b/vector/src/main/java/im/vector/riotx/features/home/room/detail/timeline/action/MessageActionsViewModel.kt @@ -42,7 +42,8 @@ import im.vector.riotx.features.home.room.detail.timeline.format.NoticeEventForm import im.vector.riotx.features.home.room.detail.timeline.item.MessageInformationData import im.vector.riotx.features.html.EventHtmlRenderer import java.text.SimpleDateFormat -import java.util.* +import java.util.Date +import java.util.Locale /** * Quick reactions state diff --git a/vector/src/main/java/im/vector/riotx/features/home/room/detail/timeline/edithistory/ViewEditHistoryEpoxyController.kt b/vector/src/main/java/im/vector/riotx/features/home/room/detail/timeline/edithistory/ViewEditHistoryEpoxyController.kt index d36e98f67c..4661d8f8cd 100644 --- a/vector/src/main/java/im/vector/riotx/features/home/room/detail/timeline/edithistory/ViewEditHistoryEpoxyController.kt +++ b/vector/src/main/java/im/vector/riotx/features/home/room/detail/timeline/edithistory/ViewEditHistoryEpoxyController.kt @@ -38,7 +38,7 @@ import im.vector.riotx.features.html.EventHtmlRenderer import me.gujun.android.span.span import name.fraser.neil.plaintext.diff_match_patch import timber.log.Timber -import java.util.* +import java.util.Calendar /** * Epoxy controller for edit history list @@ -94,7 +94,7 @@ class ViewEditHistoryEpoxyController(private val context: Context, val body = cContent.second?.let { eventHtmlRenderer.render(it) } ?: cContent.first - val nextEvent = if (index + 1 <= sourceEvents.lastIndex) sourceEvents[index + 1] else null + val nextEvent = sourceEvents.getOrNull(index + 1) var spannedDiff: Spannable? = null if (nextEvent != null && cContent.second == null /*No diff for html*/) { diff --git a/vector/src/main/java/im/vector/riotx/features/home/room/detail/timeline/edithistory/ViewEditHistoryViewModel.kt b/vector/src/main/java/im/vector/riotx/features/home/room/detail/timeline/edithistory/ViewEditHistoryViewModel.kt index e2b976b273..93e7709b55 100644 --- a/vector/src/main/java/im/vector/riotx/features/home/room/detail/timeline/edithistory/ViewEditHistoryViewModel.kt +++ b/vector/src/main/java/im/vector/riotx/features/home/room/detail/timeline/edithistory/ViewEditHistoryViewModel.kt @@ -30,7 +30,7 @@ import im.vector.riotx.core.platform.VectorViewModel import im.vector.riotx.core.date.VectorDateFormatter import im.vector.riotx.features.home.room.detail.timeline.action.TimelineEventFragmentArgs import timber.log.Timber -import java.util.* +import java.util.UUID data class ViewEditHistoryViewState( val eventId: String, diff --git a/vector/src/main/java/im/vector/riotx/features/notifications/NotifiableEventResolver.kt b/vector/src/main/java/im/vector/riotx/features/notifications/NotifiableEventResolver.kt index 06108e07fe..786fabfca2 100644 --- a/vector/src/main/java/im/vector/riotx/features/notifications/NotifiableEventResolver.kt +++ b/vector/src/main/java/im/vector/riotx/features/notifications/NotifiableEventResolver.kt @@ -33,7 +33,7 @@ import im.vector.riotx.R import im.vector.riotx.core.resources.StringProvider import im.vector.riotx.features.home.room.detail.timeline.format.NoticeEventFormatter import timber.log.Timber -import java.util.* +import java.util.UUID import javax.inject.Inject /** diff --git a/vector/src/main/java/im/vector/riotx/features/notifications/NotificationBroadcastReceiver.kt b/vector/src/main/java/im/vector/riotx/features/notifications/NotificationBroadcastReceiver.kt index e26395641d..63cd1c5ce6 100644 --- a/vector/src/main/java/im/vector/riotx/features/notifications/NotificationBroadcastReceiver.kt +++ b/vector/src/main/java/im/vector/riotx/features/notifications/NotificationBroadcastReceiver.kt @@ -27,7 +27,7 @@ import im.vector.riotx.R import im.vector.riotx.core.di.ActiveSessionHolder import im.vector.riotx.core.extensions.vectorComponent import timber.log.Timber -import java.util.* +import java.util.UUID import javax.inject.Inject /** diff --git a/vector/src/main/java/im/vector/riotx/features/notifications/NotificationUtils.kt b/vector/src/main/java/im/vector/riotx/features/notifications/NotificationUtils.kt index 1a5385663b..7d8e43d0be 100755 --- a/vector/src/main/java/im/vector/riotx/features/notifications/NotificationUtils.kt +++ b/vector/src/main/java/im/vector/riotx/features/notifications/NotificationUtils.kt @@ -45,9 +45,9 @@ import im.vector.riotx.features.home.room.detail.RoomDetailActivity import im.vector.riotx.features.home.room.detail.RoomDetailArgs import im.vector.riotx.features.settings.VectorPreferences import timber.log.Timber -import java.util.* import javax.inject.Inject import javax.inject.Singleton +import kotlin.random.Random /** * Util class for creating notifications. @@ -299,7 +299,7 @@ class NotificationUtils @Inject constructor(private val context: Context, // use a generator for the private requestCode. // When using 0, the intent is not created/launched when the user taps on the notification. // - val pendingIntent = stackBuilder.getPendingIntent(Random().nextInt(1000), PendingIntent.FLAG_UPDATE_CURRENT) + val pendingIntent = stackBuilder.getPendingIntent(Random.nextInt(1000), PendingIntent.FLAG_UPDATE_CURRENT) builder.setContentIntent(pendingIntent) @@ -599,7 +599,7 @@ class NotificationUtils @Inject constructor(private val context: Context, val intent = HomeActivity.newIntent(context, clearNotification = true) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP intent.data = Uri.parse("foobar://tapSummary") - return PendingIntent.getActivity(context, Random().nextInt(1000), intent, PendingIntent.FLAG_UPDATE_CURRENT) + return PendingIntent.getActivity(context, Random.nextInt(1000), intent, PendingIntent.FLAG_UPDATE_CURRENT) } /* diff --git a/vector/src/main/java/im/vector/riotx/features/rageshake/BugReporter.kt b/vector/src/main/java/im/vector/riotx/features/rageshake/BugReporter.kt index 9a7707d063..b96542a8ce 100755 --- a/vector/src/main/java/im/vector/riotx/features/rageshake/BugReporter.kt +++ b/vector/src/main/java/im/vector/riotx/features/rageshake/BugReporter.kt @@ -46,7 +46,7 @@ import org.json.JSONObject import timber.log.Timber import java.io.* import java.net.HttpURLConnection -import java.util.* +import java.util.Locale import java.util.zip.GZIPOutputStream import javax.inject.Inject import javax.inject.Singleton diff --git a/vector/src/main/java/im/vector/riotx/features/rageshake/VectorFileLogger.kt b/vector/src/main/java/im/vector/riotx/features/rageshake/VectorFileLogger.kt index 0b9cb5798c..95053790c8 100644 --- a/vector/src/main/java/im/vector/riotx/features/rageshake/VectorFileLogger.kt +++ b/vector/src/main/java/im/vector/riotx/features/rageshake/VectorFileLogger.kt @@ -24,7 +24,9 @@ import java.io.File import java.io.PrintWriter import java.io.StringWriter import java.text.SimpleDateFormat -import java.util.* +import java.util.Date +import java.util.Locale +import java.util.TimeZone import java.util.logging.* import java.util.logging.Formatter import javax.inject.Inject diff --git a/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsGeneralFragment.kt b/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsGeneralFragment.kt index 331b6e935a..ff76c61754 100644 --- a/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsGeneralFragment.kt +++ b/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsGeneralFragment.kt @@ -51,7 +51,6 @@ import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File -import java.util.* class VectorSettingsGeneralFragment : VectorSettingsBaseFragment() { diff --git a/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsSecurityPrivacyFragment.kt b/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsSecurityPrivacyFragment.kt index 2f52cdef13..a78529f06c 100644 --- a/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsSecurityPrivacyFragment.kt +++ b/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsSecurityPrivacyFragment.kt @@ -56,7 +56,8 @@ import im.vector.riotx.features.crypto.keysbackup.settings.KeysBackupManageActiv import timber.log.Timber import java.text.DateFormat import java.text.SimpleDateFormat -import java.util.* +import java.util.Date +import java.util.Locale import javax.inject.Inject class VectorSettingsSecurityPrivacyFragment : VectorSettingsBaseFragment() { diff --git a/vector/src/main/java/im/vector/riotx/features/themes/ThemeUtils.kt b/vector/src/main/java/im/vector/riotx/features/themes/ThemeUtils.kt index 2edb59104b..40a14b3e6f 100644 --- a/vector/src/main/java/im/vector/riotx/features/themes/ThemeUtils.kt +++ b/vector/src/main/java/im/vector/riotx/features/themes/ThemeUtils.kt @@ -28,7 +28,6 @@ import androidx.core.graphics.drawable.DrawableCompat import androidx.preference.PreferenceManager import im.vector.riotx.R import timber.log.Timber -import java.util.* /** * Util class for managing themes. @@ -131,24 +130,16 @@ object ThemeUtils { */ @ColorInt fun getColor(c: Context, @AttrRes colorAttribute: Int): Int { - if (mColorByAttr.containsKey(colorAttribute)) { - return mColorByAttr[colorAttribute] as Int + return mColorByAttr.getOrPut(colorAttribute) { + try { + val color = TypedValue() + c.theme.resolveAttribute(colorAttribute, color, true) + color.data + } catch (e: Exception) { + Timber.e(e, "Unable to get color") + ContextCompat.getColor(c, android.R.color.holo_red_dark) + } } - - var matchedColor: Int - - try { - val color = TypedValue() - c.theme.resolveAttribute(colorAttribute, color, true) - matchedColor = color.data - } catch (e: Exception) { - Timber.e(e, "Unable to get color") - matchedColor = ContextCompat.getColor(c, android.R.color.holo_red_dark) - } - - mColorByAttr[colorAttribute] = matchedColor - - return matchedColor } fun getAttribute(c: Context, @AttrRes attribute: Int): TypedValue? {