From 8cf1ff424b3863907abd9aa6eca728a66eec104c Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Wed, 9 Feb 2022 15:40:03 +0100 Subject: [PATCH 01/65] Made open class an interface. --- base-permissions/src/commonMain/kotlin/PermissionState.kt | 2 +- base/src/commonMain/kotlin/state/State.kt | 6 +++--- base/src/commonTest/kotlin/state/ColdStateFlowRepoTest.kt | 6 +++--- base/src/commonTest/kotlin/state/ColdStateRepoTest.kt | 2 +- .../commonTest/kotlin/state/ReplayBufferStateRepoTest.kt | 8 ++++---- base/src/commonTest/kotlin/state/StateRepoTest.kt | 2 +- bluetooth/src/commonMain/kotlin/device/DeviceState.kt | 2 +- bluetooth/src/commonMain/kotlin/scanner/ScanningState.kt | 2 +- .../com/splendo/kaluga/datetime/timer/RecurringTimer.kt | 2 +- location/src/commonMain/kotlin/location/LocationState.kt | 2 +- .../splendo/kaluga/system/network/state/NetworkState.kt | 2 +- 11 files changed, 18 insertions(+), 18 deletions(-) diff --git a/base-permissions/src/commonMain/kotlin/PermissionState.kt b/base-permissions/src/commonMain/kotlin/PermissionState.kt index caf484ea6..257579e6f 100644 --- a/base-permissions/src/commonMain/kotlin/PermissionState.kt +++ b/base-permissions/src/commonMain/kotlin/PermissionState.kt @@ -27,7 +27,7 @@ import kotlin.coroutines.CoroutineContext /** * State of a [Permission] */ -sealed class PermissionState

: State() { +sealed class PermissionState

: State { class Unknown

: PermissionState

(), SpecialFlowValue.NotImportant diff --git a/base/src/commonMain/kotlin/state/State.kt b/base/src/commonMain/kotlin/state/State.kt index 9776b5805..41df37445 100644 --- a/base/src/commonMain/kotlin/state/State.kt +++ b/base/src/commonMain/kotlin/state/State.kt @@ -52,7 +52,7 @@ private val remain: suspend() -> State = { error("This should never be called. I /** * State to be represented in a state machine */ -open class State { +interface State { /** * Use this to indicate to the state machine the state should stay the same @@ -65,13 +65,13 @@ open class State { * Called when this state is the first state of the state machine */ @Deprecated("Use an initializer state rather than relying on this method, it might be called after the initial state is already changed") - open suspend fun initialState() {} + suspend fun initialState() {} /** * Called when this state is the final state of the state machine */ @Deprecated("This method is not always actually called (e.g. for a HotRepo) since there is not always a final state") - open suspend fun finalState() {} + suspend fun finalState() {} } interface HandleBeforeCreating { diff --git a/base/src/commonTest/kotlin/state/ColdStateFlowRepoTest.kt b/base/src/commonTest/kotlin/state/ColdStateFlowRepoTest.kt index a88eaa55b..e5693e3d3 100644 --- a/base/src/commonTest/kotlin/state/ColdStateFlowRepoTest.kt +++ b/base/src/commonTest/kotlin/state/ColdStateFlowRepoTest.kt @@ -31,9 +31,9 @@ import kotlin.test.assertEquals class ColdStateFlowRepoTest : BaseTest() { companion object { - val first = object : State() {} - val active = object : State() {} - val deinit = object : State() {} + val first = object : State {} + val active = object : State {} + val deinit = object : State {} } class Repo : ColdStateFlowRepo( diff --git a/base/src/commonTest/kotlin/state/ColdStateRepoTest.kt b/base/src/commonTest/kotlin/state/ColdStateRepoTest.kt index 4314fbb8b..86f4cf272 100644 --- a/base/src/commonTest/kotlin/state/ColdStateRepoTest.kt +++ b/base/src/commonTest/kotlin/state/ColdStateRepoTest.kt @@ -31,7 +31,7 @@ import kotlin.test.assertEquals class ColdStateRepoTest : BaseTest() { - sealed class CircuitState : State() { + sealed class CircuitState : State { val initialStateCounter = MutableStateFlow(0) override suspend fun initialState() { diff --git a/base/src/commonTest/kotlin/state/ReplayBufferStateRepoTest.kt b/base/src/commonTest/kotlin/state/ReplayBufferStateRepoTest.kt index 3fd90b9e9..f2cea13f6 100644 --- a/base/src/commonTest/kotlin/state/ReplayBufferStateRepoTest.kt +++ b/base/src/commonTest/kotlin/state/ReplayBufferStateRepoTest.kt @@ -30,10 +30,10 @@ import kotlin.test.assertEquals class ReplayBufferStateRepoTest { companion object { - val state1 = object : State() {} - val state2 = object : State() {} - val state3 = object : State() {} - val state4 = object : State() {} + val state1 = object : State {} + val state2 = object : State {} + val state3 = object : State {} + val state4 = object : State {} } class Repo : BaseHotStateRepo>() { diff --git a/base/src/commonTest/kotlin/state/StateRepoTest.kt b/base/src/commonTest/kotlin/state/StateRepoTest.kt index b12224d88..d85f144ff 100644 --- a/base/src/commonTest/kotlin/state/StateRepoTest.kt +++ b/base/src/commonTest/kotlin/state/StateRepoTest.kt @@ -33,7 +33,7 @@ import kotlin.test.assertFalse import kotlin.test.assertTrue sealed class TrafficLightState : - State(), + State, HandleBeforeCreating, HandleAfterCreating, HandleBeforeOldStateIsRemoved, diff --git a/bluetooth/src/commonMain/kotlin/device/DeviceState.kt b/bluetooth/src/commonMain/kotlin/device/DeviceState.kt index c7896f2a1..65bef316f 100644 --- a/bluetooth/src/commonMain/kotlin/device/DeviceState.kt +++ b/bluetooth/src/commonMain/kotlin/device/DeviceState.kt @@ -58,7 +58,7 @@ typealias DeviceStateFlowRepo = StateRepo -sealed class ScanningState : State() { +sealed class ScanningState : State { data class Discovered( val devices: List, diff --git a/date-time/src/commonMain/kotlin/com/splendo/kaluga/datetime/timer/RecurringTimer.kt b/date-time/src/commonMain/kotlin/com/splendo/kaluga/datetime/timer/RecurringTimer.kt index 8686c82a2..d9ee0e11c 100644 --- a/date-time/src/commonMain/kotlin/com/splendo/kaluga/datetime/timer/RecurringTimer.kt +++ b/date-time/src/commonMain/kotlin/com/splendo/kaluga/datetime/timer/RecurringTimer.kt @@ -107,7 +107,7 @@ private class TimerStateRepo( } /** Timer state. */ - sealed class State : KalugaState(), Timer.State { + sealed class State : KalugaState, Timer.State { abstract val totalDuration: Duration /** Timer is not running. */ sealed class NotRunning(protected val elapsedSoFar: Duration) : State(), Timer.State.NotRunning { diff --git a/location/src/commonMain/kotlin/location/LocationState.kt b/location/src/commonMain/kotlin/location/LocationState.kt index f742beb39..29b86c829 100644 --- a/location/src/commonMain/kotlin/location/LocationState.kt +++ b/location/src/commonMain/kotlin/location/LocationState.kt @@ -34,7 +34,7 @@ import kotlin.coroutines.CoroutineContext * @param location The [Location] associated with the state. * @param locationManager The [BaseLocationManager] managing the location state */ -sealed class LocationState(open val location: Location, private val locationManager: BaseLocationManager) : State() { +sealed class LocationState(open val location: Location, private val locationManager: BaseLocationManager) : State { override suspend fun initialState() { locationManager.startMonitoringPermissions() diff --git a/system/src/commonMain/kotlin/com/splendo/kaluga/system/network/state/NetworkState.kt b/system/src/commonMain/kotlin/com/splendo/kaluga/system/network/state/NetworkState.kt index eb990214b..81279ce4f 100644 --- a/system/src/commonMain/kotlin/com/splendo/kaluga/system/network/state/NetworkState.kt +++ b/system/src/commonMain/kotlin/com/splendo/kaluga/system/network/state/NetworkState.kt @@ -22,7 +22,7 @@ import com.splendo.kaluga.system.network.Network sealed class NetworkState( open val networkType: Network, -) : State() { +) : State { data class Unknown( override val networkType: Network.Unknown From 945560fd860f7f6fae224d8893889489d1802bd7 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Fri, 11 Feb 2022 13:25:22 +0100 Subject: [PATCH 02/65] Add FocusHandlerMock, update keyboard's. --- .../kotlin/mock/focus/MockFocusHandler.kt | 31 +++++++++++++++ .../kotlin/mock/focus/MockFocusHandler.kt | 39 +++++++++++++++++++ .../mock/keyboard/MockKeyboardManager.kt | 27 ++++++------- .../kotlin/mock/focus/MockFocusHandler.kt | 26 +++++++++++++ .../kotlin/mock/focus/MockFocusHandler.kt | 26 +++++++++++++ .../kotlin/mock/focus/MockFocusHandler.kt | 26 +++++++++++++ 6 files changed, 162 insertions(+), 13 deletions(-) create mode 100644 test-utils/src/androidLibMain/kotlin/mock/focus/MockFocusHandler.kt create mode 100644 test-utils/src/commonMain/kotlin/mock/focus/MockFocusHandler.kt create mode 100644 test-utils/src/iosMain/kotlin/mock/focus/MockFocusHandler.kt create mode 100644 test-utils/src/jsMain/kotlin/mock/focus/MockFocusHandler.kt create mode 100644 test-utils/src/jvmMain/kotlin/mock/focus/MockFocusHandler.kt diff --git a/test-utils/src/androidLibMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/androidLibMain/kotlin/mock/focus/MockFocusHandler.kt new file mode 100644 index 000000000..9f4bc717f --- /dev/null +++ b/test-utils/src/androidLibMain/kotlin/mock/focus/MockFocusHandler.kt @@ -0,0 +1,31 @@ +/* + Copyright 2022 Splendo Consulting B.V. The Netherlands + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + */ + +package com.splendo.kaluga.test.mock.focus + +import android.app.Activity +import com.splendo.kaluga.keyboard.FocusHandler + +actual class MockFocusHandler : BaseMockFocusHandler(), FocusHandler { + override fun requestFocus(activity: Activity?) { + super.giveFocus() + } + + actual fun requestFocus() { + requestFocus(activity = null) + } +} diff --git a/test-utils/src/commonMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/commonMain/kotlin/mock/focus/MockFocusHandler.kt new file mode 100644 index 000000000..4c7d75b37 --- /dev/null +++ b/test-utils/src/commonMain/kotlin/mock/focus/MockFocusHandler.kt @@ -0,0 +1,39 @@ +/* + Copyright 2022 Splendo Consulting B.V. The Netherlands + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + */ + +package com.splendo.kaluga.test.mock.focus + +import com.splendo.kaluga.keyboard.FocusHandler +import kotlinx.coroutines.flow.MutableStateFlow + +open class BaseMockFocusHandler { + private val _isFocused = MutableStateFlow(false) + val isFocused: Boolean + get() = _isFocused.value + + protected fun giveFocus() { + _isFocused.value = true + } + + fun removeFocus() { + _isFocused.value = false + } +} + +expect class MockFocusHandler constructor() : BaseMockFocusHandler, FocusHandler { + fun requestFocus() +} diff --git a/test-utils/src/commonMain/kotlin/mock/keyboard/MockKeyboardManager.kt b/test-utils/src/commonMain/kotlin/mock/keyboard/MockKeyboardManager.kt index 8788403d6..9b1aba482 100644 --- a/test-utils/src/commonMain/kotlin/mock/keyboard/MockKeyboardManager.kt +++ b/test-utils/src/commonMain/kotlin/mock/keyboard/MockKeyboardManager.kt @@ -19,27 +19,28 @@ package com.splendo.kaluga.test.mock.keyboard import com.splendo.kaluga.keyboard.BaseKeyboardManager import com.splendo.kaluga.keyboard.FocusHandler +import com.splendo.kaluga.test.mock.focus.MockFocusHandler import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.MutableStateFlow class MockKeyboardManager : BaseKeyboardManager { - class Builder : BaseKeyboardManager.Builder { - - val builtKeyboardManagers = mutableListOf() - - override fun create(coroutineScope: CoroutineScope): MockKeyboardManager { - return MockKeyboardManager().also { builtKeyboardManagers.add(it) } - } + override fun create(coroutineScope: CoroutineScope): BaseKeyboardManager = MockKeyboardManager() } - var focusHandler: FocusHandler? = null - private set + private val _focusHandler: MutableStateFlow = MutableStateFlow(null) - override fun show(focusHandler: FocusHandler) { - this.focusHandler = focusHandler - } + private val _isShown = MutableStateFlow(false) + val isShown get() = _isShown.value override fun hide() { - focusHandler = null + _isShown.value = false + _focusHandler.value?.removeFocus() + } + + override fun show(focusHandler: FocusHandler) { + _isShown.value = true + _focusHandler.value = focusHandler as? MockFocusHandler + _focusHandler.value?.requestFocus() } } diff --git a/test-utils/src/iosMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/iosMain/kotlin/mock/focus/MockFocusHandler.kt new file mode 100644 index 000000000..e2ad571c8 --- /dev/null +++ b/test-utils/src/iosMain/kotlin/mock/focus/MockFocusHandler.kt @@ -0,0 +1,26 @@ +/* + Copyright 2022 Splendo Consulting B.V. The Netherlands + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + */ + +package com.splendo.kaluga.test.mock.focus + +import com.splendo.kaluga.keyboard.FocusHandler + +actual class MockFocusHandler : BaseMockFocusHandler(), FocusHandler { + actual override fun requestFocus() { + super.giveFocus() + } +} diff --git a/test-utils/src/jsMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/jsMain/kotlin/mock/focus/MockFocusHandler.kt new file mode 100644 index 000000000..c0c156764 --- /dev/null +++ b/test-utils/src/jsMain/kotlin/mock/focus/MockFocusHandler.kt @@ -0,0 +1,26 @@ +/* + Copyright 2022 Splendo Consulting B.V. The Netherlands + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + */ + +package com.splendo.kaluga.test.mock.focus + +import com.splendo.kaluga.keyboard.FocusHandler + +actual class MockFocusHandler : BaseMockFocusHandler(), FocusHandler { + actual fun requestFocus() { + super.giveFocus() + } +} diff --git a/test-utils/src/jvmMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/jvmMain/kotlin/mock/focus/MockFocusHandler.kt new file mode 100644 index 000000000..c0c156764 --- /dev/null +++ b/test-utils/src/jvmMain/kotlin/mock/focus/MockFocusHandler.kt @@ -0,0 +1,26 @@ +/* + Copyright 2022 Splendo Consulting B.V. The Netherlands + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + */ + +package com.splendo.kaluga.test.mock.focus + +import com.splendo.kaluga.keyboard.FocusHandler + +actual class MockFocusHandler : BaseMockFocusHandler(), FocusHandler { + actual fun requestFocus() { + super.giveFocus() + } +} From e8d9200c31b13e129e1f408784a830141862a6ac Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Fri, 11 Feb 2022 13:46:21 +0100 Subject: [PATCH 03/65] Rename method. --- .../androidLibMain/kotlin/mock/focus/MockFocusHandler.kt | 2 +- .../src/commonMain/kotlin/mock/focus/MockFocusHandler.kt | 2 +- .../src/iosMain/kotlin/mock/focus/MockFocusHandler.kt | 6 +++++- test-utils/src/jsMain/kotlin/mock/focus/MockFocusHandler.kt | 2 +- .../src/jvmMain/kotlin/mock/focus/MockFocusHandler.kt | 2 +- 5 files changed, 9 insertions(+), 5 deletions(-) diff --git a/test-utils/src/androidLibMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/androidLibMain/kotlin/mock/focus/MockFocusHandler.kt index 9f4bc717f..3f65fec24 100644 --- a/test-utils/src/androidLibMain/kotlin/mock/focus/MockFocusHandler.kt +++ b/test-utils/src/androidLibMain/kotlin/mock/focus/MockFocusHandler.kt @@ -25,7 +25,7 @@ actual class MockFocusHandler : BaseMockFocusHandler(), FocusHandler { super.giveFocus() } - actual fun requestFocus() { + actual fun focus() { requestFocus(activity = null) } } diff --git a/test-utils/src/commonMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/commonMain/kotlin/mock/focus/MockFocusHandler.kt index 4c7d75b37..1b910ea63 100644 --- a/test-utils/src/commonMain/kotlin/mock/focus/MockFocusHandler.kt +++ b/test-utils/src/commonMain/kotlin/mock/focus/MockFocusHandler.kt @@ -35,5 +35,5 @@ open class BaseMockFocusHandler { } expect class MockFocusHandler constructor() : BaseMockFocusHandler, FocusHandler { - fun requestFocus() + fun focus() } diff --git a/test-utils/src/iosMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/iosMain/kotlin/mock/focus/MockFocusHandler.kt index e2ad571c8..e39654d9e 100644 --- a/test-utils/src/iosMain/kotlin/mock/focus/MockFocusHandler.kt +++ b/test-utils/src/iosMain/kotlin/mock/focus/MockFocusHandler.kt @@ -20,7 +20,11 @@ package com.splendo.kaluga.test.mock.focus import com.splendo.kaluga.keyboard.FocusHandler actual class MockFocusHandler : BaseMockFocusHandler(), FocusHandler { - actual override fun requestFocus() { + override fun requestFocus() { super.giveFocus() } + + actual fun focus() { + requestFocus() + } } diff --git a/test-utils/src/jsMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/jsMain/kotlin/mock/focus/MockFocusHandler.kt index c0c156764..6dae3096d 100644 --- a/test-utils/src/jsMain/kotlin/mock/focus/MockFocusHandler.kt +++ b/test-utils/src/jsMain/kotlin/mock/focus/MockFocusHandler.kt @@ -20,7 +20,7 @@ package com.splendo.kaluga.test.mock.focus import com.splendo.kaluga.keyboard.FocusHandler actual class MockFocusHandler : BaseMockFocusHandler(), FocusHandler { - actual fun requestFocus() { + actual fun focus() { super.giveFocus() } } diff --git a/test-utils/src/jvmMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/jvmMain/kotlin/mock/focus/MockFocusHandler.kt index c0c156764..6dae3096d 100644 --- a/test-utils/src/jvmMain/kotlin/mock/focus/MockFocusHandler.kt +++ b/test-utils/src/jvmMain/kotlin/mock/focus/MockFocusHandler.kt @@ -20,7 +20,7 @@ package com.splendo.kaluga.test.mock.focus import com.splendo.kaluga.keyboard.FocusHandler actual class MockFocusHandler : BaseMockFocusHandler(), FocusHandler { - actual fun requestFocus() { + actual fun focus() { super.giveFocus() } } From 1c4232957edc3f32886e6d67d7beaffea0fc34f1 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Fri, 11 Feb 2022 14:02:48 +0100 Subject: [PATCH 04/65] Rename interface. --- .../src/commonMain/kotlin/PermissionState.kt | 4 +- .../kotlin/state/{State.kt => KalugaState.kt} | 60 +++++++++---------- .../kotlin/state/ColdStateFlowRepoTest.kt | 12 ++-- .../kotlin/state/ColdStateRepoTest.kt | 2 +- .../kotlin/state/ReplayBufferStateRepoTest.kt | 12 ++-- .../commonTest/kotlin/state/StateRepoTest.kt | 2 +- .../commonMain/kotlin/device/DeviceState.kt | 4 +- .../kotlin/scanner/ScanningState.kt | 4 +- .../kaluga/datetime/timer/RecurringTimer.kt | 2 +- .../kotlin/location/LocationState.kt | 4 +- .../system/network/state/NetworkState.kt | 4 +- 11 files changed, 55 insertions(+), 55 deletions(-) rename base/src/commonMain/kotlin/state/{State.kt => KalugaState.kt} (87%) diff --git a/base-permissions/src/commonMain/kotlin/PermissionState.kt b/base-permissions/src/commonMain/kotlin/PermissionState.kt index 257579e6f..b29e0b6bb 100644 --- a/base-permissions/src/commonMain/kotlin/PermissionState.kt +++ b/base-permissions/src/commonMain/kotlin/PermissionState.kt @@ -20,14 +20,14 @@ package com.splendo.kaluga.permissions import com.splendo.kaluga.base.flow.SpecialFlowValue import com.splendo.kaluga.state.ColdStateFlowRepo -import com.splendo.kaluga.state.State +import com.splendo.kaluga.state.KalugaState import kotlinx.coroutines.Dispatchers import kotlin.coroutines.CoroutineContext /** * State of a [Permission] */ -sealed class PermissionState

: State { +sealed class PermissionState

: KalugaState { class Unknown

: PermissionState

(), SpecialFlowValue.NotImportant diff --git a/base/src/commonMain/kotlin/state/State.kt b/base/src/commonMain/kotlin/state/KalugaState.kt similarity index 87% rename from base/src/commonMain/kotlin/state/State.kt rename to base/src/commonMain/kotlin/state/KalugaState.kt index 41df37445..1343c2b41 100644 --- a/base/src/commonMain/kotlin/state/State.kt +++ b/base/src/commonMain/kotlin/state/KalugaState.kt @@ -47,19 +47,19 @@ import kotlin.native.concurrent.SharedImmutable import kotlin.reflect.KClass @SharedImmutable -private val remain: suspend() -> State = { error("This should never be called. It's only used to indicate the state should remain the same") } +private val remain: suspend() -> KalugaState = { error("This should never be called. It's only used to indicate the state should remain the same") } /** * State to be represented in a state machine */ -interface State { +interface KalugaState { /** * Use this to indicate to the state machine the state should stay the same * @return a special continuation that will be recognized by the state machine. Running this continuation will cause an error. */ @Suppress("UNCHECKED_CAST") // cast should normally work since the receiver uses one type of state - fun remain(): suspend() -> S = remain as suspend () -> S + fun remain(): suspend() -> S = remain as suspend () -> S /** * Called when this state is the first state of the state machine @@ -81,7 +81,7 @@ interface HandleBeforeCreating { suspend fun beforeCreatingNewState() } -interface HandleAfterCreating { +interface HandleAfterCreating { /** * Called while transitioning to a new state after the new state is created * @@ -90,27 +90,27 @@ interface HandleAfterCreating { suspend fun afterCreatingNewState(newState: S) } -interface HandleAfterNewStateIsSet { +interface HandleAfterNewStateIsSet { /** * Called while transitioning to a new state after the new state is set. * - * @param newState the newly set [State] + * @param newState the newly set [KalugaState] */ suspend fun afterNewStateIsSet(newState: S) } -interface HandleBeforeOldStateIsRemoved { +interface HandleBeforeOldStateIsRemoved { /** * Called while transitioning from an old state before it is removed. * - * @param oldState the [State] to be removed + * @param oldState the [KalugaState] to be removed */ suspend fun beforeOldStateIsRemoved(oldState: S) } -interface HandleAfterOldStateIsRemoved { +interface HandleAfterOldStateIsRemoved { /** * Called while transitioning from an old state after it is removed @@ -121,12 +121,12 @@ interface HandleAfterOldStateIsRemoved { } /** - * The state repo can change holds the current [State] (which can be accessed as a flow), and can be used to change the current state + * The state repo can change holds the current [KalugaState] (which can be accessed as a flow), and can be used to change the current state * - * @param S the [State] represented by this repo. + * @param S the [KalugaState] represented by this repo. * @param coroutineContext the [CoroutineContext] used to create a coroutine scope for this state machine. Make sure that if you pass a coroutine context that has sequential execution if you do not want simultaneous state changes. The default Main dispatcher meets these criteria. */ -abstract class StateRepo>(coroutineContext: CoroutineContext = Dispatchers.Main.immediate) : CoroutineScope by CoroutineScope(coroutineContext + CoroutineName("State Repo")), Flow { +abstract class StateRepo>(coroutineContext: CoroutineContext = Dispatchers.Main.immediate) : CoroutineScope by CoroutineScope(coroutineContext + CoroutineName("State Repo")), Flow { override suspend fun collect(collector: FlowCollector) = mutableFlow.collect(collector) @@ -142,7 +142,7 @@ abstract class StateRepo>(coroutineContext: get() = mutableFlow.subscriptionCount /** - * Provides a [Flow] of the [State] of this repo. + * Provides a [Flow] of the [KalugaState] of this repo. * * @return The [Flow] */ @@ -197,7 +197,7 @@ abstract class StateRepo>(coroutineContext: * If your code relies on the state not changing use [useState]. * If you want to change the state based on the current state use [takeAndChangeState] * - * @return the current [State] of the [StateRepo] + * @return the current [KalugaState] of the [StateRepo] */ fun peekState() = runBlocking { initialize() @@ -205,12 +205,12 @@ abstract class StateRepo>(coroutineContext: } /** - * Makes the current [State] available in [action]. The state is guaranteed not to change during the execution of [action]. + * Makes the current [KalugaState] available in [action]. The state is guaranteed not to change during the execution of [action]. * This operation ensures atomic state observations, so the state will not change while the [action] is being executed. * * This method uses a separate coroutineScope, meaning it will suspend until all child Jobs are completed, including those that asynchronously call this method itself (however a different state might be current at that point). * - * @param action the function for which will [State] receive the state, guaranteed to be unchanged for the duration of the function. + * @param action the function for which will [KalugaState] receive the state, guaranteed to be unchanged for the duration of the function. */ suspend fun useState(action: suspend (S) -> Unit) = coroutineScope { initialize() @@ -239,16 +239,16 @@ abstract class StateRepo>(coroutineContext: doTakeAndChangeState(remainIfStateNot = null, action) /** - * Changes from the current [State] to a new [State]. This operation ensures atomic state changes. - * The new state is determined by an [action], which takes the current [State] upon starting the state transition and provides a deferred state creation. - * You are strongly encouraged to use the [State] provided by the [action] to determine the new state, to ensure no illegal state transitions occur, as the state may have changed between calling [doTakeAndChangeState] and the execution of [action]. - * If the [action] returns [State.remain] no state transition will occur. + * Changes from the current [KalugaState] to a new [KalugaState]. This operation ensures atomic state changes. + * The new state is determined by an [action], which takes the current [KalugaState] upon starting the state transition and provides a deferred state creation. + * You are strongly encouraged to use the [KalugaState] provided by the [action] to determine the new state, to ensure no illegal state transitions occur, as the state may have changed between calling [doTakeAndChangeState] and the execution of [action]. + * If the [action] returns [KalugaState.remain] no state transition will occur. * Since this operation is atomic, the [action] should not directly call [doTakeAndChangeState] itself. If required to do this, handle the additional transition in a separate coroutine. * * This method uses a separate coroutineScope, meaning it will suspend until all child Jobs are completed, including those that asynchronously call this method itself. * * @param remainIfStateNot If the current state at the time of Action is not an instance of this class, the state will automatically remain. - * @param action Function to determine the [State] to be transitioned to from the current [State]. If no state transition should occur, return [State.remain] + * @param action Function to determine the [KalugaState] to be transitioned to from the current [KalugaState]. If no state transition should occur, return [KalugaState.remain] */ suspend fun takeAndChangeState(remainIfStateNot: KClass, action: suspend(K) -> suspend () -> S) = doTakeAndChangeState(remainIfStateNot) { @@ -313,19 +313,19 @@ abstract class StateRepo>(coroutineContext: // Somewhat similar to a ConflatedBroadcastChannel, which was used in the previous implementation inline fun defaultLazySharedFlow(): Lazy> = lazy { MutableSharedFlow(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) } -interface StateFlowRepo { +interface StateFlowRepo { val stateFlow: StateFlow } /** - * A [StateRepo] that represents its [State] as a Hot flow. + * A [StateRepo] that represents its [KalugaState] as a Hot flow. */ -abstract class HotStateRepo(coroutineContext: CoroutineContext = Dispatchers.Main.immediate) : +abstract class HotStateRepo(coroutineContext: CoroutineContext = Dispatchers.Main.immediate) : BaseHotStateRepo>(coroutineContext) { final override val lazyMutableSharedFlow: Lazy> = defaultLazySharedFlow() } -abstract class HotStateFlowRepo( +abstract class HotStateFlowRepo( coroutineContext: CoroutineContext = Dispatchers.Main.immediate, val initialState: (HotStateFlowRepo) -> S ) : StateFlowRepo, @@ -339,7 +339,7 @@ abstract class HotStateFlowRepo( final override suspend fun initialValue(): S = mutableFlow.value } -abstract class BaseHotStateRepo>( +abstract class BaseHotStateRepo>( coroutineContext: CoroutineContext = Dispatchers.Main.immediate ) : StateRepo(coroutineContext) { @@ -370,7 +370,7 @@ abstract class BaseHotStateRepo>( * Be aware an initialization can take place if state is read, for example by [useState] or [takeAndChangeState], without actual collection events occurring. * However a SharedFlow without a replay buffer might trigger a collection to get the initial state if no explicit state is provided */ -abstract class BaseColdStateRepo>( +abstract class BaseColdStateRepo>( context: CoroutineContext = Dispatchers.Main.immediate ) : StateRepo(context) { @@ -412,7 +412,7 @@ abstract class BaseColdStateRepo>( * * It also has an optional initial state. */ -open class ColdStateFlowRepo( +open class ColdStateFlowRepo( coroutineContext: CoroutineContext = Dispatchers.Main.immediate, val initChangeStateWithRepo: suspend (S?, ColdStateFlowRepo) -> (suspend () -> S), val deinitChangeStateWithRepo: suspend (S, ColdStateFlowRepo) -> (suspend () -> S)?, @@ -476,14 +476,14 @@ open class ColdStateFlowRepo( } /** - * A [StateRepo] that represents its [State] as a Cold flow. Data will only be set when the state is observed. + * A [StateRepo] that represents its [KalugaState] as a Cold flow. Data will only be set when the state is observed. * * This class uses a very simple initialize and deinitialize pattern without changes of state by default * * This implementation uses a [MutableSharedFlow]. If you want to use a cold state repo based on StateFlow, * consider [ColdStateFlowRepo] */ -abstract class ColdStateRepo( +abstract class ColdStateRepo( coroutineContext: CoroutineContext = Dispatchers.Main.immediate, override val lazyMutableFlow: Lazy> = defaultLazySharedFlow() ) : BaseColdStateRepo>(coroutineContext) { diff --git a/base/src/commonTest/kotlin/state/ColdStateFlowRepoTest.kt b/base/src/commonTest/kotlin/state/ColdStateFlowRepoTest.kt index e5693e3d3..557226efe 100644 --- a/base/src/commonTest/kotlin/state/ColdStateFlowRepoTest.kt +++ b/base/src/commonTest/kotlin/state/ColdStateFlowRepoTest.kt @@ -31,12 +31,12 @@ import kotlin.test.assertEquals class ColdStateFlowRepoTest : BaseTest() { companion object { - val first = object : State {} - val active = object : State {} - val deinit = object : State {} + val first = object : KalugaState {} + val active = object : KalugaState {} + val deinit = object : KalugaState {} } - class Repo : ColdStateFlowRepo( + class Repo : ColdStateFlowRepo( init = { delay(100) // give some time for the `first` state to be collected active @@ -54,8 +54,8 @@ class ColdStateFlowRepoTest : BaseTest() { assertEquals(first, state) } - val firstCollect = CompletableDeferred() - val secondCollect = CompletableDeferred() + val firstCollect = CompletableDeferred() + val secondCollect = CompletableDeferred() val job = launch { repo.collect { if (!firstCollect.isCompleted) diff --git a/base/src/commonTest/kotlin/state/ColdStateRepoTest.kt b/base/src/commonTest/kotlin/state/ColdStateRepoTest.kt index 86f4cf272..c621b736f 100644 --- a/base/src/commonTest/kotlin/state/ColdStateRepoTest.kt +++ b/base/src/commonTest/kotlin/state/ColdStateRepoTest.kt @@ -31,7 +31,7 @@ import kotlin.test.assertEquals class ColdStateRepoTest : BaseTest() { - sealed class CircuitState : State { + sealed class CircuitState : KalugaState { val initialStateCounter = MutableStateFlow(0) override suspend fun initialState() { diff --git a/base/src/commonTest/kotlin/state/ReplayBufferStateRepoTest.kt b/base/src/commonTest/kotlin/state/ReplayBufferStateRepoTest.kt index f2cea13f6..d296cc96a 100644 --- a/base/src/commonTest/kotlin/state/ReplayBufferStateRepoTest.kt +++ b/base/src/commonTest/kotlin/state/ReplayBufferStateRepoTest.kt @@ -30,16 +30,16 @@ import kotlin.test.assertEquals class ReplayBufferStateRepoTest { companion object { - val state1 = object : State {} - val state2 = object : State {} - val state3 = object : State {} - val state4 = object : State {} + val state1 = object : KalugaState {} + val state2 = object : KalugaState {} + val state3 = object : KalugaState {} + val state4 = object : KalugaState {} } - class Repo : BaseHotStateRepo>() { + class Repo : BaseHotStateRepo>() { override suspend fun initialValue() = state1 override val lazyMutableSharedFlow = lazy { - MutableSharedFlow(3, 0) + MutableSharedFlow(3, 0) } } diff --git a/base/src/commonTest/kotlin/state/StateRepoTest.kt b/base/src/commonTest/kotlin/state/StateRepoTest.kt index d85f144ff..c4f661a33 100644 --- a/base/src/commonTest/kotlin/state/StateRepoTest.kt +++ b/base/src/commonTest/kotlin/state/StateRepoTest.kt @@ -33,7 +33,7 @@ import kotlin.test.assertFalse import kotlin.test.assertTrue sealed class TrafficLightState : - State, + KalugaState, HandleBeforeCreating, HandleAfterCreating, HandleBeforeOldStateIsRemoved, diff --git a/bluetooth/src/commonMain/kotlin/device/DeviceState.kt b/bluetooth/src/commonMain/kotlin/device/DeviceState.kt index 65bef316f..2b03e3958 100644 --- a/bluetooth/src/commonMain/kotlin/device/DeviceState.kt +++ b/bluetooth/src/commonMain/kotlin/device/DeviceState.kt @@ -20,7 +20,7 @@ package com.splendo.kaluga.bluetooth.device import com.splendo.kaluga.bluetooth.Service import com.splendo.kaluga.state.HandleAfterOldStateIsRemoved import com.splendo.kaluga.state.HotStateFlowRepo -import com.splendo.kaluga.state.State +import com.splendo.kaluga.state.KalugaState import com.splendo.kaluga.state.StateRepo import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope @@ -58,7 +58,7 @@ typealias DeviceStateFlowRepo = StateRepo -sealed class ScanningState : State { +sealed class ScanningState : KalugaState { data class Discovered( val devices: List, diff --git a/date-time/src/commonMain/kotlin/com/splendo/kaluga/datetime/timer/RecurringTimer.kt b/date-time/src/commonMain/kotlin/com/splendo/kaluga/datetime/timer/RecurringTimer.kt index d9ee0e11c..4a418ba3c 100644 --- a/date-time/src/commonMain/kotlin/com/splendo/kaluga/datetime/timer/RecurringTimer.kt +++ b/date-time/src/commonMain/kotlin/com/splendo/kaluga/datetime/timer/RecurringTimer.kt @@ -33,7 +33,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.time.Duration import kotlin.time.TimeSource -import com.splendo.kaluga.state.State as KalugaState +import com.splendo.kaluga.state.KalugaState as KalugaState /** A coroutine delay function. */ typealias DelayFunction = suspend (Duration) -> Unit diff --git a/location/src/commonMain/kotlin/location/LocationState.kt b/location/src/commonMain/kotlin/location/LocationState.kt index 29b86c829..a00c9230c 100644 --- a/location/src/commonMain/kotlin/location/LocationState.kt +++ b/location/src/commonMain/kotlin/location/LocationState.kt @@ -23,7 +23,7 @@ import com.splendo.kaluga.permissions.location.LocationPermission import com.splendo.kaluga.state.ColdStateRepo import com.splendo.kaluga.state.HandleAfterNewStateIsSet import com.splendo.kaluga.state.HandleBeforeOldStateIsRemoved -import com.splendo.kaluga.state.State +import com.splendo.kaluga.state.KalugaState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map @@ -34,7 +34,7 @@ import kotlin.coroutines.CoroutineContext * @param location The [Location] associated with the state. * @param locationManager The [BaseLocationManager] managing the location state */ -sealed class LocationState(open val location: Location, private val locationManager: BaseLocationManager) : State { +sealed class LocationState(open val location: Location, private val locationManager: BaseLocationManager) : KalugaState { override suspend fun initialState() { locationManager.startMonitoringPermissions() diff --git a/system/src/commonMain/kotlin/com/splendo/kaluga/system/network/state/NetworkState.kt b/system/src/commonMain/kotlin/com/splendo/kaluga/system/network/state/NetworkState.kt index 81279ce4f..5e2f21735 100644 --- a/system/src/commonMain/kotlin/com/splendo/kaluga/system/network/state/NetworkState.kt +++ b/system/src/commonMain/kotlin/com/splendo/kaluga/system/network/state/NetworkState.kt @@ -17,12 +17,12 @@ package com.splendo.kaluga.system.network.state -import com.splendo.kaluga.state.State +import com.splendo.kaluga.state.KalugaState import com.splendo.kaluga.system.network.Network sealed class NetworkState( open val networkType: Network, -) : State { +) : KalugaState { data class Unknown( override val networkType: Network.Unknown From 676a16efd560790b163e21c2eba72d096e7d2e72 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Fri, 11 Feb 2022 14:21:59 +0100 Subject: [PATCH 05/65] Add deprecated annotation to State. --- base/src/commonMain/kotlin/state/KalugaState.kt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/base/src/commonMain/kotlin/state/KalugaState.kt b/base/src/commonMain/kotlin/state/KalugaState.kt index 1343c2b41..6f45d8b64 100644 --- a/base/src/commonMain/kotlin/state/KalugaState.kt +++ b/base/src/commonMain/kotlin/state/KalugaState.kt @@ -74,6 +74,9 @@ interface KalugaState { suspend fun finalState() {} } +@Deprecated("Due to name clashes with platform classes and API changes this class has been renamed and changed to an interface. It will be removed in a future release.", ReplaceWith("KalugaState")) +interface State : KalugaState + interface HandleBeforeCreating { /** * Called while transitioning to a new state before the new state is created From 8f55ede1ef65c6bccbe4814fd2506761f8b5dcc7 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Fri, 11 Feb 2022 14:39:58 +0100 Subject: [PATCH 06/65] Rename Color class. --- resources/src/androidLibMain/kotlin/{Color.kt => KalugaColor.kt} | 0 resources/src/commonMain/kotlin/{Color.kt => KalugaColor.kt} | 0 resources/src/iosMain/kotlin/{Color.kt => KalugaColor.kt} | 0 resources/src/jsMain/kotlin/{Color.kt => KalugaColor.kt} | 0 resources/src/jvmMain/kotlin/{Color.kt => KalugaColor.kt} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename resources/src/androidLibMain/kotlin/{Color.kt => KalugaColor.kt} (100%) rename resources/src/commonMain/kotlin/{Color.kt => KalugaColor.kt} (100%) rename resources/src/iosMain/kotlin/{Color.kt => KalugaColor.kt} (100%) rename resources/src/jsMain/kotlin/{Color.kt => KalugaColor.kt} (100%) rename resources/src/jvmMain/kotlin/{Color.kt => KalugaColor.kt} (100%) diff --git a/resources/src/androidLibMain/kotlin/Color.kt b/resources/src/androidLibMain/kotlin/KalugaColor.kt similarity index 100% rename from resources/src/androidLibMain/kotlin/Color.kt rename to resources/src/androidLibMain/kotlin/KalugaColor.kt diff --git a/resources/src/commonMain/kotlin/Color.kt b/resources/src/commonMain/kotlin/KalugaColor.kt similarity index 100% rename from resources/src/commonMain/kotlin/Color.kt rename to resources/src/commonMain/kotlin/KalugaColor.kt diff --git a/resources/src/iosMain/kotlin/Color.kt b/resources/src/iosMain/kotlin/KalugaColor.kt similarity index 100% rename from resources/src/iosMain/kotlin/Color.kt rename to resources/src/iosMain/kotlin/KalugaColor.kt diff --git a/resources/src/jsMain/kotlin/Color.kt b/resources/src/jsMain/kotlin/KalugaColor.kt similarity index 100% rename from resources/src/jsMain/kotlin/Color.kt rename to resources/src/jsMain/kotlin/KalugaColor.kt diff --git a/resources/src/jvmMain/kotlin/Color.kt b/resources/src/jvmMain/kotlin/KalugaColor.kt similarity index 100% rename from resources/src/jvmMain/kotlin/Color.kt rename to resources/src/jvmMain/kotlin/KalugaColor.kt From fe7be465088d5c4522f810b3a83848990cd9502d Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Fri, 11 Feb 2022 14:40:23 +0100 Subject: [PATCH 07/65] Rename Color references. --- resources/src/androidLibMain/kotlin/Image.kt | 2 +- .../src/androidLibMain/kotlin/KalugaColor.kt | 22 +++++----- .../src/androidLibMain/kotlin/Resources.kt | 4 +- resources/src/commonMain/kotlin/Image.kt | 6 +-- .../src/commonMain/kotlin/KalugaColor.kt | 30 ++++++------- resources/src/commonMain/kotlin/Resources.kt | 42 +++++++++---------- resources/src/iosMain/kotlin/Image.kt | 2 +- resources/src/iosMain/kotlin/KalugaColor.kt | 26 ++++++------ resources/src/iosMain/kotlin/Resources.kt | 4 +- resources/src/jsMain/kotlin/Image.kt | 2 +- resources/src/jsMain/kotlin/KalugaColor.kt | 22 +++++----- resources/src/jsMain/kotlin/Resources.kt | 4 +- resources/src/jvmMain/kotlin/Image.kt | 2 +- resources/src/jvmMain/kotlin/KalugaColor.kt | 22 +++++----- resources/src/jvmMain/kotlin/Resources.kt | 4 +- .../kotlin/mock/resources/MockResources.kt | 4 +- .../kotlin/mock/resources/MockResources.kt | 18 ++++---- .../kotlin/mock/resources/MockResources.kt | 4 +- .../kotlin/mock/resources/MockResources.kt | 4 +- .../kotlin/mock/resources/MockResources.kt | 4 +- 20 files changed, 114 insertions(+), 114 deletions(-) diff --git a/resources/src/androidLibMain/kotlin/Image.kt b/resources/src/androidLibMain/kotlin/Image.kt index f2c759618..a87adaffe 100644 --- a/resources/src/androidLibMain/kotlin/Image.kt +++ b/resources/src/androidLibMain/kotlin/Image.kt @@ -22,7 +22,7 @@ import androidx.core.graphics.drawable.DrawableCompat actual data class Image(val drawable: Drawable) -actual fun Image.tinted(color: Color): Image? { +actual fun Image.tinted(color: KalugaColor): Image? { return drawable.constantState?.newDrawable()?.mutate()?.let { val wrapped = DrawableCompat.wrap(it) DrawableCompat.setTint(wrapped, color) diff --git a/resources/src/androidLibMain/kotlin/KalugaColor.kt b/resources/src/androidLibMain/kotlin/KalugaColor.kt index 6e3db2c1f..d18912dbf 100644 --- a/resources/src/androidLibMain/kotlin/KalugaColor.kt +++ b/resources/src/androidLibMain/kotlin/KalugaColor.kt @@ -17,19 +17,19 @@ package com.splendo.kaluga.resources -actual typealias Color = Int +actual typealias KalugaColor = Int -actual val Color.red: Double get() = redInt.toDouble() / 255.0 -actual val Color.redInt: Int get() = android.graphics.Color.red(this) -actual val Color.green: Double get() = greenInt.toDouble() / 255.0 -actual val Color.greenInt: Int get() = android.graphics.Color.green(this) -actual val Color.blue: Double get() = blueInt.toDouble() / 255.0 -actual val Color.blueInt: Int get() = android.graphics.Color.blue(this) -actual val Color.alpha: Double get() = alphaInt.toDouble() / 255.0 -actual val Color.alphaInt: Int get() = android.graphics.Color.alpha(this) +actual val KalugaColor.red: Double get() = redInt.toDouble() / 255.0 +actual val KalugaColor.redInt: Int get() = android.graphics.Color.red(this) +actual val KalugaColor.green: Double get() = greenInt.toDouble() / 255.0 +actual val KalugaColor.greenInt: Int get() = android.graphics.Color.green(this) +actual val KalugaColor.blue: Double get() = blueInt.toDouble() / 255.0 +actual val KalugaColor.blueInt: Int get() = android.graphics.Color.blue(this) +actual val KalugaColor.alpha: Double get() = alphaInt.toDouble() / 255.0 +actual val KalugaColor.alphaInt: Int get() = android.graphics.Color.alpha(this) -actual fun colorFrom(red: Double, green: Double, blue: Double, alpha: Double): Color { +actual fun colorFrom(red: Double, green: Double, blue: Double, alpha: Double): KalugaColor { return android.graphics.Color.argb((alpha * 255.0).toInt(), (red * 255.0).toInt(), (green * 255.0).toInt(), (blue * 255.0).toInt()) } -actual fun colorFrom(redInt: Int, greenInt: Int, blueInt: Int, alphaInt: Int): Color = android.graphics.Color.argb(alphaInt, redInt, greenInt, blueInt) +actual fun colorFrom(redInt: Int, greenInt: Int, blueInt: Int, alphaInt: Int): KalugaColor = android.graphics.Color.argb(alphaInt, redInt, greenInt, blueInt) diff --git a/resources/src/androidLibMain/kotlin/Resources.kt b/resources/src/androidLibMain/kotlin/Resources.kt index 030e8b6f0..ae0d1a55c 100644 --- a/resources/src/androidLibMain/kotlin/Resources.kt +++ b/resources/src/androidLibMain/kotlin/Resources.kt @@ -51,9 +51,9 @@ actual class DefaultStringLoader(private val context: Context?) : StringLoader { } } -actual class DefaultColorLoader(private val context: Context?) : ColorLoader { +actual class DefaultColorLoader(private val context: Context?) : KalugaColorLoader { actual constructor() : this(if (application != null) applicationContext else null) - override fun loadColor(identifier: String, defaultValue: Color?): Color? { + override fun loadColor(identifier: String, defaultValue: KalugaColor?): KalugaColor? { if (context == null) return defaultValue val id = context.resources.getIdentifier(identifier, "color", context.packageName) diff --git a/resources/src/commonMain/kotlin/Image.kt b/resources/src/commonMain/kotlin/Image.kt index 50252299a..bdf27fdf1 100644 --- a/resources/src/commonMain/kotlin/Image.kt +++ b/resources/src/commonMain/kotlin/Image.kt @@ -23,8 +23,8 @@ package com.splendo.kaluga.resources expect class Image /** - * Attempts to create a new [Image] that is tinted in a given [Color] - * @param color The [Color] to use for tinting. + * Attempts to create a new [Image] that is tinted in a given [KalugaColor] + * @param color The [KalugaColor] to use for tinting. * @return The tinted [Image] or `null` if tinting could not be applied. */ -expect fun Image.tinted(color: Color): Image? +expect fun Image.tinted(color: KalugaColor): Image? diff --git a/resources/src/commonMain/kotlin/KalugaColor.kt b/resources/src/commonMain/kotlin/KalugaColor.kt index 770ae6d02..477336c0b 100644 --- a/resources/src/commonMain/kotlin/KalugaColor.kt +++ b/resources/src/commonMain/kotlin/KalugaColor.kt @@ -20,57 +20,57 @@ package com.splendo.kaluga.resources /** * Class describing a color */ -expect class Color +expect class KalugaColor /** * Gets the red value of the color in a range between `0.0` and `1.0` */ -expect val Color.red: Double +expect val KalugaColor.red: Double /** * Gets the red value of the color in a range between `0` and `255` */ -expect val Color.redInt: Int +expect val KalugaColor.redInt: Int /** * Gets the green value of the color in a range between `0.0` and `1.0` */ -expect val Color.green: Double +expect val KalugaColor.green: Double /** * Gets the green value of the color in a range between `0` and `255` */ -expect val Color.greenInt: Int +expect val KalugaColor.greenInt: Int /** * Gets the blue value of the color in a range between `0.0` and `1.0` */ -expect val Color.blue: Double +expect val KalugaColor.blue: Double /** * Gets the blue value of the color in a range between `0` and `255` */ -expect val Color.blueInt: Int +expect val KalugaColor.blueInt: Int /** * Gets the alpha value of the color in a range between `0.0` and `1.0` */ -expect val Color.alpha: Double +expect val KalugaColor.alpha: Double /** * Gets the alpha value of the color in a range between `0` and `255` */ -expect val Color.alphaInt: Int +expect val KalugaColor.alphaInt: Int /** - * Creates a [Color] using red, green, blue, and (optional) alpha, all ranging between `0.0` and `1.0`. + * Creates a [KalugaColor] using red, green, blue, and (optional) alpha, all ranging between `0.0` and `1.0`. * @param red The red color value ranging between `0.0` and `1.0`. * @param green The green color value ranging between `0.0` and `1.0`. * @param blue The blue color value ranging between `0.0` and `1.0`. * @param alpha The alpha color value ranging between `0.0` and `1.0`. Defaults to `1.0` - * @return The [Color] with the corresponding red, green, blue, and alpha values + * @return The [KalugaColor] with the corresponding red, green, blue, and alpha values */ -expect fun colorFrom(red: Double, green: Double, blue: Double, alpha: Double = 1.0): Color +expect fun colorFrom(red: Double, green: Double, blue: Double, alpha: Double = 1.0): KalugaColor /** - * Creates a [Color] using red, green, blue, and (optional) alpha, all ranging between `0` and `255`. + * Creates a [KalugaColor] using red, green, blue, and (optional) alpha, all ranging between `0` and `255`. * @param red The red color value ranging between `0` and `255`. * @param green The green color value ranging between `0` and `255`. * @param blue The blue color value ranging between `0` and `255`. * @param alpha The alpha color value ranging between `0` and `255`. Defaults to `255` - * @return The [Color] with the corresponding red, green, blue, and alpha values + * @return The [KalugaColor] with the corresponding red, green, blue, and alpha values */ -expect fun colorFrom(redInt: Int, greenInt: Int, blueInt: Int, alphaInt: Int = 255): Color +expect fun colorFrom(redInt: Int, greenInt: Int, blueInt: Int, alphaInt: Int = 255): KalugaColor diff --git a/resources/src/commonMain/kotlin/Resources.kt b/resources/src/commonMain/kotlin/Resources.kt index 799394440..dcd073c5b 100644 --- a/resources/src/commonMain/kotlin/Resources.kt +++ b/resources/src/commonMain/kotlin/Resources.kt @@ -44,20 +44,20 @@ interface StringLoader { expect class DefaultStringLoader() : StringLoader /** - * Loads a [Color] based on a provided identifier. + * Loads a [KalugaColor] based on a provided identifier. */ -interface ColorLoader { +interface KalugaColorLoader { /** - * Attempts to load the [Color] resource associated with a given identifier. If no match is found, the [defaultValue] will be returned. - * @param identifier The identifier to find the [Color] resource for. - * @param defaultValue The [Color] to return if no match was found for the identifier. - * @return The associated [Color] resources or [defaultValue] if no such resource was found. + * Attempts to load the [KalugaColor] resource associated with a given identifier. If no match is found, the [defaultValue] will be returned. + * @param identifier The identifier to find the [KalugaColor] resource for. + * @param defaultValue The [KalugaColor] to return if no match was found for the identifier. + * @return The associated [KalugaColor] resources or [defaultValue] if no such resource was found. */ - fun loadColor(identifier: String, defaultValue: Color?): Color? + fun loadColor(identifier: String, defaultValue: KalugaColor?): KalugaColor? } -/** Default implementation of a [ColorLoader]. */ -expect class DefaultColorLoader() : ColorLoader +/** Default implementation of a [KalugaColorLoader]. */ +expect class DefaultColorLoader() : KalugaColorLoader /** * Loads an [Image] based on a provided identifier. @@ -117,18 +117,18 @@ fun String.quantity( ): String = stringLoader.loadQuantityString(this, quantity, defaultValue) /** - * Treats this string as a resource identifier for a [Color] and grabs the associated [Color] - * @param colorLoader The [ColorLoader] used for loading the associated [Color] resource. - * @param defaultValue The [Color] to return if no match was found for the identifier. Defaults to `null`. - * @return The [Color] associated with the identifier represented by this String, or [defaultValue] if no such [Color] could be found. + * Treats this string as a resource identifier for a [KalugaColor] and grabs the associated [KalugaColor] + * @param colorLoader The [KalugaColorLoader] used for loading the associated [KalugaColor] resource. + * @param defaultValue The [KalugaColor] to return if no match was found for the identifier. Defaults to `null`. + * @return The [KalugaColor] associated with the identifier represented by this String, or [defaultValue] if no such [KalugaColor] could be found. */ fun String.asColor( - colorLoader: ColorLoader = DefaultColorLoader(), - defaultValue: Color? = null -): Color? = colorLoader.loadColor(this, defaultValue) + colorLoader: KalugaColorLoader = DefaultColorLoader(), + defaultValue: KalugaColor? = null +): KalugaColor? = colorLoader.loadColor(this, defaultValue) /** - * Treats this string as a resource identifier for a [Color] and grabs the associated [Image] + * Treats this string as a resource identifier for a [KalugaColor] and grabs the associated [Image] * @param imageLoader The [ImageLoader] used for loading the associated [Image] resource. * @param defaultValue The [Image] to return if no match was found for the identifier. Defaults to `null`. * @return The [Image] associated with the identifier represented by this String, or [defaultValue] if no such [Image] could be found. @@ -150,12 +150,12 @@ suspend fun String.asFont( ): Font? = fontLoader.loadFont(this, defaultValue) /** - * Attempts to parse a given [String] into a [Color]. + * Attempts to parse a given [String] into a [KalugaColor]. * The string should be formatted as either `#AARRGGBB` or `#RRGGBB` for the parsing to succeed. - * @param hexString The [String] to parse as a [Color] - * @return The [Color] associated with [hexString] or `null` if improperly formatted. + * @param hexString The [String] to parse as a [KalugaColor] + * @return The [KalugaColor] associated with [hexString] or `null` if improperly formatted. */ -fun colorFrom(hexString: String): Color? { +fun colorFrom(hexString: String): KalugaColor? { return if (hexString.startsWith('#')) { val hexColor = hexString.substring(1).toLong(16) when (hexString.length) { diff --git a/resources/src/iosMain/kotlin/Image.kt b/resources/src/iosMain/kotlin/Image.kt index 6029f1f21..3197591ad 100644 --- a/resources/src/iosMain/kotlin/Image.kt +++ b/resources/src/iosMain/kotlin/Image.kt @@ -22,4 +22,4 @@ import platform.UIKit.UIImageRenderingMode actual typealias Image = UIImage -actual fun Image.tinted(color: Color): Image? = this.imageWithTintColor(color.uiColor, UIImageRenderingMode.UIImageRenderingModeAlwaysOriginal) +actual fun Image.tinted(color: KalugaColor): Image? = this.imageWithTintColor(color.uiColor, UIImageRenderingMode.UIImageRenderingModeAlwaysOriginal) diff --git a/resources/src/iosMain/kotlin/KalugaColor.kt b/resources/src/iosMain/kotlin/KalugaColor.kt index 8c7e277dc..ecb18a5e3 100644 --- a/resources/src/iosMain/kotlin/KalugaColor.kt +++ b/resources/src/iosMain/kotlin/KalugaColor.kt @@ -23,18 +23,18 @@ import platform.CoreGraphics.CGColorGetComponents import platform.CoreGraphics.CGFloat import platform.UIKit.UIColor -actual data class Color(val uiColor: UIColor) - -actual val Color.red: Double get() = CGColorGetComponents(uiColor.CGColor)?.get(0)?.toDouble() ?: 0.0 -actual val Color.redInt: Int get() = (red * 255.0).toInt() -actual val Color.green: Double get() = CGColorGetComponents(uiColor.CGColor)?.get(1)?.toDouble() ?: 0.0 -actual val Color.blueInt: Int get() = (blue * 255.0).toInt() -actual val Color.blue: Double get() = CGColorGetComponents(uiColor.CGColor)?.get(2)?.toDouble() ?: 0.0 -actual val Color.greenInt: Int get() = (green * 255.0).toInt() -actual val Color.alpha: Double get() = CGColorGetAlpha(uiColor.CGColor)?.toDouble() -actual val Color.alphaInt: Int get() = (alpha * 255.0).toInt() - -actual fun colorFrom(red: Double, green: Double, blue: Double, alpha: Double): Color = Color(UIColor.colorWithRed(red as CGFloat, green as CGFloat, blue as CGFloat, alpha as CGFloat)) -actual fun colorFrom(redInt: Int, greenInt: Int, blueInt: Int, alphaInt: Int): Color { +actual data class KalugaColor(val uiColor: UIColor) + +actual val KalugaColor.red: Double get() = CGColorGetComponents(uiColor.CGColor)?.get(0)?.toDouble() ?: 0.0 +actual val KalugaColor.redInt: Int get() = (red * 255.0).toInt() +actual val KalugaColor.green: Double get() = CGColorGetComponents(uiColor.CGColor)?.get(1)?.toDouble() ?: 0.0 +actual val KalugaColor.blueInt: Int get() = (blue * 255.0).toInt() +actual val KalugaColor.blue: Double get() = CGColorGetComponents(uiColor.CGColor)?.get(2)?.toDouble() ?: 0.0 +actual val KalugaColor.greenInt: Int get() = (green * 255.0).toInt() +actual val KalugaColor.alpha: Double get() = CGColorGetAlpha(uiColor.CGColor)?.toDouble() +actual val KalugaColor.alphaInt: Int get() = (alpha * 255.0).toInt() + +actual fun colorFrom(red: Double, green: Double, blue: Double, alpha: Double): KalugaColor = KalugaColor(UIColor.colorWithRed(red as CGFloat, green as CGFloat, blue as CGFloat, alpha as CGFloat)) +actual fun colorFrom(redInt: Int, greenInt: Int, blueInt: Int, alphaInt: Int): KalugaColor { return colorFrom(redInt.toDouble() / 255.0, greenInt.toDouble() / 255.0, blueInt.toDouble() / 255.0, alphaInt.toDouble() / 255.0) } diff --git a/resources/src/iosMain/kotlin/Resources.kt b/resources/src/iosMain/kotlin/Resources.kt index dbc54fc50..f5d8928c5 100644 --- a/resources/src/iosMain/kotlin/Resources.kt +++ b/resources/src/iosMain/kotlin/Resources.kt @@ -40,9 +40,9 @@ actual class DefaultStringLoader(private val bundle: NSBundle, private val table } } -actual class DefaultColorLoader(private val bundle: NSBundle, private val traitCollection: UITraitCollection?) : ColorLoader { +actual class DefaultColorLoader(private val bundle: NSBundle, private val traitCollection: UITraitCollection?) : KalugaColorLoader { actual constructor() : this(NSBundle.mainBundle, null) - override fun loadColor(identifier: String, defaultValue: Color?): Color? = UIColor.colorNamed(identifier, bundle, traitCollection)?.let { Color(it) } ?: defaultValue + override fun loadColor(identifier: String, defaultValue: KalugaColor?): KalugaColor? = UIColor.colorNamed(identifier, bundle, traitCollection)?.let { KalugaColor(it) } ?: defaultValue } actual class DefaultImageLoader(private val bundle: NSBundle, private val traitCollection: UITraitCollection?) : ImageLoader { diff --git a/resources/src/jsMain/kotlin/Image.kt b/resources/src/jsMain/kotlin/Image.kt index 0726969e8..431fb32c0 100644 --- a/resources/src/jsMain/kotlin/Image.kt +++ b/resources/src/jsMain/kotlin/Image.kt @@ -19,4 +19,4 @@ package com.splendo.kaluga.resources actual class Image -actual fun Image.tinted(color: Color): Image? = null +actual fun Image.tinted(color: KalugaColor): Image? = null diff --git a/resources/src/jsMain/kotlin/KalugaColor.kt b/resources/src/jsMain/kotlin/KalugaColor.kt index fd3dbeacc..6f36575ed 100644 --- a/resources/src/jsMain/kotlin/KalugaColor.kt +++ b/resources/src/jsMain/kotlin/KalugaColor.kt @@ -17,19 +17,19 @@ package com.splendo.kaluga.resources -actual typealias Color = Int +actual typealias KalugaColor = Int -actual val Color.red: Double get() = redInt.toDouble() / 255.0 -actual val Color.redInt: Int get() = this shr 16 and 0xFF -actual val Color.green: Double get() = greenInt.toDouble() / 255.0 -actual val Color.greenInt: Int get() = this shr 8 and 0xFF -actual val Color.blue: Double get() = blueInt.toDouble() / 255.0 -actual val Color.blueInt: Int get() = this and 0xFF -actual val Color.alpha: Double get() = alphaInt.toDouble() / 255.0 -actual val Color.alphaInt: Int get() = this ushr 24 +actual val KalugaColor.red: Double get() = redInt.toDouble() / 255.0 +actual val KalugaColor.redInt: Int get() = this shr 16 and 0xFF +actual val KalugaColor.green: Double get() = greenInt.toDouble() / 255.0 +actual val KalugaColor.greenInt: Int get() = this shr 8 and 0xFF +actual val KalugaColor.blue: Double get() = blueInt.toDouble() / 255.0 +actual val KalugaColor.blueInt: Int get() = this and 0xFF +actual val KalugaColor.alpha: Double get() = alphaInt.toDouble() / 255.0 +actual val KalugaColor.alphaInt: Int get() = this ushr 24 -actual fun colorFrom(red: Double, green: Double, blue: Double, alpha: Double): Color { +actual fun colorFrom(red: Double, green: Double, blue: Double, alpha: Double): KalugaColor { return colorFrom((red * 255.0).toInt(), (green * 255.0).toInt(), (blue * 255.0).toInt(), (alpha * 255.0).toInt()) } -actual fun colorFrom(redInt: Int, greenInt: Int, blueInt: Int, alphaInt: Int): Color = alphaInt shl 24 or (redInt shl 16) or (greenInt shl 8) or blueInt +actual fun colorFrom(redInt: Int, greenInt: Int, blueInt: Int, alphaInt: Int): KalugaColor = alphaInt shl 24 or (redInt shl 16) or (greenInt shl 8) or blueInt diff --git a/resources/src/jsMain/kotlin/Resources.kt b/resources/src/jsMain/kotlin/Resources.kt index 3b474e150..68ecf6f8e 100644 --- a/resources/src/jsMain/kotlin/Resources.kt +++ b/resources/src/jsMain/kotlin/Resources.kt @@ -35,10 +35,10 @@ actual class DefaultStringLoader( ): String = formatter(identifier, quantity) ?: defaultValue } -actual class DefaultColorLoader(private val transformer: (String) -> Color?) : ColorLoader { +actual class DefaultColorLoader(private val transformer: (String) -> KalugaColor?) : KalugaColorLoader { actual constructor() : this({ null }) - override fun loadColor(identifier: String, defaultValue: Color?): Color? = + override fun loadColor(identifier: String, defaultValue: KalugaColor?): KalugaColor? = transformer(identifier) ?: defaultValue } diff --git a/resources/src/jvmMain/kotlin/Image.kt b/resources/src/jvmMain/kotlin/Image.kt index baff059e1..729a88738 100644 --- a/resources/src/jvmMain/kotlin/Image.kt +++ b/resources/src/jvmMain/kotlin/Image.kt @@ -19,4 +19,4 @@ package com.splendo.kaluga.resources actual class Image -actual fun Image.tinted(color: Color): Image? = null +actual fun Image.tinted(color: KalugaColor): Image? = null diff --git a/resources/src/jvmMain/kotlin/KalugaColor.kt b/resources/src/jvmMain/kotlin/KalugaColor.kt index fd3dbeacc..6f36575ed 100644 --- a/resources/src/jvmMain/kotlin/KalugaColor.kt +++ b/resources/src/jvmMain/kotlin/KalugaColor.kt @@ -17,19 +17,19 @@ package com.splendo.kaluga.resources -actual typealias Color = Int +actual typealias KalugaColor = Int -actual val Color.red: Double get() = redInt.toDouble() / 255.0 -actual val Color.redInt: Int get() = this shr 16 and 0xFF -actual val Color.green: Double get() = greenInt.toDouble() / 255.0 -actual val Color.greenInt: Int get() = this shr 8 and 0xFF -actual val Color.blue: Double get() = blueInt.toDouble() / 255.0 -actual val Color.blueInt: Int get() = this and 0xFF -actual val Color.alpha: Double get() = alphaInt.toDouble() / 255.0 -actual val Color.alphaInt: Int get() = this ushr 24 +actual val KalugaColor.red: Double get() = redInt.toDouble() / 255.0 +actual val KalugaColor.redInt: Int get() = this shr 16 and 0xFF +actual val KalugaColor.green: Double get() = greenInt.toDouble() / 255.0 +actual val KalugaColor.greenInt: Int get() = this shr 8 and 0xFF +actual val KalugaColor.blue: Double get() = blueInt.toDouble() / 255.0 +actual val KalugaColor.blueInt: Int get() = this and 0xFF +actual val KalugaColor.alpha: Double get() = alphaInt.toDouble() / 255.0 +actual val KalugaColor.alphaInt: Int get() = this ushr 24 -actual fun colorFrom(red: Double, green: Double, blue: Double, alpha: Double): Color { +actual fun colorFrom(red: Double, green: Double, blue: Double, alpha: Double): KalugaColor { return colorFrom((red * 255.0).toInt(), (green * 255.0).toInt(), (blue * 255.0).toInt(), (alpha * 255.0).toInt()) } -actual fun colorFrom(redInt: Int, greenInt: Int, blueInt: Int, alphaInt: Int): Color = alphaInt shl 24 or (redInt shl 16) or (greenInt shl 8) or blueInt +actual fun colorFrom(redInt: Int, greenInt: Int, blueInt: Int, alphaInt: Int): KalugaColor = alphaInt shl 24 or (redInt shl 16) or (greenInt shl 8) or blueInt diff --git a/resources/src/jvmMain/kotlin/Resources.kt b/resources/src/jvmMain/kotlin/Resources.kt index 3b474e150..68ecf6f8e 100644 --- a/resources/src/jvmMain/kotlin/Resources.kt +++ b/resources/src/jvmMain/kotlin/Resources.kt @@ -35,10 +35,10 @@ actual class DefaultStringLoader( ): String = formatter(identifier, quantity) ?: defaultValue } -actual class DefaultColorLoader(private val transformer: (String) -> Color?) : ColorLoader { +actual class DefaultColorLoader(private val transformer: (String) -> KalugaColor?) : KalugaColorLoader { actual constructor() : this({ null }) - override fun loadColor(identifier: String, defaultValue: Color?): Color? = + override fun loadColor(identifier: String, defaultValue: KalugaColor?): KalugaColor? = transformer(identifier) ?: defaultValue } diff --git a/test-utils/src/androidLibMain/kotlin/mock/resources/MockResources.kt b/test-utils/src/androidLibMain/kotlin/mock/resources/MockResources.kt index 1f924d38d..2ce3900d3 100644 --- a/test-utils/src/androidLibMain/kotlin/mock/resources/MockResources.kt +++ b/test-utils/src/androidLibMain/kotlin/mock/resources/MockResources.kt @@ -18,11 +18,11 @@ package com.splendo.kaluga.test.mock.resources import android.graphics.drawable.ColorDrawable -import com.splendo.kaluga.resources.Color +import com.splendo.kaluga.resources.KalugaColor import com.splendo.kaluga.resources.Font import com.splendo.kaluga.resources.Image import org.mockito.Mockito -actual fun mockColor(): Color = 0 +actual fun mockColor(): KalugaColor = 0 actual fun mockImage(): Image = Image(ColorDrawable(0)) actual fun mockFont(): Font = Font.DEFAULT ?: Mockito.mock(Font::class.java) diff --git a/test-utils/src/commonMain/kotlin/mock/resources/MockResources.kt b/test-utils/src/commonMain/kotlin/mock/resources/MockResources.kt index 099d6c1f2..e39d2e69e 100644 --- a/test-utils/src/commonMain/kotlin/mock/resources/MockResources.kt +++ b/test-utils/src/commonMain/kotlin/mock/resources/MockResources.kt @@ -18,8 +18,8 @@ package com.splendo.kaluga.test.mock.resources import com.splendo.kaluga.base.text.format -import com.splendo.kaluga.resources.Color -import com.splendo.kaluga.resources.ColorLoader +import com.splendo.kaluga.resources.KalugaColor +import com.splendo.kaluga.resources.KalugaColorLoader import com.splendo.kaluga.resources.Font import com.splendo.kaluga.resources.FontLoader import com.splendo.kaluga.resources.Image @@ -49,13 +49,13 @@ class MockStringLoader private constructor ( } class MockColorLoader private constructor ( - private val color: Color?, - private val colorMap: Map -) : ColorLoader { - constructor(color: Color? = null) : this(color, emptyMap()) - constructor(colorMap: Map) : this(null, colorMap) + private val color: KalugaColor?, + private val colorMap: Map +) : KalugaColorLoader { + constructor(color: KalugaColor? = null) : this(color, emptyMap()) + constructor(colorMap: Map) : this(null, colorMap) - override fun loadColor(identifier: String, defaultValue: Color?): Color? = + override fun loadColor(identifier: String, defaultValue: KalugaColor?): KalugaColor? = colorMap[identifier] ?: color ?: defaultValue } @@ -81,6 +81,6 @@ class MockFontLoader private constructor ( fontMap[identifier] ?: font ?: defaultValue } -expect fun mockColor(): Color +expect fun mockColor(): KalugaColor expect fun mockImage(): Image expect fun mockFont(): Font diff --git a/test-utils/src/iosMain/kotlin/mock/resources/MockResources.kt b/test-utils/src/iosMain/kotlin/mock/resources/MockResources.kt index 7f5864e6e..acd41bf38 100644 --- a/test-utils/src/iosMain/kotlin/mock/resources/MockResources.kt +++ b/test-utils/src/iosMain/kotlin/mock/resources/MockResources.kt @@ -17,11 +17,11 @@ package com.splendo.kaluga.test.mock.resources -import com.splendo.kaluga.resources.Color +import com.splendo.kaluga.resources.KalugaColor import com.splendo.kaluga.resources.Font import com.splendo.kaluga.resources.Image import platform.UIKit.UIColor -actual fun mockColor(): Color = Color(UIColor.blackColor()) +actual fun mockColor(): KalugaColor = KalugaColor(UIColor.blackColor()) actual fun mockImage(): Image = Image() actual fun mockFont(): Font = Font() diff --git a/test-utils/src/jsMain/kotlin/mock/resources/MockResources.kt b/test-utils/src/jsMain/kotlin/mock/resources/MockResources.kt index d6ba07fc0..42a0c240c 100644 --- a/test-utils/src/jsMain/kotlin/mock/resources/MockResources.kt +++ b/test-utils/src/jsMain/kotlin/mock/resources/MockResources.kt @@ -17,10 +17,10 @@ package com.splendo.kaluga.test.mock.resources -import com.splendo.kaluga.resources.Color +import com.splendo.kaluga.resources.KalugaColor import com.splendo.kaluga.resources.Font import com.splendo.kaluga.resources.Image -actual fun mockColor(): Color = 0 +actual fun mockColor(): KalugaColor = 0 actual fun mockImage(): Image = Image() actual fun mockFont(): Font = Font() diff --git a/test-utils/src/jvmMain/kotlin/mock/resources/MockResources.kt b/test-utils/src/jvmMain/kotlin/mock/resources/MockResources.kt index d6ba07fc0..42a0c240c 100644 --- a/test-utils/src/jvmMain/kotlin/mock/resources/MockResources.kt +++ b/test-utils/src/jvmMain/kotlin/mock/resources/MockResources.kt @@ -17,10 +17,10 @@ package com.splendo.kaluga.test.mock.resources -import com.splendo.kaluga.resources.Color +import com.splendo.kaluga.resources.KalugaColor import com.splendo.kaluga.resources.Font import com.splendo.kaluga.resources.Image -actual fun mockColor(): Color = 0 +actual fun mockColor(): KalugaColor = 0 actual fun mockImage(): Image = Image() actual fun mockFont(): Font = Font() From 59eefb7f6a75d2a5501932f50aabaa9d2c381381 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Fri, 11 Feb 2022 14:46:39 +0100 Subject: [PATCH 08/65] Add Deprecated Color. --- resources/src/commonMain/kotlin/KalugaColor.kt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/resources/src/commonMain/kotlin/KalugaColor.kt b/resources/src/commonMain/kotlin/KalugaColor.kt index 477336c0b..6dda88218 100644 --- a/resources/src/commonMain/kotlin/KalugaColor.kt +++ b/resources/src/commonMain/kotlin/KalugaColor.kt @@ -17,11 +17,15 @@ package com.splendo.kaluga.resources + /** * Class describing a color */ expect class KalugaColor +@Deprecated("Due to name clashes with platform classes and API changes this class has been renamed and changed to an interface. It will be removed in a future release.", ReplaceWith("KalugaState")) +typealias Color = KalugaColor + /** * Gets the red value of the color in a range between `0.0` and `1.0` */ From 03ed917fe0f50f6ad91b0d141fbc463173ca32d5 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Fri, 11 Feb 2022 15:04:25 +0100 Subject: [PATCH 09/65] Rename Date classes. --- .../kotlin/utils/{Date.kt => KalugaDate.kt} | 12 ++++++------ .../kotlin/utils/{Date.kt => KalugaDate.kt} | 0 .../iosMain/kotlin/utils/{Date.kt => KalugaDate.kt} | 0 .../jsMain/kotlin/utils/{Date.kt => KalugaDate.kt} | 12 ++++++------ .../jvmMain/kotlin/utils/{Date.kt => KalugaDate.kt} | 0 5 files changed, 12 insertions(+), 12 deletions(-) rename base/src/androidLibMain/kotlin/utils/{Date.kt => KalugaDate.kt} (90%) rename base/src/commonMain/kotlin/utils/{Date.kt => KalugaDate.kt} (100%) rename base/src/iosMain/kotlin/utils/{Date.kt => KalugaDate.kt} (100%) rename base/src/jsMain/kotlin/utils/{Date.kt => KalugaDate.kt} (84%) rename base/src/jvmMain/kotlin/utils/{Date.kt => KalugaDate.kt} (100%) diff --git a/base/src/androidLibMain/kotlin/utils/Date.kt b/base/src/androidLibMain/kotlin/utils/KalugaDate.kt similarity index 90% rename from base/src/androidLibMain/kotlin/utils/Date.kt rename to base/src/androidLibMain/kotlin/utils/KalugaDate.kt index 6c457e90f..fe21a2c4b 100644 --- a/base/src/androidLibMain/kotlin/utils/Date.kt +++ b/base/src/androidLibMain/kotlin/utils/KalugaDate.kt @@ -19,15 +19,15 @@ package com.splendo.kaluga.base.utils import java.util.Calendar -actual class Date internal constructor(internal val calendar: Calendar) : Comparable { +actual class KalugaDate internal constructor(internal val calendar: Calendar) : Comparable { actual companion object { - actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): Date = Date( + actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = KalugaDate( Calendar.getInstance(timeZone.timeZone, locale.locale).apply { add(Calendar.MILLISECOND, offsetInMilliseconds.toInt()) } ) - actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): Date = Date( + actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = KalugaDate( Calendar.getInstance(timeZone.timeZone, locale.locale).apply { timeInMillis = offsetInMilliseconds } @@ -83,15 +83,15 @@ actual class Date internal constructor(internal val calendar: Calendar) : Compar get() = calendar.timeInMillis set(value) { calendar.timeInMillis = value } - actual fun copy(): Date = Date(calendar.clone() as Calendar) + actual fun copy(): KalugaDate = KalugaDate(calendar.clone() as Calendar) actual override fun equals(other: Any?): Boolean { - return (other as? Date)?.let { + return (other as? KalugaDate)?.let { timeZone == other.timeZone && millisecondSinceEpoch == other.millisecondSinceEpoch } ?: false } - override fun compareTo(other: Date): Int { + override fun compareTo(other: KalugaDate): Int { return this.calendar.time.compareTo(other.calendar.time) } diff --git a/base/src/commonMain/kotlin/utils/Date.kt b/base/src/commonMain/kotlin/utils/KalugaDate.kt similarity index 100% rename from base/src/commonMain/kotlin/utils/Date.kt rename to base/src/commonMain/kotlin/utils/KalugaDate.kt diff --git a/base/src/iosMain/kotlin/utils/Date.kt b/base/src/iosMain/kotlin/utils/KalugaDate.kt similarity index 100% rename from base/src/iosMain/kotlin/utils/Date.kt rename to base/src/iosMain/kotlin/utils/KalugaDate.kt diff --git a/base/src/jsMain/kotlin/utils/Date.kt b/base/src/jsMain/kotlin/utils/KalugaDate.kt similarity index 84% rename from base/src/jsMain/kotlin/utils/Date.kt rename to base/src/jsMain/kotlin/utils/KalugaDate.kt index 9885fae2f..7b2c96ce6 100644 --- a/base/src/jsMain/kotlin/utils/Date.kt +++ b/base/src/jsMain/kotlin/utils/KalugaDate.kt @@ -18,11 +18,11 @@ package com.splendo.kaluga.base.utils // TODO Implement with proper date solution for Java Script -actual class Date internal constructor(internal val date: kotlin.js.Date) : Comparable { +actual class KalugaDate internal constructor(internal val date: kotlin.js.Date) : Comparable { actual companion object { - actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): Date = Date(kotlin.js.Date(kotlin.js.Date.now() + offsetInMilliseconds)) - actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): Date = Date(kotlin.js.Date(offsetInMilliseconds)) + actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = KalugaDate(kotlin.js.Date(kotlin.js.Date.now() + offsetInMilliseconds)) + actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = KalugaDate(kotlin.js.Date(offsetInMilliseconds)) } actual var timeZone: TimeZone @@ -74,15 +74,15 @@ actual class Date internal constructor(internal val date: kotlin.js.Date) : Comp get() = date.getTime().toLong() set(value) { } - actual fun copy(): Date = Date(kotlin.js.Date(date.getMilliseconds())) + actual fun copy(): KalugaDate = KalugaDate(kotlin.js.Date(date.getMilliseconds())) actual override fun equals(other: Any?): Boolean { - return (other as? Date)?.let { + return (other as? KalugaDate)?.let { timeZone == other.timeZone && millisecondSinceEpoch == other.millisecondSinceEpoch } ?: false } - override fun compareTo(other: Date): Int { + override fun compareTo(other: KalugaDate): Int { return when { date.getMilliseconds() < other.millisecond -> -1 date.getMilliseconds() == other.millisecond -> 0 diff --git a/base/src/jvmMain/kotlin/utils/Date.kt b/base/src/jvmMain/kotlin/utils/KalugaDate.kt similarity index 100% rename from base/src/jvmMain/kotlin/utils/Date.kt rename to base/src/jvmMain/kotlin/utils/KalugaDate.kt From fb01da3a4babc42a22894b046489e1ca3279d49c Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Fri, 11 Feb 2022 15:06:16 +0100 Subject: [PATCH 10/65] Rename Date references. --- .../compose/navigation/NavGraphBuilder.kt | 10 +- .../kaluga/architecture/compose/RouteTests.kt | 6 +- .../navigation/AndroidNavigationBundleTest.kt | 8 +- .../kotlin/navigation/NavigationBundle.kt | 6 +- .../kotlin/navigation/NavigationBundle.kt | 6 +- .../kotlin/navigation/NavigationBundleSpec.kt | 10 +- .../kotlin/navigation/MockSpecRow.kt | 6 +- .../kotlin/navigation/NavigationBundleTest.kt | 8 +- .../kotlin/text/DateFormatter.kt | 8 +- .../androidLibMain/kotlin/utils/TimeZone.kt | 4 +- .../commonMain/kotlin/text/DateFormatter.kt | 44 +++--- .../commonMain/kotlin/text/FormatSpecifier.kt | 10 +- .../commonMain/kotlin/text/StringFormatter.kt | 2 +- .../src/commonMain/kotlin/utils/KalugaDate.kt | 138 +++++++++--------- base/src/commonMain/kotlin/utils/Locale.kt | 2 +- base/src/commonMain/kotlin/utils/TimeZone.kt | 14 +- .../kotlin/text/DateFormatterTest.kt | 8 +- .../kotlin/text/StringFormatterTest.kt | 4 +- base/src/commonTest/kotlin/utils/DateTest.kt | 32 ++-- base/src/iosMain/kotlin/text/DateFormatter.kt | 8 +- base/src/iosMain/kotlin/utils/KalugaDate.kt | 16 +- base/src/iosMain/kotlin/utils/TimeZone.kt | 4 +- base/src/jsMain/kotlin/text/DateFormatter.kt | 6 +- base/src/jsMain/kotlin/utils/TimeZone.kt | 4 +- base/src/jvmMain/kotlin/text/DateFormatter.kt | 8 +- base/src/jvmMain/kotlin/utils/KalugaDate.kt | 12 +- base/src/jvmMain/kotlin/utils/TimeZone.kt | 4 +- beacons/src/commonMain/kotlin/BeaconInfo.kt | 6 +- beacons/src/commonMain/kotlin/Beacons.kt | 4 +- .../src/commonTest/kotlin/BeaconUpdateTest.kt | 4 +- .../commonMain/kotlin/device/DeviceInfo.kt | 6 +- .../AndroidDateTimePickerPresenterTest.kt | 2 +- .../kotlin/DateTimePickerPresenter.kt | 6 +- .../src/commonMain/kotlin/DateTimePicker.kt | 30 ++-- .../iosMain/kotlin/DateTimePickerPresenter.kt | 6 +- .../jsMain/kotlin/DateTimePickerPresenter.kt | 8 +- .../jvmMain/kotlin/DateTimePickerPresenter.kt | 8 +- 37 files changed, 234 insertions(+), 234 deletions(-) diff --git a/architecture-compose/src/androidLibMain/kotlin/com/splendo/kaluga/architecture/compose/navigation/NavGraphBuilder.kt b/architecture-compose/src/androidLibMain/kotlin/com/splendo/kaluga/architecture/compose/navigation/NavGraphBuilder.kt index 1f54f3aeb..66bd72c02 100644 --- a/architecture-compose/src/androidLibMain/kotlin/com/splendo/kaluga/architecture/compose/navigation/NavGraphBuilder.kt +++ b/architecture-compose/src/androidLibMain/kotlin/com/splendo/kaluga/architecture/compose/navigation/NavGraphBuilder.kt @@ -37,7 +37,7 @@ import com.splendo.kaluga.architecture.navigation.SingleValueNavigationSpec import com.splendo.kaluga.architecture.navigation.toBundle import com.splendo.kaluga.base.text.DateFormatter import com.splendo.kaluga.base.text.iso8601Pattern -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import kotlinx.serialization.KSerializer import kotlinx.serialization.builtins.BooleanArraySerializer import kotlinx.serialization.builtins.ByteArraySerializer @@ -199,13 +199,13 @@ inline fun >> NavGraph ) = composable(Action::class, NavigationBundleSpecType.StringArrayType, content) @JvmName("singleValueDateComposable") -inline fun > NavGraphBuilder.composable( - noinline content: @Composable (Date) -> Unit +inline fun > NavGraphBuilder.composable( + noinline content: @Composable (KalugaDate) -> Unit ) = composable(Action::class, NavigationBundleSpecType.DateType, content) @JvmName("singleValueDateArrayComposable") -inline fun >> NavGraphBuilder.composable( - noinline content: @Composable (List) -> Unit +inline fun >> NavGraphBuilder.composable( + noinline content: @Composable (List) -> Unit ) = composable(Action::class, NavigationBundleSpecType.DateArrayType, content) inline fun > NavGraphBuilder.composable( diff --git a/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt b/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt index b3faf8c4c..6bd2c7077 100644 --- a/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt +++ b/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt @@ -26,7 +26,7 @@ import com.splendo.kaluga.architecture.navigation.NavigationBundleSpecType import com.splendo.kaluga.architecture.navigation.toBundle import com.splendo.kaluga.base.text.DateFormatter import com.splendo.kaluga.base.text.iso8601Pattern -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.TimeZone import com.splendo.kaluga.base.utils.utc import kotlinx.serialization.Serializable @@ -57,7 +57,7 @@ sealed class MockSpecRow(associatedType: NavigationBundleSpecType) : Navig object OptionalString : MockSpecRow(NavigationBundleSpecType.OptionalType(NavigationBundleSpecType.StringType)) object OptionalFloat : MockSpecRow(NavigationBundleSpecType.OptionalType(NavigationBundleSpecType.FloatType)) object OptionalMockSerializable : MockSpecRow(NavigationBundleSpecType.OptionalType(NavigationBundleSpecType.SerializedType(MockSerializable.serializer()))) - object DateSpecRow : MockSpecRow(NavigationBundleSpecType.DateType) + object DateSpecRow : MockSpecRow(NavigationBundleSpecType.DateType) } class NestedSpec : NavigationBundleSpec>(setOf(NestedSpecRow.StringSpecRow)) @@ -73,7 +73,7 @@ class RouteTests { @Test fun testRoute() { - val time = Date.epoch(timeZone = TimeZone.utc) + val time = KalugaDate.epoch(timeZone = TimeZone.utc) val bundle = MockSpec.toBundle { row -> when (row) { is MockSpecRow.StringSpecRow -> row.convertValue("string") diff --git a/architecture/src/androidLibAndroidTest/kotlin/navigation/AndroidNavigationBundleTest.kt b/architecture/src/androidLibAndroidTest/kotlin/navigation/AndroidNavigationBundleTest.kt index b3d4f6c30..88d3f0023 100644 --- a/architecture/src/androidLibAndroidTest/kotlin/navigation/AndroidNavigationBundleTest.kt +++ b/architecture/src/androidLibAndroidTest/kotlin/navigation/AndroidNavigationBundleTest.kt @@ -18,7 +18,7 @@ package com.splendo.kaluga.architecture.navigation import android.os.Bundle -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -38,10 +38,10 @@ class AndroidNavigationBundleTest { } val optionalString: String? = "Some String" val optionalFloat: Float? = null - val dateValue = Date.epoch(offsetInMilliseconds = 1606204800000) + val dateValue = KalugaDate.epoch(offsetInMilliseconds = 1606204800000) val dateArray = listOf( - Date.epoch(offsetInMilliseconds = 1606204800001), - Date.epoch(offsetInMilliseconds = 1606204800002) + KalugaDate.epoch(offsetInMilliseconds = 1606204800001), + KalugaDate.epoch(offsetInMilliseconds = 1606204800002) ) val mockSpec = MockSpec() diff --git a/architecture/src/androidLibMain/kotlin/navigation/NavigationBundle.kt b/architecture/src/androidLibMain/kotlin/navigation/NavigationBundle.kt index 1badb7fe9..1369eff77 100644 --- a/architecture/src/androidLibMain/kotlin/navigation/NavigationBundle.kt +++ b/architecture/src/androidLibMain/kotlin/navigation/NavigationBundle.kt @@ -18,7 +18,7 @@ package com.splendo.kaluga.architecture.navigation import android.os.Bundle -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate /** * Converts a [NavigationBundle] to a [Bundle] @@ -133,10 +133,10 @@ internal fun Bundle.mapValue(key: String, specType: NavigationBundleSpecType<*>) } } is NavigationBundleSpecType.DateType -> getLong(key).let { value -> - specType.convertValue(Date.epoch(value)) + specType.convertValue(KalugaDate.epoch(value)) } is NavigationBundleSpecType.DateArrayType -> getLongArray(key)?.let { array -> - specType.convertValue(array.map { Date.epoch(it) }) + specType.convertValue(array.map { KalugaDate.epoch(it) }) } } } diff --git a/architecture/src/commonMain/kotlin/navigation/NavigationBundle.kt b/architecture/src/commonMain/kotlin/navigation/NavigationBundle.kt index 5a06752d1..209497a8a 100644 --- a/architecture/src/commonMain/kotlin/navigation/NavigationBundle.kt +++ b/architecture/src/commonMain/kotlin/navigation/NavigationBundle.kt @@ -17,7 +17,7 @@ package com.splendo.kaluga.architecture.navigation -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import kotlinx.serialization.KSerializer import kotlinx.serialization.json.Json @@ -172,8 +172,8 @@ sealed class NavigationBundleValue { data class StringValue internal constructor(override val value: String) : NavigationBundleValue() data class StringArrayValue internal constructor(override val value: List) : NavigationBundleValue>() - data class DateValue internal constructor(override val value: Date) : NavigationBundleValue() - data class DateArrayValue internal constructor(override val value: List) : NavigationBundleValue>() + data class DateValue internal constructor(override val value: KalugaDate) : NavigationBundleValue() + data class DateArrayValue internal constructor(override val value: List) : NavigationBundleValue>() data class OptionalValue internal constructor(val optionalValue: NavigationBundleValue?) : NavigationBundleValue() { override val value: T? = optionalValue?.value diff --git a/architecture/src/commonMain/kotlin/navigation/NavigationBundleSpec.kt b/architecture/src/commonMain/kotlin/navigation/NavigationBundleSpec.kt index 404c77bda..5fd48955c 100644 --- a/architecture/src/commonMain/kotlin/navigation/NavigationBundleSpec.kt +++ b/architecture/src/commonMain/kotlin/navigation/NavigationBundleSpec.kt @@ -17,7 +17,7 @@ package com.splendo.kaluga.architecture.navigation -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import kotlinx.serialization.KSerializer import kotlinx.serialization.SerializationException import kotlinx.serialization.json.Json @@ -196,14 +196,14 @@ sealed class NavigationBundleSpecType { } } - object DateType : NavigationBundleSpecType() { - override fun convertValue(value: Date): NavigationBundleValue { + object DateType : NavigationBundleSpecType() { + override fun convertValue(value: KalugaDate): NavigationBundleValue { return NavigationBundleValue.DateValue(value) } } - object DateArrayType : NavigationBundleSpecType>() { - override fun convertValue(value: List): NavigationBundleValue> { + object DateArrayType : NavigationBundleSpecType>() { + override fun convertValue(value: List): NavigationBundleValue> { return NavigationBundleValue.DateArrayValue(value) } } diff --git a/architecture/src/commonTest/kotlin/navigation/MockSpecRow.kt b/architecture/src/commonTest/kotlin/navigation/MockSpecRow.kt index b3bc2183b..4970cf2dc 100644 --- a/architecture/src/commonTest/kotlin/navigation/MockSpecRow.kt +++ b/architecture/src/commonTest/kotlin/navigation/MockSpecRow.kt @@ -17,7 +17,7 @@ package com.splendo.kaluga.architecture.navigation -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import kotlinx.serialization.Serializable @Serializable @@ -41,8 +41,8 @@ sealed class MockSpecRow(associatedType: NavigationBundleSpecType) : Navig object NestedBundleSpecRow : MockSpecRow>>(NavigationBundleSpecType.BundleType(NestedSpec())) object OptionalString : MockSpecRow(NavigationBundleSpecType.OptionalType(NavigationBundleSpecType.StringType)) object OptionalFloat : MockSpecRow(NavigationBundleSpecType.OptionalType(NavigationBundleSpecType.FloatType)) - object DateSpecRow : MockSpecRow(NavigationBundleSpecType.DateType) - object DateArraySpecRow : MockSpecRow>(NavigationBundleSpecType.DateArrayType) + object DateSpecRow : MockSpecRow(NavigationBundleSpecType.DateType) + object DateArraySpecRow : MockSpecRow>(NavigationBundleSpecType.DateArrayType) } class NestedSpec : NavigationBundleSpec>(setOf(NestedSpecRow.StringSpecRow)) diff --git a/architecture/src/commonTest/kotlin/navigation/NavigationBundleTest.kt b/architecture/src/commonTest/kotlin/navigation/NavigationBundleTest.kt index ceac48be8..517c0c653 100644 --- a/architecture/src/commonTest/kotlin/navigation/NavigationBundleTest.kt +++ b/architecture/src/commonTest/kotlin/navigation/NavigationBundleTest.kt @@ -17,7 +17,7 @@ package com.splendo.kaluga.architecture.navigation -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.test.BaseTest import kotlin.test.Test import kotlin.test.assertEquals @@ -38,10 +38,10 @@ class NavigationBundleTest : BaseTest() { } val optionalString: String? = "Some String" val optionalFloat: Float? = null - val dateValue = Date.epoch(offsetInMilliseconds = 1606204800000) + val dateValue = KalugaDate.epoch(offsetInMilliseconds = 1606204800000) val dateArray = listOf( - Date.epoch(offsetInMilliseconds = 1606204800001), - Date.epoch(offsetInMilliseconds = 1606204800002) + KalugaDate.epoch(offsetInMilliseconds = 1606204800001), + KalugaDate.epoch(offsetInMilliseconds = 1606204800002) ) val mockSpec = MockSpec() diff --git a/base/src/androidLibMain/kotlin/text/DateFormatter.kt b/base/src/androidLibMain/kotlin/text/DateFormatter.kt index 6126e836d..5e530e340 100644 --- a/base/src/androidLibMain/kotlin/text/DateFormatter.kt +++ b/base/src/androidLibMain/kotlin/text/DateFormatter.kt @@ -18,7 +18,7 @@ @file:JvmName("AndroidDateFormatter") package com.splendo.kaluga.base.text -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone import java.text.DateFormat @@ -122,12 +122,12 @@ actual class DateFormatter private constructor(private val format: SimpleDateFor get() = symbols.amPmStrings.toList()[1] set(value) { updateSymbols { it.amPmStrings = it.amPmStrings.toMutableList().apply { this[1] = value }.toTypedArray() } } - actual fun format(date: Date): String = format.format(date.calendar.time) - actual fun parse(string: String): Date? { + actual fun format(date: KalugaDate): String = format.format(date.calendar.time) + actual fun parse(string: String): KalugaDate? { return try { format.parse(string)?.let { date -> val calendar = format.calendar.clone() as Calendar - Date(calendar.apply { time = date }) + KalugaDate(calendar.apply { time = date }) } } catch (e: ParseException) { null diff --git a/base/src/androidLibMain/kotlin/utils/TimeZone.kt b/base/src/androidLibMain/kotlin/utils/TimeZone.kt index 1f4f11c23..595840a34 100644 --- a/base/src/androidLibMain/kotlin/utils/TimeZone.kt +++ b/base/src/androidLibMain/kotlin/utils/TimeZone.kt @@ -41,8 +41,8 @@ actual class TimeZone internal constructor(internal val timeZone: java.util.Time } actual val offsetFromGMTInMilliseconds = timeZone.rawOffset.toLong() actual val daylightSavingsOffsetInMilliseconds: Long = timeZone.dstSavings.toLong() - actual fun offsetFromGMTAtDateInMilliseconds(date: Date): Long = timeZone.getOffset(date.millisecondSinceEpoch).toLong() - actual fun usesDaylightSavingsTime(date: Date): Boolean = timeZone.inDaylightTime(date.calendar.time) + actual fun offsetFromGMTAtDateInMilliseconds(date: KalugaDate): Long = timeZone.getOffset(date.millisecondSinceEpoch).toLong() + actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.inDaylightTime(date.calendar.time) actual fun copy(): TimeZone = TimeZone(timeZone.clone() as java.util.TimeZone) override fun equals(other: Any?): Boolean { return (other as? TimeZone)?.let { timeZone == other.timeZone } ?: false diff --git a/base/src/commonMain/kotlin/text/DateFormatter.kt b/base/src/commonMain/kotlin/text/DateFormatter.kt index e7c998a2d..e20caf917 100644 --- a/base/src/commonMain/kotlin/text/DateFormatter.kt +++ b/base/src/commonMain/kotlin/text/DateFormatter.kt @@ -17,14 +17,14 @@ package com.splendo.kaluga.base.text -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.Locale.Companion.defaultLocale import com.splendo.kaluga.base.utils.TimeZone import com.splendo.kaluga.base.utils.enUsPosix /** - * Style used for formatting a [Date] to and from a [String] + * Style used for formatting a [KalugaDate] to and from a [String] */ enum class DateFormatStyle { /** @@ -49,14 +49,14 @@ enum class DateFormatStyle { } /** - * Class for parsing and formatting a [Date] from/to a [String]. + * Class for parsing and formatting a [KalugaDate] from/to a [String]. */ expect class DateFormatter { companion object { /** - * Creates a [DateFormatter] that only formats the date components of a [Date] - * @param style The [DateFormatStyle] used for formatting the date components of the [Date]. Defaults to [DateFormatStyle.Medium]. + * Creates a [DateFormatter] that only formats the date components of a [KalugaDate] + * @param style The [DateFormatStyle] used for formatting the date components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. * @param timeZone The [TimeZone] for which the date should be formatted. Defaults to [TimeZone.current]. * @param locale The [Locale] for which the date should be formatted. Defaults to [Locale.defaultLocale]. */ @@ -67,8 +67,8 @@ expect class DateFormatter { ): DateFormatter /** - * Creates a [DateFormatter] that only formats the time components of a [Date] - * @param style The [DateFormatStyle] used for formatting the time components of the [Date]. Defaults to [DateFormatStyle.Medium]. + * Creates a [DateFormatter] that only formats the time components of a [KalugaDate] + * @param style The [DateFormatStyle] used for formatting the time components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. * @param timeZone The [TimeZone] for which the date should be formatted. Defaults to [TimeZone.current]. * @param locale The [Locale] for which the date should be formatted. Defaults to [Locale.defaultLocale]. */ @@ -79,9 +79,9 @@ expect class DateFormatter { ): DateFormatter /** - * Creates a [DateFormatter] that formats both date and time components of a [Date] - * @param dateStyle The [DateFormatStyle] used for formatting the date components of the [Date]. Defaults to [DateFormatStyle.Medium]. - * @param timeStyle The [DateFormatStyle] used for formatting the time components of the [Date]. Defaults to [DateFormatStyle.Medium]. + * Creates a [DateFormatter] that formats both date and time components of a [KalugaDate] + * @param dateStyle The [DateFormatStyle] used for formatting the date components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. + * @param timeStyle The [DateFormatStyle] used for formatting the time components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. * @param timeZone The [TimeZone] for which the date should be formatted. Defaults to [TimeZone.current]. * @param locale The [Locale] for which the date should be formatted. Defaults to [Locale.defaultLocale]. */ @@ -150,18 +150,18 @@ expect class DateFormatter { var pmString: String /** - * Formats a given [Date] to a [String] using the format described by this [DateFormatter]. - * @param date The [Date] to format. - * @return The formatted [Date] as a [String] + * Formats a given [KalugaDate] to a [String] using the format described by this [DateFormatter]. + * @param date The [KalugaDate] to format. + * @return The formatted [KalugaDate] as a [String] */ - fun format(date: Date): String + fun format(date: KalugaDate): String /** - * Attempts to parse a given [String] into a [Date] using the format described. + * Attempts to parse a given [String] into a [KalugaDate] using the format described. * @param string The [String] to parse. - * @return A [Date] matching the format described by [string] or `null` if no such match could be made. + * @return A [KalugaDate] matching the format described by [string] or `null` if no such match could be made. */ - fun parse(string: String): Date? + fun parse(string: String): KalugaDate? } /** @@ -179,8 +179,8 @@ fun DateFormatter.Companion.fixedPatternFormat(pattern: String, timeZone: TimeZo fun DateFormatter.Companion.iso8601Pattern(timeZone: TimeZone = TimeZone.current()) = fixedPatternFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", timeZone) /** - * Creates a [DateFormatter] that only formats the date components of a [Date] - * @param style The [DateFormatStyle] used for formatting the date components of the [Date]. Defaults to [DateFormatStyle.Medium]. + * Creates a [DateFormatter] that only formats the date components of a [KalugaDate] + * @param style The [DateFormatStyle] used for formatting the date components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. * @param excludeYear When [true] the year will not be part of the format. * @param timeZone The [TimeZone] for which the date should be formatted. Defaults to [TimeZone.current]. * @param locale The [Locale] for which the date should be formatted. Defaults to [Locale.defaultLocale]. @@ -200,10 +200,10 @@ fun DateFormatter.Companion.dateFormat( } /** - * Creates a [DateFormatter] that formats both date and time components of a [Date] - * @param dateStyle The [DateFormatStyle] used for formatting the date components of the [Date]. Defaults to [DateFormatStyle.Medium]. + * Creates a [DateFormatter] that formats both date and time components of a [KalugaDate] + * @param dateStyle The [DateFormatStyle] used for formatting the date components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. * @param excludeYear When [true] the year will not be part of the format. - * @param timeStyle The [DateFormatStyle] used for formatting the time components of the [Date]. Defaults to [DateFormatStyle.Medium]. + * @param timeStyle The [DateFormatStyle] used for formatting the time components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. * @param timeZone The [TimeZone] for which the date should be formatted. Defaults to [TimeZone.current]. * @param locale The [Locale] for which the date should be formatted. Defaults to [Locale.defaultLocale]. */ diff --git a/base/src/commonMain/kotlin/text/FormatSpecifier.kt b/base/src/commonMain/kotlin/text/FormatSpecifier.kt index 2c8b0be75..c3c6b4fdf 100644 --- a/base/src/commonMain/kotlin/text/FormatSpecifier.kt +++ b/base/src/commonMain/kotlin/text/FormatSpecifier.kt @@ -18,7 +18,7 @@ package com.splendo.kaluga.base.text import com.splendo.kaluga.base.text.StringFormatter.Companion.getZero -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone import com.splendo.kaluga.base.utils.TimeZoneNameStyle @@ -107,9 +107,9 @@ internal class FormatSpecifier(private val out: StringBuilder, matchResult: Matc is Long, is Int, is Short -> { - Date.epoch((arg as Number).toLong(), TimeZone.current(), locale) + KalugaDate.epoch((arg as Number).toLong(), TimeZone.current(), locale) } - is Date -> { + is KalugaDate -> { arg.copy() } else -> throw StringFormatterException.IllegalFormatConversionException(currentChar.char, arg) @@ -346,7 +346,7 @@ internal class FormatSpecifier(private val out: StringBuilder, matchResult: Matc } } - private fun print(time: Date, currentChar: ParsingCharacter.DateTime, locale: Locale) { + private fun print(time: KalugaDate, currentChar: ParsingCharacter.DateTime, locale: Locale) { val sb = StringBuilder() print(sb, time, currentChar, locale) @@ -358,7 +358,7 @@ internal class FormatSpecifier(private val out: StringBuilder, matchResult: Matc } } - private fun print(sb: StringBuilder, time: Date, currentChar: ParsingCharacter.DateTime, locale: Locale): StringBuilder { + private fun print(sb: StringBuilder, time: KalugaDate, currentChar: ParsingCharacter.DateTime, locale: Locale): StringBuilder { when (currentChar.dateTime) { DateTime.HOUR_OF_DAY_0, DateTime.HOUR_0, DateTime.HOUR_OF_DAY, DateTime.HOUR -> { // 'l' (1 - 12) -- like I diff --git a/base/src/commonMain/kotlin/text/StringFormatter.kt b/base/src/commonMain/kotlin/text/StringFormatter.kt index a0f7efe97..8d2703047 100644 --- a/base/src/commonMain/kotlin/text/StringFormatter.kt +++ b/base/src/commonMain/kotlin/text/StringFormatter.kt @@ -48,7 +48,7 @@ interface Formattable { /** * Formats a given [String] using a printf-style format strings. - * Supports formats for [Number], [String], [Char], [Boolean], and [com.splendo.kaluga.base.utils.Date]. + * Supports formats for [Number], [String], [Char], [Boolean], and [com.splendo.kaluga.base.utils.KalugaDate]. * Custom formatting is supported by implementing [Formattable]. * Flags, precision and width are supported by this formatter as well. * Formatting will adjust for a provided [Locale]. diff --git a/base/src/commonMain/kotlin/utils/KalugaDate.kt b/base/src/commonMain/kotlin/utils/KalugaDate.kt index dc2c40997..192b80927 100644 --- a/base/src/commonMain/kotlin/utils/KalugaDate.kt +++ b/base/src/commonMain/kotlin/utils/KalugaDate.kt @@ -23,25 +23,25 @@ import com.splendo.kaluga.base.utils.Locale.Companion.defaultLocale * Class describing a point in time * Dates are localized according to a [Locale] and relative to a given [TimeZone] */ -expect class Date : Comparable { +expect class KalugaDate : Comparable { companion object { /** - * Creates a [Date] relative to the current time + * Creates a [KalugaDate] relative to the current time * @param offsetInMilliseconds The offset in milliseconds from the current time. Defaults to 0 * @param timeZone The [TimeZone] in which the Date is set. Defaults to [TimeZone.current] * @param locale The [Locale] for which the Date is configured. Defaults to [Locale.defaultLocale] - * @return A [Date] relative to the current time + * @return A [KalugaDate] relative to the current time */ - fun now(offsetInMilliseconds: Long = 0L, timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale): Date + fun now(offsetInMilliseconds: Long = 0L, timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale): KalugaDate /** - * Creates a [Date] relative to January 1st 1970 00:00:00 GMT + * Creates a [KalugaDate] relative to January 1st 1970 00:00:00 GMT * @param offsetInMilliseconds The offset in milliseconds from the epoch time. Defaults to 0 * @param timeZone The [TimeZone] in which the Date is set. Defaults to [TimeZone.current] * @param locale The [Locale] for which the Date is configured. Defaults to [Locale.defaultLocale] - * @return A [Date] relative to the current time + * @return A [KalugaDate] relative to the current time */ - fun epoch(offsetInMilliseconds: Long = 0L, timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale): Date + fun epoch(offsetInMilliseconds: Long = 0L, timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale): KalugaDate } /** @@ -125,10 +125,10 @@ expect class Date : Comparable { var millisecondSinceEpoch: Long /** - * Creates a copy of a [Date] - * @return A copy of this [Date] + * Creates a copy of a [KalugaDate] + * @return A copy of this [KalugaDate] */ - fun copy(): Date + fun copy(): KalugaDate /** * Returns whether this Date is in the same [timeZone] and has the same time based on [millisecondSinceEpoch] @@ -140,41 +140,41 @@ expect class Date : Comparable { } /** - * Creates a [Date] with the same [Locale] and [TimeZone] as the left date, but earlier by the right date millisecondSinceEpoch - * @param date The [Date] of which the millisecondSinceEpoch to subtract should be retrieved - * @return A new [Date] with the same [Locale] and [TimeZone] as the left date, but earlier by the right date millisecondSinceEpoch + * Creates a [KalugaDate] with the same [Locale] and [TimeZone] as the left date, but earlier by the right date millisecondSinceEpoch + * @param date The [KalugaDate] of which the millisecondSinceEpoch to subtract should be retrieved + * @return A new [KalugaDate] with the same [Locale] and [TimeZone] as the left date, but earlier by the right date millisecondSinceEpoch */ -operator fun Date.minus(date: Date): Date { +operator fun KalugaDate.minus(date: KalugaDate): KalugaDate { return copy().apply { millisecondSinceEpoch -= date.millisecondSinceEpoch } } /** - * Creates a [Date] with the same [Locale] and [TimeZone] as the left date, but later by the right date millisecondSinceEpoch - * @param date The [Date] of which the millisecondSinceEpoch to add should be retrieved - * @return A new [Date] with the same [Locale] and [TimeZone] as the left date, but later by the right date millisecondSinceEpoch + * Creates a [KalugaDate] with the same [Locale] and [TimeZone] as the left date, but later by the right date millisecondSinceEpoch + * @param date The [KalugaDate] of which the millisecondSinceEpoch to add should be retrieved + * @return A new [KalugaDate] with the same [Locale] and [TimeZone] as the left date, but later by the right date millisecondSinceEpoch */ -operator fun Date.plus(date: Date): Date { +operator fun KalugaDate.plus(date: KalugaDate): KalugaDate { return copy().apply { millisecondSinceEpoch += date.millisecondSinceEpoch } } /** - * Creates a [Date] relative to the current time, in the UTC timezone + * Creates a [KalugaDate] relative to the current time, in the UTC timezone * @param offsetInMilliseconds The offset in milliseconds from the current time. Defaults to 0 * @param locale The [Locale] for which the Date is configured. Defaults to [Locale.defaultLocale] - * @return A [Date] relative to the current time, in the UTC timezone + * @return A [KalugaDate] relative to the current time, in the UTC timezone */ -fun Date.Companion.nowUtc(offsetInMilliseconds: Long = 0L, locale: Locale = defaultLocale): Date = +fun KalugaDate.Companion.nowUtc(offsetInMilliseconds: Long = 0L, locale: Locale = defaultLocale): KalugaDate = now(offsetInMilliseconds, TimeZone.utc, locale) /** - * Gets a [Date] equal to midnight on the same day as this Date - * @return A [Date] equal to midnight on the same day as this Date + * Gets a [KalugaDate] equal to midnight on the same day as this Date + * @return A [KalugaDate] equal to midnight on the same day as this Date */ -fun Date.toStartOfDay() = this.copy().apply { +fun KalugaDate.toStartOfDay() = this.copy().apply { hour = 0 minute = 0 second = 0 @@ -182,27 +182,27 @@ fun Date.toStartOfDay() = this.copy().apply { } /** - * Gets a [Date] that is set at midnight on the same day as the current time. + * Gets a [KalugaDate] that is set at midnight on the same day as the current time. * @param timeZone The [TimeZone] in which the Date is set. Defaults to [TimeZone.current] * @param locale The [Locale] for which the Date is configured. Defaults to [Locale.defaultLocale] - * @return A [Date] that is set at midnight on the same day as the current time. + * @return A [KalugaDate] that is set at midnight on the same day as the current time. */ -fun Date.Companion.today(timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale) = now(timeZone = timeZone, locale = locale).toStartOfDay() +fun KalugaDate.Companion.today(timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale) = now(timeZone = timeZone, locale = locale).toStartOfDay() /** - * Gets a [Date] that is set at midnight on the day after the current time. + * Gets a [KalugaDate] that is set at midnight on the day after the current time. * @param timeZone The [TimeZone] in which the Date is set. Defaults to [TimeZone.current] * @param locale The [Locale] for which the Date is configured. Defaults to [Locale.defaultLocale] - * @return A [Date] that is set at midnight on the day after the current time. + * @return A [KalugaDate] that is set at midnight on the day after the current time. */ -fun Date.Companion.tomorrow(timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale) = today(timeZone = timeZone, locale = locale).apply { day += 1 } +fun KalugaDate.Companion.tomorrow(timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale) = today(timeZone = timeZone, locale = locale).apply { day += 1 } /** - * Checks whether a [Date] is on the same day as a given Date. - * @param date The [Date] to check - * @return `true` if this [Date] is on the same day as [date] + * Checks whether a [KalugaDate] is on the same day as a given Date. + * @param date The [KalugaDate] to check + * @return `true` if this [KalugaDate] is on the same day as [date] */ -fun Date.isOnSameDay(date: Date): Boolean { +fun KalugaDate.isOnSameDay(date: KalugaDate): Boolean { return this.era == date.era && this.year == date.year && this.month == date.month && @@ -210,76 +210,76 @@ fun Date.isOnSameDay(date: Date): Boolean { } /** - * Checks whether a [Date] is on the same month as a given Date. - * @param date The [Date] to check - * @return `true` if this [Date] is on the same month as [date] + * Checks whether a [KalugaDate] is on the same month as a given Date. + * @param date The [KalugaDate] to check + * @return `true` if this [KalugaDate] is on the same month as [date] */ -fun Date.isOnSameMonth(date: Date): Boolean { +fun KalugaDate.isOnSameMonth(date: KalugaDate): Boolean { return this.era == date.era && this.year == date.year && this.month == date.month } /** - * Checks whether a [Date] is in the same year as a given Date. - * @param date The [Date] to check - * @return `true` if this [Date] is in the same year as [date] + * Checks whether a [KalugaDate] is in the same year as a given Date. + * @param date The [KalugaDate] to check + * @return `true` if this [KalugaDate] is in the same year as [date] */ -fun Date.isInSameYear(date: Date): Boolean { +fun KalugaDate.isInSameYear(date: KalugaDate): Boolean { return this.era == date.era && this.year == date.year } /** - * True if this [Date] is today + * True if this [KalugaDate] is today */ -val Date.isToday: Boolean - get() = isOnSameDay(Date.now(timeZone = this.timeZone)) +val KalugaDate.isToday: Boolean + get() = isOnSameDay(KalugaDate.now(timeZone = this.timeZone)) /** - * True if this [Date] is yesterday + * True if this [KalugaDate] is yesterday */ -val Date.isYesterday: Boolean - get() = isOnSameDay(Date.now(timeZone = this.timeZone).apply { day -= 1 }) +val KalugaDate.isYesterday: Boolean + get() = isOnSameDay(KalugaDate.now(timeZone = this.timeZone).apply { day -= 1 }) /** - * True if this [Date] is tomorrow + * True if this [KalugaDate] is tomorrow */ -val Date.isTomorrow: Boolean - get() = isOnSameDay(Date.now(timeZone = this.timeZone).apply { day += 1 }) +val KalugaDate.isTomorrow: Boolean + get() = isOnSameDay(KalugaDate.now(timeZone = this.timeZone).apply { day += 1 }) /** - * True if this [Date] is this month + * True if this [KalugaDate] is this month */ -val Date.isThisMonth: Boolean - get() = isOnSameMonth(Date.now(timeZone = this.timeZone)) +val KalugaDate.isThisMonth: Boolean + get() = isOnSameMonth(KalugaDate.now(timeZone = this.timeZone)) /** - * True if this [Date] is last month + * True if this [KalugaDate] is last month */ -val Date.isLastMonth: Boolean - get() = isOnSameMonth(Date.now(timeZone = this.timeZone).apply { month -= 1 }) +val KalugaDate.isLastMonth: Boolean + get() = isOnSameMonth(KalugaDate.now(timeZone = this.timeZone).apply { month -= 1 }) /** - * True if this [Date] is next month + * True if this [KalugaDate] is next month */ -val Date.isNextMonth: Boolean - get() = isOnSameMonth(Date.now(timeZone = this.timeZone).apply { month += 1 }) +val KalugaDate.isNextMonth: Boolean + get() = isOnSameMonth(KalugaDate.now(timeZone = this.timeZone).apply { month += 1 }) /** - * True if this [Date] is this year + * True if this [KalugaDate] is this year */ -val Date.isThisYear: Boolean - get() = isInSameYear(Date.now(timeZone = this.timeZone)) +val KalugaDate.isThisYear: Boolean + get() = isInSameYear(KalugaDate.now(timeZone = this.timeZone)) /** - * True if this [Date] is last year + * True if this [KalugaDate] is last year */ -val Date.isLastYear: Boolean - get() = isInSameYear(Date.now(timeZone = this.timeZone).apply { year -= 1 }) +val KalugaDate.isLastYear: Boolean + get() = isInSameYear(KalugaDate.now(timeZone = this.timeZone).apply { year -= 1 }) /** - * True if this [Date] is next year + * True if this [KalugaDate] is next year */ -val Date.isNextYear: Boolean - get() = isInSameYear(Date.now(timeZone = this.timeZone).apply { year += 1 }) +val KalugaDate.isNextYear: Boolean + get() = isInSameYear(KalugaDate.now(timeZone = this.timeZone).apply { year += 1 }) diff --git a/base/src/commonMain/kotlin/utils/Locale.kt b/base/src/commonMain/kotlin/utils/Locale.kt index 4d408c72e..7c393d166 100644 --- a/base/src/commonMain/kotlin/utils/Locale.kt +++ b/base/src/commonMain/kotlin/utils/Locale.kt @@ -151,6 +151,6 @@ val Locale.Companion.enUsPosix get() = createLocale("en", "US", "POSIX") */ val Locale.uses24HourClock: Boolean get() { val formatter = DateFormatter.timeFormat(DateFormatStyle.Medium, locale = this) - val formattedDate = formatter.format(Date.now()) + val formattedDate = formatter.format(KalugaDate.now()) return !formattedDate.contains(formatter.amString) && !formattedDate.contains(formatter.pmString) } diff --git a/base/src/commonMain/kotlin/utils/TimeZone.kt b/base/src/commonMain/kotlin/utils/TimeZone.kt index fed36bb97..45f63af76 100644 --- a/base/src/commonMain/kotlin/utils/TimeZone.kt +++ b/base/src/commonMain/kotlin/utils/TimeZone.kt @@ -17,7 +17,7 @@ package com.splendo.kaluga.base.utils -import com.splendo.kaluga.base.utils.Date.Companion.now +import com.splendo.kaluga.base.utils.KalugaDate.Companion.now import com.splendo.kaluga.base.utils.Locale.Companion.defaultLocale import kotlin.native.concurrent.ThreadLocal @@ -78,18 +78,18 @@ expect class TimeZone { val daylightSavingsOffsetInMilliseconds: Long /** - * The number of milliseconds this [TimeZone] differs from GMT at a given [Date] - * @param date The [Date] for which to check the offset. Defaults to [Date.now] + * The number of milliseconds this [TimeZone] differs from GMT at a given [KalugaDate] + * @param date The [KalugaDate] for which to check the offset. Defaults to [KalugaDate.now] * @return The number of milliseconds this [TimeZone] differs from GMT at [date] */ - fun offsetFromGMTAtDateInMilliseconds(date: Date = now()): Long + fun offsetFromGMTAtDateInMilliseconds(date: KalugaDate = now()): Long /** - * Returns `true` if this [TimeZone] is observing daylight savings at a given [Date] - * @param date The [Date] for which to check whether daylight savings is observed. Defaults to [Date.now] + * Returns `true` if this [TimeZone] is observing daylight savings at a given [KalugaDate] + * @param date The [KalugaDate] for which to check whether daylight savings is observed. Defaults to [KalugaDate.now] * @return `true` if this [TimeZone] if observing daylight savings at [date] */ - fun usesDaylightSavingsTime(date: Date = now()): Boolean + fun usesDaylightSavingsTime(date: KalugaDate = now()): Boolean /** * Creates a copy of this [TimeZone] diff --git a/base/src/commonTest/kotlin/text/DateFormatterTest.kt b/base/src/commonTest/kotlin/text/DateFormatterTest.kt index 6881fbcc5..825c84743 100644 --- a/base/src/commonTest/kotlin/text/DateFormatterTest.kt +++ b/base/src/commonTest/kotlin/text/DateFormatterTest.kt @@ -21,7 +21,7 @@ import com.splendo.kaluga.base.text.DateFormatStyle import com.splendo.kaluga.base.text.DateFormatter import com.splendo.kaluga.base.text.dateFormat import com.splendo.kaluga.base.text.iso8601Pattern -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale.Companion.createLocale import com.splendo.kaluga.base.utils.TimeZone import com.splendo.kaluga.base.utils.nowUtc @@ -38,14 +38,14 @@ class DateFormatterTest { private val FranceLocale = createLocale("fr", "FR") private val PSTTimeZone = TimeZone.get("America/Los_Angeles")!! - private val January81988 = Date.epoch(568627200000) - private val March181988 = Date.epoch(574695462750) + private val January81988 = KalugaDate.epoch(568627200000) + private val March181988 = KalugaDate.epoch(574695462750) } @Test fun testFormatDate() { val formatter = DateFormatter.dateFormat(DateFormatStyle.Short, PSTTimeZone, UnitedStatesLocale) - val date = Date.nowUtc().apply { + val date = KalugaDate.nowUtc().apply { year = 2020 month = 1 day = 8 diff --git a/base/src/commonTest/kotlin/text/StringFormatterTest.kt b/base/src/commonTest/kotlin/text/StringFormatterTest.kt index fa0eb02c7..656bfbcad 100644 --- a/base/src/commonTest/kotlin/text/StringFormatterTest.kt +++ b/base/src/commonTest/kotlin/text/StringFormatterTest.kt @@ -18,7 +18,7 @@ package com.splendo.kaluga.base.test.text import com.splendo.kaluga.base.text.format -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale.Companion.createLocale import com.splendo.kaluga.base.utils.TimeZone import kotlin.test.Test @@ -444,7 +444,7 @@ class StringFormatterTest { @Test fun testFormatDate() { - val date = Date.now(timeZone = TimeZone.get("America/Los_Angeles")!!, locale = locale).apply { + val date = KalugaDate.now(timeZone = TimeZone.get("America/Los_Angeles")!!, locale = locale).apply { year = 2020 month = 7 day = 23 diff --git a/base/src/commonTest/kotlin/utils/DateTest.kt b/base/src/commonTest/kotlin/utils/DateTest.kt index 47b47255d..dda9cc982 100644 --- a/base/src/commonTest/kotlin/utils/DateTest.kt +++ b/base/src/commonTest/kotlin/utils/DateTest.kt @@ -17,7 +17,7 @@ package com.splendo.kaluga.base.test.utils -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone import com.splendo.kaluga.base.utils.enUsPosix @@ -33,49 +33,49 @@ class DateTest { @Test fun testEquality() { - val now = Date.now(locale = Locale.enUsPosix) + val now = KalugaDate.now(locale = Locale.enUsPosix) assertEquals(now, now.copy(), "copied Date should be equal") - val nearEpoch = Date.epoch(1001) - assertEquals(Date.epoch(1001), nearEpoch, "equally created dates should be equal") + val nearEpoch = KalugaDate.epoch(1001) + assertEquals(KalugaDate.epoch(1001), nearEpoch, "equally created dates should be equal") - assertEquals(Date.epoch(1002), nearEpoch + Date.epoch(1), "Date from addition should be equal") + assertEquals(KalugaDate.epoch(1002), nearEpoch + KalugaDate.epoch(1), "Date from addition should be equal") } @Test fun testUTCDate() { - val utcNow = Date.nowUtc(locale = Locale.enUsPosix) + val utcNow = KalugaDate.nowUtc(locale = Locale.enUsPosix) val epochNow = utcNow.millisecondSinceEpoch - val now = Date.epoch(epochNow, TimeZone.utc, locale = Locale.enUsPosix) + val now = KalugaDate.epoch(epochNow, TimeZone.utc, locale = Locale.enUsPosix) assertEquals(utcNow.millisecondSinceEpoch, now.millisecondSinceEpoch) assertEquals(utcNow, now) } @Test fun testCreateEpochDate() { - val someDay = Date.epoch(locale = Locale.enUsPosix).apply { + val someDay = KalugaDate.epoch(locale = Locale.enUsPosix).apply { year = 2020 month = 5 day = 12 hour = 8 minute = 45 } - val epoch = Date.epoch(locale = Locale.enUsPosix) + val epoch = KalugaDate.epoch(locale = Locale.enUsPosix) assertTrue(epoch < someDay) } @Test fun testCreateNowDate() { - val now = Date.now(locale = Locale.enUsPosix) - val epoch = Date.epoch(locale = Locale.enUsPosix) + val now = KalugaDate.now(locale = Locale.enUsPosix) + val epoch = KalugaDate.epoch(locale = Locale.enUsPosix) assertTrue(now > epoch) } @Test fun testUpdateDate() { - val epoch = Date.epoch(locale = Locale.enUsPosix) + val epoch = KalugaDate.epoch(locale = Locale.enUsPosix) val isEarlierThanGMT = epoch.timeZone.offsetFromGMTAtDateInMilliseconds(epoch) < 0 assertEquals(if (isEarlierThanGMT) 1969 else 1970, epoch.year) assertEquals(if (isEarlierThanGMT) 12 else 1, epoch.month) @@ -86,7 +86,7 @@ class DateTest { @Test fun testGet() { - val someDay = Date.epoch(574695462750, TimeZone.utc, locale = Locale.enUsPosix) + val someDay = KalugaDate.epoch(574695462750, TimeZone.utc, locale = Locale.enUsPosix) assertEquals(1, someDay.era) assertEquals(1988, someDay.year) @@ -108,8 +108,8 @@ class DateTest { val france = Locale.createLocale("fr", "FR") val us = Locale.createLocale("en", "US") - val frenchNow = Date.now(0, TimeZone.utc, france) - val usNow = Date.now(0, TimeZone.utc, us) + val frenchNow = KalugaDate.now(0, TimeZone.utc, france) + val usNow = KalugaDate.now(0, TimeZone.utc, us) assertEquals(2, frenchNow.firstWeekDay) assertEquals(1, usNow.firstWeekDay) @@ -117,7 +117,7 @@ class DateTest { @Test fun testDaylightSavings() { - val dayBeforeDLS = Date.epoch(1616828400000, locale = Locale.createLocale("nl", "NL"), timeZone = TimeZone.get("Europe/Amsterdam")!!) + val dayBeforeDLS = KalugaDate.epoch(1616828400000, locale = Locale.createLocale("nl", "NL"), timeZone = TimeZone.get("Europe/Amsterdam")!!) val startOfDayBeforeDLS = dayBeforeDLS.toStartOfDay() assertEquals(0, startOfDayBeforeDLS.hour) assertEquals(27, startOfDayBeforeDLS.day) diff --git a/base/src/iosMain/kotlin/text/DateFormatter.kt b/base/src/iosMain/kotlin/text/DateFormatter.kt index 60d4c3442..9c321e329 100644 --- a/base/src/iosMain/kotlin/text/DateFormatter.kt +++ b/base/src/iosMain/kotlin/text/DateFormatter.kt @@ -18,7 +18,7 @@ package com.splendo.kaluga.base.text import com.splendo.kaluga.base.typedList -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone import platform.Foundation.NSCalendar @@ -108,11 +108,11 @@ actual class DateFormatter private constructor(private val format: NSDateFormatt get() = format.PMSymbol set(value) { format.PMSymbol = value } - actual fun format(date: Date): String = format.stringFromDate(date.date) - actual fun parse(string: String): Date? { + actual fun format(date: KalugaDate): String = format.stringFromDate(date.date) + actual fun parse(string: String): KalugaDate? { return format.dateFromString(string)?.let { date -> val calendar = format.calendar.copy() as NSCalendar - Date(calendar, date) + KalugaDate(calendar, date) } } } diff --git a/base/src/iosMain/kotlin/utils/KalugaDate.kt b/base/src/iosMain/kotlin/utils/KalugaDate.kt index 8af3c46f8..9ce1d394d 100644 --- a/base/src/iosMain/kotlin/utils/KalugaDate.kt +++ b/base/src/iosMain/kotlin/utils/KalugaDate.kt @@ -44,26 +44,26 @@ import platform.darwin.NSInteger import platform.darwin.NSUInteger import kotlin.math.round -actual class Date internal constructor(private val calendar: NSCalendar, initialDate: NSDate) : Comparable { +actual class KalugaDate internal constructor(private val calendar: NSCalendar, initialDate: NSDate) : Comparable { actual companion object { const val nanoSecondPerMilliSecond = 1000 * 1000 - actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): Date { + actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate { val calendar = NSCalendar.currentCalendar.apply { this.locale = locale.nsLocale this.timeZone = timeZone.timeZone } val date = NSDate.dateWithTimeIntervalSinceNow(offsetInMilliseconds.toDouble() / 1000.0) - return Date(calendar, date) + return KalugaDate(calendar, date) } - actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): Date { + actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate { val calendar = NSCalendar.currentCalendar.apply { this.locale = locale.nsLocale this.timeZone = timeZone.timeZone } val date = NSDate.dateWithTimeIntervalSince1970(offsetInMilliseconds.toDouble() / 1000.0) - return Date(calendar, date) + return KalugaDate(calendar, date) } } @@ -121,10 +121,10 @@ actual class Date internal constructor(private val calendar: NSCalendar, initial } set(value) { date = NSDate.dateWithTimeIntervalSince1970(value.toDouble() / 1000.0) } - actual fun copy(): Date = Date(calendar.copy() as NSCalendar, date.copy() as NSDate) + actual fun copy(): KalugaDate = KalugaDate(calendar.copy() as NSCalendar, date.copy() as NSDate) actual override fun equals(other: Any?): Boolean { - return (other as? Date)?.let { other -> + return (other as? KalugaDate)?.let { other -> calendar.calendarIdentifier == other.calendar.calendarIdentifier && millisecondSinceEpoch == other.millisecondSinceEpoch && this.calendar.timeZone == other.calendar.timeZone } ?: false } @@ -135,7 +135,7 @@ actual class Date internal constructor(private val calendar: NSCalendar, initial return result } - override fun compareTo(other: Date): Int = this.date.compare(other.date).toInt() + override fun compareTo(other: KalugaDate): Int = this.date.compare(other.date).toInt() private fun updateDateForComponent(component: NSCalendarUnit, value: Int) { // Check whether this component update can use dateBySettingUnit. diff --git a/base/src/iosMain/kotlin/utils/TimeZone.kt b/base/src/iosMain/kotlin/utils/TimeZone.kt index 5b2f73684..82818d24c 100644 --- a/base/src/iosMain/kotlin/utils/TimeZone.kt +++ b/base/src/iosMain/kotlin/utils/TimeZone.kt @@ -75,8 +75,8 @@ actual class TimeZone internal constructor(val timeZone: NSTimeZone) { } return rawOffset * 1000L } - actual fun offsetFromGMTAtDateInMilliseconds(date: Date): Long = (timeZone.secondsFromGMTForDate(date.date) * 1000L) - actual fun usesDaylightSavingsTime(date: Date): Boolean = timeZone.isDaylightSavingTimeForDate(date.date) + actual fun offsetFromGMTAtDateInMilliseconds(date: KalugaDate): Long = (timeZone.secondsFromGMTForDate(date.date) * 1000L) + actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.isDaylightSavingTimeForDate(date.date) actual fun copy(): TimeZone = TimeZone(timeZone.copy() as NSTimeZone) override fun equals(other: Any?): Boolean { return (other as? TimeZone)?.let { timeZone == other.timeZone } ?: false diff --git a/base/src/jsMain/kotlin/text/DateFormatter.kt b/base/src/jsMain/kotlin/text/DateFormatter.kt index 242ddbe7c..c21f74cc9 100644 --- a/base/src/jsMain/kotlin/text/DateFormatter.kt +++ b/base/src/jsMain/kotlin/text/DateFormatter.kt @@ -17,7 +17,7 @@ package com.splendo.kaluga.base.text -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone @@ -61,8 +61,8 @@ actual class DateFormatter private constructor(initialTimeZone: TimeZone, privat actual var amString: String = "" actual var pmString: String = "" - actual fun format(date: Date): String = formatter(date.date) - actual fun parse(string: String): Date? = null + actual fun format(date: KalugaDate): String = formatter(date.date) + actual fun parse(string: String): KalugaDate? = null } private fun DateFormatStyle.stringValue(): String = when (this) { diff --git a/base/src/jsMain/kotlin/utils/TimeZone.kt b/base/src/jsMain/kotlin/utils/TimeZone.kt index 495dab0a8..f77016636 100644 --- a/base/src/jsMain/kotlin/utils/TimeZone.kt +++ b/base/src/jsMain/kotlin/utils/TimeZone.kt @@ -30,7 +30,7 @@ actual class TimeZone internal constructor() { actual fun displayName(style: TimeZoneNameStyle, withDaylightSavings: Boolean, locale: Locale): String = "" actual val offsetFromGMTInMilliseconds = 0L actual val daylightSavingsOffsetInMilliseconds: Long = 0L - actual fun offsetFromGMTAtDateInMilliseconds(date: Date): Long = 0L - actual fun usesDaylightSavingsTime(date: Date): Boolean = false + actual fun offsetFromGMTAtDateInMilliseconds(date: KalugaDate): Long = 0L + actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = false actual fun copy(): TimeZone = TimeZone() } diff --git a/base/src/jvmMain/kotlin/text/DateFormatter.kt b/base/src/jvmMain/kotlin/text/DateFormatter.kt index 4b3ac8b56..40410f832 100644 --- a/base/src/jvmMain/kotlin/text/DateFormatter.kt +++ b/base/src/jvmMain/kotlin/text/DateFormatter.kt @@ -18,7 +18,7 @@ @file:JvmName("JvmDateFormatter") package com.splendo.kaluga.base.text -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone import java.text.DateFormat @@ -125,12 +125,12 @@ actual class DateFormatter private constructor(private val format: SimpleDateFor get() = symbols.amPmStrings.toList()[1] set(value) { updateSymbols { it.amPmStrings = it.amPmStrings.toMutableList().apply { this[1] = value }.toTypedArray() } } - actual fun format(date: Date): String = format.format(date.calendar.time) - actual fun parse(string: String): Date? { + actual fun format(date: KalugaDate): String = format.format(date.calendar.time) + actual fun parse(string: String): KalugaDate? { return try { format.parse(string)?.let { date -> val calendar = format.calendar.clone() as Calendar - Date(calendar.apply { time = date }) + KalugaDate(calendar.apply { time = date }) } } catch (e: ParseException) { null diff --git a/base/src/jvmMain/kotlin/utils/KalugaDate.kt b/base/src/jvmMain/kotlin/utils/KalugaDate.kt index fc2ea5353..7c760a1a6 100644 --- a/base/src/jvmMain/kotlin/utils/KalugaDate.kt +++ b/base/src/jvmMain/kotlin/utils/KalugaDate.kt @@ -19,15 +19,15 @@ package com.splendo.kaluga.base.utils import java.util.Calendar -actual class Date internal constructor(internal val calendar: Calendar) : Comparable { +actual class KalugaDate internal constructor(internal val calendar: Calendar) : Comparable { actual companion object { - actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): Date = Date( + actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = KalugaDate( Calendar.getInstance(timeZone.timeZone, locale.locale).apply { add(Calendar.MILLISECOND, offsetInMilliseconds.toInt()) } ) - actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): Date = Date( + actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = KalugaDate( Calendar.getInstance(timeZone.timeZone, locale.locale).apply { timeInMillis = offsetInMilliseconds } @@ -83,15 +83,15 @@ actual class Date internal constructor(internal val calendar: Calendar) : Compar get() = calendar.timeInMillis set(value) { calendar.timeInMillis = value } - actual fun copy(): Date = Date(calendar.clone() as Calendar) + actual fun copy(): KalugaDate = KalugaDate(calendar.clone() as Calendar) actual override fun equals(other: Any?): Boolean { - return (other as? Date)?.let { + return (other as? KalugaDate)?.let { timeZone == other.timeZone && millisecondSinceEpoch == other.millisecondSinceEpoch } ?: false } - override fun compareTo(other: Date): Int { + override fun compareTo(other: KalugaDate): Int { return this.calendar.time.compareTo(other.calendar.time) } } diff --git a/base/src/jvmMain/kotlin/utils/TimeZone.kt b/base/src/jvmMain/kotlin/utils/TimeZone.kt index 1f4f11c23..595840a34 100644 --- a/base/src/jvmMain/kotlin/utils/TimeZone.kt +++ b/base/src/jvmMain/kotlin/utils/TimeZone.kt @@ -41,8 +41,8 @@ actual class TimeZone internal constructor(internal val timeZone: java.util.Time } actual val offsetFromGMTInMilliseconds = timeZone.rawOffset.toLong() actual val daylightSavingsOffsetInMilliseconds: Long = timeZone.dstSavings.toLong() - actual fun offsetFromGMTAtDateInMilliseconds(date: Date): Long = timeZone.getOffset(date.millisecondSinceEpoch).toLong() - actual fun usesDaylightSavingsTime(date: Date): Boolean = timeZone.inDaylightTime(date.calendar.time) + actual fun offsetFromGMTAtDateInMilliseconds(date: KalugaDate): Long = timeZone.getOffset(date.millisecondSinceEpoch).toLong() + actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.inDaylightTime(date.calendar.time) actual fun copy(): TimeZone = TimeZone(timeZone.clone() as java.util.TimeZone) override fun equals(other: Any?): Boolean { return (other as? TimeZone)?.let { timeZone == other.timeZone } ?: false diff --git a/beacons/src/commonMain/kotlin/BeaconInfo.kt b/beacons/src/commonMain/kotlin/BeaconInfo.kt index 0a74834aa..41520b024 100644 --- a/beacons/src/commonMain/kotlin/BeaconInfo.kt +++ b/beacons/src/commonMain/kotlin/BeaconInfo.kt @@ -17,7 +17,7 @@ package com.splendo.kaluga.bluetooth.beacons -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.bluetooth.device.Identifier typealias BeaconID = Eddystone.UID @@ -29,7 +29,7 @@ data class BeaconInfo( var beaconID: BeaconID, var txPower: TxPower, var RSSI: RSSI, - var lastSeen: Date + var lastSeen: KalugaDate ) @Deprecated( @@ -37,4 +37,4 @@ data class BeaconInfo( replaceWith = ReplaceWith(expression = "beaconID.asString()") ) fun BeaconInfo.fullID() = this.beaconID.namespace + this.beaconID.instance -fun BeaconInfo.seenMs() = Date.now().millisecondSinceEpoch - lastSeen.millisecondSinceEpoch +fun BeaconInfo.seenMs() = KalugaDate.now().millisecondSinceEpoch - lastSeen.millisecondSinceEpoch diff --git a/beacons/src/commonMain/kotlin/Beacons.kt b/beacons/src/commonMain/kotlin/Beacons.kt index 3f9bbd795..112156c85 100644 --- a/beacons/src/commonMain/kotlin/Beacons.kt +++ b/beacons/src/commonMain/kotlin/Beacons.kt @@ -19,7 +19,7 @@ package com.splendo.kaluga.bluetooth.beacons import co.touchlab.stately.collections.IsoMutableMap import com.splendo.kaluga.base.AtomicReferenceDelegate -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.bluetooth.BluetoothService import com.splendo.kaluga.bluetooth.device.Device import com.splendo.kaluga.bluetooth.device.Identifier @@ -116,7 +116,7 @@ class Beacons( val data = serviceData[Eddystone.SERVICE_UUID] ?: return null val frame = Eddystone.unpack(data) ?: return null val rssi = device.map { it.rssi }.firstOrNull() ?: 0 - val lastSeen = device.map { it.updatedAt }.firstOrNull() ?: Date.now() + val lastSeen = device.map { it.updatedAt }.firstOrNull() ?: KalugaDate.now() return BeaconInfo(device.identifier, frame.uid, frame.txPower, rssi, lastSeen) } } diff --git a/beacons/src/commonTest/kotlin/BeaconUpdateTest.kt b/beacons/src/commonTest/kotlin/BeaconUpdateTest.kt index a0f8104b6..4babc734e 100644 --- a/beacons/src/commonTest/kotlin/BeaconUpdateTest.kt +++ b/beacons/src/commonTest/kotlin/BeaconUpdateTest.kt @@ -17,7 +17,7 @@ package com.splendo.kaluga.bluetooth.beacons -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import kotlinx.coroutines.delay import kotlin.test.Test import kotlin.test.assertTrue @@ -38,7 +38,7 @@ class BeaconUpdateTest : BeaconFlowTest() { ) } - val lastSeen = Date.now() + val lastSeen = KalugaDate.now() action { delay(1_000) diff --git a/bluetooth/src/commonMain/kotlin/device/DeviceInfo.kt b/bluetooth/src/commonMain/kotlin/device/DeviceInfo.kt index 4b932d601..d2845a157 100644 --- a/bluetooth/src/commonMain/kotlin/device/DeviceInfo.kt +++ b/bluetooth/src/commonMain/kotlin/device/DeviceInfo.kt @@ -17,7 +17,7 @@ package com.splendo.kaluga.bluetooth.device -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import kotlin.math.pow expect class Identifier @@ -34,7 +34,7 @@ interface DeviceInfo { val name: String? val rssi: Int val advertisementData: BaseAdvertisementData - val updatedAt: Date + val updatedAt: KalugaDate fun distance(environmentalFactor: Double = 2.0): Double } @@ -50,7 +50,7 @@ data class DeviceInfoImpl( override val name: String? get() = deviceWrapper.name - override val updatedAt = Date.now() + override val updatedAt = KalugaDate.now() override fun distance(environmentalFactor: Double): Double { if (advertisementData.txPowerLevel == Int.MIN_VALUE || environmentalFactor.isNaN()) diff --git a/date-time-picker/src/androidLibAndroidTest/kotlin/AndroidDateTimePickerPresenterTest.kt b/date-time-picker/src/androidLibAndroidTest/kotlin/AndroidDateTimePickerPresenterTest.kt index af5799b1d..9cca473b3 100644 --- a/date-time-picker/src/androidLibAndroidTest/kotlin/AndroidDateTimePickerPresenterTest.kt +++ b/date-time-picker/src/androidLibAndroidTest/kotlin/AndroidDateTimePickerPresenterTest.kt @@ -22,7 +22,7 @@ import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until -import com.splendo.kaluga.base.utils.Date.Companion.epoch +import com.splendo.kaluga.base.utils.KalugaDate.Companion.epoch import com.splendo.kaluga.test.DateTimePickerPresenterTests import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers diff --git a/date-time-picker/src/androidLibMain/kotlin/DateTimePickerPresenter.kt b/date-time-picker/src/androidLibMain/kotlin/DateTimePickerPresenter.kt index 81ecb48e1..bfc9d2ec0 100644 --- a/date-time-picker/src/androidLibMain/kotlin/DateTimePickerPresenter.kt +++ b/date-time-picker/src/androidLibMain/kotlin/DateTimePickerPresenter.kt @@ -27,7 +27,7 @@ import com.splendo.kaluga.architecture.lifecycle.LifecycleManagerObserver import com.splendo.kaluga.architecture.lifecycle.LifecycleSubscribable import com.splendo.kaluga.architecture.lifecycle.getOrPutAndRemoveOnDestroyFromCache import com.splendo.kaluga.architecture.lifecycle.lifecycleManagerObserver -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.uses24HourClock import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow @@ -50,7 +50,7 @@ actual class DateTimePickerPresenter( } private sealed class DialogPresentation { - data class Showing(val animated: Boolean, val completion: (Date?) -> Unit) : DialogPresentation() + data class Showing(val animated: Boolean, val completion: (KalugaDate?) -> Unit) : DialogPresentation() object Hidden : DialogPresentation() } @@ -74,7 +74,7 @@ actual class DateTimePickerPresenter( presentation.value = DialogPresentation.Hidden } - override fun showDateTimePicker(animated: Boolean, completion: (Date?) -> Unit) { + override fun showDateTimePicker(animated: Boolean, completion: (KalugaDate?) -> Unit) { presentation.value = DialogPresentation.Showing(animated, completion) } diff --git a/date-time-picker/src/commonMain/kotlin/DateTimePicker.kt b/date-time-picker/src/commonMain/kotlin/DateTimePicker.kt index cf2c23a7b..3e6788081 100644 --- a/date-time-picker/src/commonMain/kotlin/DateTimePicker.kt +++ b/date-time-picker/src/commonMain/kotlin/DateTimePicker.kt @@ -21,8 +21,8 @@ package com.splendo.kaluga.datetimepicker import co.touchlab.stately.concurrency.Lock import co.touchlab.stately.concurrency.withLock import com.splendo.kaluga.architecture.lifecycle.LifecycleSubscribableMarker -import com.splendo.kaluga.base.utils.Date -import com.splendo.kaluga.base.utils.Date.Companion.epoch +import com.splendo.kaluga.base.utils.KalugaDate +import com.splendo.kaluga.base.utils.KalugaDate.Companion.epoch import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.Locale.Companion.defaultLocale import kotlinx.coroutines.CoroutineScope @@ -35,7 +35,7 @@ data class DateTimePicker( val confirmButtonTitle: String, val type: Type, val locale: Locale, - val selectedDate: Date + val selectedDate: KalugaDate ) { /** @@ -47,8 +47,8 @@ data class DateTimePicker( * A range can be provided to limit the dates selectable */ class DateType( - val earliestDate: Date? = null, - val latestDate: Date? = null + val earliestDate: KalugaDate? = null, + val latestDate: KalugaDate? = null ) : Type() /** @@ -68,15 +68,15 @@ interface DateTimePickerActions { * @param animated Pass `true` to animate the presentation * @param completion The callback invoked when a Date is selected or the dialog is cancelled */ - fun showAsync(animated: Boolean = true, completion: (Date?) -> Unit = {}) + fun showAsync(animated: Boolean = true, completion: (KalugaDate?) -> Unit = {}) /** * Presents an DateTimePicker and suspends * * @param animated - * @return The [Date] that was selected or `null` if the DateTimePicker was cancelled + * @return The [KalugaDate] that was selected or `null` if the DateTimePicker was cancelled */ - suspend fun show(animated: Boolean = true): Date? + suspend fun show(animated: Boolean = true): KalugaDate? /** * Dismisses the DateTimePicker, which was presented previously @@ -106,7 +106,7 @@ abstract class BaseDateTimePickerPresenter(private val dateTimePicker: DateTimeP private var cancelButtonTitle: String = "" private var confirmButtonTitle: String = "" private var locale: Locale = defaultLocale - private var selectedDate: Date = epoch() + private var selectedDate: KalugaDate = epoch() private var type: DateTimePicker.Type = DateTimePicker.Type.TimeType internal val lock = Lock() @@ -132,7 +132,7 @@ abstract class BaseDateTimePickerPresenter(private val dateTimePicker: DateTimeP */ fun setLocale(locale: Locale) = apply { this.locale = locale } - fun setSelectedDate(date: Date) = apply { this.selectedDate = date } + fun setSelectedDate(date: KalugaDate) = apply { this.selectedDate = date } /** * Sets a style of the alert @@ -174,11 +174,11 @@ abstract class BaseDateTimePickerPresenter(private val dateTimePicker: DateTimeP abstract fun create(coroutineScope: CoroutineScope): BaseDateTimePickerPresenter } - override fun showAsync(animated: Boolean, completion: (Date?) -> Unit) { + override fun showAsync(animated: Boolean, completion: (KalugaDate?) -> Unit) { showDateTimePicker(animated, completion = completion) } - override suspend fun show(animated: Boolean): Date? = + override suspend fun show(animated: Boolean): KalugaDate? = suspendCancellableCoroutine { continuation -> continuation.invokeOnCancellation { dismissDateTimePicker(animated) @@ -195,7 +195,7 @@ abstract class BaseDateTimePickerPresenter(private val dateTimePicker: DateTimeP protected abstract fun showDateTimePicker( animated: Boolean = true, - completion: (Date?) -> Unit = {} + completion: (KalugaDate?) -> Unit = {} ) } @@ -223,8 +223,8 @@ expect class DateTimePickerPresenter : BaseDateTimePickerPresenter { */ fun BaseDateTimePickerPresenter.Builder.buildDatePicker( coroutineScope: CoroutineScope, - earliestDate: Date? = null, - latestDate: Date? = null, + earliestDate: KalugaDate? = null, + latestDate: KalugaDate? = null, initialize: BaseDateTimePickerPresenter.Builder.() -> Unit ): BaseDateTimePickerPresenter = lock.withLock { reset() diff --git a/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt b/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt index b13acf7d2..ec61124bf 100644 --- a/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt +++ b/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt @@ -19,7 +19,7 @@ Copyright 2020 Splendo Consulting B.V. The Netherlands package com.splendo.kaluga.datetimepicker import com.splendo.kaluga.base.IOSVersion -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import kotlinx.cinterop.ObjCAction import kotlinx.coroutines.CoroutineScope import platform.CoreGraphics.CGFloat @@ -56,7 +56,7 @@ actual class DateTimePickerPresenter( private val parent: UIViewController ) : BaseDateTimePickerPresenter(datePicker) { - private inner class DateTimePickerViewController(private val datePicker: DateTimePicker, private val completion: (Date?) -> Unit) : UIViewController(null, null) { + private inner class DateTimePickerViewController(private val datePicker: DateTimePicker, private val completion: (KalugaDate?) -> Unit) : UIViewController(null, null) { private lateinit var datePickerView: UIDatePicker @@ -163,7 +163,7 @@ actual class DateTimePickerPresenter( parent.dismissModalViewControllerAnimated(animated) } - override fun showDateTimePicker(animated: Boolean, completion: (Date?) -> Unit) { + override fun showDateTimePicker(animated: Boolean, completion: (KalugaDate?) -> Unit) { parent.presentViewController(DateTimePickerViewController(datePicker, completion), animated, null) } } diff --git a/date-time-picker/src/jsMain/kotlin/DateTimePickerPresenter.kt b/date-time-picker/src/jsMain/kotlin/DateTimePickerPresenter.kt index 854aa31a5..fb8c4e791 100644 --- a/date-time-picker/src/jsMain/kotlin/DateTimePickerPresenter.kt +++ b/date-time-picker/src/jsMain/kotlin/DateTimePickerPresenter.kt @@ -18,7 +18,7 @@ Copyright 2020 Splendo Consulting B.V. The Netherlands package com.splendo.kaluga.datetimepicker -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import kotlinx.coroutines.CoroutineScope actual class DateTimePickerPresenter( @@ -32,11 +32,11 @@ actual class DateTimePickerPresenter( } } - override fun showAsync(animated: Boolean, completion: (Date?) -> Unit) { + override fun showAsync(animated: Boolean, completion: (KalugaDate?) -> Unit) { TODO("Not yet implemented") } - override suspend fun show(animated: Boolean): Date? { + override suspend fun show(animated: Boolean): KalugaDate? { TODO("not implemented") } @@ -48,7 +48,7 @@ actual class DateTimePickerPresenter( TODO("not implemented") } - override fun showDateTimePicker(animated: Boolean, completion: (Date?) -> Unit) { + override fun showDateTimePicker(animated: Boolean, completion: (KalugaDate?) -> Unit) { TODO("not implemented") } } diff --git a/date-time-picker/src/jvmMain/kotlin/DateTimePickerPresenter.kt b/date-time-picker/src/jvmMain/kotlin/DateTimePickerPresenter.kt index a11d63185..26e82477f 100644 --- a/date-time-picker/src/jvmMain/kotlin/DateTimePickerPresenter.kt +++ b/date-time-picker/src/jvmMain/kotlin/DateTimePickerPresenter.kt @@ -17,7 +17,7 @@ Copyright 2020 Splendo Consulting B.V. The Netherlands */ package com.splendo.kaluga.datetimepicker -import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.KalugaDate import kotlinx.coroutines.CoroutineScope actual class DateTimePickerPresenter( @@ -31,11 +31,11 @@ actual class DateTimePickerPresenter( } } - override fun showAsync(animated: Boolean, completion: (Date?) -> Unit) { + override fun showAsync(animated: Boolean, completion: (KalugaDate?) -> Unit) { TODO("Not yet implemented") } - override suspend fun show(animated: Boolean): Date? { + override suspend fun show(animated: Boolean): KalugaDate? { TODO("not implemented") } @@ -47,7 +47,7 @@ actual class DateTimePickerPresenter( TODO("not implemented") } - override fun showDateTimePicker(animated: Boolean, completion: (Date?) -> Unit) { + override fun showDateTimePicker(animated: Boolean, completion: (KalugaDate?) -> Unit) { TODO("not implemented") } } From ee1f5e71dc87cc0dc3c874c62a461ee09a99cff8 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Fri, 11 Feb 2022 15:07:34 +0100 Subject: [PATCH 11/65] Add deprecated Date class. --- base/src/commonMain/kotlin/utils/KalugaDate.kt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/base/src/commonMain/kotlin/utils/KalugaDate.kt b/base/src/commonMain/kotlin/utils/KalugaDate.kt index 192b80927..2b760bfcb 100644 --- a/base/src/commonMain/kotlin/utils/KalugaDate.kt +++ b/base/src/commonMain/kotlin/utils/KalugaDate.kt @@ -139,6 +139,9 @@ expect class KalugaDate : Comparable { override fun hashCode(): Int } +@Deprecated("Due to name clashes with platform classes and API changes this class has been renamed and changed to an interface. It will be removed in a future release.", ReplaceWith("KalugaState")) +typealias Date = KalugaDate + /** * Creates a [KalugaDate] with the same [Locale] and [TimeZone] as the left date, but earlier by the right date millisecondSinceEpoch * @param date The [KalugaDate] of which the millisecondSinceEpoch to subtract should be retrieved From cb5bd334306d2c20eb99ba9070da70a4c6b7e995 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Fri, 11 Feb 2022 16:33:44 +0100 Subject: [PATCH 12/65] Add JvmName annotation --- resources/src/androidLibMain/kotlin/KalugaColor.kt | 2 ++ resources/src/commonMain/kotlin/KalugaColor.kt | 1 - resources/src/jvmMain/kotlin/KalugaColor.kt | 2 ++ 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/resources/src/androidLibMain/kotlin/KalugaColor.kt b/resources/src/androidLibMain/kotlin/KalugaColor.kt index d18912dbf..844b99d32 100644 --- a/resources/src/androidLibMain/kotlin/KalugaColor.kt +++ b/resources/src/androidLibMain/kotlin/KalugaColor.kt @@ -15,6 +15,8 @@ */ +@file:JvmName("AndroidKalugaColor") + package com.splendo.kaluga.resources actual typealias KalugaColor = Int diff --git a/resources/src/commonMain/kotlin/KalugaColor.kt b/resources/src/commonMain/kotlin/KalugaColor.kt index 6dda88218..97d1fbc8f 100644 --- a/resources/src/commonMain/kotlin/KalugaColor.kt +++ b/resources/src/commonMain/kotlin/KalugaColor.kt @@ -17,7 +17,6 @@ package com.splendo.kaluga.resources - /** * Class describing a color */ diff --git a/resources/src/jvmMain/kotlin/KalugaColor.kt b/resources/src/jvmMain/kotlin/KalugaColor.kt index 6f36575ed..83254c5a0 100644 --- a/resources/src/jvmMain/kotlin/KalugaColor.kt +++ b/resources/src/jvmMain/kotlin/KalugaColor.kt @@ -15,6 +15,8 @@ */ +@file:JvmName("JvmKalugaColor") + package com.splendo.kaluga.resources actual typealias KalugaColor = Int From e73588b6c1ff24a13bad326b083c31b589f9f8ba Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Sat, 12 Feb 2022 12:41:44 +0100 Subject: [PATCH 13/65] Replace `Date` with `KalugaDate` --- date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt b/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt index ec61124bf..e77d4514d 100644 --- a/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt +++ b/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt @@ -149,7 +149,7 @@ actual class DateTimePickerPresenter( @ObjCAction private fun onSelected() { - completion(Date.epoch((datePickerView.date.timeIntervalSince1970 * 1000.0).toLong(), datePicker.selectedDate.timeZone, datePicker.locale)) + completion(KalugaDate.epoch((datePickerView.date.timeIntervalSince1970 * 1000.0).toLong(), datePicker.selectedDate.timeZone, datePicker.locale)) dismissDateTimePicker(true) } } From e99860ebe5706a723a67a6f686e700fc674aad8d Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Sat, 12 Feb 2022 13:52:28 +0100 Subject: [PATCH 14/65] Rename DateFormatter classes. --- .../kotlin/text/{DateFormatter.kt => KalugaDateFormatter.kt} | 0 .../kotlin/text/{DateFormatter.kt => KalugaDateFormatter.kt} | 0 .../kotlin/text/{DateFormatter.kt => KalugaDateFormatter.kt} | 0 .../kotlin/text/{DateFormatter.kt => KalugaDateFormatter.kt} | 0 .../kotlin/text/{DateFormatter.kt => KalugaDateFormatter.kt} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename base/src/androidLibMain/kotlin/text/{DateFormatter.kt => KalugaDateFormatter.kt} (100%) rename base/src/commonMain/kotlin/text/{DateFormatter.kt => KalugaDateFormatter.kt} (100%) rename base/src/iosMain/kotlin/text/{DateFormatter.kt => KalugaDateFormatter.kt} (100%) rename base/src/jsMain/kotlin/text/{DateFormatter.kt => KalugaDateFormatter.kt} (100%) rename base/src/jvmMain/kotlin/text/{DateFormatter.kt => KalugaDateFormatter.kt} (100%) diff --git a/base/src/androidLibMain/kotlin/text/DateFormatter.kt b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt similarity index 100% rename from base/src/androidLibMain/kotlin/text/DateFormatter.kt rename to base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt diff --git a/base/src/commonMain/kotlin/text/DateFormatter.kt b/base/src/commonMain/kotlin/text/KalugaDateFormatter.kt similarity index 100% rename from base/src/commonMain/kotlin/text/DateFormatter.kt rename to base/src/commonMain/kotlin/text/KalugaDateFormatter.kt diff --git a/base/src/iosMain/kotlin/text/DateFormatter.kt b/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt similarity index 100% rename from base/src/iosMain/kotlin/text/DateFormatter.kt rename to base/src/iosMain/kotlin/text/KalugaDateFormatter.kt diff --git a/base/src/jsMain/kotlin/text/DateFormatter.kt b/base/src/jsMain/kotlin/text/KalugaDateFormatter.kt similarity index 100% rename from base/src/jsMain/kotlin/text/DateFormatter.kt rename to base/src/jsMain/kotlin/text/KalugaDateFormatter.kt diff --git a/base/src/jvmMain/kotlin/text/DateFormatter.kt b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt similarity index 100% rename from base/src/jvmMain/kotlin/text/DateFormatter.kt rename to base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt From a1a7e1a1adbd06862a9b55b9bb0da7a593cd7150 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Sat, 12 Feb 2022 13:53:04 +0100 Subject: [PATCH 15/65] Rename DateFormatter references. --- .../compose/navigation/NavGraphBuilder.kt | 6 +-- .../architecture/compose/navigation/Route.kt | 6 +-- .../kaluga/architecture/compose/RouteTests.kt | 4 +- base/README.md | 2 +- .../kotlin/text/KalugaDateFormatter.kt | 14 +++--- .../commonMain/kotlin/text/FormatSpecifier.kt | 6 +-- .../kotlin/text/KalugaDateFormatter.kt | 47 ++++++++++--------- base/src/commonMain/kotlin/utils/Locale.kt | 4 +- .../kotlin/text/DateFormatterTest.kt | 22 ++++----- .../kotlin/text/KalugaDateFormatter.kt | 12 ++--- .../jsMain/kotlin/text/KalugaDateFormatter.kt | 10 ++-- .../kotlin/text/KalugaDateFormatter.kt | 14 +++--- date-time-picker/README.md | 4 +- .../datetimepicker/DateTimePickerViewModel.kt | 4 +- .../kotlin/mock/resources/MockResources.kt | 2 +- .../kotlin/mock/resources/MockResources.kt | 4 +- .../kotlin/mock/resources/MockResources.kt | 2 +- .../kotlin/mock/resources/MockResources.kt | 2 +- .../kotlin/mock/resources/MockResources.kt | 2 +- 19 files changed, 85 insertions(+), 82 deletions(-) diff --git a/architecture-compose/src/androidLibMain/kotlin/com/splendo/kaluga/architecture/compose/navigation/NavGraphBuilder.kt b/architecture-compose/src/androidLibMain/kotlin/com/splendo/kaluga/architecture/compose/navigation/NavGraphBuilder.kt index 66bd72c02..9c37b6eed 100644 --- a/architecture-compose/src/androidLibMain/kotlin/com/splendo/kaluga/architecture/compose/navigation/NavGraphBuilder.kt +++ b/architecture-compose/src/androidLibMain/kotlin/com/splendo/kaluga/architecture/compose/navigation/NavGraphBuilder.kt @@ -35,7 +35,7 @@ import com.splendo.kaluga.architecture.navigation.NavigationBundleValue import com.splendo.kaluga.architecture.navigation.SingleValueNavigationAction import com.splendo.kaluga.architecture.navigation.SingleValueNavigationSpec import com.splendo.kaluga.architecture.navigation.toBundle -import com.splendo.kaluga.base.text.DateFormatter +import com.splendo.kaluga.base.text.KalugaDateFormatter import com.splendo.kaluga.base.text.iso8601Pattern import com.splendo.kaluga.base.utils.KalugaDate import kotlinx.serialization.KSerializer @@ -292,11 +292,11 @@ private fun Bundle.composableValue( ListSerializer(String.serializer()), nonNullableValue ).map { - DateFormatter.Companion.iso8601Pattern().parse(it) ?: throw BundleConversionError() + KalugaDateFormatter.Companion.iso8601Pattern().parse(it) ?: throw BundleConversionError() } ) is NavigationBundleSpecType.DateType -> specType.convertValue( - DateFormatter.Companion.iso8601Pattern().parse(nonNullableValue) + KalugaDateFormatter.Companion.iso8601Pattern().parse(nonNullableValue) ?: throw BundleConversionError() ) is NavigationBundleSpecType.DoubleArrayType -> specType.convertValue( diff --git a/architecture-compose/src/androidLibMain/kotlin/com/splendo/kaluga/architecture/compose/navigation/Route.kt b/architecture-compose/src/androidLibMain/kotlin/com/splendo/kaluga/architecture/compose/navigation/Route.kt index a553af908..ef280330b 100644 --- a/architecture-compose/src/androidLibMain/kotlin/com/splendo/kaluga/architecture/compose/navigation/Route.kt +++ b/architecture-compose/src/androidLibMain/kotlin/com/splendo/kaluga/architecture/compose/navigation/Route.kt @@ -22,7 +22,7 @@ import com.splendo.kaluga.architecture.navigation.NavigationBundleSpec import com.splendo.kaluga.architecture.navigation.NavigationBundleSpecRow import com.splendo.kaluga.architecture.navigation.NavigationBundleSpecType import com.splendo.kaluga.architecture.navigation.NavigationBundleValue -import com.splendo.kaluga.base.text.DateFormatter +import com.splendo.kaluga.base.text.KalugaDateFormatter import com.splendo.kaluga.base.text.iso8601Pattern import kotlinx.serialization.builtins.BooleanArraySerializer import kotlinx.serialization.builtins.ByteArraySerializer @@ -129,9 +129,9 @@ private val NavigationBundleValue<*>.routeArgument: String? is NavigationBundleValue.CharValue -> Json.encodeToString(Char.serializer(), value) is NavigationBundleValue.DateArrayValue -> Json.encodeToString( ListSerializer(String.serializer()), - value.map { DateFormatter.Companion.iso8601Pattern().format(it) } + value.map { KalugaDateFormatter.Companion.iso8601Pattern().format(it) } ) - is NavigationBundleValue.DateValue -> DateFormatter.Companion.iso8601Pattern().format(value) + is NavigationBundleValue.DateValue -> KalugaDateFormatter.Companion.iso8601Pattern().format(value) is NavigationBundleValue.DoubleArrayValue -> Json.encodeToString( DoubleArraySerializer(), value diff --git a/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt b/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt index 6bd2c7077..5fe612b43 100644 --- a/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt +++ b/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt @@ -24,7 +24,7 @@ import com.splendo.kaluga.architecture.navigation.NavigationBundleSpec import com.splendo.kaluga.architecture.navigation.NavigationBundleSpecRow import com.splendo.kaluga.architecture.navigation.NavigationBundleSpecType import com.splendo.kaluga.architecture.navigation.toBundle -import com.splendo.kaluga.base.text.DateFormatter +import com.splendo.kaluga.base.text.KalugaDateFormatter import com.splendo.kaluga.base.text.iso8601Pattern import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.TimeZone @@ -87,6 +87,6 @@ class RouteTests { } } val action = TestNavigationAction(bundle) - assertEquals("TestNavigationAction/string/true/0.5/{\"value\":\"Mock\"}/${DateFormatter.iso8601Pattern().format(time)}?OptionalString={optional}&OptionalMockSerializable={{\"value\":\"OptionalMock\"}}", action.route()) + assertEquals("TestNavigationAction/string/true/0.5/{\"value\":\"Mock\"}/${KalugaDateFormatter.iso8601Pattern().format(time)}?OptionalString={optional}&OptionalMockSerializable={{\"value\":\"OptionalMock\"}}", action.route()) } } diff --git a/base/README.md b/base/README.md index 8dfc617b4..ecc1b1ed6 100644 --- a/base/README.md +++ b/base/README.md @@ -132,6 +132,6 @@ Use Decimals to do standard arithmetic operations. A Rounding mode or scale can It's possible to format to and from some data types using Kaluga. -- `Date` can be formatted and parsed using a `DateFormatter` +- `Date` can be formatted and parsed using a `KalugaDateFormatter` - `Number` can be formatted and parsed using a `NumberFormatter` - `String` can be formatted to include different data types using `StringFormatter` diff --git a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt index 5e530e340..90e2de6ab 100644 --- a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt @@ -27,7 +27,7 @@ import java.text.ParseException import java.text.SimpleDateFormat import java.util.Calendar -actual class DateFormatter private constructor(private val format: SimpleDateFormat) { +actual class KalugaDateFormatter private constructor(private val format: SimpleDateFormat) { actual companion object { @@ -35,25 +35,25 @@ actual class DateFormatter private constructor(private val format: SimpleDateFor style: DateFormatStyle, timeZone: TimeZone, locale: Locale - ): DateFormatter = createDateFormatter(DateFormat.getDateInstance(style.javaStyle(), locale.locale) as SimpleDateFormat, timeZone) + ): KalugaDateFormatter = createDateFormatter(DateFormat.getDateInstance(style.javaStyle(), locale.locale) as SimpleDateFormat, timeZone) actual fun timeFormat( style: DateFormatStyle, timeZone: TimeZone, locale: Locale - ): DateFormatter = createDateFormatter(DateFormat.getTimeInstance(style.javaStyle(), locale.locale) as SimpleDateFormat, timeZone) + ): KalugaDateFormatter = createDateFormatter(DateFormat.getTimeInstance(style.javaStyle(), locale.locale) as SimpleDateFormat, timeZone) actual fun dateTimeFormat( dateStyle: DateFormatStyle, timeStyle: DateFormatStyle, timeZone: TimeZone, locale: Locale - ): DateFormatter = createDateFormatter(DateFormat.getDateTimeInstance(dateStyle.javaStyle(), timeStyle.javaStyle(), locale.locale) as SimpleDateFormat, timeZone) + ): KalugaDateFormatter = createDateFormatter(DateFormat.getDateTimeInstance(dateStyle.javaStyle(), timeStyle.javaStyle(), locale.locale) as SimpleDateFormat, timeZone) - actual fun patternFormat(pattern: String, timeZone: TimeZone, locale: Locale): DateFormatter = createDateFormatter(SimpleDateFormat(pattern, locale.locale), timeZone) + actual fun patternFormat(pattern: String, timeZone: TimeZone, locale: Locale): KalugaDateFormatter = createDateFormatter(SimpleDateFormat(pattern, locale.locale), timeZone) - private fun createDateFormatter(simpleDateFormat: SimpleDateFormat, timeZone: TimeZone): DateFormatter { - return DateFormatter(simpleDateFormat).apply { + private fun createDateFormatter(simpleDateFormat: SimpleDateFormat, timeZone: TimeZone): KalugaDateFormatter { + return KalugaDateFormatter(simpleDateFormat).apply { this.timeZone = timeZone } } diff --git a/base/src/commonMain/kotlin/text/FormatSpecifier.kt b/base/src/commonMain/kotlin/text/FormatSpecifier.kt index c3c6b4fdf..7b8b723b8 100644 --- a/base/src/commonMain/kotlin/text/FormatSpecifier.kt +++ b/base/src/commonMain/kotlin/text/FormatSpecifier.kt @@ -396,7 +396,7 @@ internal class FormatSpecifier(private val out: StringBuilder, matchResult: Matc DateTime.AM_PM -> { // 'p' (am or pm) val isAm = time.hour < 12 - val dateFormat = DateFormatter.patternFormat("aa", TimeZone.current(), locale) + val dateFormat = KalugaDateFormatter.patternFormat("aa", TimeZone.current(), locale) sb.append((if (isAm) dateFormat.amString else dateFormat.pmString).lowerCased(locale)) } DateTime.SECONDS_SINCE_EPOCH -> { @@ -430,14 +430,14 @@ internal class FormatSpecifier(private val out: StringBuilder, matchResult: Matc DateTime.NAME_OF_DAY_ABBREV, DateTime.NAME_OF_DAY -> { // 'A' val i: Int = time.weekDay - 1 - val dateFormat = DateFormatter.patternFormat("EEEE") + val dateFormat = KalugaDateFormatter.patternFormat("EEEE") val weekdays = if (currentChar.dateTime == DateTime.NAME_OF_DAY) dateFormat.weekdays else dateFormat.shortWeekdays sb.append(weekdays[i]) } DateTime.NAME_OF_MONTH_ABBREV, DateTime.NAME_OF_MONTH_ABBREV_X, DateTime.NAME_OF_MONTH -> { // 'B' val i: Int = time.month - 1 - val dateFormat = DateFormatter.patternFormat("MMMM") + val dateFormat = KalugaDateFormatter.patternFormat("MMMM") val months = if (currentChar.dateTime == DateTime.NAME_OF_MONTH) dateFormat.months else dateFormat.shortMonths sb.append(months[i]) } diff --git a/base/src/commonMain/kotlin/text/KalugaDateFormatter.kt b/base/src/commonMain/kotlin/text/KalugaDateFormatter.kt index e20caf917..240f15a0a 100644 --- a/base/src/commonMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/commonMain/kotlin/text/KalugaDateFormatter.kt @@ -51,11 +51,11 @@ enum class DateFormatStyle { /** * Class for parsing and formatting a [KalugaDate] from/to a [String]. */ -expect class DateFormatter { +expect class KalugaDateFormatter { companion object { /** - * Creates a [DateFormatter] that only formats the date components of a [KalugaDate] + * Creates a [KalugaDateFormatter] that only formats the date components of a [KalugaDate] * @param style The [DateFormatStyle] used for formatting the date components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. * @param timeZone The [TimeZone] for which the date should be formatted. Defaults to [TimeZone.current]. * @param locale The [Locale] for which the date should be formatted. Defaults to [Locale.defaultLocale]. @@ -64,10 +64,10 @@ expect class DateFormatter { style: DateFormatStyle = DateFormatStyle.Medium, timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale - ): DateFormatter + ): KalugaDateFormatter /** - * Creates a [DateFormatter] that only formats the time components of a [KalugaDate] + * Creates a [KalugaDateFormatter] that only formats the time components of a [KalugaDate] * @param style The [DateFormatStyle] used for formatting the time components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. * @param timeZone The [TimeZone] for which the date should be formatted. Defaults to [TimeZone.current]. * @param locale The [Locale] for which the date should be formatted. Defaults to [Locale.defaultLocale]. @@ -76,10 +76,10 @@ expect class DateFormatter { style: DateFormatStyle = DateFormatStyle.Medium, timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale - ): DateFormatter + ): KalugaDateFormatter /** - * Creates a [DateFormatter] that formats both date and time components of a [KalugaDate] + * Creates a [KalugaDateFormatter] that formats both date and time components of a [KalugaDate] * @param dateStyle The [DateFormatStyle] used for formatting the date components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. * @param timeStyle The [DateFormatStyle] used for formatting the time components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. * @param timeZone The [TimeZone] for which the date should be formatted. Defaults to [TimeZone.current]. @@ -90,10 +90,10 @@ expect class DateFormatter { timeStyle: DateFormatStyle = DateFormatStyle.Medium, timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale - ): DateFormatter + ): KalugaDateFormatter /** - * Creates a [DateFormatter] using a custom Date format pattern. + * Creates a [KalugaDateFormatter] using a custom Date format pattern. * On iOS some user settings may take precedent over the format (i.e. using 12 hour clock). * To prevent this, ensure that the provided [locale] is of a `POSIX` type. * A convenience [fixedPatternFormat] method exists to default to this behaviour. @@ -105,13 +105,13 @@ expect class DateFormatter { pattern: String, timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale - ): DateFormatter + ): KalugaDateFormatter } var pattern: String /** - * The [TimeZone] this [DateFormatter] formats its dates to. + * The [TimeZone] this [KalugaDateFormatter] formats its dates to. */ var timeZone: TimeZone @@ -150,7 +150,7 @@ expect class DateFormatter { var pmString: String /** - * Formats a given [KalugaDate] to a [String] using the format described by this [DateFormatter]. + * Formats a given [KalugaDate] to a [String] using the format described by this [KalugaDateFormatter]. * @param date The [KalugaDate] to format. * @return The formatted [KalugaDate] as a [String] */ @@ -164,33 +164,36 @@ expect class DateFormatter { fun parse(string: String): KalugaDate? } +@Deprecated("Due to name clashes with platform classes and API changes this class has been renamed and changed to an interface. It will be removed in a future release.", ReplaceWith("KalugaState")) +typealias DateFormatter = KalugaDateFormatter + /** - * Creates a fixed [DateFormatter] using a custom Date format pattern, localized by the [Locale.enUsPosix] [Locale]. + * Creates a fixed [KalugaDateFormatter] using a custom Date format pattern, localized by the [Locale.enUsPosix] [Locale]. * Use this to ensure that displaying time in 12 or 24 hour format is not overridden by the user. * @param pattern The pattern to apply. * @param timeZone The [TimeZone] for which the date should be formatted. Defaults to [TimeZone.current]. */ -fun DateFormatter.Companion.fixedPatternFormat(pattern: String, timeZone: TimeZone = TimeZone.current()) = patternFormat(pattern, timeZone, Locale.enUsPosix) +fun KalugaDateFormatter.Companion.fixedPatternFormat(pattern: String, timeZone: TimeZone = TimeZone.current()) = patternFormat(pattern, timeZone, Locale.enUsPosix) /** - * Creates a [DateFormatter] that formats time according to the ISo 8601 format. + * Creates a [KalugaDateFormatter] that formats time according to the ISo 8601 format. * @param timeZone The [TimeZone] for which the date should be formatted. Defaults to [TimeZone.current]. */ -fun DateFormatter.Companion.iso8601Pattern(timeZone: TimeZone = TimeZone.current()) = fixedPatternFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", timeZone) +fun KalugaDateFormatter.Companion.iso8601Pattern(timeZone: TimeZone = TimeZone.current()) = fixedPatternFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", timeZone) /** - * Creates a [DateFormatter] that only formats the date components of a [KalugaDate] + * Creates a [KalugaDateFormatter] that only formats the date components of a [KalugaDate] * @param style The [DateFormatStyle] used for formatting the date components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. * @param excludeYear When [true] the year will not be part of the format. * @param timeZone The [TimeZone] for which the date should be formatted. Defaults to [TimeZone.current]. * @param locale The [Locale] for which the date should be formatted. Defaults to [Locale.defaultLocale]. */ -fun DateFormatter.Companion.dateFormat( +fun KalugaDateFormatter.Companion.dateFormat( style: DateFormatStyle = DateFormatStyle.Medium, excludeYear: Boolean, timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale -): DateFormatter { +): KalugaDateFormatter { val formatWithYear = dateFormat(style, timeZone, locale) return if (excludeYear) { patternFormat(patternWithoutYear(formatWithYear.pattern), timeZone, locale) @@ -200,20 +203,20 @@ fun DateFormatter.Companion.dateFormat( } /** - * Creates a [DateFormatter] that formats both date and time components of a [KalugaDate] + * Creates a [KalugaDateFormatter] that formats both date and time components of a [KalugaDate] * @param dateStyle The [DateFormatStyle] used for formatting the date components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. * @param excludeYear When [true] the year will not be part of the format. * @param timeStyle The [DateFormatStyle] used for formatting the time components of the [KalugaDate]. Defaults to [DateFormatStyle.Medium]. * @param timeZone The [TimeZone] for which the date should be formatted. Defaults to [TimeZone.current]. * @param locale The [Locale] for which the date should be formatted. Defaults to [Locale.defaultLocale]. */ -fun DateFormatter.Companion.dateTimeFormat( +fun KalugaDateFormatter.Companion.dateTimeFormat( dateStyle: DateFormatStyle = DateFormatStyle.Medium, excludeYear: Boolean, timeStyle: DateFormatStyle = DateFormatStyle.Medium, timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale -): DateFormatter { +): KalugaDateFormatter { val formatWithYear = dateTimeFormat(dateStyle, timeStyle, timeZone, locale) return if (excludeYear) { val datePatternWithYear = dateFormat(dateStyle, timeZone, locale).pattern @@ -224,4 +227,4 @@ fun DateFormatter.Companion.dateTimeFormat( } } -internal fun DateFormatter.Companion.patternWithoutYear(pattern: String): String = pattern.replace("\\W*[Yy]+\\W*".toRegex(), "") +internal fun KalugaDateFormatter.Companion.patternWithoutYear(pattern: String): String = pattern.replace("\\W*[Yy]+\\W*".toRegex(), "") diff --git a/base/src/commonMain/kotlin/utils/Locale.kt b/base/src/commonMain/kotlin/utils/Locale.kt index 7c393d166..9a3193475 100644 --- a/base/src/commonMain/kotlin/utils/Locale.kt +++ b/base/src/commonMain/kotlin/utils/Locale.kt @@ -18,7 +18,7 @@ package com.splendo.kaluga.base.utils import com.splendo.kaluga.base.text.DateFormatStyle -import com.splendo.kaluga.base.text.DateFormatter +import com.splendo.kaluga.base.text.KalugaDateFormatter /** * A [Locale] object represents a specific geographical, political, or cultural region. @@ -150,7 +150,7 @@ val Locale.Companion.enUsPosix get() = createLocale("en", "US", "POSIX") * Indicates whether this locale use a 24 hour clock cycle. */ val Locale.uses24HourClock: Boolean get() { - val formatter = DateFormatter.timeFormat(DateFormatStyle.Medium, locale = this) + val formatter = KalugaDateFormatter.timeFormat(DateFormatStyle.Medium, locale = this) val formattedDate = formatter.format(KalugaDate.now()) return !formattedDate.contains(formatter.amString) && !formattedDate.contains(formatter.pmString) } diff --git a/base/src/commonTest/kotlin/text/DateFormatterTest.kt b/base/src/commonTest/kotlin/text/DateFormatterTest.kt index 825c84743..e14c46b2c 100644 --- a/base/src/commonTest/kotlin/text/DateFormatterTest.kt +++ b/base/src/commonTest/kotlin/text/DateFormatterTest.kt @@ -18,7 +18,7 @@ package com.splendo.kaluga.base.test.text import com.splendo.kaluga.base.text.DateFormatStyle -import com.splendo.kaluga.base.text.DateFormatter +import com.splendo.kaluga.base.text.KalugaDateFormatter import com.splendo.kaluga.base.text.dateFormat import com.splendo.kaluga.base.text.iso8601Pattern import com.splendo.kaluga.base.utils.KalugaDate @@ -44,7 +44,7 @@ class DateFormatterTest { @Test fun testFormatDate() { - val formatter = DateFormatter.dateFormat(DateFormatStyle.Short, PSTTimeZone, UnitedStatesLocale) + val formatter = KalugaDateFormatter.dateFormat(DateFormatStyle.Short, PSTTimeZone, UnitedStatesLocale) val date = KalugaDate.nowUtc().apply { year = 2020 month = 1 @@ -58,7 +58,7 @@ class DateFormatterTest { @Test fun testParseDate() { - val formatter = DateFormatter.dateFormat(DateFormatStyle.Short, PSTTimeZone, UnitedStatesLocale) + val formatter = KalugaDateFormatter.dateFormat(DateFormatStyle.Short, PSTTimeZone, UnitedStatesLocale) val date = formatter.parse("1/8/20") assertNotNull(date) assertEquals(2020, date.year) @@ -68,8 +68,8 @@ class DateFormatterTest { @Test fun testDateFormat() { - val usFormatter = DateFormatter.dateFormat(DateFormatStyle.Medium, TimeZone.utc, UnitedStatesLocale) - val frFormatter = DateFormatter.dateFormat(DateFormatStyle.Medium, TimeZone.utc, FranceLocale) + val usFormatter = KalugaDateFormatter.dateFormat(DateFormatStyle.Medium, TimeZone.utc, UnitedStatesLocale) + val frFormatter = KalugaDateFormatter.dateFormat(DateFormatStyle.Medium, TimeZone.utc, FranceLocale) assertEquals("Jan 8, 1988", usFormatter.format(January81988)) assertEquals("8 janv. 1988", frFormatter.format(January81988)) @@ -77,8 +77,8 @@ class DateFormatterTest { @Test fun testDateFormatWithoutYear() { - val usFormatter = DateFormatter.dateFormat(DateFormatStyle.Medium, true, TimeZone.utc, UnitedStatesLocale) - val frFormatter = DateFormatter.dateFormat(DateFormatStyle.Medium, true, TimeZone.utc, FranceLocale) + val usFormatter = KalugaDateFormatter.dateFormat(DateFormatStyle.Medium, true, TimeZone.utc, UnitedStatesLocale) + val frFormatter = KalugaDateFormatter.dateFormat(DateFormatStyle.Medium, true, TimeZone.utc, FranceLocale) assertEquals("Jan 8", usFormatter.format(January81988)) assertEquals("8 janv.", frFormatter.format(January81988)) @@ -86,8 +86,8 @@ class DateFormatterTest { @Test fun testTimeFormat() { - val usFormatter = DateFormatter.timeFormat(DateFormatStyle.Medium, TimeZone.utc, UnitedStatesLocale) - val frFormatter = DateFormatter.timeFormat(DateFormatStyle.Medium, TimeZone.utc, FranceLocale) + val usFormatter = KalugaDateFormatter.timeFormat(DateFormatStyle.Medium, TimeZone.utc, UnitedStatesLocale) + val frFormatter = KalugaDateFormatter.timeFormat(DateFormatStyle.Medium, TimeZone.utc, FranceLocale) assertEquals("1:37:42 PM", usFormatter.format(March181988)) assertEquals("13:37:42", frFormatter.format(March181988)) @@ -95,13 +95,13 @@ class DateFormatterTest { @Test fun testFormatFixedDate() { - val formatter = DateFormatter.iso8601Pattern(TimeZone.utc) + val formatter = KalugaDateFormatter.iso8601Pattern(TimeZone.utc) assertEquals("1988-03-18T13:37:42.750+0000", formatter.format(March181988)) } @Test fun testFailToParseInvalidString() { - val formatter = DateFormatter.iso8601Pattern(TimeZone.utc) + val formatter = KalugaDateFormatter.iso8601Pattern(TimeZone.utc) assertNull(formatter.parse("invalid date")) } } diff --git a/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt b/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt index 9c321e329..85b411fb4 100644 --- a/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt @@ -30,29 +30,29 @@ import platform.Foundation.NSDateFormatterNoStyle import platform.Foundation.NSDateFormatterShortStyle import platform.Foundation.NSDateFormatterStyle -actual class DateFormatter private constructor(private val format: NSDateFormatter) { +actual class KalugaDateFormatter private constructor(private val format: NSDateFormatter) { actual companion object { actual fun dateFormat( style: DateFormatStyle, timeZone: TimeZone, locale: Locale - ): DateFormatter = createDateFormatter(style, null, timeZone, locale) + ): KalugaDateFormatter = createDateFormatter(style, null, timeZone, locale) actual fun timeFormat( style: DateFormatStyle, timeZone: TimeZone, locale: Locale - ): DateFormatter = createDateFormatter(null, style, timeZone, locale) + ): KalugaDateFormatter = createDateFormatter(null, style, timeZone, locale) actual fun dateTimeFormat( dateStyle: DateFormatStyle, timeStyle: DateFormatStyle, timeZone: TimeZone, locale: Locale - ): DateFormatter = createDateFormatter(dateStyle, timeStyle, timeZone, locale) + ): KalugaDateFormatter = createDateFormatter(dateStyle, timeStyle, timeZone, locale) - actual fun patternFormat(pattern: String, timeZone: TimeZone, locale: Locale): DateFormatter = DateFormatter( + actual fun patternFormat(pattern: String, timeZone: TimeZone, locale: Locale): KalugaDateFormatter = KalugaDateFormatter( NSDateFormatter().apply { this.locale = locale.nsLocale this.timeZone = timeZone.timeZone @@ -65,7 +65,7 @@ actual class DateFormatter private constructor(private val format: NSDateFormatt timeStyle: DateFormatStyle?, timeZone: TimeZone, locale: Locale - ): DateFormatter = DateFormatter( + ): KalugaDateFormatter = KalugaDateFormatter( NSDateFormatter().apply { this.locale = locale.nsLocale this.timeZone = timeZone.timeZone diff --git a/base/src/jsMain/kotlin/text/KalugaDateFormatter.kt b/base/src/jsMain/kotlin/text/KalugaDateFormatter.kt index c21f74cc9..f92fe4303 100644 --- a/base/src/jsMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/jsMain/kotlin/text/KalugaDateFormatter.kt @@ -22,29 +22,29 @@ import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone // TODO Implement with proper dateformatter solution for Java Script -actual class DateFormatter private constructor(initialTimeZone: TimeZone, private val formatter: (kotlin.js.Date) -> String) { +actual class KalugaDateFormatter private constructor(initialTimeZone: TimeZone, private val formatter: (kotlin.js.Date) -> String) { actual companion object { actual fun dateFormat( style: DateFormatStyle, timeZone: TimeZone, locale: Locale - ): DateFormatter = DateFormatter(timeZone) { date -> date.toLocaleDateString(arrayOf("${locale.languageCode}-${locale.countryCode}")) } + ): KalugaDateFormatter = KalugaDateFormatter(timeZone) { date -> date.toLocaleDateString(arrayOf("${locale.languageCode}-${locale.countryCode}")) } actual fun timeFormat( style: DateFormatStyle, timeZone: TimeZone, locale: Locale - ): DateFormatter = DateFormatter(timeZone) { date -> date.toLocaleTimeString(arrayOf("${locale.languageCode}-${locale.countryCode}")) } + ): KalugaDateFormatter = KalugaDateFormatter(timeZone) { date -> date.toLocaleTimeString(arrayOf("${locale.languageCode}-${locale.countryCode}")) } actual fun dateTimeFormat( dateStyle: DateFormatStyle, timeStyle: DateFormatStyle, timeZone: TimeZone, locale: Locale - ): DateFormatter = DateFormatter(timeZone) { date -> date.toLocaleString(arrayOf("${locale.languageCode}-${locale.countryCode}")) } + ): KalugaDateFormatter = KalugaDateFormatter(timeZone) { date -> date.toLocaleString(arrayOf("${locale.languageCode}-${locale.countryCode}")) } - actual fun patternFormat(pattern: String, timeZone: TimeZone, locale: Locale): DateFormatter = DateFormatter(timeZone) { date -> date.toLocaleString(arrayOf("${locale.languageCode}-${locale.countryCode}")) } + actual fun patternFormat(pattern: String, timeZone: TimeZone, locale: Locale): KalugaDateFormatter = KalugaDateFormatter(timeZone) { date -> date.toLocaleString(arrayOf("${locale.languageCode}-${locale.countryCode}")) } } actual var pattern: String = "" diff --git a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt index 40410f832..419d4ceca 100644 --- a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt @@ -27,36 +27,36 @@ import java.text.ParseException import java.text.SimpleDateFormat import java.util.Calendar -actual class DateFormatter private constructor(private val format: SimpleDateFormat) { +actual class KalugaDateFormatter private constructor(private val format: SimpleDateFormat) { actual companion object { actual fun dateFormat( style: DateFormatStyle, timeZone: TimeZone, locale: Locale - ): DateFormatter = createDateFormatter(DateFormat.getDateInstance(style.javaStyle(), locale.locale) as SimpleDateFormat, timeZone) + ): KalugaDateFormatter = createDateFormatter(DateFormat.getDateInstance(style.javaStyle(), locale.locale) as SimpleDateFormat, timeZone) actual fun timeFormat( style: DateFormatStyle, timeZone: TimeZone, locale: Locale - ): DateFormatter = createDateFormatter(DateFormat.getTimeInstance(style.javaStyle(), locale.locale) as SimpleDateFormat, timeZone) + ): KalugaDateFormatter = createDateFormatter(DateFormat.getTimeInstance(style.javaStyle(), locale.locale) as SimpleDateFormat, timeZone) actual fun dateTimeFormat( dateStyle: DateFormatStyle, timeStyle: DateFormatStyle, timeZone: TimeZone, locale: Locale - ): DateFormatter = createDateFormatter(DateFormat.getDateTimeInstance(dateStyle.javaStyle(), timeStyle.javaStyle(), locale.locale) as SimpleDateFormat, timeZone) + ): KalugaDateFormatter = createDateFormatter(DateFormat.getDateTimeInstance(dateStyle.javaStyle(), timeStyle.javaStyle(), locale.locale) as SimpleDateFormat, timeZone) actual fun patternFormat( pattern: String, timeZone: TimeZone, locale: Locale - ): DateFormatter = createDateFormatter(SimpleDateFormat(pattern, locale.locale), timeZone) + ): KalugaDateFormatter = createDateFormatter(SimpleDateFormat(pattern, locale.locale), timeZone) - fun createDateFormatter(simpleDateFormat: SimpleDateFormat, timeZone: TimeZone): DateFormatter { - return DateFormatter(simpleDateFormat).apply { + fun createDateFormatter(simpleDateFormat: SimpleDateFormat, timeZone: TimeZone): KalugaDateFormatter { + return KalugaDateFormatter(simpleDateFormat).apply { this.timeZone = timeZone } } diff --git a/date-time-picker/README.md b/date-time-picker/README.md index a54e927cc..5d0b5f719 100644 --- a/date-time-picker/README.md +++ b/date-time-picker/README.md @@ -31,7 +31,7 @@ fun showAlert(builder: DateTimePickerPresenter.Builder) = MainScope().launch { } datePicker.show()?.let { - val formatter = DateFormatter.dateFormat(DateFormatStyle.Medium) + val formatter = KalugaDateFormatter.dateFormat(DateFormatStyle.Medium) println(formatter.format(it)) } } @@ -48,7 +48,7 @@ fun showAlert(builder: DateTimePickerPresenter.Builder) = MainScope().launch { } timePicker.show()?.let { - val formatter = DateFormatter.timeFormat(DateFormatStyle.Medium) + val formatter = KalugaDateFormatter.timeFormat(DateFormatStyle.Medium) println(formatter.format(it)) } } diff --git a/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt b/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt index 157f021b5..c6593d0da 100644 --- a/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt +++ b/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt @@ -3,7 +3,7 @@ package com.splendo.kaluga.example.shared.viewmodel.datetimepicker import com.splendo.kaluga.architecture.observable.toUninitializedObservable import com.splendo.kaluga.architecture.viewmodel.BaseViewModel import com.splendo.kaluga.base.text.DateFormatStyle -import com.splendo.kaluga.base.text.DateFormatter +import com.splendo.kaluga.base.text.KalugaDateFormatter import com.splendo.kaluga.base.utils.Date import com.splendo.kaluga.datetimepicker.DateTimePickerPresenter import com.splendo.kaluga.datetimepicker.buildDatePicker @@ -16,7 +16,7 @@ import kotlinx.coroutines.launch class DateTimePickerViewModel(val dateTimePickerPresenterBuilder: DateTimePickerPresenter.Builder) : BaseViewModel() { companion object { - private val formatter = DateFormatter.dateTimeFormat(DateFormatStyle.Long, DateFormatStyle.Long) + private val formatter = KalugaDateFormatter.dateTimeFormat(DateFormatStyle.Long, DateFormatStyle.Long) } private val selectedDate = MutableStateFlow( diff --git a/test-utils/src/androidLibMain/kotlin/mock/resources/MockResources.kt b/test-utils/src/androidLibMain/kotlin/mock/resources/MockResources.kt index 2ce3900d3..1bbeb230a 100644 --- a/test-utils/src/androidLibMain/kotlin/mock/resources/MockResources.kt +++ b/test-utils/src/androidLibMain/kotlin/mock/resources/MockResources.kt @@ -18,9 +18,9 @@ package com.splendo.kaluga.test.mock.resources import android.graphics.drawable.ColorDrawable -import com.splendo.kaluga.resources.KalugaColor import com.splendo.kaluga.resources.Font import com.splendo.kaluga.resources.Image +import com.splendo.kaluga.resources.KalugaColor import org.mockito.Mockito actual fun mockColor(): KalugaColor = 0 diff --git a/test-utils/src/commonMain/kotlin/mock/resources/MockResources.kt b/test-utils/src/commonMain/kotlin/mock/resources/MockResources.kt index e39d2e69e..f375d8ce7 100644 --- a/test-utils/src/commonMain/kotlin/mock/resources/MockResources.kt +++ b/test-utils/src/commonMain/kotlin/mock/resources/MockResources.kt @@ -18,12 +18,12 @@ package com.splendo.kaluga.test.mock.resources import com.splendo.kaluga.base.text.format -import com.splendo.kaluga.resources.KalugaColor -import com.splendo.kaluga.resources.KalugaColorLoader import com.splendo.kaluga.resources.Font import com.splendo.kaluga.resources.FontLoader import com.splendo.kaluga.resources.Image import com.splendo.kaluga.resources.ImageLoader +import com.splendo.kaluga.resources.KalugaColor +import com.splendo.kaluga.resources.KalugaColorLoader import com.splendo.kaluga.resources.StringLoader class MockStringLoader private constructor ( diff --git a/test-utils/src/iosMain/kotlin/mock/resources/MockResources.kt b/test-utils/src/iosMain/kotlin/mock/resources/MockResources.kt index acd41bf38..53ab1370b 100644 --- a/test-utils/src/iosMain/kotlin/mock/resources/MockResources.kt +++ b/test-utils/src/iosMain/kotlin/mock/resources/MockResources.kt @@ -17,9 +17,9 @@ package com.splendo.kaluga.test.mock.resources -import com.splendo.kaluga.resources.KalugaColor import com.splendo.kaluga.resources.Font import com.splendo.kaluga.resources.Image +import com.splendo.kaluga.resources.KalugaColor import platform.UIKit.UIColor actual fun mockColor(): KalugaColor = KalugaColor(UIColor.blackColor()) diff --git a/test-utils/src/jsMain/kotlin/mock/resources/MockResources.kt b/test-utils/src/jsMain/kotlin/mock/resources/MockResources.kt index 42a0c240c..639ef19a4 100644 --- a/test-utils/src/jsMain/kotlin/mock/resources/MockResources.kt +++ b/test-utils/src/jsMain/kotlin/mock/resources/MockResources.kt @@ -17,9 +17,9 @@ package com.splendo.kaluga.test.mock.resources -import com.splendo.kaluga.resources.KalugaColor import com.splendo.kaluga.resources.Font import com.splendo.kaluga.resources.Image +import com.splendo.kaluga.resources.KalugaColor actual fun mockColor(): KalugaColor = 0 actual fun mockImage(): Image = Image() diff --git a/test-utils/src/jvmMain/kotlin/mock/resources/MockResources.kt b/test-utils/src/jvmMain/kotlin/mock/resources/MockResources.kt index 42a0c240c..639ef19a4 100644 --- a/test-utils/src/jvmMain/kotlin/mock/resources/MockResources.kt +++ b/test-utils/src/jvmMain/kotlin/mock/resources/MockResources.kt @@ -17,9 +17,9 @@ package com.splendo.kaluga.test.mock.resources -import com.splendo.kaluga.resources.KalugaColor import com.splendo.kaluga.resources.Font import com.splendo.kaluga.resources.Image +import com.splendo.kaluga.resources.KalugaColor actual fun mockColor(): KalugaColor = 0 actual fun mockImage(): Image = Image() From 2705a80b8b2ca617d6ec22404e68338dddbc70af Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Sat, 12 Feb 2022 22:32:36 +0100 Subject: [PATCH 16/65] Rename methods and use AtomicReference/Boolean. --- .../kotlin/mock/focus/MockFocusHandler.kt | 6 +++++- .../commonMain/kotlin/mock/focus/MockFocusHandler.kt | 9 +++++---- .../kotlin/mock/keyboard/MockKeyboardManager.kt | 12 +++++++----- .../iosMain/kotlin/mock/focus/MockFocusHandler.kt | 6 +++++- .../src/jsMain/kotlin/mock/focus/MockFocusHandler.kt | 6 +++++- .../jvmMain/kotlin/mock/focus/MockFocusHandler.kt | 6 +++++- 6 files changed, 32 insertions(+), 13 deletions(-) diff --git a/test-utils/src/androidLibMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/androidLibMain/kotlin/mock/focus/MockFocusHandler.kt index 3f65fec24..467738dc1 100644 --- a/test-utils/src/androidLibMain/kotlin/mock/focus/MockFocusHandler.kt +++ b/test-utils/src/androidLibMain/kotlin/mock/focus/MockFocusHandler.kt @@ -25,7 +25,11 @@ actual class MockFocusHandler : BaseMockFocusHandler(), FocusHandler { super.giveFocus() } - actual fun focus() { + actual fun simulateGiveFocus() { requestFocus(activity = null) } + + actual fun simulateRemoveFocus() { + super.removeFocus() + } } diff --git a/test-utils/src/commonMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/commonMain/kotlin/mock/focus/MockFocusHandler.kt index 1b910ea63..30a5145ad 100644 --- a/test-utils/src/commonMain/kotlin/mock/focus/MockFocusHandler.kt +++ b/test-utils/src/commonMain/kotlin/mock/focus/MockFocusHandler.kt @@ -17,11 +17,11 @@ package com.splendo.kaluga.test.mock.focus +import co.touchlab.stately.concurrency.AtomicBoolean import com.splendo.kaluga.keyboard.FocusHandler -import kotlinx.coroutines.flow.MutableStateFlow open class BaseMockFocusHandler { - private val _isFocused = MutableStateFlow(false) + private val _isFocused = AtomicBoolean(false) val isFocused: Boolean get() = _isFocused.value @@ -29,11 +29,12 @@ open class BaseMockFocusHandler { _isFocused.value = true } - fun removeFocus() { + protected fun removeFocus() { _isFocused.value = false } } expect class MockFocusHandler constructor() : BaseMockFocusHandler, FocusHandler { - fun focus() + fun simulateGiveFocus() + fun simulateRemoveFocus() } diff --git a/test-utils/src/commonMain/kotlin/mock/keyboard/MockKeyboardManager.kt b/test-utils/src/commonMain/kotlin/mock/keyboard/MockKeyboardManager.kt index 9b1aba482..469bd2a96 100644 --- a/test-utils/src/commonMain/kotlin/mock/keyboard/MockKeyboardManager.kt +++ b/test-utils/src/commonMain/kotlin/mock/keyboard/MockKeyboardManager.kt @@ -17,30 +17,32 @@ package com.splendo.kaluga.test.mock.keyboard +import co.touchlab.stately.concurrency.AtomicBoolean +import co.touchlab.stately.concurrency.AtomicReference +import co.touchlab.stately.concurrency.value import com.splendo.kaluga.keyboard.BaseKeyboardManager import com.splendo.kaluga.keyboard.FocusHandler import com.splendo.kaluga.test.mock.focus.MockFocusHandler import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.flow.MutableStateFlow class MockKeyboardManager : BaseKeyboardManager { class Builder : BaseKeyboardManager.Builder { override fun create(coroutineScope: CoroutineScope): BaseKeyboardManager = MockKeyboardManager() } - private val _focusHandler: MutableStateFlow = MutableStateFlow(null) + private val _focusHandler: AtomicReference = AtomicReference(null) - private val _isShown = MutableStateFlow(false) + private val _isShown = AtomicBoolean(false) val isShown get() = _isShown.value override fun hide() { _isShown.value = false - _focusHandler.value?.removeFocus() + _focusHandler.value?.simulateRemoveFocus() } override fun show(focusHandler: FocusHandler) { _isShown.value = true _focusHandler.value = focusHandler as? MockFocusHandler - _focusHandler.value?.requestFocus() + _focusHandler.value?.simulateGiveFocus() } } diff --git a/test-utils/src/iosMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/iosMain/kotlin/mock/focus/MockFocusHandler.kt index e39654d9e..f148e3ce1 100644 --- a/test-utils/src/iosMain/kotlin/mock/focus/MockFocusHandler.kt +++ b/test-utils/src/iosMain/kotlin/mock/focus/MockFocusHandler.kt @@ -24,7 +24,11 @@ actual class MockFocusHandler : BaseMockFocusHandler(), FocusHandler { super.giveFocus() } - actual fun focus() { + actual fun simulateGiveFocus() { requestFocus() } + + actual fun simulateRemoveFocus() { + super.removeFocus() + } } diff --git a/test-utils/src/jsMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/jsMain/kotlin/mock/focus/MockFocusHandler.kt index 6dae3096d..2c7794ca9 100644 --- a/test-utils/src/jsMain/kotlin/mock/focus/MockFocusHandler.kt +++ b/test-utils/src/jsMain/kotlin/mock/focus/MockFocusHandler.kt @@ -20,7 +20,11 @@ package com.splendo.kaluga.test.mock.focus import com.splendo.kaluga.keyboard.FocusHandler actual class MockFocusHandler : BaseMockFocusHandler(), FocusHandler { - actual fun focus() { + actual fun simulateGiveFocus() { super.giveFocus() } + + actual fun simulateRemoveFocus() { + super.removeFocus() + } } diff --git a/test-utils/src/jvmMain/kotlin/mock/focus/MockFocusHandler.kt b/test-utils/src/jvmMain/kotlin/mock/focus/MockFocusHandler.kt index 6dae3096d..2c7794ca9 100644 --- a/test-utils/src/jvmMain/kotlin/mock/focus/MockFocusHandler.kt +++ b/test-utils/src/jvmMain/kotlin/mock/focus/MockFocusHandler.kt @@ -20,7 +20,11 @@ package com.splendo.kaluga.test.mock.focus import com.splendo.kaluga.keyboard.FocusHandler actual class MockFocusHandler : BaseMockFocusHandler(), FocusHandler { - actual fun focus() { + actual fun simulateGiveFocus() { super.giveFocus() } + + actual fun simulateRemoveFocus() { + super.removeFocus() + } } From 6cc9ee89f828a1c6bbb2e0f4ad30f2f1eac02e5d Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Sat, 12 Feb 2022 22:33:38 +0100 Subject: [PATCH 17/65] Add keyboard test. --- .../mocks/keyboard/MockKeyboardManagerTest.kt | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 test-utils/src/commonTest/kotlin/mocks/keyboard/MockKeyboardManagerTest.kt diff --git a/test-utils/src/commonTest/kotlin/mocks/keyboard/MockKeyboardManagerTest.kt b/test-utils/src/commonTest/kotlin/mocks/keyboard/MockKeyboardManagerTest.kt new file mode 100644 index 000000000..930a4b11b --- /dev/null +++ b/test-utils/src/commonTest/kotlin/mocks/keyboard/MockKeyboardManagerTest.kt @@ -0,0 +1,74 @@ +/* + Copyright 2022 Splendo Consulting B.V. The Netherlands + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + */ + +package mocks.keyboard + +import com.splendo.kaluga.base.runBlocking +import com.splendo.kaluga.test.mock.focus.MockFocusHandler +import com.splendo.kaluga.test.mock.keyboard.MockKeyboardManager +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class MockKeyboardManagerTest { + private val keyboardManagerBuilder = MockKeyboardManager.Builder() + private val focusHandler = MockFocusHandler() + + @Test + fun test_initial_manager_state() = testKeyboardManager { + assertFalse { it.isShown } + } + + @Test + fun test_show_keyboard() = testKeyboardManager { + assertFalse { it.isShown } + it.show(focusHandler) + assertTrue { focusHandler.isFocused } + assertTrue { it.isShown } + } + + @Test + fun test_hide_keyboard() = testKeyboardManager { + assertFalse { it.isShown } + it.show(focusHandler) + assertTrue { focusHandler.isFocused } + assertTrue { it.isShown } + + it.hide() + assertFalse { focusHandler.isFocused } + assertFalse { it.isShown } + } + + @Test + fun test_show_hide_keyboard_multiple_times() = testKeyboardManager { + assertFalse { it.isShown } + for(i in 0..10) { + it.show(focusHandler) + assertTrue { focusHandler.isFocused } + assertTrue { it.isShown } + + it.hide() + assertFalse { focusHandler.isFocused } + assertFalse { it.isShown } + } + + } + + private fun testKeyboardManager(block: (keyboardManager: MockKeyboardManager) -> Unit) = runBlocking { + block(keyboardManagerBuilder.create(this) as MockKeyboardManager) + } +} \ No newline at end of file From 116491cd28f79a812feeb007f014c880726c2f6c Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Sat, 12 Feb 2022 22:42:05 +0100 Subject: [PATCH 18/65] Add focus handler tests. --- .../mocks/keyboard/MockFocusHandlerTest.kt | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 test-utils/src/commonTest/kotlin/mocks/keyboard/MockFocusHandlerTest.kt diff --git a/test-utils/src/commonTest/kotlin/mocks/keyboard/MockFocusHandlerTest.kt b/test-utils/src/commonTest/kotlin/mocks/keyboard/MockFocusHandlerTest.kt new file mode 100644 index 000000000..7f5d19ba4 --- /dev/null +++ b/test-utils/src/commonTest/kotlin/mocks/keyboard/MockFocusHandlerTest.kt @@ -0,0 +1,65 @@ +/* + Copyright 2022 Splendo Consulting B.V. The Netherlands + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + */ + +package mocks.keyboard + +import com.splendo.kaluga.base.runBlocking +import com.splendo.kaluga.test.mock.focus.MockFocusHandler +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class MockFocusHandlerTest { + + @Test + fun test_initial_state() = testFocusHandler { + assertFalse { it.isFocused } + } + + @Test + fun test_give_focus() = testFocusHandler { + assertFalse { it.isFocused } + it.simulateGiveFocus() + assertTrue { it.isFocused } + } + + @Test + fun test_remove_focus() = testFocusHandler { + assertFalse { it.isFocused } + it.simulateGiveFocus() + assertTrue { it.isFocused } + + it.simulateRemoveFocus() + assertFalse { it.isFocused } + } + + @Test + fun test_give_remove_multiple_times() = testFocusHandler { + assertFalse { it.isFocused } + for(i in 0..10) { + it.simulateGiveFocus() + assertTrue { it.isFocused } + + it.simulateRemoveFocus() + assertFalse { it.isFocused } + } + } + + private fun testFocusHandler(block: (focusHandler: MockFocusHandler) -> Unit) = runBlocking { + block(MockFocusHandler()) + } +} \ No newline at end of file From dc3c91228680ce2b17b84a409a6a46d5e96c18d5 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Sat, 12 Feb 2022 22:44:15 +0100 Subject: [PATCH 19/65] Code lint. --- .../commonTest/kotlin/mocks/keyboard/MockFocusHandlerTest.kt | 4 ++-- .../kotlin/mocks/keyboard/MockKeyboardManagerTest.kt | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/test-utils/src/commonTest/kotlin/mocks/keyboard/MockFocusHandlerTest.kt b/test-utils/src/commonTest/kotlin/mocks/keyboard/MockFocusHandlerTest.kt index 7f5d19ba4..2b2e65461 100644 --- a/test-utils/src/commonTest/kotlin/mocks/keyboard/MockFocusHandlerTest.kt +++ b/test-utils/src/commonTest/kotlin/mocks/keyboard/MockFocusHandlerTest.kt @@ -50,7 +50,7 @@ class MockFocusHandlerTest { @Test fun test_give_remove_multiple_times() = testFocusHandler { assertFalse { it.isFocused } - for(i in 0..10) { + for (i in 0..10) { it.simulateGiveFocus() assertTrue { it.isFocused } @@ -62,4 +62,4 @@ class MockFocusHandlerTest { private fun testFocusHandler(block: (focusHandler: MockFocusHandler) -> Unit) = runBlocking { block(MockFocusHandler()) } -} \ No newline at end of file +} diff --git a/test-utils/src/commonTest/kotlin/mocks/keyboard/MockKeyboardManagerTest.kt b/test-utils/src/commonTest/kotlin/mocks/keyboard/MockKeyboardManagerTest.kt index 930a4b11b..75b164601 100644 --- a/test-utils/src/commonTest/kotlin/mocks/keyboard/MockKeyboardManagerTest.kt +++ b/test-utils/src/commonTest/kotlin/mocks/keyboard/MockKeyboardManagerTest.kt @@ -56,7 +56,7 @@ class MockKeyboardManagerTest { @Test fun test_show_hide_keyboard_multiple_times() = testKeyboardManager { assertFalse { it.isShown } - for(i in 0..10) { + for (i in 0..10) { it.show(focusHandler) assertTrue { focusHandler.isFocused } assertTrue { it.isShown } @@ -65,10 +65,9 @@ class MockKeyboardManagerTest { assertFalse { focusHandler.isFocused } assertFalse { it.isShown } } - } private fun testKeyboardManager(block: (keyboardManager: MockKeyboardManager) -> Unit) = runBlocking { block(keyboardManagerBuilder.create(this) as MockKeyboardManager) } -} \ No newline at end of file +} From 8c33e258941a22b6be6087355f0455c4ebb30b2a Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Mon, 14 Feb 2022 10:40:48 +0100 Subject: [PATCH 20/65] Update `ReplaceWith` with `KalugaColor`. Replace deprecated types with new type. --- resources/src/commonMain/kotlin/KalugaColor.kt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/resources/src/commonMain/kotlin/KalugaColor.kt b/resources/src/commonMain/kotlin/KalugaColor.kt index f0c6a05d9..e116f057d 100644 --- a/resources/src/commonMain/kotlin/KalugaColor.kt +++ b/resources/src/commonMain/kotlin/KalugaColor.kt @@ -32,13 +32,13 @@ import kotlin.jvm.JvmName */ expect class KalugaColor -@Deprecated("Due to name clashes with platform classes and API changes this class has been renamed and changed to an interface. It will be removed in a future release.", ReplaceWith("KalugaState")) +@Deprecated("Due to name clashes with platform classes and API changes this class has been renamed and changed to an interface. It will be removed in a future release.", ReplaceWith("KalugaColor")) typealias Color = KalugaColor @Serializable(with = ColorSerializer::class) -data class SerializableColor(val color: Color) +data class SerializableColor(val color: KalugaColor) -val Color.serializable get() = SerializableColor(this) +val KalugaColor.serializable get() = SerializableColor(this) /** * Gets the red value of the color in a range between `0.0` and `1.0` From 2eebd5651fc1e0ef92110f7ef1c306e178a358aa Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Wed, 16 Feb 2022 16:15:51 +0100 Subject: [PATCH 21/65] Rename class. --- .../androidLibMain/kotlin/utils/KalugaDate.kt | 46 ++++++------ .../src/commonMain/kotlin/utils/KalugaDate.kt | 70 ++++++++++--------- base/src/iosMain/kotlin/utils/KalugaDate.kt | 48 ++++++------- base/src/jsMain/kotlin/utils/KalugaDate.kt | 44 ++++++------ base/src/jvmMain/kotlin/utils/KalugaDate.kt | 46 ++++++------ 5 files changed, 129 insertions(+), 125 deletions(-) diff --git a/base/src/androidLibMain/kotlin/utils/KalugaDate.kt b/base/src/androidLibMain/kotlin/utils/KalugaDate.kt index fe21a2c4b..1c92fc911 100644 --- a/base/src/androidLibMain/kotlin/utils/KalugaDate.kt +++ b/base/src/androidLibMain/kotlin/utils/KalugaDate.kt @@ -19,83 +19,83 @@ package com.splendo.kaluga.base.utils import java.util.Calendar -actual class KalugaDate internal constructor(internal val calendar: Calendar) : Comparable { +actual class DefaultKalugaDate internal constructor(internal val calendar: Calendar) : KalugaDate { actual companion object { - actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = KalugaDate( + actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = DefaultKalugaDate( Calendar.getInstance(timeZone.timeZone, locale.locale).apply { add(Calendar.MILLISECOND, offsetInMilliseconds.toInt()) } ) - actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = KalugaDate( + actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = DefaultKalugaDate( Calendar.getInstance(timeZone.timeZone, locale.locale).apply { timeInMillis = offsetInMilliseconds } ) } - actual var timeZone: TimeZone + override var timeZone: TimeZone get() = TimeZone(calendar.timeZone) set(value) { calendar.timeZone = value.timeZone } - actual var era: Int + override var era: Int get() = calendar.get(Calendar.ERA) set(value) { calendar.set(Calendar.ERA, value) } - actual var year: Int + override var year: Int get() = calendar.get(Calendar.YEAR) set(value) { calendar.set(Calendar.YEAR, value) } - actual var month: Int + override var month: Int get() = calendar.get(Calendar.MONTH) + 1 set(value) { calendar.set(Calendar.MONTH, value - 1) } - actual val daysInMonth: Int get() = calendar.getActualMaximum(Calendar.DAY_OF_MONTH) - actual var weekOfYear: Int + override val daysInMonth: Int get() = calendar.getActualMaximum(Calendar.DAY_OF_MONTH) + override var weekOfYear: Int get() = calendar.get(Calendar.WEEK_OF_YEAR) set(value) { calendar.set(Calendar.WEEK_OF_YEAR, value) } - actual var weekOfMonth: Int + override var weekOfMonth: Int get() = calendar.get(Calendar.WEEK_OF_MONTH) set(value) { calendar.set(Calendar.WEEK_OF_MONTH, value) } - actual var day: Int + override var day: Int get() = calendar.get(Calendar.DAY_OF_MONTH) set(value) { calendar.set(Calendar.DAY_OF_MONTH, value) } - actual var dayOfYear: Int + override var dayOfYear: Int get() = calendar.get(Calendar.DAY_OF_YEAR) set(value) { calendar.set(Calendar.DAY_OF_YEAR, value) } - actual var weekDay: Int + override var weekDay: Int get() = calendar.get(Calendar.DAY_OF_WEEK) set(value) { calendar.set(Calendar.DAY_OF_WEEK, value) } - actual var firstWeekDay: Int + override var firstWeekDay: Int get() = calendar.firstDayOfWeek set(value) { calendar.firstDayOfWeek = value } - actual var hour: Int + override var hour: Int get() = calendar.get(Calendar.HOUR_OF_DAY) set(value) { calendar.set(Calendar.HOUR_OF_DAY, value) } - actual var minute: Int + override var minute: Int get() = calendar.get(Calendar.MINUTE) set(value) { calendar.set(Calendar.MINUTE, value) } - actual var second: Int + override var second: Int get() = calendar.get(Calendar.SECOND) set(value) { calendar.set(Calendar.SECOND, value) } - actual var millisecond: Int + override var millisecond: Int get() = calendar.get(Calendar.MILLISECOND) set(value) { calendar.set(Calendar.MILLISECOND, value) } - actual var millisecondSinceEpoch: Long + override var millisecondSinceEpoch: Long get() = calendar.timeInMillis set(value) { calendar.timeInMillis = value } - actual fun copy(): KalugaDate = KalugaDate(calendar.clone() as Calendar) + override fun copy(): KalugaDate = DefaultKalugaDate(calendar.clone() as Calendar) - actual override fun equals(other: Any?): Boolean { + override fun equals(other: Any?): Boolean { return (other as? KalugaDate)?.let { timeZone == other.timeZone && millisecondSinceEpoch == other.millisecondSinceEpoch } ?: false } override fun compareTo(other: KalugaDate): Int { - return this.calendar.time.compareTo(other.calendar.time) + return this.calendar.time.compareTo((other as DefaultKalugaDate).calendar.time) } - actual override fun hashCode(): Int { + override fun hashCode(): Int { return calendar.hashCode() } } diff --git a/base/src/commonMain/kotlin/utils/KalugaDate.kt b/base/src/commonMain/kotlin/utils/KalugaDate.kt index 2b760bfcb..25dca8795 100644 --- a/base/src/commonMain/kotlin/utils/KalugaDate.kt +++ b/base/src/commonMain/kotlin/utils/KalugaDate.kt @@ -23,27 +23,7 @@ import com.splendo.kaluga.base.utils.Locale.Companion.defaultLocale * Class describing a point in time * Dates are localized according to a [Locale] and relative to a given [TimeZone] */ -expect class KalugaDate : Comparable { - companion object { - /** - * Creates a [KalugaDate] relative to the current time - * @param offsetInMilliseconds The offset in milliseconds from the current time. Defaults to 0 - * @param timeZone The [TimeZone] in which the Date is set. Defaults to [TimeZone.current] - * @param locale The [Locale] for which the Date is configured. Defaults to [Locale.defaultLocale] - * @return A [KalugaDate] relative to the current time - */ - fun now(offsetInMilliseconds: Long = 0L, timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale): KalugaDate - - /** - * Creates a [KalugaDate] relative to January 1st 1970 00:00:00 GMT - * @param offsetInMilliseconds The offset in milliseconds from the epoch time. Defaults to 0 - * @param timeZone The [TimeZone] in which the Date is set. Defaults to [TimeZone.current] - * @param locale The [Locale] for which the Date is configured. Defaults to [Locale.defaultLocale] - * @return A [KalugaDate] relative to the current time - */ - fun epoch(offsetInMilliseconds: Long = 0L, timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale): KalugaDate - } - +interface KalugaDate : Comparable { /** * The [TimeZone] in which the Date is set */ @@ -139,7 +119,29 @@ expect class KalugaDate : Comparable { override fun hashCode(): Int } -@Deprecated("Due to name clashes with platform classes and API changes this class has been renamed and changed to an interface. It will be removed in a future release.", ReplaceWith("KalugaState")) +expect class DefaultKalugaDate : KalugaDate { + companion object { + /** + * Creates a [KalugaDate] relative to the current time + * @param offsetInMilliseconds The offset in milliseconds from the current time. Defaults to 0 + * @param timeZone The [TimeZone] in which the Date is set. Defaults to [TimeZone.current] + * @param locale The [Locale] for which the Date is configured. Defaults to [Locale.defaultLocale] + * @return A [KalugaDate] relative to the current time + */ + fun now(offsetInMilliseconds: Long = 0L, timeZone: TimeZone = TimeZone.current(), locale: Locale = Locale.defaultLocale): KalugaDate + + /** + * Creates a [KalugaDate] relative to January 1st 1970 00:00:00 GMT + * @param offsetInMilliseconds The offset in milliseconds from the epoch time. Defaults to 0 + * @param timeZone The [TimeZone] in which the Date is set. Defaults to [TimeZone.current] + * @param locale The [Locale] for which the Date is configured. Defaults to [Locale.defaultLocale] + * @return A [KalugaDate] relative to the current time + */ + fun epoch(offsetInMilliseconds: Long = 0L, timeZone: TimeZone = TimeZone.current(), locale: Locale = Locale.defaultLocale): KalugaDate + } +} + +@Deprecated("Due to name clashes with platform classes and API changes this class has been renamed and changed to an interface. It will be removed in a future release.", ReplaceWith("KalugaDate")) typealias Date = KalugaDate /** @@ -170,7 +172,7 @@ operator fun KalugaDate.plus(date: KalugaDate): KalugaDate { * @param locale The [Locale] for which the Date is configured. Defaults to [Locale.defaultLocale] * @return A [KalugaDate] relative to the current time, in the UTC timezone */ -fun KalugaDate.Companion.nowUtc(offsetInMilliseconds: Long = 0L, locale: Locale = defaultLocale): KalugaDate = +fun DefaultKalugaDate.Companion.nowUtc(offsetInMilliseconds: Long = 0L, locale: Locale = defaultLocale): KalugaDate = now(offsetInMilliseconds, TimeZone.utc, locale) /** @@ -190,7 +192,7 @@ fun KalugaDate.toStartOfDay() = this.copy().apply { * @param locale The [Locale] for which the Date is configured. Defaults to [Locale.defaultLocale] * @return A [KalugaDate] that is set at midnight on the same day as the current time. */ -fun KalugaDate.Companion.today(timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale) = now(timeZone = timeZone, locale = locale).toStartOfDay() +fun DefaultKalugaDate.Companion.today(timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale) = now(timeZone = timeZone, locale = locale).toStartOfDay() /** * Gets a [KalugaDate] that is set at midnight on the day after the current time. @@ -198,7 +200,7 @@ fun KalugaDate.Companion.today(timeZone: TimeZone = TimeZone.current(), locale: * @param locale The [Locale] for which the Date is configured. Defaults to [Locale.defaultLocale] * @return A [KalugaDate] that is set at midnight on the day after the current time. */ -fun KalugaDate.Companion.tomorrow(timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale) = today(timeZone = timeZone, locale = locale).apply { day += 1 } +fun DefaultKalugaDate.Companion.tomorrow(timeZone: TimeZone = TimeZone.current(), locale: Locale = defaultLocale) = today(timeZone = timeZone, locale = locale).apply { day += 1 } /** * Checks whether a [KalugaDate] is on the same day as a given Date. @@ -237,52 +239,52 @@ fun KalugaDate.isInSameYear(date: KalugaDate): Boolean { * True if this [KalugaDate] is today */ val KalugaDate.isToday: Boolean - get() = isOnSameDay(KalugaDate.now(timeZone = this.timeZone)) + get() = isOnSameDay(DefaultKalugaDate.now(timeZone = this.timeZone)) /** * True if this [KalugaDate] is yesterday */ val KalugaDate.isYesterday: Boolean - get() = isOnSameDay(KalugaDate.now(timeZone = this.timeZone).apply { day -= 1 }) + get() = isOnSameDay(DefaultKalugaDate.now(timeZone = this.timeZone).apply { day -= 1 }) /** * True if this [KalugaDate] is tomorrow */ val KalugaDate.isTomorrow: Boolean - get() = isOnSameDay(KalugaDate.now(timeZone = this.timeZone).apply { day += 1 }) + get() = isOnSameDay(DefaultKalugaDate.now(timeZone = this.timeZone).apply { day += 1 }) /** * True if this [KalugaDate] is this month */ val KalugaDate.isThisMonth: Boolean - get() = isOnSameMonth(KalugaDate.now(timeZone = this.timeZone)) + get() = isOnSameMonth(DefaultKalugaDate.now(timeZone = this.timeZone)) /** * True if this [KalugaDate] is last month */ val KalugaDate.isLastMonth: Boolean - get() = isOnSameMonth(KalugaDate.now(timeZone = this.timeZone).apply { month -= 1 }) + get() = isOnSameMonth(DefaultKalugaDate.now(timeZone = this.timeZone).apply { month -= 1 }) /** * True if this [KalugaDate] is next month */ val KalugaDate.isNextMonth: Boolean - get() = isOnSameMonth(KalugaDate.now(timeZone = this.timeZone).apply { month += 1 }) + get() = isOnSameMonth(DefaultKalugaDate.now(timeZone = this.timeZone).apply { month += 1 }) /** * True if this [KalugaDate] is this year */ val KalugaDate.isThisYear: Boolean - get() = isInSameYear(KalugaDate.now(timeZone = this.timeZone)) + get() = isInSameYear(DefaultKalugaDate.now(timeZone = this.timeZone)) /** * True if this [KalugaDate] is last year */ val KalugaDate.isLastYear: Boolean - get() = isInSameYear(KalugaDate.now(timeZone = this.timeZone).apply { year -= 1 }) + get() = isInSameYear(DefaultKalugaDate.now(timeZone = this.timeZone).apply { year -= 1 }) /** * True if this [KalugaDate] is next year */ val KalugaDate.isNextYear: Boolean - get() = isInSameYear(KalugaDate.now(timeZone = this.timeZone).apply { year += 1 }) + get() = isInSameYear(DefaultKalugaDate.now(timeZone = this.timeZone).apply { year += 1 }) diff --git a/base/src/iosMain/kotlin/utils/KalugaDate.kt b/base/src/iosMain/kotlin/utils/KalugaDate.kt index 9ce1d394d..30cbeb660 100644 --- a/base/src/iosMain/kotlin/utils/KalugaDate.kt +++ b/base/src/iosMain/kotlin/utils/KalugaDate.kt @@ -44,7 +44,7 @@ import platform.darwin.NSInteger import platform.darwin.NSUInteger import kotlin.math.round -actual class KalugaDate internal constructor(private val calendar: NSCalendar, initialDate: NSDate) : Comparable { +actual class DefaultKalugaDate internal constructor(private val calendar: NSCalendar, initialDate: NSDate) : KalugaDate { actual companion object { const val nanoSecondPerMilliSecond = 1000 * 1000 @@ -55,7 +55,7 @@ actual class KalugaDate internal constructor(private val calendar: NSCalendar, i this.timeZone = timeZone.timeZone } val date = NSDate.dateWithTimeIntervalSinceNow(offsetInMilliseconds.toDouble() / 1000.0) - return KalugaDate(calendar, date) + return DefaultKalugaDate(calendar, date) } actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate { val calendar = NSCalendar.currentCalendar.apply { @@ -63,57 +63,57 @@ actual class KalugaDate internal constructor(private val calendar: NSCalendar, i this.timeZone = timeZone.timeZone } val date = NSDate.dateWithTimeIntervalSince1970(offsetInMilliseconds.toDouble() / 1000.0) - return KalugaDate(calendar, date) + return DefaultKalugaDate(calendar, date) } } internal var date: NSDate = initialDate - actual var timeZone: TimeZone + override var timeZone: TimeZone get() = TimeZone(calendar.timeZone) set(value) { calendar.timeZone = value.timeZone } - actual var era: Int + override var era: Int get() = calendar.component(NSCalendarUnitEra, fromDate = date).toInt() set(value) { updateDateForComponent(NSCalendarUnitEra, value) } - actual var year: Int + override var year: Int get() = calendar.component(NSCalendarUnitYear, fromDate = date).toInt() set(value) { updateDateForComponent(NSCalendarUnitYear, value) } - actual var month: Int + override var month: Int get() = calendar.component(NSCalendarUnitMonth, fromDate = date).toInt() set(value) { updateDateForComponent(NSCalendarUnitMonth, value) } - actual val daysInMonth: Int get() = calendar.rangeOfUnit(NSCalendarUnitDay, NSCalendarUnitMonth, forDate = date).useContents { this.length.toInt() } - actual var weekOfYear: Int + override val daysInMonth: Int get() = calendar.rangeOfUnit(NSCalendarUnitDay, NSCalendarUnitMonth, forDate = date).useContents { this.length.toInt() } + override var weekOfYear: Int get() = calendar.component(NSCalendarUnitWeekOfYear, fromDate = date).toInt() set(value) { updateDateForComponent(NSCalendarUnitWeekOfYear, value) } - actual var weekOfMonth: Int + override var weekOfMonth: Int get() = calendar.component(NSCalendarUnitWeekOfMonth, fromDate = date).toInt() set(value) { updateDateForComponent(NSCalendarUnitWeekOfMonth, value) } - actual var day: Int + override var day: Int get() = calendar.component(NSCalendarUnitDay, fromDate = date).toInt() set(value) { updateDateForComponent(NSCalendarUnitDay, value) } - actual var dayOfYear: Int + override var dayOfYear: Int get() = calendar.ordinalityOfUnit(NSCalendarUnitDay, NSCalendarUnitYear, date).toInt() set(value) { updateDateForComponent(NSCalendarUnitDay, value - dayOfYear + day) } - actual var weekDay: Int + override var weekDay: Int get() = calendar.component(NSCalendarUnitWeekday, fromDate = date).toInt() set(value) { updateDateForComponent(NSCalendarUnitWeekday, value) } - actual var firstWeekDay: Int + override var firstWeekDay: Int get() = (calendar.firstWeekday.toInt()) set(value) { calendar.firstWeekday = value.toULong() as NSUInteger } - actual var hour: Int + override var hour: Int get() = calendar.component(NSCalendarUnitHour, fromDate = date).toInt() set(value) { updateDateForComponent(NSCalendarUnitHour, value) } - actual var minute: Int + override var minute: Int get() = calendar.component(NSCalendarUnitMinute, fromDate = date).toInt() set(value) { updateDateForComponent(NSCalendarUnitMinute, value) } - actual var second: Int + override var second: Int get() = calendar.component(NSCalendarUnitSecond, fromDate = date).toInt() set(value) { updateDateForComponent(NSCalendarUnitSecond, value) } - actual var millisecond: Int + override var millisecond: Int get() = calendar.component(NSCalendarUnitNanosecond, fromDate = date).toInt() / nanoSecondPerMilliSecond set(value) { updateDateForComponent(NSCalendarUnitNanosecond, value * nanoSecondPerMilliSecond) } - actual var millisecondSinceEpoch: Long + override var millisecondSinceEpoch: Long get() { val time = date.timeIntervalSince1970 val decimalDigits = (time % 1.0) * 1000 @@ -121,21 +121,21 @@ actual class KalugaDate internal constructor(private val calendar: NSCalendar, i } set(value) { date = NSDate.dateWithTimeIntervalSince1970(value.toDouble() / 1000.0) } - actual fun copy(): KalugaDate = KalugaDate(calendar.copy() as NSCalendar, date.copy() as NSDate) + override fun copy(): KalugaDate = DefaultKalugaDate(calendar.copy() as NSCalendar, date.copy() as NSDate) - actual override fun equals(other: Any?): Boolean { - return (other as? KalugaDate)?.let { other -> + override fun equals(other: Any?): Boolean { + return (other as? DefaultKalugaDate)?.let { other -> calendar.calendarIdentifier == other.calendar.calendarIdentifier && millisecondSinceEpoch == other.millisecondSinceEpoch && this.calendar.timeZone == other.calendar.timeZone } ?: false } - actual override fun hashCode(): Int { + override fun hashCode(): Int { var result = calendar.calendarIdentifier.hashCode() result = 31 * result + date.hashCode() return result } - override fun compareTo(other: KalugaDate): Int = this.date.compare(other.date).toInt() + override fun compareTo(other: KalugaDate): Int = this.date.compare((other as DefaultKalugaDate).date).toInt() private fun updateDateForComponent(component: NSCalendarUnit, value: Int) { // Check whether this component update can use dateBySettingUnit. diff --git a/base/src/jsMain/kotlin/utils/KalugaDate.kt b/base/src/jsMain/kotlin/utils/KalugaDate.kt index 7b2c96ce6..99e705d67 100644 --- a/base/src/jsMain/kotlin/utils/KalugaDate.kt +++ b/base/src/jsMain/kotlin/utils/KalugaDate.kt @@ -18,65 +18,65 @@ package com.splendo.kaluga.base.utils // TODO Implement with proper date solution for Java Script -actual class KalugaDate internal constructor(internal val date: kotlin.js.Date) : Comparable { +actual class DefaultKalugaDate internal constructor(internal val date: kotlin.js.Date) : KalugaDate { actual companion object { - actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = KalugaDate(kotlin.js.Date(kotlin.js.Date.now() + offsetInMilliseconds)) - actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = KalugaDate(kotlin.js.Date(offsetInMilliseconds)) + actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = DefaultKalugaDate(kotlin.js.Date(kotlin.js.Date.now() + offsetInMilliseconds)) + actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = DefaultKalugaDate(kotlin.js.Date(offsetInMilliseconds)) } - actual var timeZone: TimeZone + override var timeZone: TimeZone get() = TimeZone() set(value) { } - actual var era: Int + override var era: Int get() = 0 set(value) { } - actual var year: Int + override var year: Int get() = date.getFullYear() set(value) { } - actual var month: Int + override var month: Int get() = date.getMonth() set(value) { } - actual val daysInMonth: Int = 0 - actual var weekOfYear: Int + override val daysInMonth: Int = 0 + override var weekOfYear: Int get() = 0 set(value) { } - actual var weekOfMonth: Int + override var weekOfMonth: Int get() = 0 set(value) { } - actual var day: Int + override var day: Int get() = 0 set(value) { } - actual var dayOfYear: Int + override var dayOfYear: Int get() = date.getDay() set(value) { } - actual var weekDay: Int + override var weekDay: Int get() = date.getDate() + 1 set(value) { } - actual var firstWeekDay: Int + override var firstWeekDay: Int get() = 1 set(value) { } - actual var hour: Int + override var hour: Int get() = date.getHours() set(value) { } - actual var minute: Int + override var minute: Int get() = date.getMinutes() set(value) { } - actual var second: Int + override var second: Int get() = date.getSeconds() set(value) { } - actual var millisecond: Int + override var millisecond: Int get() = date.getMilliseconds() set(value) { } - actual var millisecondSinceEpoch: Long + override var millisecondSinceEpoch: Long get() = date.getTime().toLong() set(value) { } - actual fun copy(): KalugaDate = KalugaDate(kotlin.js.Date(date.getMilliseconds())) + override fun copy(): KalugaDate = DefaultKalugaDate(kotlin.js.Date(date.getMilliseconds())) - actual override fun equals(other: Any?): Boolean { + override fun equals(other: Any?): Boolean { return (other as? KalugaDate)?.let { timeZone == other.timeZone && millisecondSinceEpoch == other.millisecondSinceEpoch } ?: false @@ -90,7 +90,7 @@ actual class KalugaDate internal constructor(internal val date: kotlin.js.Date) } } - actual override fun hashCode(): Int { + override fun hashCode(): Int { return date.hashCode() } } diff --git a/base/src/jvmMain/kotlin/utils/KalugaDate.kt b/base/src/jvmMain/kotlin/utils/KalugaDate.kt index 7c760a1a6..6ae054fbf 100644 --- a/base/src/jvmMain/kotlin/utils/KalugaDate.kt +++ b/base/src/jvmMain/kotlin/utils/KalugaDate.kt @@ -19,79 +19,81 @@ package com.splendo.kaluga.base.utils import java.util.Calendar -actual class KalugaDate internal constructor(internal val calendar: Calendar) : Comparable { +actual class DefaultKalugaDate internal constructor(internal val calendar: Calendar) : KalugaDate { actual companion object { - actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = KalugaDate( + actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = DefaultKalugaDate( Calendar.getInstance(timeZone.timeZone, locale.locale).apply { add(Calendar.MILLISECOND, offsetInMilliseconds.toInt()) } ) - actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = KalugaDate( + actual fun epoch(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = DefaultKalugaDate( Calendar.getInstance(timeZone.timeZone, locale.locale).apply { timeInMillis = offsetInMilliseconds } ) } - actual var timeZone: TimeZone + override var timeZone: TimeZone get() = TimeZone(calendar.timeZone) set(value) { calendar.timeZone = value.timeZone } - actual var era: Int + override var era: Int get() = calendar.get(Calendar.ERA) set(value) { calendar.set(Calendar.ERA, value) } - actual var year: Int + override var year: Int get() = calendar.get(Calendar.YEAR) set(value) { calendar.set(Calendar.YEAR, value) } - actual var month: Int + override var month: Int get() = calendar.get(Calendar.MONTH) + 1 set(value) { calendar.set(Calendar.MONTH, value - 1) } - actual val daysInMonth: Int get() = calendar.getActualMaximum(Calendar.DAY_OF_MONTH) - actual var weekOfYear: Int + override val daysInMonth: Int get() = calendar.getActualMaximum(Calendar.DAY_OF_MONTH) + override var weekOfYear: Int get() = calendar.get(Calendar.WEEK_OF_YEAR) set(value) { calendar.set(Calendar.WEEK_OF_YEAR, value) } - actual var weekOfMonth: Int + override var weekOfMonth: Int get() = calendar.get(Calendar.WEEK_OF_MONTH) set(value) { calendar.set(Calendar.WEEK_OF_MONTH, value) } - actual var day: Int + override var day: Int get() = calendar.get(Calendar.DAY_OF_MONTH) set(value) { calendar.set(Calendar.DAY_OF_MONTH, value) } - actual var dayOfYear: Int + override var dayOfYear: Int get() = calendar.get(Calendar.DAY_OF_YEAR) set(value) { calendar.set(Calendar.DAY_OF_YEAR, value) } - actual var weekDay: Int + override var weekDay: Int get() = calendar.get(Calendar.DAY_OF_WEEK) set(value) { calendar.set(Calendar.DAY_OF_WEEK, value) } - actual var firstWeekDay: Int + override var firstWeekDay: Int get() = calendar.firstDayOfWeek set(value) { calendar.firstDayOfWeek = value } - actual var hour: Int + override var hour: Int get() = calendar.get(Calendar.HOUR_OF_DAY) set(value) { calendar.set(Calendar.HOUR_OF_DAY, value) } - actual var minute: Int + override var minute: Int get() = calendar.get(Calendar.MINUTE) set(value) { calendar.set(Calendar.MINUTE, value) } - actual var second: Int + override var second: Int get() = calendar.get(Calendar.SECOND) set(value) { calendar.set(Calendar.SECOND, value) } - actual var millisecond: Int + override var millisecond: Int get() = calendar.get(Calendar.MILLISECOND) set(value) { calendar.set(Calendar.MILLISECOND, value) } - actual var millisecondSinceEpoch: Long + override var millisecondSinceEpoch: Long get() = calendar.timeInMillis set(value) { calendar.timeInMillis = value } - actual fun copy(): KalugaDate = KalugaDate(calendar.clone() as Calendar) + override fun copy(): KalugaDate = DefaultKalugaDate(calendar.clone() as Calendar) - actual override fun equals(other: Any?): Boolean { + override fun equals(other: Any?): Boolean { return (other as? KalugaDate)?.let { timeZone == other.timeZone && millisecondSinceEpoch == other.millisecondSinceEpoch } ?: false } + override fun hashCode(): Int = calendar.hashCode() + override fun compareTo(other: KalugaDate): Int { - return this.calendar.time.compareTo(other.calendar.time) + return this.calendar.time.compareTo((other as DefaultKalugaDate).calendar.time) } } From 8cdfaf06361604025991288aaa85158a87df8480 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Wed, 16 Feb 2022 16:16:25 +0100 Subject: [PATCH 22/65] Update references --- .../androidLibMain/kotlin/navigation/NavigationBundle.kt | 5 +++-- .../commonTest/kotlin/navigation/NavigationBundleTest.kt | 8 ++++---- .../src/androidLibMain/kotlin/text/KalugaDateFormatter.kt | 5 +++-- base/src/androidLibMain/kotlin/utils/TimeZone.kt | 2 +- base/src/commonMain/kotlin/text/FormatSpecifier.kt | 3 ++- base/src/commonMain/kotlin/utils/Locale.kt | 2 +- base/src/commonMain/kotlin/utils/TimeZone.kt | 2 +- base/src/commonTest/kotlin/text/DateFormatterTest.kt | 8 ++++---- base/src/iosMain/kotlin/text/KalugaDateFormatter.kt | 5 +++-- base/src/iosMain/kotlin/utils/TimeZone.kt | 4 ++-- base/src/jsMain/kotlin/text/KalugaDateFormatter.kt | 3 ++- beacons/src/commonMain/kotlin/BeaconInfo.kt | 3 ++- bluetooth/src/commonMain/kotlin/device/DeviceInfo.kt | 3 ++- 13 files changed, 30 insertions(+), 23 deletions(-) diff --git a/architecture/src/androidLibMain/kotlin/navigation/NavigationBundle.kt b/architecture/src/androidLibMain/kotlin/navigation/NavigationBundle.kt index 1369eff77..02d074319 100644 --- a/architecture/src/androidLibMain/kotlin/navigation/NavigationBundle.kt +++ b/architecture/src/androidLibMain/kotlin/navigation/NavigationBundle.kt @@ -18,6 +18,7 @@ package com.splendo.kaluga.architecture.navigation import android.os.Bundle +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.KalugaDate /** @@ -133,10 +134,10 @@ internal fun Bundle.mapValue(key: String, specType: NavigationBundleSpecType<*>) } } is NavigationBundleSpecType.DateType -> getLong(key).let { value -> - specType.convertValue(KalugaDate.epoch(value)) + specType.convertValue(DefaultKalugaDate.epoch(value)) } is NavigationBundleSpecType.DateArrayType -> getLongArray(key)?.let { array -> - specType.convertValue(array.map { KalugaDate.epoch(it) }) + specType.convertValue(array.map { DefaultKalugaDate.epoch(it) }) } } } diff --git a/architecture/src/commonTest/kotlin/navigation/NavigationBundleTest.kt b/architecture/src/commonTest/kotlin/navigation/NavigationBundleTest.kt index 517c0c653..b0ee40bd9 100644 --- a/architecture/src/commonTest/kotlin/navigation/NavigationBundleTest.kt +++ b/architecture/src/commonTest/kotlin/navigation/NavigationBundleTest.kt @@ -17,7 +17,7 @@ package com.splendo.kaluga.architecture.navigation -import com.splendo.kaluga.base.utils.KalugaDate +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.test.BaseTest import kotlin.test.Test import kotlin.test.assertEquals @@ -38,10 +38,10 @@ class NavigationBundleTest : BaseTest() { } val optionalString: String? = "Some String" val optionalFloat: Float? = null - val dateValue = KalugaDate.epoch(offsetInMilliseconds = 1606204800000) + val dateValue = DefaultKalugaDate.epoch(offsetInMilliseconds = 1606204800000) val dateArray = listOf( - KalugaDate.epoch(offsetInMilliseconds = 1606204800001), - KalugaDate.epoch(offsetInMilliseconds = 1606204800002) + DefaultKalugaDate.epoch(offsetInMilliseconds = 1606204800001), + DefaultKalugaDate.epoch(offsetInMilliseconds = 1606204800002) ) val mockSpec = MockSpec() diff --git a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt index 90e2de6ab..3a2fddc00 100644 --- a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt @@ -18,6 +18,7 @@ @file:JvmName("AndroidDateFormatter") package com.splendo.kaluga.base.text +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone @@ -122,12 +123,12 @@ actual class KalugaDateFormatter private constructor(private val format: SimpleD get() = symbols.amPmStrings.toList()[1] set(value) { updateSymbols { it.amPmStrings = it.amPmStrings.toMutableList().apply { this[1] = value }.toTypedArray() } } - actual fun format(date: KalugaDate): String = format.format(date.calendar.time) + actual fun format(date: KalugaDate): String = format.format((date as DefaultKalugaDate).calendar.time) actual fun parse(string: String): KalugaDate? { return try { format.parse(string)?.let { date -> val calendar = format.calendar.clone() as Calendar - KalugaDate(calendar.apply { time = date }) + DefaultKalugaDate(calendar.apply { time = date }) } } catch (e: ParseException) { null diff --git a/base/src/androidLibMain/kotlin/utils/TimeZone.kt b/base/src/androidLibMain/kotlin/utils/TimeZone.kt index 595840a34..b67b64b47 100644 --- a/base/src/androidLibMain/kotlin/utils/TimeZone.kt +++ b/base/src/androidLibMain/kotlin/utils/TimeZone.kt @@ -42,7 +42,7 @@ actual class TimeZone internal constructor(internal val timeZone: java.util.Time actual val offsetFromGMTInMilliseconds = timeZone.rawOffset.toLong() actual val daylightSavingsOffsetInMilliseconds: Long = timeZone.dstSavings.toLong() actual fun offsetFromGMTAtDateInMilliseconds(date: KalugaDate): Long = timeZone.getOffset(date.millisecondSinceEpoch).toLong() - actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.inDaylightTime(date.calendar.time) + actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.inDaylightTime((date as DefaultKalugaDate).calendar.time) actual fun copy(): TimeZone = TimeZone(timeZone.clone() as java.util.TimeZone) override fun equals(other: Any?): Boolean { return (other as? TimeZone)?.let { timeZone == other.timeZone } ?: false diff --git a/base/src/commonMain/kotlin/text/FormatSpecifier.kt b/base/src/commonMain/kotlin/text/FormatSpecifier.kt index 7b8b723b8..b4ba3e858 100644 --- a/base/src/commonMain/kotlin/text/FormatSpecifier.kt +++ b/base/src/commonMain/kotlin/text/FormatSpecifier.kt @@ -18,6 +18,7 @@ package com.splendo.kaluga.base.text import com.splendo.kaluga.base.text.StringFormatter.Companion.getZero +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone @@ -107,7 +108,7 @@ internal class FormatSpecifier(private val out: StringBuilder, matchResult: Matc is Long, is Int, is Short -> { - KalugaDate.epoch((arg as Number).toLong(), TimeZone.current(), locale) + DefaultKalugaDate.epoch((arg as Number).toLong(), TimeZone.current(), locale) } is KalugaDate -> { arg.copy() diff --git a/base/src/commonMain/kotlin/utils/Locale.kt b/base/src/commonMain/kotlin/utils/Locale.kt index 9a3193475..528d3b137 100644 --- a/base/src/commonMain/kotlin/utils/Locale.kt +++ b/base/src/commonMain/kotlin/utils/Locale.kt @@ -151,6 +151,6 @@ val Locale.Companion.enUsPosix get() = createLocale("en", "US", "POSIX") */ val Locale.uses24HourClock: Boolean get() { val formatter = KalugaDateFormatter.timeFormat(DateFormatStyle.Medium, locale = this) - val formattedDate = formatter.format(KalugaDate.now()) + val formattedDate = formatter.format(DefaultKalugaDate.now()) return !formattedDate.contains(formatter.amString) && !formattedDate.contains(formatter.pmString) } diff --git a/base/src/commonMain/kotlin/utils/TimeZone.kt b/base/src/commonMain/kotlin/utils/TimeZone.kt index 45f63af76..a92866afb 100644 --- a/base/src/commonMain/kotlin/utils/TimeZone.kt +++ b/base/src/commonMain/kotlin/utils/TimeZone.kt @@ -17,7 +17,7 @@ package com.splendo.kaluga.base.utils -import com.splendo.kaluga.base.utils.KalugaDate.Companion.now +import com.splendo.kaluga.base.utils.DefaultKalugaDate.Companion.now import com.splendo.kaluga.base.utils.Locale.Companion.defaultLocale import kotlin.native.concurrent.ThreadLocal diff --git a/base/src/commonTest/kotlin/text/DateFormatterTest.kt b/base/src/commonTest/kotlin/text/DateFormatterTest.kt index e14c46b2c..3d8f69c4e 100644 --- a/base/src/commonTest/kotlin/text/DateFormatterTest.kt +++ b/base/src/commonTest/kotlin/text/DateFormatterTest.kt @@ -21,7 +21,7 @@ import com.splendo.kaluga.base.text.DateFormatStyle import com.splendo.kaluga.base.text.KalugaDateFormatter import com.splendo.kaluga.base.text.dateFormat import com.splendo.kaluga.base.text.iso8601Pattern -import com.splendo.kaluga.base.utils.KalugaDate +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.Locale.Companion.createLocale import com.splendo.kaluga.base.utils.TimeZone import com.splendo.kaluga.base.utils.nowUtc @@ -38,14 +38,14 @@ class DateFormatterTest { private val FranceLocale = createLocale("fr", "FR") private val PSTTimeZone = TimeZone.get("America/Los_Angeles")!! - private val January81988 = KalugaDate.epoch(568627200000) - private val March181988 = KalugaDate.epoch(574695462750) + private val January81988 = DefaultKalugaDate.epoch(568627200000) + private val March181988 = DefaultKalugaDate.epoch(574695462750) } @Test fun testFormatDate() { val formatter = KalugaDateFormatter.dateFormat(DateFormatStyle.Short, PSTTimeZone, UnitedStatesLocale) - val date = KalugaDate.nowUtc().apply { + val date = DefaultKalugaDate.nowUtc().apply { year = 2020 month = 1 day = 8 diff --git a/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt b/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt index 85b411fb4..0ce9b2ebd 100644 --- a/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt @@ -18,6 +18,7 @@ package com.splendo.kaluga.base.text import com.splendo.kaluga.base.typedList +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone @@ -108,11 +109,11 @@ actual class KalugaDateFormatter private constructor(private val format: NSDateF get() = format.PMSymbol set(value) { format.PMSymbol = value } - actual fun format(date: KalugaDate): String = format.stringFromDate(date.date) + actual fun format(date: KalugaDate): String = format.stringFromDate((date as DefaultKalugaDate).date) actual fun parse(string: String): KalugaDate? { return format.dateFromString(string)?.let { date -> val calendar = format.calendar.copy() as NSCalendar - KalugaDate(calendar, date) + DefaultKalugaDate(calendar, date) } } } diff --git a/base/src/iosMain/kotlin/utils/TimeZone.kt b/base/src/iosMain/kotlin/utils/TimeZone.kt index 82818d24c..e1d50b985 100644 --- a/base/src/iosMain/kotlin/utils/TimeZone.kt +++ b/base/src/iosMain/kotlin/utils/TimeZone.kt @@ -75,8 +75,8 @@ actual class TimeZone internal constructor(val timeZone: NSTimeZone) { } return rawOffset * 1000L } - actual fun offsetFromGMTAtDateInMilliseconds(date: KalugaDate): Long = (timeZone.secondsFromGMTForDate(date.date) * 1000L) - actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.isDaylightSavingTimeForDate(date.date) + actual fun offsetFromGMTAtDateInMilliseconds(date: KalugaDate): Long = (timeZone.secondsFromGMTForDate((date as DefaultKalugaDate).date) * 1000L) + actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.isDaylightSavingTimeForDate((date as DefaultKalugaDate).date) actual fun copy(): TimeZone = TimeZone(timeZone.copy() as NSTimeZone) override fun equals(other: Any?): Boolean { return (other as? TimeZone)?.let { timeZone == other.timeZone } ?: false diff --git a/base/src/jsMain/kotlin/text/KalugaDateFormatter.kt b/base/src/jsMain/kotlin/text/KalugaDateFormatter.kt index f92fe4303..6b1dc9a45 100644 --- a/base/src/jsMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/jsMain/kotlin/text/KalugaDateFormatter.kt @@ -17,6 +17,7 @@ package com.splendo.kaluga.base.text +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone @@ -61,7 +62,7 @@ actual class KalugaDateFormatter private constructor(initialTimeZone: TimeZone, actual var amString: String = "" actual var pmString: String = "" - actual fun format(date: KalugaDate): String = formatter(date.date) + actual fun format(date: KalugaDate): String = formatter((date as DefaultKalugaDate).date) actual fun parse(string: String): KalugaDate? = null } diff --git a/beacons/src/commonMain/kotlin/BeaconInfo.kt b/beacons/src/commonMain/kotlin/BeaconInfo.kt index 41520b024..888a42c0f 100644 --- a/beacons/src/commonMain/kotlin/BeaconInfo.kt +++ b/beacons/src/commonMain/kotlin/BeaconInfo.kt @@ -17,6 +17,7 @@ package com.splendo.kaluga.bluetooth.beacons +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.bluetooth.device.Identifier @@ -37,4 +38,4 @@ data class BeaconInfo( replaceWith = ReplaceWith(expression = "beaconID.asString()") ) fun BeaconInfo.fullID() = this.beaconID.namespace + this.beaconID.instance -fun BeaconInfo.seenMs() = KalugaDate.now().millisecondSinceEpoch - lastSeen.millisecondSinceEpoch +fun BeaconInfo.seenMs() = DefaultKalugaDate.now().millisecondSinceEpoch - lastSeen.millisecondSinceEpoch diff --git a/bluetooth/src/commonMain/kotlin/device/DeviceInfo.kt b/bluetooth/src/commonMain/kotlin/device/DeviceInfo.kt index d2845a157..fa648cdf7 100644 --- a/bluetooth/src/commonMain/kotlin/device/DeviceInfo.kt +++ b/bluetooth/src/commonMain/kotlin/device/DeviceInfo.kt @@ -17,6 +17,7 @@ package com.splendo.kaluga.bluetooth.device +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.KalugaDate import kotlin.math.pow @@ -50,7 +51,7 @@ data class DeviceInfoImpl( override val name: String? get() = deviceWrapper.name - override val updatedAt = KalugaDate.now() + override val updatedAt = DefaultKalugaDate.now() override fun distance(environmentalFactor: Double): Double { if (advertisementData.txPowerLevel == Int.MIN_VALUE || environmentalFactor.isNaN()) From 45e8a4851163df033053c79a7feb97b61d0e4ccc Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Tue, 8 Mar 2022 14:14:45 +0100 Subject: [PATCH 23/65] Cast variable. --- .../kotlin/text/StringFormatterTest.kt | 3 +- base/src/commonTest/kotlin/utils/DateTest.kt | 31 ++++++++++--------- .../kotlin/text/KalugaDateFormatter.kt | 5 +-- base/src/jvmMain/kotlin/utils/TimeZone.kt | 2 +- 4 files changed, 22 insertions(+), 19 deletions(-) diff --git a/base/src/commonTest/kotlin/text/StringFormatterTest.kt b/base/src/commonTest/kotlin/text/StringFormatterTest.kt index 656bfbcad..c20078a31 100644 --- a/base/src/commonTest/kotlin/text/StringFormatterTest.kt +++ b/base/src/commonTest/kotlin/text/StringFormatterTest.kt @@ -18,6 +18,7 @@ package com.splendo.kaluga.base.test.text import com.splendo.kaluga.base.text.format +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale.Companion.createLocale import com.splendo.kaluga.base.utils.TimeZone @@ -444,7 +445,7 @@ class StringFormatterTest { @Test fun testFormatDate() { - val date = KalugaDate.now(timeZone = TimeZone.get("America/Los_Angeles")!!, locale = locale).apply { + val date = DefaultKalugaDate.now(timeZone = TimeZone.get("America/Los_Angeles")!!, locale = locale).apply { year = 2020 month = 7 day = 23 diff --git a/base/src/commonTest/kotlin/utils/DateTest.kt b/base/src/commonTest/kotlin/utils/DateTest.kt index dda9cc982..9c4663eda 100644 --- a/base/src/commonTest/kotlin/utils/DateTest.kt +++ b/base/src/commonTest/kotlin/utils/DateTest.kt @@ -17,6 +17,7 @@ package com.splendo.kaluga.base.test.utils +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone @@ -33,49 +34,49 @@ class DateTest { @Test fun testEquality() { - val now = KalugaDate.now(locale = Locale.enUsPosix) + val now = DefaultKalugaDate.now(locale = Locale.enUsPosix) assertEquals(now, now.copy(), "copied Date should be equal") - val nearEpoch = KalugaDate.epoch(1001) - assertEquals(KalugaDate.epoch(1001), nearEpoch, "equally created dates should be equal") + val nearEpoch = DefaultKalugaDate.epoch(1001) + assertEquals(DefaultKalugaDate.epoch(1001), nearEpoch, "equally created dates should be equal") - assertEquals(KalugaDate.epoch(1002), nearEpoch + KalugaDate.epoch(1), "Date from addition should be equal") + assertEquals(DefaultKalugaDate.epoch(1002), nearEpoch + DefaultKalugaDate.epoch(1), "Date from addition should be equal") } @Test fun testUTCDate() { - val utcNow = KalugaDate.nowUtc(locale = Locale.enUsPosix) + val utcNow = DefaultKalugaDate.nowUtc(locale = Locale.enUsPosix) val epochNow = utcNow.millisecondSinceEpoch - val now = KalugaDate.epoch(epochNow, TimeZone.utc, locale = Locale.enUsPosix) + val now = DefaultKalugaDate.epoch(epochNow, TimeZone.utc, locale = Locale.enUsPosix) assertEquals(utcNow.millisecondSinceEpoch, now.millisecondSinceEpoch) assertEquals(utcNow, now) } @Test fun testCreateEpochDate() { - val someDay = KalugaDate.epoch(locale = Locale.enUsPosix).apply { + val someDay = DefaultKalugaDate.epoch(locale = Locale.enUsPosix).apply { year = 2020 month = 5 day = 12 hour = 8 minute = 45 } - val epoch = KalugaDate.epoch(locale = Locale.enUsPosix) + val epoch = DefaultKalugaDate.epoch(locale = Locale.enUsPosix) assertTrue(epoch < someDay) } @Test fun testCreateNowDate() { - val now = KalugaDate.now(locale = Locale.enUsPosix) - val epoch = KalugaDate.epoch(locale = Locale.enUsPosix) + val now = DefaultKalugaDate.now(locale = Locale.enUsPosix) + val epoch = DefaultKalugaDate.epoch(locale = Locale.enUsPosix) assertTrue(now > epoch) } @Test fun testUpdateDate() { - val epoch = KalugaDate.epoch(locale = Locale.enUsPosix) + val epoch = DefaultKalugaDate.epoch(locale = Locale.enUsPosix) val isEarlierThanGMT = epoch.timeZone.offsetFromGMTAtDateInMilliseconds(epoch) < 0 assertEquals(if (isEarlierThanGMT) 1969 else 1970, epoch.year) assertEquals(if (isEarlierThanGMT) 12 else 1, epoch.month) @@ -86,7 +87,7 @@ class DateTest { @Test fun testGet() { - val someDay = KalugaDate.epoch(574695462750, TimeZone.utc, locale = Locale.enUsPosix) + val someDay = DefaultKalugaDate.epoch(574695462750, TimeZone.utc, locale = Locale.enUsPosix) assertEquals(1, someDay.era) assertEquals(1988, someDay.year) @@ -108,8 +109,8 @@ class DateTest { val france = Locale.createLocale("fr", "FR") val us = Locale.createLocale("en", "US") - val frenchNow = KalugaDate.now(0, TimeZone.utc, france) - val usNow = KalugaDate.now(0, TimeZone.utc, us) + val frenchNow = DefaultKalugaDate.now(0, TimeZone.utc, france) + val usNow = DefaultKalugaDate.now(0, TimeZone.utc, us) assertEquals(2, frenchNow.firstWeekDay) assertEquals(1, usNow.firstWeekDay) @@ -117,7 +118,7 @@ class DateTest { @Test fun testDaylightSavings() { - val dayBeforeDLS = KalugaDate.epoch(1616828400000, locale = Locale.createLocale("nl", "NL"), timeZone = TimeZone.get("Europe/Amsterdam")!!) + val dayBeforeDLS = DefaultKalugaDate.epoch(1616828400000, locale = Locale.createLocale("nl", "NL"), timeZone = TimeZone.get("Europe/Amsterdam")!!) val startOfDayBeforeDLS = dayBeforeDLS.toStartOfDay() assertEquals(0, startOfDayBeforeDLS.hour) assertEquals(27, startOfDayBeforeDLS.day) diff --git a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt index 419d4ceca..47f953c73 100644 --- a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt @@ -18,6 +18,7 @@ @file:JvmName("JvmDateFormatter") package com.splendo.kaluga.base.text +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone @@ -125,12 +126,12 @@ actual class KalugaDateFormatter private constructor(private val format: SimpleD get() = symbols.amPmStrings.toList()[1] set(value) { updateSymbols { it.amPmStrings = it.amPmStrings.toMutableList().apply { this[1] = value }.toTypedArray() } } - actual fun format(date: KalugaDate): String = format.format(date.calendar.time) + actual fun format(date: KalugaDate): String = format.format((date as DefaultKalugaDate).calendar.time) actual fun parse(string: String): KalugaDate? { return try { format.parse(string)?.let { date -> val calendar = format.calendar.clone() as Calendar - KalugaDate(calendar.apply { time = date }) + DefaultKalugaDate(calendar.apply { time = date }) } } catch (e: ParseException) { null diff --git a/base/src/jvmMain/kotlin/utils/TimeZone.kt b/base/src/jvmMain/kotlin/utils/TimeZone.kt index 595840a34..b67b64b47 100644 --- a/base/src/jvmMain/kotlin/utils/TimeZone.kt +++ b/base/src/jvmMain/kotlin/utils/TimeZone.kt @@ -42,7 +42,7 @@ actual class TimeZone internal constructor(internal val timeZone: java.util.Time actual val offsetFromGMTInMilliseconds = timeZone.rawOffset.toLong() actual val daylightSavingsOffsetInMilliseconds: Long = timeZone.dstSavings.toLong() actual fun offsetFromGMTAtDateInMilliseconds(date: KalugaDate): Long = timeZone.getOffset(date.millisecondSinceEpoch).toLong() - actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.inDaylightTime(date.calendar.time) + actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.inDaylightTime((date as DefaultKalugaDate).calendar.time) actual fun copy(): TimeZone = TimeZone(timeZone.clone() as java.util.TimeZone) override fun equals(other: Any?): Boolean { return (other as? TimeZone)?.let { timeZone == other.timeZone } ?: false From 27a6e0c07c10bbd76fea455c54c8b90771793acd Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Tue, 8 Mar 2022 15:40:51 +0100 Subject: [PATCH 24/65] Fix android and jvm implementation --- base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt | 2 +- base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt index 193a593d4..20eff691c 100644 --- a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt @@ -132,7 +132,7 @@ actual class KalugaDateFormatter private constructor(private val format: SimpleD DefaultKalugaDate( calendar.apply { time = date - timeZone = currentTimeZone + timeZone = currentTimeZone.timeZone } ) } diff --git a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt index bea938831..d5f8cdd4b 100644 --- a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt @@ -135,7 +135,7 @@ actual class KalugaDateFormatter private constructor(private val format: SimpleD DefaultKalugaDate( calendar.apply { time = date - timeZone = currentTimeZone + timeZone = currentTimeZone.timeZone } ) } From cdc789c95c5f74bce5338d281d97d9a2cd8a58ef Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Tue, 8 Mar 2022 17:41:42 +0100 Subject: [PATCH 25/65] Fix ios sourceset. --- base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt | 1 - base/src/iosMain/kotlin/text/KalugaDateFormatter.kt | 6 +++--- base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt | 1 - beacons/src/commonMain/kotlin/Beacons.kt | 3 ++- date-time-picker/src/commonMain/kotlin/DateTimePicker.kt | 6 +++--- .../src/iosMain/kotlin/DateTimePickerPresenter.kt | 3 ++- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt index 20eff691c..168a48c10 100644 --- a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt @@ -132,7 +132,6 @@ actual class KalugaDateFormatter private constructor(private val format: SimpleD DefaultKalugaDate( calendar.apply { time = date - timeZone = currentTimeZone.timeZone } ) } diff --git a/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt b/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt index 47ff6232b..2a3cbed62 100644 --- a/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt @@ -79,15 +79,15 @@ actual class KalugaDateFormatter private constructor(private val format: NSDateF // Due to a problem related to the commonizer we need to supply all the // default arguments expected from the method signature - private fun defaultDate(timeZone: TimeZone) = Date.now( + private fun defaultDate(timeZone: TimeZone) = (DefaultKalugaDate.now( offsetInMilliseconds = 0L, timeZone = timeZone, locale = Locale.defaultLocale - ).apply { + ) as DefaultKalugaDate).apply { // Cannot use .utc since it may not be available when this method is called // This is likely caused by https://youtrack.jetbrains.com/issue/KT-38181 // TODO When moving Date and Date formatter to separate modules, this should be updated to use .utc - val epoch = Date.epoch( + val epoch = DefaultKalugaDate.epoch( offsetInMilliseconds = 0L, timeZone = TimeZone.get("UTC")!!, locale = Locale.defaultLocale diff --git a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt index d5f8cdd4b..f3ed6a2dc 100644 --- a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt @@ -135,7 +135,6 @@ actual class KalugaDateFormatter private constructor(private val format: SimpleD DefaultKalugaDate( calendar.apply { time = date - timeZone = currentTimeZone.timeZone } ) } diff --git a/beacons/src/commonMain/kotlin/Beacons.kt b/beacons/src/commonMain/kotlin/Beacons.kt index 112156c85..4fce233f3 100644 --- a/beacons/src/commonMain/kotlin/Beacons.kt +++ b/beacons/src/commonMain/kotlin/Beacons.kt @@ -19,6 +19,7 @@ package com.splendo.kaluga.bluetooth.beacons import co.touchlab.stately.collections.IsoMutableMap import com.splendo.kaluga.base.AtomicReferenceDelegate +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.bluetooth.BluetoothService import com.splendo.kaluga.bluetooth.device.Device @@ -116,7 +117,7 @@ class Beacons( val data = serviceData[Eddystone.SERVICE_UUID] ?: return null val frame = Eddystone.unpack(data) ?: return null val rssi = device.map { it.rssi }.firstOrNull() ?: 0 - val lastSeen = device.map { it.updatedAt }.firstOrNull() ?: KalugaDate.now() + val lastSeen = device.map { it.updatedAt }.firstOrNull() ?: DefaultKalugaDate.now() return BeaconInfo(device.identifier, frame.uid, frame.txPower, rssi, lastSeen) } } diff --git a/date-time-picker/src/commonMain/kotlin/DateTimePicker.kt b/date-time-picker/src/commonMain/kotlin/DateTimePicker.kt index 3e6788081..c240b716e 100644 --- a/date-time-picker/src/commonMain/kotlin/DateTimePicker.kt +++ b/date-time-picker/src/commonMain/kotlin/DateTimePicker.kt @@ -21,8 +21,8 @@ package com.splendo.kaluga.datetimepicker import co.touchlab.stately.concurrency.Lock import co.touchlab.stately.concurrency.withLock import com.splendo.kaluga.architecture.lifecycle.LifecycleSubscribableMarker +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.KalugaDate -import com.splendo.kaluga.base.utils.KalugaDate.Companion.epoch import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.Locale.Companion.defaultLocale import kotlinx.coroutines.CoroutineScope @@ -106,7 +106,7 @@ abstract class BaseDateTimePickerPresenter(private val dateTimePicker: DateTimeP private var cancelButtonTitle: String = "" private var confirmButtonTitle: String = "" private var locale: Locale = defaultLocale - private var selectedDate: KalugaDate = epoch() + private var selectedDate: KalugaDate = DefaultKalugaDate.epoch() private var type: DateTimePicker.Type = DateTimePicker.Type.TimeType internal val lock = Lock() @@ -149,7 +149,7 @@ abstract class BaseDateTimePickerPresenter(private val dateTimePicker: DateTimeP this.cancelButtonTitle = "" this.confirmButtonTitle = "" this.locale = defaultLocale - this.selectedDate = epoch() + this.selectedDate = DefaultKalugaDate.epoch() this.type = DateTimePicker.Type.TimeType } diff --git a/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt b/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt index e77d4514d..fbf6bc376 100644 --- a/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt +++ b/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt @@ -20,6 +20,7 @@ package com.splendo.kaluga.datetimepicker import com.splendo.kaluga.base.IOSVersion import com.splendo.kaluga.base.utils.KalugaDate +import com.splendo.kaluga.base.utils.DefaultKalugaDate import kotlinx.cinterop.ObjCAction import kotlinx.coroutines.CoroutineScope import platform.CoreGraphics.CGFloat @@ -149,7 +150,7 @@ actual class DateTimePickerPresenter( @ObjCAction private fun onSelected() { - completion(KalugaDate.epoch((datePickerView.date.timeIntervalSince1970 * 1000.0).toLong(), datePicker.selectedDate.timeZone, datePicker.locale)) + completion(DefaultKalugaDate.epoch((datePickerView.date.timeIntervalSince1970 * 1000.0).toLong(), datePicker.selectedDate.timeZone, datePicker.locale)) dismissDateTimePicker(true) } } From 9524fcc8e3a7f684456db7bb9d8ab1d883fe28ff Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Tue, 8 Mar 2022 18:10:36 +0100 Subject: [PATCH 26/65] Update kaluga example. --- .../datetimepicker/DateTimePickerViewModel.kt | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt b/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt index c6593d0da..c880a2c60 100644 --- a/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt +++ b/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt @@ -5,6 +5,8 @@ import com.splendo.kaluga.architecture.viewmodel.BaseViewModel import com.splendo.kaluga.base.text.DateFormatStyle import com.splendo.kaluga.base.text.KalugaDateFormatter import com.splendo.kaluga.base.utils.Date +import com.splendo.kaluga.base.utils.DefaultKalugaDate +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.datetimepicker.DateTimePickerPresenter import com.splendo.kaluga.datetimepicker.buildDatePicker import com.splendo.kaluga.datetimepicker.buildTimePicker @@ -20,7 +22,7 @@ class DateTimePickerViewModel(val dateTimePickerPresenterBuilder: DateTimePicker } private val selectedDate = MutableStateFlow( - Date.now().apply { + DefaultKalugaDate.now().apply { second = 0 millisecond = 0 } @@ -29,7 +31,11 @@ class DateTimePickerViewModel(val dateTimePickerPresenterBuilder: DateTimePicker fun onSelectDatePressed() { coroutineScope.launch { - dateTimePickerPresenterBuilder.buildDatePicker(this, Date.epoch(), Date.now()) { + dateTimePickerPresenterBuilder.buildDatePicker( + this, + DefaultKalugaDate.epoch(), + DefaultKalugaDate.now() + ) { setSelectedDate(this@DateTimePickerViewModel.selectedDate.value) setCancelButtonTitle("cancel_selection".localized()) setConfirmButtonTitle("confirm_selection".localized()) From 6d90fbe9a0d029f56647bd81ab8e56cfd3bdc350 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Tue, 8 Mar 2022 18:26:46 +0100 Subject: [PATCH 27/65] ios Code lint and fix tests. --- base/src/commonTest/kotlin/text/DateFormatterTest.kt | 8 ++++---- base/src/iosMain/kotlin/text/KalugaDateFormatter.kt | 12 +++++++----- .../src/iosMain/kotlin/DateTimePickerPresenter.kt | 2 +- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/base/src/commonTest/kotlin/text/DateFormatterTest.kt b/base/src/commonTest/kotlin/text/DateFormatterTest.kt index 7229ed920..1266f45b9 100644 --- a/base/src/commonTest/kotlin/text/DateFormatterTest.kt +++ b/base/src/commonTest/kotlin/text/DateFormatterTest.kt @@ -113,11 +113,11 @@ class DateFormatterTest { @Test fun testParseDateWithDifferentTimezone() { - val utcFormatter = DateFormatter.patternFormat("yyyy.MM.dd G 'at' HH:mm:ss z", TimeZone.utc, Locale.enUsPosix) - val pstFormatter = DateFormatter.patternFormat("yyyy.MM.dd G 'at' HH:mm:ss z", PSTTimeZone, Locale.enUsPosix) + val utcFormatter = KalugaDateFormatter.patternFormat("yyyy.MM.dd G 'at' HH:mm:ss z", TimeZone.utc, Locale.enUsPosix) + val pstFormatter = KalugaDateFormatter.patternFormat("yyyy.MM.dd G 'at' HH:mm:ss z", PSTTimeZone, Locale.enUsPosix) - val epochInUtc = Date.epoch(timeZone = TimeZone.utc, locale = Locale.enUsPosix) - val epochInPst = Date.epoch(timeZone = PSTTimeZone, locale = Locale.enUsPosix) + val epochInUtc = DefaultKalugaDate.epoch(timeZone = TimeZone.utc, locale = Locale.enUsPosix) + val epochInPst = DefaultKalugaDate.epoch(timeZone = PSTTimeZone, locale = Locale.enUsPosix) assertEquals("1970.01.01 AD at 00:00:00 ${TimeZone.utc.identifier}", utcFormatter.format(epochInUtc)) assertEquals("1970.01.01 AD at 00:00:00 ${TimeZone.utc.identifier}", utcFormatter.format(epochInPst)) assertEquals("1969.12.31 AD at 16:00:00 PST", pstFormatter.format(epochInUtc)) diff --git a/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt b/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt index 2a3cbed62..9af5e9c80 100644 --- a/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt @@ -79,11 +79,13 @@ actual class KalugaDateFormatter private constructor(private val format: NSDateF // Due to a problem related to the commonizer we need to supply all the // default arguments expected from the method signature - private fun defaultDate(timeZone: TimeZone) = (DefaultKalugaDate.now( - offsetInMilliseconds = 0L, - timeZone = timeZone, - locale = Locale.defaultLocale - ) as DefaultKalugaDate).apply { + private fun defaultDate(timeZone: TimeZone) = ( + DefaultKalugaDate.now( + offsetInMilliseconds = 0L, + timeZone = timeZone, + locale = Locale.defaultLocale + ) as DefaultKalugaDate + ).apply { // Cannot use .utc since it may not be available when this method is called // This is likely caused by https://youtrack.jetbrains.com/issue/KT-38181 // TODO When moving Date and Date formatter to separate modules, this should be updated to use .utc diff --git a/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt b/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt index fbf6bc376..ee1f7b492 100644 --- a/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt +++ b/date-time-picker/src/iosMain/kotlin/DateTimePickerPresenter.kt @@ -19,8 +19,8 @@ Copyright 2020 Splendo Consulting B.V. The Netherlands package com.splendo.kaluga.datetimepicker import com.splendo.kaluga.base.IOSVersion -import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.DefaultKalugaDate +import com.splendo.kaluga.base.utils.KalugaDate import kotlinx.cinterop.ObjCAction import kotlinx.coroutines.CoroutineScope import platform.CoreGraphics.CGFloat From 3b0b6c8a0afff38b56ef41bcd22204545c880000 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Wed, 9 Mar 2022 09:19:39 +0100 Subject: [PATCH 28/65] Code lint. --- beacons/src/commonMain/kotlin/Beacons.kt | 1 - beacons/src/commonTest/kotlin/BeaconUpdateTest.kt | 4 ++-- .../kotlin/AndroidDateTimePickerPresenterTest.kt | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/beacons/src/commonMain/kotlin/Beacons.kt b/beacons/src/commonMain/kotlin/Beacons.kt index 4fce233f3..f69af5bfe 100644 --- a/beacons/src/commonMain/kotlin/Beacons.kt +++ b/beacons/src/commonMain/kotlin/Beacons.kt @@ -20,7 +20,6 @@ package com.splendo.kaluga.bluetooth.beacons import co.touchlab.stately.collections.IsoMutableMap import com.splendo.kaluga.base.AtomicReferenceDelegate import com.splendo.kaluga.base.utils.DefaultKalugaDate -import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.bluetooth.BluetoothService import com.splendo.kaluga.bluetooth.device.Device import com.splendo.kaluga.bluetooth.device.Identifier diff --git a/beacons/src/commonTest/kotlin/BeaconUpdateTest.kt b/beacons/src/commonTest/kotlin/BeaconUpdateTest.kt index 4babc734e..3a02cba95 100644 --- a/beacons/src/commonTest/kotlin/BeaconUpdateTest.kt +++ b/beacons/src/commonTest/kotlin/BeaconUpdateTest.kt @@ -17,7 +17,7 @@ package com.splendo.kaluga.bluetooth.beacons -import com.splendo.kaluga.base.utils.KalugaDate +import com.splendo.kaluga.base.utils.DefaultKalugaDate import kotlinx.coroutines.delay import kotlin.test.Test import kotlin.test.assertTrue @@ -38,7 +38,7 @@ class BeaconUpdateTest : BeaconFlowTest() { ) } - val lastSeen = KalugaDate.now() + val lastSeen = DefaultKalugaDate.now() action { delay(1_000) diff --git a/date-time-picker/src/androidLibAndroidTest/kotlin/AndroidDateTimePickerPresenterTest.kt b/date-time-picker/src/androidLibAndroidTest/kotlin/AndroidDateTimePickerPresenterTest.kt index 9cca473b3..853031aec 100644 --- a/date-time-picker/src/androidLibAndroidTest/kotlin/AndroidDateTimePickerPresenterTest.kt +++ b/date-time-picker/src/androidLibAndroidTest/kotlin/AndroidDateTimePickerPresenterTest.kt @@ -22,7 +22,7 @@ import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until -import com.splendo.kaluga.base.utils.KalugaDate.Companion.epoch +import com.splendo.kaluga.base.utils.DefaultKalugaDate.Companion.epoch import com.splendo.kaluga.test.DateTimePickerPresenterTests import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers From 79eaa036aafdb7534de66afb18ccd4489f19da23 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Wed, 9 Mar 2022 09:54:06 +0100 Subject: [PATCH 29/65] Fixed jvm set --- base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt | 1 + base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt | 1 + 2 files changed, 2 insertions(+) diff --git a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt index 168a48c10..193a593d4 100644 --- a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt @@ -132,6 +132,7 @@ actual class KalugaDateFormatter private constructor(private val format: SimpleD DefaultKalugaDate( calendar.apply { time = date + timeZone = currentTimeZone } ) } diff --git a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt index f3ed6a2dc..bea938831 100644 --- a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt @@ -135,6 +135,7 @@ actual class KalugaDateFormatter private constructor(private val format: SimpleD DefaultKalugaDate( calendar.apply { time = date + timeZone = currentTimeZone } ) } From a8adf49813843bb49e4e64d27d8f73b1cbd3a40d Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Wed, 9 Mar 2022 11:26:47 +0100 Subject: [PATCH 30/65] Fix formatter --- base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt | 2 +- base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt index 193a593d4..20eff691c 100644 --- a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt @@ -132,7 +132,7 @@ actual class KalugaDateFormatter private constructor(private val format: SimpleD DefaultKalugaDate( calendar.apply { time = date - timeZone = currentTimeZone + timeZone = currentTimeZone.timeZone } ) } diff --git a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt index bea938831..d5f8cdd4b 100644 --- a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt @@ -135,7 +135,7 @@ actual class KalugaDateFormatter private constructor(private val format: SimpleD DefaultKalugaDate( calendar.apply { time = date - timeZone = currentTimeZone + timeZone = currentTimeZone.timeZone } ) } From 21b1589d93dfb56959b2a7df833e696e2b1dba27 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Sun, 13 Mar 2022 15:10:43 +0100 Subject: [PATCH 31/65] Update references. --- .../com/splendo/kaluga/architecture/compose/RouteTests.kt | 3 ++- .../kotlin/navigation/AndroidNavigationBundleTest.kt | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt b/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt index 5fe612b43..aa6989b0b 100644 --- a/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt +++ b/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt @@ -27,6 +27,7 @@ import com.splendo.kaluga.architecture.navigation.toBundle import com.splendo.kaluga.base.text.KalugaDateFormatter import com.splendo.kaluga.base.text.iso8601Pattern import com.splendo.kaluga.base.utils.KalugaDate +import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.TimeZone import com.splendo.kaluga.base.utils.utc import kotlinx.serialization.Serializable @@ -73,7 +74,7 @@ class RouteTests { @Test fun testRoute() { - val time = KalugaDate.epoch(timeZone = TimeZone.utc) + val time = DefaultKalugaDate.epoch(timeZone = TimeZone.utc) val bundle = MockSpec.toBundle { row -> when (row) { is MockSpecRow.StringSpecRow -> row.convertValue("string") diff --git a/architecture/src/androidLibAndroidTest/kotlin/navigation/AndroidNavigationBundleTest.kt b/architecture/src/androidLibAndroidTest/kotlin/navigation/AndroidNavigationBundleTest.kt index 88d3f0023..c66642248 100644 --- a/architecture/src/androidLibAndroidTest/kotlin/navigation/AndroidNavigationBundleTest.kt +++ b/architecture/src/androidLibAndroidTest/kotlin/navigation/AndroidNavigationBundleTest.kt @@ -18,7 +18,7 @@ package com.splendo.kaluga.architecture.navigation import android.os.Bundle -import com.splendo.kaluga.base.utils.KalugaDate +import com.splendo.kaluga.base.utils.DefaultKalugaDate import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -38,10 +38,10 @@ class AndroidNavigationBundleTest { } val optionalString: String? = "Some String" val optionalFloat: Float? = null - val dateValue = KalugaDate.epoch(offsetInMilliseconds = 1606204800000) + val dateValue = DefaultKalugaDate.epoch(offsetInMilliseconds = 1606204800000) val dateArray = listOf( - KalugaDate.epoch(offsetInMilliseconds = 1606204800001), - KalugaDate.epoch(offsetInMilliseconds = 1606204800002) + DefaultKalugaDate.epoch(offsetInMilliseconds = 1606204800001), + DefaultKalugaDate.epoch(offsetInMilliseconds = 1606204800002) ) val mockSpec = MockSpec() From 6b2069f20918456127ccf7a0802d1290392a28c7 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Sun, 13 Mar 2022 16:46:02 +0100 Subject: [PATCH 32/65] Code lint. --- .../com/splendo/kaluga/architecture/compose/RouteTests.kt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt b/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt index aa6989b0b..d378f530d 100644 --- a/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt +++ b/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt @@ -17,7 +17,6 @@ package com.splendo.kaluga.architecture.compose -import com.splendo.kaluga.architecture.compose.navigation.route import com.splendo.kaluga.architecture.navigation.NavigationAction import com.splendo.kaluga.architecture.navigation.NavigationBundle import com.splendo.kaluga.architecture.navigation.NavigationBundleSpec @@ -26,8 +25,8 @@ import com.splendo.kaluga.architecture.navigation.NavigationBundleSpecType import com.splendo.kaluga.architecture.navigation.toBundle import com.splendo.kaluga.base.text.KalugaDateFormatter import com.splendo.kaluga.base.text.iso8601Pattern -import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.DefaultKalugaDate +import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.TimeZone import com.splendo.kaluga.base.utils.utc import kotlinx.serialization.Serializable From 62f59accee369593feda0f627c76cef9310b2dd5 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Mon, 14 Mar 2022 08:53:18 +0100 Subject: [PATCH 33/65] Lint --- .../com/splendo/kaluga/architecture/compose/RouteTests.kt | 1 + .../kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt | 2 -- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt b/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt index d378f530d..04ea0fcd4 100644 --- a/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt +++ b/architecture-compose/src/androidLibUnitTest/kotlin/com/splendo/kaluga/architecture/compose/RouteTests.kt @@ -17,6 +17,7 @@ package com.splendo.kaluga.architecture.compose +import com.splendo.kaluga.architecture.compose.navigation.route import com.splendo.kaluga.architecture.navigation.NavigationAction import com.splendo.kaluga.architecture.navigation.NavigationBundle import com.splendo.kaluga.architecture.navigation.NavigationBundleSpec diff --git a/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt b/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt index c880a2c60..fa80953b5 100644 --- a/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt +++ b/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt @@ -1,6 +1,5 @@ package com.splendo.kaluga.example.shared.viewmodel.datetimepicker -import com.splendo.kaluga.architecture.observable.toUninitializedObservable import com.splendo.kaluga.architecture.viewmodel.BaseViewModel import com.splendo.kaluga.base.text.DateFormatStyle import com.splendo.kaluga.base.text.KalugaDateFormatter @@ -12,7 +11,6 @@ import com.splendo.kaluga.datetimepicker.buildDatePicker import com.splendo.kaluga.datetimepicker.buildTimePicker import com.splendo.kaluga.resources.localized import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch class DateTimePickerViewModel(val dateTimePickerPresenterBuilder: DateTimePickerPresenter.Builder) : BaseViewModel() { From 5e670c2ff9125776f24d199f356077755518985e Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Mon, 14 Mar 2022 11:17:37 +0100 Subject: [PATCH 34/65] Lint --- .../kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt | 2 -- 1 file changed, 2 deletions(-) diff --git a/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt b/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt index fa80953b5..5f11597a8 100644 --- a/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt +++ b/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt @@ -3,9 +3,7 @@ package com.splendo.kaluga.example.shared.viewmodel.datetimepicker import com.splendo.kaluga.architecture.viewmodel.BaseViewModel import com.splendo.kaluga.base.text.DateFormatStyle import com.splendo.kaluga.base.text.KalugaDateFormatter -import com.splendo.kaluga.base.utils.Date import com.splendo.kaluga.base.utils.DefaultKalugaDate -import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.datetimepicker.DateTimePickerPresenter import com.splendo.kaluga.datetimepicker.buildDatePicker import com.splendo.kaluga.datetimepicker.buildTimePicker From 636ffcdd7aa90624e114326f7605c008b10ce974 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Mon, 14 Mar 2022 12:07:59 +0100 Subject: [PATCH 35/65] Use asserts without block call, replace for-each with repeat convenience method. --- .../mocks/keyboard/MockFocusHandlerTest.kt | 28 +++++++------- .../mocks/keyboard/MockKeyboardManagerTest.kt | 38 +++++++++---------- 2 files changed, 33 insertions(+), 33 deletions(-) diff --git a/test-utils/src/commonTest/kotlin/mocks/keyboard/MockFocusHandlerTest.kt b/test-utils/src/commonTest/kotlin/mocks/keyboard/MockFocusHandlerTest.kt index 2b2e65461..6c0d5e084 100644 --- a/test-utils/src/commonTest/kotlin/mocks/keyboard/MockFocusHandlerTest.kt +++ b/test-utils/src/commonTest/kotlin/mocks/keyboard/MockFocusHandlerTest.kt @@ -15,7 +15,7 @@ */ -package mocks.keyboard +package com.splendo.kaluga.test.keyboard import com.splendo.kaluga.base.runBlocking import com.splendo.kaluga.test.mock.focus.MockFocusHandler @@ -27,35 +27,35 @@ class MockFocusHandlerTest { @Test fun test_initial_state() = testFocusHandler { - assertFalse { it.isFocused } + assertFalse(it.isFocused) } @Test fun test_give_focus() = testFocusHandler { - assertFalse { it.isFocused } + assertFalse(it.isFocused) it.simulateGiveFocus() - assertTrue { it.isFocused } + assertTrue(it.isFocused) } @Test fun test_remove_focus() = testFocusHandler { - assertFalse { it.isFocused } + assertFalse(it.isFocused) it.simulateGiveFocus() - assertTrue { it.isFocused } + assertTrue(it.isFocused) it.simulateRemoveFocus() - assertFalse { it.isFocused } + assertFalse(it.isFocused) } @Test - fun test_give_remove_multiple_times() = testFocusHandler { - assertFalse { it.isFocused } - for (i in 0..10) { - it.simulateGiveFocus() - assertTrue { it.isFocused } + fun test_give_remove_multiple_times() = testFocusHandler { focusHandler -> + assertFalse(focusHandler.isFocused) + repeat(10) { + focusHandler.simulateGiveFocus() + assertTrue(focusHandler.isFocused) - it.simulateRemoveFocus() - assertFalse { it.isFocused } + focusHandler.simulateRemoveFocus() + assertFalse(focusHandler.isFocused) } } diff --git a/test-utils/src/commonTest/kotlin/mocks/keyboard/MockKeyboardManagerTest.kt b/test-utils/src/commonTest/kotlin/mocks/keyboard/MockKeyboardManagerTest.kt index 75b164601..1cd4f4f8a 100644 --- a/test-utils/src/commonTest/kotlin/mocks/keyboard/MockKeyboardManagerTest.kt +++ b/test-utils/src/commonTest/kotlin/mocks/keyboard/MockKeyboardManagerTest.kt @@ -15,7 +15,7 @@ */ -package mocks.keyboard +package com.splendo.kaluga.test.keyboard import com.splendo.kaluga.base.runBlocking import com.splendo.kaluga.test.mock.focus.MockFocusHandler @@ -30,40 +30,40 @@ class MockKeyboardManagerTest { @Test fun test_initial_manager_state() = testKeyboardManager { - assertFalse { it.isShown } + assertFalse(it.isShown) } @Test fun test_show_keyboard() = testKeyboardManager { - assertFalse { it.isShown } + assertFalse(it.isShown) it.show(focusHandler) - assertTrue { focusHandler.isFocused } - assertTrue { it.isShown } + assertTrue(focusHandler.isFocused) + assertTrue(it.isShown) } @Test fun test_hide_keyboard() = testKeyboardManager { - assertFalse { it.isShown } + assertFalse(it.isShown) it.show(focusHandler) - assertTrue { focusHandler.isFocused } - assertTrue { it.isShown } + assertTrue(focusHandler.isFocused) + assertTrue(it.isShown) it.hide() - assertFalse { focusHandler.isFocused } - assertFalse { it.isShown } + assertFalse(focusHandler.isFocused) + assertFalse(it.isShown) } @Test - fun test_show_hide_keyboard_multiple_times() = testKeyboardManager { - assertFalse { it.isShown } - for (i in 0..10) { - it.show(focusHandler) - assertTrue { focusHandler.isFocused } - assertTrue { it.isShown } + fun test_show_hide_keyboard_multiple_times() = testKeyboardManager { keyboardManager -> + assertFalse(keyboardManager.isShown) + repeat(10) { + keyboardManager.show(focusHandler) + assertTrue(focusHandler.isFocused) + assertTrue(keyboardManager.isShown) - it.hide() - assertFalse { focusHandler.isFocused } - assertFalse { it.isShown } + keyboardManager.hide() + assertFalse(focusHandler.isFocused) + assertFalse(keyboardManager.isShown) } } From 5e5fc742854e36e0cf5ee490c1f5225b4883eb07 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Mon, 14 Mar 2022 12:30:32 +0100 Subject: [PATCH 36/65] Resolve build error. --- .../kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt b/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt index 5f11597a8..8d3eaed53 100644 --- a/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt +++ b/example/shared/src/commonMain/kotlin/viewmodel/datetimepicker/DateTimePickerViewModel.kt @@ -1,5 +1,6 @@ package com.splendo.kaluga.example.shared.viewmodel.datetimepicker +import com.splendo.kaluga.architecture.observable.toUninitializedObservable import com.splendo.kaluga.architecture.viewmodel.BaseViewModel import com.splendo.kaluga.base.text.DateFormatStyle import com.splendo.kaluga.base.text.KalugaDateFormatter @@ -9,6 +10,7 @@ import com.splendo.kaluga.datetimepicker.buildDatePicker import com.splendo.kaluga.datetimepicker.buildTimePicker import com.splendo.kaluga.resources.localized import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch class DateTimePickerViewModel(val dateTimePickerPresenterBuilder: DateTimePickerPresenter.Builder) : BaseViewModel() { From f71ed73288f8d5893a7027f90f44ed06bbc6daba Mon Sep 17 00:00:00 2001 From: Carmelo Gallo Date: Wed, 23 Mar 2022 18:08:58 +0100 Subject: [PATCH 37/65] Bumped version to 0.4.0 --- gradle/ext.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/ext.gradle b/gradle/ext.gradle index 06e77a09e..9c902cecf 100644 --- a/gradle/ext.gradle +++ b/gradle/ext.gradle @@ -30,7 +30,7 @@ gradle.ext { serialization_version = '1.3.2' napier_version = '2.4.0' android_ble_scanner_version = '1.5.0' - library_version_base = '0.3.0' + library_version_base = '0.4.0' library_version = libraryVersionLocalProperties ?: "$library_version_base${System.properties.kaluga_branch_postfix}" android_min_sdk_version = 21 android_compile_sdk_version = 31 From bbfa6199ef31c491a151b1cd4734cdff3a1edc85 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 24 Mar 2022 14:17:22 +0100 Subject: [PATCH 38/65] Raised CBCentralManagerScanOptionAllowDuplicatesKey for iOS centralManager.scanForPeripheralsWithServices to make it behave like Android --- bluetooth/src/iosMain/kotlin/scanner/Scanner.kt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt b/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt index bb29918ad..e2472d454 100644 --- a/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt +++ b/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt @@ -38,6 +38,7 @@ import kotlinx.coroutines.flow.first import platform.CoreBluetooth.CBCentralManager import platform.CoreBluetooth.CBCentralManagerDelegateProtocol import platform.CoreBluetooth.CBCentralManagerOptionShowPowerAlertKey +import platform.CoreBluetooth.CBCentralManagerScanOptionAllowDuplicatesKey import platform.CoreBluetooth.CBCentralManagerStatePoweredOn import platform.CoreBluetooth.CBPeripheral import platform.Foundation.NSError @@ -141,7 +142,10 @@ actual class Scanner internal constructor( discoveringDelegates.add(delegate) centralManager.delegate = delegate awaitPoweredOn.await() - centralManager.scanForPeripheralsWithServices(filter?.let { listOf(filter) }, null) + centralManager.scanForPeripheralsWithServices( + filter?.let { listOf(filter) }, + mapOf(CBCentralManagerScanOptionAllowDuplicatesKey to true) + ) } override suspend fun scanForDevices(filter: Set) = From 2473b2cc31c07a92b441363eb3feb995d8898204 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 25 Mar 2022 12:16:05 +0100 Subject: [PATCH 39/65] Added scan settings as builder param for iOS actual Scanner impl --- bluetooth/src/iosMain/kotlin/scanner/Scanner.kt | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt b/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt index e2472d454..5489c02c3 100644 --- a/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt +++ b/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt @@ -38,7 +38,6 @@ import kotlinx.coroutines.flow.first import platform.CoreBluetooth.CBCentralManager import platform.CoreBluetooth.CBCentralManagerDelegateProtocol import platform.CoreBluetooth.CBCentralManagerOptionShowPowerAlertKey -import platform.CoreBluetooth.CBCentralManagerScanOptionAllowDuplicatesKey import platform.CoreBluetooth.CBCentralManagerStatePoweredOn import platform.CoreBluetooth.CBPeripheral import platform.Foundation.NSError @@ -49,12 +48,13 @@ import platform.darwin.dispatch_get_main_queue actual class Scanner internal constructor( permissions: Permissions, private val connectionSettings: ConnectionSettings, + private val scanSettings: Map?, autoRequestPermission: Boolean, autoEnableSensors: Boolean, stateRepo: ScanningStateFlowRepo, ) : BaseScanner(permissions, connectionSettings, autoRequestPermission, autoEnableSensors, stateRepo) { - class Builder : BaseScanner.Builder { + class Builder(private val scanSettings: Map? = defaultScanSettings) : BaseScanner.Builder { override fun create( permissions: Permissions, @@ -63,12 +63,13 @@ actual class Scanner internal constructor( autoEnableSensors: Boolean, scanningStateRepo: ScanningStateFlowRepo, ): BaseScanner { - return Scanner(permissions, connectionSettings, autoRequestPermission, autoEnableSensors, scanningStateRepo) + return Scanner(permissions, connectionSettings, scanSettings, autoRequestPermission, autoEnableSensors, scanningStateRepo,) } } companion object { private const val TAG = "IOS Bluetooth Scanner" + private val defaultScanSettings: Map? = null } private class EnabledCBCentralManagerDelegate(private val isCheckEnabledCompleted: CompletableDeferred) : NSObject(), CBCentralManagerDelegateProtocol { @@ -142,10 +143,7 @@ actual class Scanner internal constructor( discoveringDelegates.add(delegate) centralManager.delegate = delegate awaitPoweredOn.await() - centralManager.scanForPeripheralsWithServices( - filter?.let { listOf(filter) }, - mapOf(CBCentralManagerScanOptionAllowDuplicatesKey to true) - ) + centralManager.scanForPeripheralsWithServices(filter?.let { listOf(filter) }, scanSettings) } override suspend fun scanForDevices(filter: Set) = From 17c4ffc6254bb3e0d7ca661dbcce2cf4dc4b3c06 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 25 Mar 2022 12:17:54 +0100 Subject: [PATCH 40/65] Updated deprecated default bluetoothAdapter value for Android actual Scanner builder impl --- bluetooth/src/androidLibMain/kotlin/scanner/Scanner.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/bluetooth/src/androidLibMain/kotlin/scanner/Scanner.kt b/bluetooth/src/androidLibMain/kotlin/scanner/Scanner.kt index 67afdebda..b82e6e970 100644 --- a/bluetooth/src/androidLibMain/kotlin/scanner/Scanner.kt +++ b/bluetooth/src/androidLibMain/kotlin/scanner/Scanner.kt @@ -18,6 +18,7 @@ package com.splendo.kaluga.bluetooth.scanner import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothManager import android.content.Context import android.os.ParcelUuid import co.touchlab.stately.concurrency.AtomicReference @@ -62,7 +63,8 @@ actual class Scanner internal constructor( class Builder( private val bluetoothScanner: BluetoothLeScannerCompat = BluetoothLeScannerCompat.getScanner(), - private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter(), + private val bluetoothAdapter: BluetoothAdapter? = + (ApplicationHolder.applicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter, private val scanSettings: ScanSettings = defaultScanSettings, private val applicationContext: Context = ApplicationHolder.applicationContext, ) : BaseScanner.Builder { From a13a346548b1b3f08b0cb843c9fc9916c4dd6569 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Sat, 26 Mar 2022 21:05:27 +0100 Subject: [PATCH 41/65] Remove property initialization from method. --- logging/src/commonMain/kotlin/Logger.kt | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/logging/src/commonMain/kotlin/Logger.kt b/logging/src/commonMain/kotlin/Logger.kt index 19a2bc195..f3fbf2382 100644 --- a/logging/src/commonMain/kotlin/Logger.kt +++ b/logging/src/commonMain/kotlin/Logger.kt @@ -38,14 +38,17 @@ open class TransformLogger( ) : Logger { override fun log(level: LogLevel, tag: String?, throwable: Throwable?, message: (() -> String)?) { - + val logLevel = transformLogLevel?.invoke(level) ?: level + val logTag = transformTag?.invoke(tag) ?: tag + val logThrowable = transformThrowable?.invoke(throwable) ?: throwable + val logMessage = transformMessage?.invoke(message?.invoke())?.let { { it } } ?: message logger.log( - transformLogLevel?.invoke(level) ?: level, - transformTag?.invoke(tag) ?: tag, - transformThrowable?.invoke(throwable) ?: throwable, + logLevel, + logTag, + logThrowable, // already resolve the lazy message if it needs transformation (else we cannot transform it) // after transform wrap it in a "lazy" closure again {{🤗}} - transformMessage?.invoke(message?.invoke())?.let { { it } } ?: message + logMessage ) } } From aacb56d6d309c0b6f03ca46324614d7b4d0555a7 Mon Sep 17 00:00:00 2001 From: Carmelo Gallo Date: Mon, 28 Mar 2022 17:14:05 +0200 Subject: [PATCH 42/65] Updated publishing flow guideline --- DEVELOP.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/DEVELOP.md b/DEVELOP.md index 13ffb0501..46fb2c4e9 100644 --- a/DEVELOP.md +++ b/DEVELOP.md @@ -76,6 +76,18 @@ if this property is not set the version string is a combination of the version n For example if the version in `ext.gradle` is `1.1` and `feature/123_fix_bug` is the current branch the resulting version will be `1.1-feature-123_fix_bug-SNAPSHOT`. +#### Local Testing + +Before doing any publishing, make sure that changes are working with the one available in [Nexus Repository Manager](`oss.sonatype.org`). Test both on Android and iOS example app just adding the following code inside the `local.properties` file: +``` +kaluga.exampleAsRoot=true +kaluga.exampleMavenRepo=https://oss.sonatype.org/service/local/repositories/comsplendo-REPO_NUMBER/content/ +kaluga.libraryVersion=LIBRARY_VERSION +``` +Where +`REPO_NUMBER` is the last one created after merging to master +`LIBRARY_VERSION` is the one that we want to publish + #### Publishing locally 1. Publish to local maven: From f8dd881894edaae59a818c1479eaecb24af1a5ff Mon Sep 17 00:00:00 2001 From: Alex Date: Tue, 29 Mar 2022 14:06:04 +0200 Subject: [PATCH 43/65] Added builder for iOS scanner scanOptions --- .../src/iosMain/kotlin/scanner/Scanner.kt | 36 ++++++++++++++++--- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt b/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt index 5489c02c3..52eb13ec7 100644 --- a/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt +++ b/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt @@ -38,6 +38,8 @@ import kotlinx.coroutines.flow.first import platform.CoreBluetooth.CBCentralManager import platform.CoreBluetooth.CBCentralManagerDelegateProtocol import platform.CoreBluetooth.CBCentralManagerOptionShowPowerAlertKey +import platform.CoreBluetooth.CBCentralManagerScanOptionAllowDuplicatesKey +import platform.CoreBluetooth.CBCentralManagerScanOptionSolicitedServiceUUIDsKey import platform.CoreBluetooth.CBCentralManagerStatePoweredOn import platform.CoreBluetooth.CBPeripheral import platform.Foundation.NSError @@ -48,13 +50,13 @@ import platform.darwin.dispatch_get_main_queue actual class Scanner internal constructor( permissions: Permissions, private val connectionSettings: ConnectionSettings, - private val scanSettings: Map?, + private val scanOptions: Map, autoRequestPermission: Boolean, autoEnableSensors: Boolean, stateRepo: ScanningStateFlowRepo, ) : BaseScanner(permissions, connectionSettings, autoRequestPermission, autoEnableSensors, stateRepo) { - class Builder(private val scanSettings: Map? = defaultScanSettings) : BaseScanner.Builder { + class Builder(private val scanOptions: Map = defaultScanOptions) : BaseScanner.Builder { override fun create( permissions: Permissions, @@ -63,13 +65,13 @@ actual class Scanner internal constructor( autoEnableSensors: Boolean, scanningStateRepo: ScanningStateFlowRepo, ): BaseScanner { - return Scanner(permissions, connectionSettings, scanSettings, autoRequestPermission, autoEnableSensors, scanningStateRepo,) + return Scanner(permissions, connectionSettings, scanOptions, autoRequestPermission, autoEnableSensors, scanningStateRepo,) } } companion object { private const val TAG = "IOS Bluetooth Scanner" - private val defaultScanSettings: Map? = null + private val defaultScanOptions = ScanOptions.Builder().build() } private class EnabledCBCentralManagerDelegate(private val isCheckEnabledCompleted: CompletableDeferred) : NSObject(), CBCentralManagerDelegateProtocol { @@ -143,7 +145,7 @@ actual class Scanner internal constructor( discoveringDelegates.add(delegate) centralManager.delegate = delegate awaitPoweredOn.await() - centralManager.scanForPeripheralsWithServices(filter?.let { listOf(filter) }, scanSettings) + centralManager.scanForPeripheralsWithServices(filter?.let { listOf(filter) }, scanOptions) } override suspend fun scanForDevices(filter: Set) = @@ -195,4 +197,28 @@ actual class Scanner internal constructor( ) } } + + class ScanOptions { + class Builder( + // https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerscanoptionallowduplicateskey + private var allowDuplicateKeys: Boolean = true, + // https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerscanoptionsolicitedserviceuuidskey + private var solicitedServiceUUIDsKey: List? = null, + ) { + fun allowDuplicateKeys(allow: Boolean) = + apply { allowDuplicateKeys = allow } + + fun solicitedServiceUUIDsKey(keys: List) = + apply { solicitedServiceUUIDsKey = keys } + + fun build(): Map { + val result: MutableMap = + mutableMapOf(CBCentralManagerScanOptionAllowDuplicatesKey to allowDuplicateKeys) + solicitedServiceUUIDsKey?.let { + result[CBCentralManagerScanOptionSolicitedServiceUUIDsKey] = it + } + return result.toMap() + } + } + } } From 14e3aa28b6a8b456331ca83a6bb5be35635f3eb1 Mon Sep 17 00:00:00 2001 From: Alex Date: Tue, 29 Mar 2022 14:13:53 +0200 Subject: [PATCH 44/65] Fixed error with raw type passing instead of wrapper class. --- .../src/iosMain/kotlin/scanner/Scanner.kt | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt b/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt index 52eb13ec7..011cb4115 100644 --- a/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt +++ b/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt @@ -50,13 +50,13 @@ import platform.darwin.dispatch_get_main_queue actual class Scanner internal constructor( permissions: Permissions, private val connectionSettings: ConnectionSettings, - private val scanOptions: Map, + private val scanSettings: ScanSettings, autoRequestPermission: Boolean, autoEnableSensors: Boolean, stateRepo: ScanningStateFlowRepo, ) : BaseScanner(permissions, connectionSettings, autoRequestPermission, autoEnableSensors, stateRepo) { - class Builder(private val scanOptions: Map = defaultScanOptions) : BaseScanner.Builder { + class Builder(private val scanSettings: ScanSettings = defaultScanOptions) : BaseScanner.Builder { override fun create( permissions: Permissions, @@ -65,13 +65,13 @@ actual class Scanner internal constructor( autoEnableSensors: Boolean, scanningStateRepo: ScanningStateFlowRepo, ): BaseScanner { - return Scanner(permissions, connectionSettings, scanOptions, autoRequestPermission, autoEnableSensors, scanningStateRepo,) + return Scanner(permissions, connectionSettings, scanSettings, autoRequestPermission, autoEnableSensors, scanningStateRepo,) } } companion object { private const val TAG = "IOS Bluetooth Scanner" - private val defaultScanOptions = ScanOptions.Builder().build() + private val defaultScanOptions = ScanSettings.Builder().build() } private class EnabledCBCentralManagerDelegate(private val isCheckEnabledCompleted: CompletableDeferred) : NSObject(), CBCentralManagerDelegateProtocol { @@ -145,7 +145,10 @@ actual class Scanner internal constructor( discoveringDelegates.add(delegate) centralManager.delegate = delegate awaitPoweredOn.await() - centralManager.scanForPeripheralsWithServices(filter?.let { listOf(filter) }, scanOptions) + centralManager.scanForPeripheralsWithServices( + filter?.let { listOf(filter) }, + scanSettings.scanOptions + ) } override suspend fun scanForDevices(filter: Set) = @@ -198,12 +201,12 @@ actual class Scanner internal constructor( } } - class ScanOptions { - class Builder( + class ScanSettings private constructor(val scanOptions: Map) { + data class Builder( // https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerscanoptionallowduplicateskey - private var allowDuplicateKeys: Boolean = true, + var allowDuplicateKeys: Boolean = true, // https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerscanoptionsolicitedserviceuuidskey - private var solicitedServiceUUIDsKey: List? = null, + var solicitedServiceUUIDsKey: List? = null, ) { fun allowDuplicateKeys(allow: Boolean) = apply { allowDuplicateKeys = allow } @@ -211,13 +214,13 @@ actual class Scanner internal constructor( fun solicitedServiceUUIDsKey(keys: List) = apply { solicitedServiceUUIDsKey = keys } - fun build(): Map { + fun build(): ScanSettings { val result: MutableMap = mutableMapOf(CBCentralManagerScanOptionAllowDuplicatesKey to allowDuplicateKeys) solicitedServiceUUIDsKey?.let { result[CBCentralManagerScanOptionSolicitedServiceUUIDsKey] = it } - return result.toMap() + return ScanSettings(result.toMap()) } } } From 121e1c686efe91bc3d5f90cbac8922c5cc639a80 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 30 Mar 2022 10:44:34 +0200 Subject: [PATCH 45/65] Made Scanner Android builder use default applicationContext from constructor itself to request bluetoothAdapter. Also removed default values from Scanner private constructor as builder also does the same. --- .../src/androidLibMain/kotlin/scanner/Scanner.kt | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/bluetooth/src/androidLibMain/kotlin/scanner/Scanner.kt b/bluetooth/src/androidLibMain/kotlin/scanner/Scanner.kt index b82e6e970..dcc67baf5 100644 --- a/bluetooth/src/androidLibMain/kotlin/scanner/Scanner.kt +++ b/bluetooth/src/androidLibMain/kotlin/scanner/Scanner.kt @@ -50,10 +50,10 @@ import no.nordicsemi.android.support.v18.scanner.ScanResult import no.nordicsemi.android.support.v18.scanner.ScanSettings actual class Scanner internal constructor( - private val bluetoothScanner: BluetoothLeScannerCompat = BluetoothLeScannerCompat.getScanner(), - private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter(), - private val scanSettings: ScanSettings = defaultScanSettings, - private val applicationContext: Context = ApplicationHolder.applicationContext, + private val applicationContext: Context, + private val bluetoothScanner: BluetoothLeScannerCompat, + private val bluetoothAdapter: BluetoothAdapter?, + private val scanSettings: ScanSettings, permissions: Permissions, connectionSettings: ConnectionSettings, autoRequestPermission: Boolean, @@ -62,11 +62,10 @@ actual class Scanner internal constructor( ) : BaseScanner(permissions, connectionSettings, autoRequestPermission, autoEnableSensors, stateRepo) { class Builder( + private val applicationContext: Context = ApplicationHolder.applicationContext, private val bluetoothScanner: BluetoothLeScannerCompat = BluetoothLeScannerCompat.getScanner(), - private val bluetoothAdapter: BluetoothAdapter? = - (ApplicationHolder.applicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter, + private val bluetoothAdapter: BluetoothAdapter? = (applicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter, private val scanSettings: ScanSettings = defaultScanSettings, - private val applicationContext: Context = ApplicationHolder.applicationContext, ) : BaseScanner.Builder { override fun create( @@ -76,7 +75,7 @@ actual class Scanner internal constructor( autoEnableSensors: Boolean, scanningStateRepo: StateRepo>, ): BaseScanner { - return Scanner(bluetoothScanner, bluetoothAdapter, scanSettings, applicationContext, permissions, connectionSettings, autoRequestPermission, autoEnableSensors, scanningStateRepo) + return Scanner(applicationContext, bluetoothScanner, bluetoothAdapter, scanSettings, permissions, connectionSettings, autoRequestPermission, autoEnableSensors, scanningStateRepo) } } From 427961e70bb4218ccbe31283c2997f2de3bd4d80 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Wed, 30 Mar 2022 12:27:37 +0200 Subject: [PATCH 46/65] Update deprecated State to be a abstract class. --- base/src/commonMain/kotlin/state/KalugaState.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/base/src/commonMain/kotlin/state/KalugaState.kt b/base/src/commonMain/kotlin/state/KalugaState.kt index 6f45d8b64..7f7645c9f 100644 --- a/base/src/commonMain/kotlin/state/KalugaState.kt +++ b/base/src/commonMain/kotlin/state/KalugaState.kt @@ -75,7 +75,7 @@ interface KalugaState { } @Deprecated("Due to name clashes with platform classes and API changes this class has been renamed and changed to an interface. It will be removed in a future release.", ReplaceWith("KalugaState")) -interface State : KalugaState +abstract class State : KalugaState interface HandleBeforeCreating { /** From 99ad3646d35141038301616757893163b5f7a55f Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Wed, 30 Mar 2022 14:19:30 +0200 Subject: [PATCH 47/65] Add typealias `KalugaDateHolder` and `date: KalugaDateHolder` to `KalugaDate` interface. Remove casting to DefaultKalugaDate. --- .../kotlin/text/KalugaDateFormatter.kt | 2 +- .../androidLibMain/kotlin/utils/KalugaDate.kt | 7 +++- .../androidLibMain/kotlin/utils/TimeZone.kt | 2 +- .../src/commonMain/kotlin/utils/KalugaDate.kt | 4 ++ .../kotlin/text/KalugaDateFormatter.kt | 37 +++++++++---------- base/src/iosMain/kotlin/utils/KalugaDate.kt | 6 ++- base/src/iosMain/kotlin/utils/TimeZone.kt | 4 +- .../jsMain/kotlin/text/KalugaDateFormatter.kt | 3 +- base/src/jsMain/kotlin/utils/KalugaDate.kt | 4 +- .../kotlin/text/KalugaDateFormatter.kt | 2 +- base/src/jvmMain/kotlin/utils/KalugaDate.kt | 6 ++- base/src/jvmMain/kotlin/utils/TimeZone.kt | 2 +- 12 files changed, 47 insertions(+), 32 deletions(-) diff --git a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt index 20eff691c..9aa43ac01 100644 --- a/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/androidLibMain/kotlin/text/KalugaDateFormatter.kt @@ -123,7 +123,7 @@ actual class KalugaDateFormatter private constructor(private val format: SimpleD get() = symbols.amPmStrings.toList()[1] set(value) { updateSymbols { it.amPmStrings = it.amPmStrings.toMutableList().apply { this[1] = value }.toTypedArray() } } - actual fun format(date: KalugaDate): String = format.format((date as DefaultKalugaDate).calendar.time) + actual fun format(date: KalugaDate): String = format.format(date.date) actual fun parse(string: String): KalugaDate? { val currentTimeZone = timeZone return try { diff --git a/base/src/androidLibMain/kotlin/utils/KalugaDate.kt b/base/src/androidLibMain/kotlin/utils/KalugaDate.kt index 1c92fc911..ac56e16ec 100644 --- a/base/src/androidLibMain/kotlin/utils/KalugaDate.kt +++ b/base/src/androidLibMain/kotlin/utils/KalugaDate.kt @@ -18,6 +18,9 @@ package com.splendo.kaluga.base.utils import java.util.Calendar +import java.util.Date + +actual typealias KalugaDateHolder = Date actual class DefaultKalugaDate internal constructor(internal val calendar: Calendar) : KalugaDate { @@ -92,10 +95,12 @@ actual class DefaultKalugaDate internal constructor(internal val calendar: Calen } override fun compareTo(other: KalugaDate): Int { - return this.calendar.time.compareTo((other as DefaultKalugaDate).calendar.time) + return this.date.compareTo(other.date) } override fun hashCode(): Int { return calendar.hashCode() } + + override val date: KalugaDateHolder = calendar.time } diff --git a/base/src/androidLibMain/kotlin/utils/TimeZone.kt b/base/src/androidLibMain/kotlin/utils/TimeZone.kt index b67b64b47..831fa87c7 100644 --- a/base/src/androidLibMain/kotlin/utils/TimeZone.kt +++ b/base/src/androidLibMain/kotlin/utils/TimeZone.kt @@ -42,7 +42,7 @@ actual class TimeZone internal constructor(internal val timeZone: java.util.Time actual val offsetFromGMTInMilliseconds = timeZone.rawOffset.toLong() actual val daylightSavingsOffsetInMilliseconds: Long = timeZone.dstSavings.toLong() actual fun offsetFromGMTAtDateInMilliseconds(date: KalugaDate): Long = timeZone.getOffset(date.millisecondSinceEpoch).toLong() - actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.inDaylightTime((date as DefaultKalugaDate).calendar.time) + actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.inDaylightTime(date.date) actual fun copy(): TimeZone = TimeZone(timeZone.clone() as java.util.TimeZone) override fun equals(other: Any?): Boolean { return (other as? TimeZone)?.let { timeZone == other.timeZone } ?: false diff --git a/base/src/commonMain/kotlin/utils/KalugaDate.kt b/base/src/commonMain/kotlin/utils/KalugaDate.kt index 25dca8795..776827e6e 100644 --- a/base/src/commonMain/kotlin/utils/KalugaDate.kt +++ b/base/src/commonMain/kotlin/utils/KalugaDate.kt @@ -19,6 +19,8 @@ package com.splendo.kaluga.base.utils import com.splendo.kaluga.base.utils.Locale.Companion.defaultLocale + +expect class KalugaDateHolder /** * Class describing a point in time * Dates are localized according to a [Locale] and relative to a given [TimeZone] @@ -117,6 +119,8 @@ interface KalugaDate : Comparable { override fun equals(other: Any?): Boolean override fun hashCode(): Int + + val date: KalugaDateHolder } expect class DefaultKalugaDate : KalugaDate { diff --git a/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt b/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt index 9af5e9c80..c8fd944af 100644 --- a/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/iosMain/kotlin/text/KalugaDateFormatter.kt @@ -79,29 +79,28 @@ actual class KalugaDateFormatter private constructor(private val format: NSDateF // Due to a problem related to the commonizer we need to supply all the // default arguments expected from the method signature - private fun defaultDate(timeZone: TimeZone) = ( + private fun defaultDate(timeZone: TimeZone) = DefaultKalugaDate.now( offsetInMilliseconds = 0L, timeZone = timeZone, locale = Locale.defaultLocale - ) as DefaultKalugaDate ).apply { - // Cannot use .utc since it may not be available when this method is called - // This is likely caused by https://youtrack.jetbrains.com/issue/KT-38181 - // TODO When moving Date and Date formatter to separate modules, this should be updated to use .utc - val epoch = DefaultKalugaDate.epoch( - offsetInMilliseconds = 0L, - timeZone = TimeZone.get("UTC")!!, - locale = Locale.defaultLocale - ) - this.era = epoch.era - this.year = epoch.year - this.month = epoch.month - this.day = epoch.day - this.hour = epoch.hour - this.minute = epoch.minute - this.second = epoch.second - }.date + // Cannot use .utc since it may not be available when this method is called + // This is likely caused by https://youtrack.jetbrains.com/issue/KT-38181 + // TODO When moving Date and Date formatter to separate modules, this should be updated to use .utc + val epoch = DefaultKalugaDate.epoch( + offsetInMilliseconds = 0L, + timeZone = TimeZone.get("UTC")!!, + locale = Locale.defaultLocale + ) + this.era = epoch.era + this.year = epoch.year + this.month = epoch.month + this.day = epoch.day + this.hour = epoch.hour + this.minute = epoch.minute + this.second = epoch.second + }.date } actual var pattern: String @@ -137,7 +136,7 @@ actual class KalugaDateFormatter private constructor(private val format: NSDateF get() = format.PMSymbol set(value) { format.PMSymbol = value } - actual fun format(date: KalugaDate): String = format.stringFromDate((date as DefaultKalugaDate).date) + actual fun format(date: KalugaDate): String = format.stringFromDate(date.date) actual fun parse(string: String): KalugaDate? { return format.dateFromString(string)?.let { date -> val calendar = format.calendar.copy() as NSCalendar diff --git a/base/src/iosMain/kotlin/utils/KalugaDate.kt b/base/src/iosMain/kotlin/utils/KalugaDate.kt index 30cbeb660..d16951a6a 100644 --- a/base/src/iosMain/kotlin/utils/KalugaDate.kt +++ b/base/src/iosMain/kotlin/utils/KalugaDate.kt @@ -44,6 +44,8 @@ import platform.darwin.NSInteger import platform.darwin.NSUInteger import kotlin.math.round +actual typealias KalugaDateHolder = NSDate + actual class DefaultKalugaDate internal constructor(private val calendar: NSCalendar, initialDate: NSDate) : KalugaDate { actual companion object { @@ -67,7 +69,7 @@ actual class DefaultKalugaDate internal constructor(private val calendar: NSCale } } - internal var date: NSDate = initialDate + override var date: NSDate = initialDate override var timeZone: TimeZone get() = TimeZone(calendar.timeZone) @@ -135,7 +137,7 @@ actual class DefaultKalugaDate internal constructor(private val calendar: NSCale return result } - override fun compareTo(other: KalugaDate): Int = this.date.compare((other as DefaultKalugaDate).date).toInt() + override fun compareTo(other: KalugaDate): Int = this.date.compare(other.date).toInt() private fun updateDateForComponent(component: NSCalendarUnit, value: Int) { // Check whether this component update can use dateBySettingUnit. diff --git a/base/src/iosMain/kotlin/utils/TimeZone.kt b/base/src/iosMain/kotlin/utils/TimeZone.kt index e1d50b985..82818d24c 100644 --- a/base/src/iosMain/kotlin/utils/TimeZone.kt +++ b/base/src/iosMain/kotlin/utils/TimeZone.kt @@ -75,8 +75,8 @@ actual class TimeZone internal constructor(val timeZone: NSTimeZone) { } return rawOffset * 1000L } - actual fun offsetFromGMTAtDateInMilliseconds(date: KalugaDate): Long = (timeZone.secondsFromGMTForDate((date as DefaultKalugaDate).date) * 1000L) - actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.isDaylightSavingTimeForDate((date as DefaultKalugaDate).date) + actual fun offsetFromGMTAtDateInMilliseconds(date: KalugaDate): Long = (timeZone.secondsFromGMTForDate(date.date) * 1000L) + actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.isDaylightSavingTimeForDate(date.date) actual fun copy(): TimeZone = TimeZone(timeZone.copy() as NSTimeZone) override fun equals(other: Any?): Boolean { return (other as? TimeZone)?.let { timeZone == other.timeZone } ?: false diff --git a/base/src/jsMain/kotlin/text/KalugaDateFormatter.kt b/base/src/jsMain/kotlin/text/KalugaDateFormatter.kt index 6b1dc9a45..f92fe4303 100644 --- a/base/src/jsMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/jsMain/kotlin/text/KalugaDateFormatter.kt @@ -17,7 +17,6 @@ package com.splendo.kaluga.base.text -import com.splendo.kaluga.base.utils.DefaultKalugaDate import com.splendo.kaluga.base.utils.KalugaDate import com.splendo.kaluga.base.utils.Locale import com.splendo.kaluga.base.utils.TimeZone @@ -62,7 +61,7 @@ actual class KalugaDateFormatter private constructor(initialTimeZone: TimeZone, actual var amString: String = "" actual var pmString: String = "" - actual fun format(date: KalugaDate): String = formatter((date as DefaultKalugaDate).date) + actual fun format(date: KalugaDate): String = formatter(date.date) actual fun parse(string: String): KalugaDate? = null } diff --git a/base/src/jsMain/kotlin/utils/KalugaDate.kt b/base/src/jsMain/kotlin/utils/KalugaDate.kt index 99e705d67..8d1356ae9 100644 --- a/base/src/jsMain/kotlin/utils/KalugaDate.kt +++ b/base/src/jsMain/kotlin/utils/KalugaDate.kt @@ -17,8 +17,10 @@ package com.splendo.kaluga.base.utils +actual typealias KalugaDateHolder = kotlin.js.Date + // TODO Implement with proper date solution for Java Script -actual class DefaultKalugaDate internal constructor(internal val date: kotlin.js.Date) : KalugaDate { +actual class DefaultKalugaDate internal constructor(override val date: KalugaDateHolder) : KalugaDate { actual companion object { actual fun now(offsetInMilliseconds: Long, timeZone: TimeZone, locale: Locale): KalugaDate = DefaultKalugaDate(kotlin.js.Date(kotlin.js.Date.now() + offsetInMilliseconds)) diff --git a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt index d5f8cdd4b..9ed9b1980 100644 --- a/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt +++ b/base/src/jvmMain/kotlin/text/KalugaDateFormatter.kt @@ -126,7 +126,7 @@ actual class KalugaDateFormatter private constructor(private val format: SimpleD get() = symbols.amPmStrings.toList()[1] set(value) { updateSymbols { it.amPmStrings = it.amPmStrings.toMutableList().apply { this[1] = value }.toTypedArray() } } - actual fun format(date: KalugaDate): String = format.format((date as DefaultKalugaDate).calendar.time) + actual fun format(date: KalugaDate): String = format.format(date.date) actual fun parse(string: String): KalugaDate? { val currentTimeZone = timeZone return try { diff --git a/base/src/jvmMain/kotlin/utils/KalugaDate.kt b/base/src/jvmMain/kotlin/utils/KalugaDate.kt index 6ae054fbf..64423cc2d 100644 --- a/base/src/jvmMain/kotlin/utils/KalugaDate.kt +++ b/base/src/jvmMain/kotlin/utils/KalugaDate.kt @@ -18,6 +18,9 @@ package com.splendo.kaluga.base.utils import java.util.Calendar +import java.util.Date + +actual typealias KalugaDateHolder = Date actual class DefaultKalugaDate internal constructor(internal val calendar: Calendar) : KalugaDate { @@ -92,8 +95,9 @@ actual class DefaultKalugaDate internal constructor(internal val calendar: Calen } override fun hashCode(): Int = calendar.hashCode() + override val date: KalugaDateHolder = calendar.time override fun compareTo(other: KalugaDate): Int { - return this.calendar.time.compareTo((other as DefaultKalugaDate).calendar.time) + return this.calendar.time.compareTo(other.date) } } diff --git a/base/src/jvmMain/kotlin/utils/TimeZone.kt b/base/src/jvmMain/kotlin/utils/TimeZone.kt index b67b64b47..831fa87c7 100644 --- a/base/src/jvmMain/kotlin/utils/TimeZone.kt +++ b/base/src/jvmMain/kotlin/utils/TimeZone.kt @@ -42,7 +42,7 @@ actual class TimeZone internal constructor(internal val timeZone: java.util.Time actual val offsetFromGMTInMilliseconds = timeZone.rawOffset.toLong() actual val daylightSavingsOffsetInMilliseconds: Long = timeZone.dstSavings.toLong() actual fun offsetFromGMTAtDateInMilliseconds(date: KalugaDate): Long = timeZone.getOffset(date.millisecondSinceEpoch).toLong() - actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.inDaylightTime((date as DefaultKalugaDate).calendar.time) + actual fun usesDaylightSavingsTime(date: KalugaDate): Boolean = timeZone.inDaylightTime(date.date) actual fun copy(): TimeZone = TimeZone(timeZone.clone() as java.util.TimeZone) override fun equals(other: Any?): Boolean { return (other as? TimeZone)?.let { timeZone == other.timeZone } ?: false From 6465f6ec97a67ff63cf9b2894a794b4db5ace3bd Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Wed, 30 Mar 2022 14:30:53 +0200 Subject: [PATCH 48/65] Code linted and added jvm name. --- base/src/commonMain/kotlin/utils/KalugaDate.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/base/src/commonMain/kotlin/utils/KalugaDate.kt b/base/src/commonMain/kotlin/utils/KalugaDate.kt index 776827e6e..ee89e0c15 100644 --- a/base/src/commonMain/kotlin/utils/KalugaDate.kt +++ b/base/src/commonMain/kotlin/utils/KalugaDate.kt @@ -14,11 +14,12 @@ limitations under the License. */ +@file:JvmName("KalugaDateJvm") package com.splendo.kaluga.base.utils import com.splendo.kaluga.base.utils.Locale.Companion.defaultLocale - +import kotlin.jvm.JvmName expect class KalugaDateHolder /** From 5390366aff9aa41a0b53855d54de7131a8b4dc08 Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Wed, 30 Mar 2022 15:08:45 +0200 Subject: [PATCH 49/65] Add doc for typealias. Fix beacon reference. --- base/src/commonMain/kotlin/utils/KalugaDate.kt | 4 ++++ beacons/src/commonMain/kotlin/Beacons.kt | 3 +-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/base/src/commonMain/kotlin/utils/KalugaDate.kt b/base/src/commonMain/kotlin/utils/KalugaDate.kt index ee89e0c15..ababc7192 100644 --- a/base/src/commonMain/kotlin/utils/KalugaDate.kt +++ b/base/src/commonMain/kotlin/utils/KalugaDate.kt @@ -21,7 +21,11 @@ package com.splendo.kaluga.base.utils import com.splendo.kaluga.base.utils.Locale.Companion.defaultLocale import kotlin.jvm.JvmName +/** + * Class holding the platform value of the desired Date. + */ expect class KalugaDateHolder + /** * Class describing a point in time * Dates are localized according to a [Locale] and relative to a given [TimeZone] diff --git a/beacons/src/commonMain/kotlin/Beacons.kt b/beacons/src/commonMain/kotlin/Beacons.kt index c1da175c2..8003ea065 100644 --- a/beacons/src/commonMain/kotlin/Beacons.kt +++ b/beacons/src/commonMain/kotlin/Beacons.kt @@ -32,7 +32,6 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update @@ -95,7 +94,7 @@ class Beacons( } cache[beacon.beaconID] = beacon to coroutineScope.launch { debug(TAG, "[Added] $beacon") - delay(beacon.lastSeen.millisecondSinceEpoch + timeoutMs - Date.now().millisecondSinceEpoch) + delay(beacon.lastSeen.millisecondSinceEpoch + timeoutMs - DefaultKalugaDate.now().millisecondSinceEpoch) debug(TAG, "[Lost] $beacon") cache.remove(beacon.beaconID) updateList() From d7c9f630533fb617caf0b7cb8a20da0e86eaf54f Mon Sep 17 00:00:00 2001 From: corrado4eyes Date: Wed, 30 Mar 2022 15:27:40 +0200 Subject: [PATCH 50/65] Fix date that would be static otherwise. --- base/src/androidLibMain/kotlin/utils/KalugaDate.kt | 2 +- base/src/jvmMain/kotlin/utils/KalugaDate.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/base/src/androidLibMain/kotlin/utils/KalugaDate.kt b/base/src/androidLibMain/kotlin/utils/KalugaDate.kt index ac56e16ec..6bc6db8ac 100644 --- a/base/src/androidLibMain/kotlin/utils/KalugaDate.kt +++ b/base/src/androidLibMain/kotlin/utils/KalugaDate.kt @@ -102,5 +102,5 @@ actual class DefaultKalugaDate internal constructor(internal val calendar: Calen return calendar.hashCode() } - override val date: KalugaDateHolder = calendar.time + override val date: KalugaDateHolder get() = calendar.time } diff --git a/base/src/jvmMain/kotlin/utils/KalugaDate.kt b/base/src/jvmMain/kotlin/utils/KalugaDate.kt index 64423cc2d..ff0658fe0 100644 --- a/base/src/jvmMain/kotlin/utils/KalugaDate.kt +++ b/base/src/jvmMain/kotlin/utils/KalugaDate.kt @@ -95,7 +95,7 @@ actual class DefaultKalugaDate internal constructor(internal val calendar: Calen } override fun hashCode(): Int = calendar.hashCode() - override val date: KalugaDateHolder = calendar.time + override val date: KalugaDateHolder get() = calendar.time override fun compareTo(other: KalugaDate): Int { return this.calendar.time.compareTo(other.date) From 2621b848e705735870c9d9cbccf2fd857f08ec35 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 31 Mar 2022 12:35:16 +0200 Subject: [PATCH 51/65] Swapped raw Map input with fields for ScanSettings in iOS Scanner.kt impl and added parse() method that can be split to actual expected in the future if we manage to unify the API --- .../src/iosMain/kotlin/scanner/Scanner.kt | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt b/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt index 011cb4115..97b1ce96e 100644 --- a/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt +++ b/bluetooth/src/iosMain/kotlin/scanner/Scanner.kt @@ -147,7 +147,7 @@ actual class Scanner internal constructor( awaitPoweredOn.await() centralManager.scanForPeripheralsWithServices( filter?.let { listOf(filter) }, - scanSettings.scanOptions + scanSettings.parse() ) } @@ -201,7 +201,20 @@ actual class Scanner internal constructor( } } - class ScanSettings private constructor(val scanOptions: Map) { + class ScanSettings private constructor( + private val allowDuplicateKeys: Boolean, + private val solicitedServiceUUIDsKey: List? + ) { + + fun parse(): Map { + val result: MutableMap = + mutableMapOf(CBCentralManagerScanOptionAllowDuplicatesKey to allowDuplicateKeys) + solicitedServiceUUIDsKey?.let { + result[CBCentralManagerScanOptionSolicitedServiceUUIDsKey] = it + } + return result.toMap() + } + data class Builder( // https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerscanoptionallowduplicateskey var allowDuplicateKeys: Boolean = true, @@ -214,14 +227,7 @@ actual class Scanner internal constructor( fun solicitedServiceUUIDsKey(keys: List) = apply { solicitedServiceUUIDsKey = keys } - fun build(): ScanSettings { - val result: MutableMap = - mutableMapOf(CBCentralManagerScanOptionAllowDuplicatesKey to allowDuplicateKeys) - solicitedServiceUUIDsKey?.let { - result[CBCentralManagerScanOptionSolicitedServiceUUIDsKey] = it - } - return ScanSettings(result.toMap()) - } + fun build(): ScanSettings = ScanSettings(allowDuplicateKeys, solicitedServiceUUIDsKey) } } } From d77b61bce2a0c87853a7c2b40b5b4f82f5ab1ec4 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 7 Apr 2022 20:24:47 +0200 Subject: [PATCH 52/65] Updated README.md --- bluetooth/README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/bluetooth/README.md b/bluetooth/README.md index c8322f922..36aed1969 100644 --- a/bluetooth/README.md +++ b/bluetooth/README.md @@ -67,3 +67,10 @@ class CommonViewModel(bltBuilder: BluetoothBuilder) : BaseViewModel() { ) } ``` + +### Notes +There is a major difference when it comes to default reported device emissions between Android and iOS. Android will report multiple emissions of the same device, as iOS will filter them out. + +To make the API consistent between both platforms under the hood, we enable for iOS the [CBCentralManagerScanOptionAllowDuplicatesKey](https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerscanoptionallowduplicateskey) option (which is disabled by default). + +In most cases (like observing the distance to a beacon) this behavior satisfies both platform needs. In the future, we will provide a common API that allows customization of the emission behavior. From 0fc6e0d26e8b05453aa77f18291a35d3fa36e031 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 8 Apr 2022 14:45:19 +0200 Subject: [PATCH 53/65] Added scannerBuilder property for BluetoothBuilder.kt iOS impl like Android so users can change the default behavior we set. --- bluetooth/src/iosMain/kotlin/BluetoothBuilder.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/bluetooth/src/iosMain/kotlin/BluetoothBuilder.kt b/bluetooth/src/iosMain/kotlin/BluetoothBuilder.kt index bfa574290..467f52642 100644 --- a/bluetooth/src/iosMain/kotlin/BluetoothBuilder.kt +++ b/bluetooth/src/iosMain/kotlin/BluetoothBuilder.kt @@ -14,10 +14,11 @@ actual class BluetoothBuilder( PermissionsBuilder(bundle).apply { registerBluetoothPermission() } - ) + ), + private val scannerBuilder: Scanner.Builder = Scanner.Builder() ) : Bluetooth.Builder { override fun create(connectionSettings: ConnectionSettings, autoRequestPermission: Boolean, autoEnableBluetooth: Boolean, coroutineScope: CoroutineScope): Bluetooth { - return Bluetooth(permissions, connectionSettings, autoRequestPermission, autoEnableBluetooth, Scanner.Builder(), coroutineScope) + return Bluetooth(permissions, connectionSettings, autoRequestPermission, autoEnableBluetooth, scannerBuilder, coroutineScope) } } From 0047633d4c8461c454c3a3d08588e58b11c4749b Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 8 Apr 2022 15:10:23 +0200 Subject: [PATCH 54/65] Updated README.md --- bluetooth/README.md | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/bluetooth/README.md b/bluetooth/README.md index 36aed1969..046b103a0 100644 --- a/bluetooth/README.md +++ b/bluetooth/README.md @@ -43,7 +43,7 @@ bluetooth.devices()[someUUID].disconnect() ### Android You may notice that when you ask for kaluga's `Permission.Bluetooth` the android request alert will prompt `Location` permission. This behaviour is encountered because Android system requires Location to access the hardware identifiers of nearby external devices via Bluetooth. -In order to setup a bluetooth repo on android you need to do the following: +In order to setup a bluetooth repo you need to do the following: ```kotlin // Somewhere in Android code val permissions = Permissions( @@ -53,10 +53,33 @@ val permissions = Permissions( } ) +val scanSettings = ScanSettings.Builder() + .setScanMode(..) + .setNumOfMatches(..) + .build() + +val scannerBuilder = Scanner.Builder(scanSettings = scanSettings,..) + val bluetoothBuilder = BluetoothBuilder(permissions = permissions) CommonViewModel(bluetoothBuilder) ... +// Somewhere in iOS code +val permissions = Permissions( + PermissionsBuilder().apply { + registerBluetoothPermission() + registerLocationPermission() + } +) + +val scanSettings = ScanSettings(allowDuplicateKeys, solicitedServiceUUIDsKey) + +val scannerBuilder = Scanner.Builder(scanSettings) + +val bluetoothBuilder = BluetoothBuilder(permissions = permissions, scannerBuilder = scannerBuilder) +CommonViewModel(bluetoothBuilder) +... + // Common code class CommonViewModel(bltBuilder: BluetoothBuilder) : BaseViewModel() { private val repo: Bluetooth = bltBuilder.create( @@ -71,6 +94,4 @@ class CommonViewModel(bltBuilder: BluetoothBuilder) : BaseViewModel() { ### Notes There is a major difference when it comes to default reported device emissions between Android and iOS. Android will report multiple emissions of the same device, as iOS will filter them out. -To make the API consistent between both platforms under the hood, we enable for iOS the [CBCentralManagerScanOptionAllowDuplicatesKey](https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerscanoptionallowduplicateskey) option (which is disabled by default). - -In most cases (like observing the distance to a beacon) this behavior satisfies both platform needs. In the future, we will provide a common API that allows customization of the emission behavior. +To align the behaviour across platform the [CBCentralManagerScanOptionAllowDuplicatesKey](https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerscanoptionallowduplicateskey) option is enabled on iOS. From 5cbc537b15bfacf8f0f92df73d74e1829ae0a694 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 8 Apr 2022 15:17:32 +0200 Subject: [PATCH 55/65] Minor README.md edit --- bluetooth/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/bluetooth/README.md b/bluetooth/README.md index 046b103a0..4b0a9f383 100644 --- a/bluetooth/README.md +++ b/bluetooth/README.md @@ -43,7 +43,9 @@ bluetooth.devices()[someUUID].disconnect() ### Android You may notice that when you ask for kaluga's `Permission.Bluetooth` the android request alert will prompt `Location` permission. This behaviour is encountered because Android system requires Location to access the hardware identifiers of nearby external devices via Bluetooth. +### Setup In order to setup a bluetooth repo you need to do the following: + ```kotlin // Somewhere in Android code val permissions = Permissions( From 7e1c2ad815aefeab189bd70d0cedad656ceefca3 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 13 Apr 2022 15:11:17 +0200 Subject: [PATCH 56/65] Update bluetooth/README.md Co-authored-by: Tijl --- bluetooth/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bluetooth/README.md b/bluetooth/README.md index 4b0a9f383..8d433d2e9 100644 --- a/bluetooth/README.md +++ b/bluetooth/README.md @@ -94,6 +94,6 @@ class CommonViewModel(bltBuilder: BluetoothBuilder) : BaseViewModel() { ``` ### Notes -There is a major difference when it comes to default reported device emissions between Android and iOS. Android will report multiple emissions of the same device, as iOS will filter them out. +There is a major difference when it comes to the reporting of scanned devices between Android and iOS. Android report multiple scans of the same device, whereas iOS filters them out. To align the behaviour across platform the [CBCentralManagerScanOptionAllowDuplicatesKey](https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerscanoptionallowduplicateskey) option is enabled on iOS. From 4659b0526a95e71c91f66b20dcb1438484eaa4e7 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 13 Apr 2022 15:11:23 +0200 Subject: [PATCH 57/65] Update bluetooth/README.md Co-authored-by: Tijl --- bluetooth/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bluetooth/README.md b/bluetooth/README.md index 8d433d2e9..6dbd4f37a 100644 --- a/bluetooth/README.md +++ b/bluetooth/README.md @@ -96,4 +96,4 @@ class CommonViewModel(bltBuilder: BluetoothBuilder) : BaseViewModel() { ### Notes There is a major difference when it comes to the reporting of scanned devices between Android and iOS. Android report multiple scans of the same device, whereas iOS filters them out. -To align the behaviour across platform the [CBCentralManagerScanOptionAllowDuplicatesKey](https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerscanoptionallowduplicateskey) option is enabled on iOS. +To align the behaviour across platforms the [CBCentralManagerScanOptionAllowDuplicatesKey](https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerscanoptionallowduplicateskey) option is enabled on iOS. It can be set to another value using `ScanSettings` as shown above. From 0cfb4b67f47593ee397bad94cfe81d091f557277 Mon Sep 17 00:00:00 2001 From: Dennis Skokov Date: Fri, 6 May 2022 15:39:57 +0200 Subject: [PATCH 58/65] Add kaluga as a composite build in an example --- example/ios/Supporting Files/settings.gradle.kts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/example/ios/Supporting Files/settings.gradle.kts b/example/ios/Supporting Files/settings.gradle.kts index 26174846d..432d219ff 100644 --- a/example/ios/Supporting Files/settings.gradle.kts +++ b/example/ios/Supporting Files/settings.gradle.kts @@ -134,3 +134,5 @@ include(":shared") project(":shared").projectDir = file("../../shared") rootProject.name = file("../..").name + +includeBuild("../../..") From 0fd5e698a9213974747810c163af7b3367bf1883 Mon Sep 17 00:00:00 2001 From: Dennis Skokov Date: Mon, 9 May 2022 13:58:13 +0200 Subject: [PATCH 59/65] Added example embedding method option --- cloudbuild.yaml | 4 +- example/android/build.gradle | 45 +++---- .../ios/Supporting Files/settings.gradle.kts | 115 +++++++++--------- example/shared/build.gradle.kts | 2 +- gradle/ext.gradle | 15 ++- 5 files changed, 93 insertions(+), 88 deletions(-) diff --git a/cloudbuild.yaml b/cloudbuild.yaml index ad593bffa..5d67a2b52 100644 --- a/cloudbuild.yaml +++ b/cloudbuild.yaml @@ -33,7 +33,7 @@ steps: - 'JAVA_TOOL_OPTIONS="-Xmx3g"' - 'GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.workers.max=8 -Dkotlin.incremental=false"' - 'BRANCH_NAME=$BRANCH_NAME' - - 'EXAMPLE_AS_ROOT=false' + - 'EXAMPLE_EMBEDDING_METHOD="snapshot"' dir: "example/ios/Supporting Files" waitFor: - check @@ -61,7 +61,7 @@ steps: - 'JAVA_TOOL_OPTIONS="-Xmx3g"' - 'GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.workers.max=8 -Dkotlin.incremental=false"' - 'BRANCH_NAME=$BRANCH_NAME' - - 'EXAMPLE_AS_ROOT=true' + - 'EXAMPLE_EMBEDDING_METHOD="as-root"' dir: "example/ios/Supporting Files" waitFor: - localPublish diff --git a/example/android/build.gradle b/example/android/build.gradle index 6880980ae..959b292b2 100644 --- a/example/android/build.gradle +++ b/example/android/build.gradle @@ -71,30 +71,31 @@ gradle.ext.component_type = gradle.ext.component_type_default dependencies { - if (gradle.ext.example_as_root) { - // if the example is the root we use a maven dependency instead of the project - implementation "com.splendo.kaluga:architecture-compose:$gradle.ext.library_version" - implementation "com.splendo.kaluga:resources-compose:$gradle.ext.library_version" - implementation project(':shared') + + if (gradle.ext.example_embedding_method == "as-root") { + implementation project(':shared') + implementation project(":base-permissions") + implementation project(":location-permissions") + implementation project(":bluetooth-permissions") + implementation project(":camera-permissions") + implementation project(":contacts-permissions") + implementation project(":microphone-permissions") + implementation project(":storage-permissions") + implementation project(":notifications-permissions") + implementation project(":calendar-permissions") + implementation project(":logging") + implementation project(":alerts") + implementation project(":hud") + implementation project(":architecture") + implementation project(":architecture-compose") + implementation project(":resources") + implementation project(":resources-compose") } else { - implementation project(':shared') - implementation project(":base-permissions") - implementation project(":location-permissions") - implementation project(":bluetooth-permissions") - implementation project(":camera-permissions") - implementation project(":contacts-permissions") - implementation project(":microphone-permissions") - implementation project(":storage-permissions") - implementation project(":notifications-permissions") - implementation project(":calendar-permissions") - implementation project(":logging") - implementation project(":alerts") - implementation project(":hud") - implementation project(":architecture") - implementation project(":architecture-compose") - implementation project(":resources") - implementation project(":resources-compose") + // if the example is the root we use a maven dependency instead of the project + implementation "com.splendo.kaluga:architecture-compose:$gradle.ext.library_version" + implementation "com.splendo.kaluga:resources-compose:$gradle.ext.library_version" + implementation project(':shared') } implementation "androidx.fragment:fragment-ktx:$gradle.androidx_fragment_version" diff --git a/example/ios/Supporting Files/settings.gradle.kts b/example/ios/Supporting Files/settings.gradle.kts index 432d219ff..f429c5898 100644 --- a/example/ios/Supporting Files/settings.gradle.kts +++ b/example/ios/Supporting Files/settings.gradle.kts @@ -43,85 +43,90 @@ apply("../../../gradle/ext.gradle") val ext = (gradle as ExtensionAware).extra -if (!(ext["example_as_root"] as Boolean)) { +when (ext["example_embedding_method"] ) { + "as-root" -> { + include(":alerts") + project(":alerts").projectDir = file("../../../alerts") - include(":alerts") - project(":alerts").projectDir = file("../../../alerts") + include(":architecture") + project(":architecture").projectDir = file("../../../architecture") - include(":architecture") - project(":architecture").projectDir = file("../../../architecture") + include(":architecture-compose") + project(":architecture-compose").projectDir = file("../../../architecture-compose") - include(":architecture-compose") - project(":architecture-compose").projectDir = file("../../../architecture-compose") + include(":base") + project(":base").projectDir = file("../../../base") - include(":base") - project(":base").projectDir = file("../../../base") + include(":bluetooth") + project(":bluetooth").projectDir = file("../../../bluetooth") - include(":bluetooth") - project(":bluetooth").projectDir = file("../../../bluetooth") + include(":beacons") + project(":beacons").projectDir = file("../../../beacons") - include(":beacons") - project(":beacons").projectDir = file("../../../beacons") + include(":date-time-picker") + project(":date-time-picker").projectDir = file("../../../date-time-picker") - include(":date-time-picker") - project(":date-time-picker").projectDir = file("../../../date-time-picker") + include(":hud") + project(":hud").projectDir = file("../../../hud") - include(":hud") - project(":hud").projectDir = file("../../../hud") + include(":keyboard") + project(":keyboard").projectDir = file("../../../keyboard") - include(":keyboard") - project(":keyboard").projectDir = file("../../../keyboard") + include(":links") + project(":links").projectDir = file("../../../links") - include(":links") - project(":links").projectDir = file("../../../links") + include(":location") + project(":location").projectDir = file("../../../location") - include(":location") - project(":location").projectDir = file("../../../location") + include(":logging") + project(":logging").projectDir = file("../../../logging") - include(":logging") - project(":logging").projectDir = file("../../../logging") + include(":base-permissions") + project(":base-permissions").projectDir = file("../../../base-permissions") - include(":base-permissions") - project(":base-permissions").projectDir = file("../../../base-permissions") + include(":location-permissions") + project(":location-permissions").projectDir = file("../../../location-permissions") - include(":location-permissions") - project(":location-permissions").projectDir = file("../../../location-permissions") + include(":bluetooth-permissions") + project(":bluetooth-permissions").projectDir = file("../../../bluetooth-permissions") - include(":bluetooth-permissions") - project(":bluetooth-permissions").projectDir = file("../../../bluetooth-permissions") + include(":camera-permissions") + project(":camera-permissions").projectDir = file("../../../camera-permissions") - include(":camera-permissions") - project(":camera-permissions").projectDir = file("../../../camera-permissions") + include(":contacts-permissions") + project(":contacts-permissions").projectDir = file("../../../contacts-permissions") - include(":contacts-permissions") - project(":contacts-permissions").projectDir = file("../../../contacts-permissions") + include(":microphone-permissions") + project(":microphone-permissions").projectDir = file("../../../microphone-permissions") - include(":microphone-permissions") - project(":microphone-permissions").projectDir = file("../../../microphone-permissions") + include(":storage-permissions") + project(":storage-permissions").projectDir = file("../../../storage-permissions") - include(":storage-permissions") - project(":storage-permissions").projectDir = file("../../../storage-permissions") + include(":notifications-permissions") + project(":notifications-permissions").projectDir = + file("../../../notifications-permissions") - include(":notifications-permissions") - project(":notifications-permissions").projectDir = file("../../../notifications-permissions") + include(":calendar-permissions") + project(":calendar-permissions").projectDir = file("../../../calendar-permissions") - include(":calendar-permissions") - project(":calendar-permissions").projectDir = file("../../../calendar-permissions") + include(":resources") + project(":resources").projectDir = file("../../../resources") - include(":resources") - project(":resources").projectDir = file("../../../resources") + include(":resources-compose") + project(":resources-compose").projectDir = file("../../../resources-compose") - include(":resources-compose") - project(":resources-compose").projectDir = file("../../../resources-compose") + include(":review") + project(":review").projectDir = file("../../../review") - include(":review") - project(":review").projectDir = file("../../../review") + include(":system") + project(":system").projectDir = file("../../../system") - include(":system") - project(":system").projectDir = file("../../../system") - - include(":test-utils") - project(":test-utils").projectDir = file("../../../test-utils") + include(":test-utils") + project(":test-utils").projectDir = file("../../../test-utils") + } + "composite" -> { + includeBuild("../../..") + } } include(":android") @@ -135,4 +140,4 @@ project(":shared").projectDir = file("../../shared") rootProject.name = file("../..").name -includeBuild("../../..") + diff --git a/example/shared/build.gradle.kts b/example/shared/build.gradle.kts index 25c8f2264..dc81949b0 100644 --- a/example/shared/build.gradle.kts +++ b/example/shared/build.gradle.kts @@ -14,7 +14,7 @@ kotlin { val ext = (gradle as ExtensionAware).extra dependencies { - if (!(ext["example_as_root"] as Boolean)) { + if (ext["example_embedding_method"] == "as-root") { api(project(":alerts", "")) api(project(":architecture", "")) api(project(":base", "")) diff --git a/gradle/ext.gradle b/gradle/ext.gradle index 9c902cecf..abd255777 100644 --- a/gradle/ext.gradle +++ b/gradle/ext.gradle @@ -16,7 +16,7 @@ if (propFile.exists()) { } String libraryVersionLocalProperties = props["kaluga.libraryVersion"] -String exampleAsRootLocalProperties = props["kaluga.exampleAsRoot"] +String exampleEmbeddingMethodLocalProperties = props["kaluga.exampleEmbeddingMethod"] String exampleMavenRepoLocalProperties = props["kaluga.exampleMavenRepo"] String kotlinVersion = getProperty("kaluga.kotlinVersion") @@ -80,17 +80,16 @@ gradle.ext { component_type = component_type_default } -if (System.env.containsKey("EXAMPLE_AS_ROOT")) { - gradle.ext.example_as_root = Boolean.parseBoolean(System.env.EXAMPLE_AS_ROOT) - logger.lifecycle "System env EXAMPLE_AS_ROOT set to $System.env.EXAMPLE_AS_ROOT, using $gradle.ext.example_as_root" +if (System.env.containsKey("EXAMPLE_EMBEDDING_METHOD")) { + gradle.ext.example_embedding_method = System.env.EXAMPLE_EMBEDDING_METHOD + logger.lifecycle "System env EXAMPLE_EMBEDDING_METHOD set to $System.env.EXAMPLE_EMBEDDING_METHOD, using $gradle.ext.example_embedding_method" } else { - // load some more from local.properties or set defaults. - gradle.ext.example_as_root = exampleAsRootLocalProperties?.toBoolean() ?: false - logger.lifecycle "local.properties read (kaluga.exampleAsRoot=$exampleAsRootLocalProperties, using $gradle.ext.example_as_root)" + gradle.ext.example_embedding_method = exampleEmbeddingMethodLocalProperties ?: "composite" + logger.lifecycle "local.properties read (kaluga.exampleEmbeddingMethod=$exampleEmbeddingMethodLocalProperties, using $gradle.ext.example_embedding_method)" } if (System.env.containsKey("EXAMPLE_MAVEN_REPO")) { - gradle.ext.example_maven_repo = System.env.EXAMPLE_MAVEN_REPO + gradle.ext.example_maven_addIntoExamplerepo = System.env.EXAMPLE_MAVEN_REPO logger.lifecycle "System env EXAMPLE_MAVEN_REPO set to $System.env.EXAMPLE_MAVEN_REPO, using $gradle.ext.example_maven_repo" } else { // load some more from local.properties or set defaults. From 739bf65a578b6df29a84dee5a5afe05935bf0196 Mon Sep 17 00:00:00 2001 From: Dennis Skokov Date: Mon, 9 May 2022 14:15:44 +0200 Subject: [PATCH 60/65] Updated readme --- DEVELOP.md | 2 +- cloudbuild.yaml | 2 +- example/readme.md | 5 ++++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/DEVELOP.md b/DEVELOP.md index 46fb2c4e9..25e3f1c50 100644 --- a/DEVELOP.md +++ b/DEVELOP.md @@ -80,7 +80,7 @@ For example if the version in `ext.gradle` is `1.1` and `feature/123_fix_bug` is Before doing any publishing, make sure that changes are working with the one available in [Nexus Repository Manager](`oss.sonatype.org`). Test both on Android and iOS example app just adding the following code inside the `local.properties` file: ``` -kaluga.exampleAsRoot=true +kaluga.exampleEmbeddingMethod=composite kaluga.exampleMavenRepo=https://oss.sonatype.org/service/local/repositories/comsplendo-REPO_NUMBER/content/ kaluga.libraryVersion=LIBRARY_VERSION ``` diff --git a/cloudbuild.yaml b/cloudbuild.yaml index 5d67a2b52..d3d412135 100644 --- a/cloudbuild.yaml +++ b/cloudbuild.yaml @@ -33,7 +33,7 @@ steps: - 'JAVA_TOOL_OPTIONS="-Xmx3g"' - 'GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.workers.max=8 -Dkotlin.incremental=false"' - 'BRANCH_NAME=$BRANCH_NAME' - - 'EXAMPLE_EMBEDDING_METHOD="snapshot"' + - 'EXAMPLE_EMBEDDING_METHOD="maven"' dir: "example/ios/Supporting Files" waitFor: - check diff --git a/example/readme.md b/example/readme.md index a07a48f7f..2d39309fc 100644 --- a/example/readme.md +++ b/example/readme.md @@ -9,7 +9,10 @@ The example app can load the main components either through your (local) maven r The advantage of using a gradle module is that you can edit the source of components and run them in the example right away, without needing to publish them to maven first. -By default maven is not used for resolving dependencies (instead the individual kaluga modules are imported as project modules). To enable using maven usage put the property `kaluga.exampleAsRoot=true` in the `local.properties` file in the root of the project (this file is already generated by your IDE normally). +`kaluga.exampleEmbeddingMethod=composite` +By default maven is not used for resolving dependencies, instead the kaluga dependency included as composite build. +To enable using maven usage put the property `kaluga.exampleEmbeddingMethod=maven` in the `local.properties` file in the root of the project (this file is already generated by your IDE normally). +It is also possible to import the individual kaluga modules by using `as-root` option `kaluga.exampleEmbeddingMethod=as-root` You can also set the `kaluga.exampleMavenRepo` property to specify which maven repo to look in. By default this is `mavenLocal()` (this can also be used by explicitly setting the value `local`). For example to set this to the sonatype snapshot repository use: From c59a12bb7d1eb2582f1eb25f05ce315f836742cf Mon Sep 17 00:00:00 2001 From: Dennis Skokov Date: Mon, 9 May 2022 14:32:33 +0200 Subject: [PATCH 61/65] Remove doubble new lines --- example/ios/Supporting Files/settings.gradle.kts | 2 -- 1 file changed, 2 deletions(-) diff --git a/example/ios/Supporting Files/settings.gradle.kts b/example/ios/Supporting Files/settings.gradle.kts index f429c5898..ee81c7008 100644 --- a/example/ios/Supporting Files/settings.gradle.kts +++ b/example/ios/Supporting Files/settings.gradle.kts @@ -139,5 +139,3 @@ include(":shared") project(":shared").projectDir = file("../../shared") rootProject.name = file("../..").name - - From 6315490f0de6ec9408cc749be032783ff456e54e Mon Sep 17 00:00:00 2001 From: Dennis Skokov Date: Mon, 9 May 2022 14:38:00 +0200 Subject: [PATCH 62/65] Fixed example_maven_repo --- gradle/ext.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/ext.gradle b/gradle/ext.gradle index abd255777..e016d98cf 100644 --- a/gradle/ext.gradle +++ b/gradle/ext.gradle @@ -89,7 +89,7 @@ if (System.env.containsKey("EXAMPLE_EMBEDDING_METHOD")) { } if (System.env.containsKey("EXAMPLE_MAVEN_REPO")) { - gradle.ext.example_maven_addIntoExamplerepo = System.env.EXAMPLE_MAVEN_REPO + gradle.ext.example_maven_repo = System.env.EXAMPLE_MAVEN_REPO logger.lifecycle "System env EXAMPLE_MAVEN_REPO set to $System.env.EXAMPLE_MAVEN_REPO, using $gradle.ext.example_maven_repo" } else { // load some more from local.properties or set defaults. From ccc899a25726e6f6a41fa18ea8b913cca713f6dc Mon Sep 17 00:00:00 2001 From: Dennis Skokov Date: Mon, 9 May 2022 15:14:46 +0200 Subject: [PATCH 63/65] Clenup settings --- .../ios/Supporting Files/settings.gradle.kts | 90 +++---------------- 1 file changed, 12 insertions(+), 78 deletions(-) diff --git a/example/ios/Supporting Files/settings.gradle.kts b/example/ios/Supporting Files/settings.gradle.kts index ee81c7008..1a161b7a1 100644 --- a/example/ios/Supporting Files/settings.gradle.kts +++ b/example/ios/Supporting Files/settings.gradle.kts @@ -45,84 +45,18 @@ val ext = (gradle as ExtensionAware).extra when (ext["example_embedding_method"] ) { "as-root" -> { - include(":alerts") - project(":alerts").projectDir = file("../../../alerts") - - include(":architecture") - project(":architecture").projectDir = file("../../../architecture") - - include(":architecture-compose") - project(":architecture-compose").projectDir = file("../../../architecture-compose") - - include(":base") - project(":base").projectDir = file("../../../base") - - include(":bluetooth") - project(":bluetooth").projectDir = file("../../../bluetooth") - - include(":beacons") - project(":beacons").projectDir = file("../../../beacons") - - include(":date-time-picker") - project(":date-time-picker").projectDir = file("../../../date-time-picker") - - include(":hud") - project(":hud").projectDir = file("../../../hud") - - include(":keyboard") - project(":keyboard").projectDir = file("../../../keyboard") - - include(":links") - project(":links").projectDir = file("../../../links") - - include(":location") - project(":location").projectDir = file("../../../location") - - include(":logging") - project(":logging").projectDir = file("../../../logging") - - include(":base-permissions") - project(":base-permissions").projectDir = file("../../../base-permissions") - - include(":location-permissions") - project(":location-permissions").projectDir = file("../../../location-permissions") - - include(":bluetooth-permissions") - project(":bluetooth-permissions").projectDir = file("../../../bluetooth-permissions") - - include(":camera-permissions") - project(":camera-permissions").projectDir = file("../../../camera-permissions") - - include(":contacts-permissions") - project(":contacts-permissions").projectDir = file("../../../contacts-permissions") - - include(":microphone-permissions") - project(":microphone-permissions").projectDir = file("../../../microphone-permissions") - - include(":storage-permissions") - project(":storage-permissions").projectDir = file("../../../storage-permissions") - - include(":notifications-permissions") - project(":notifications-permissions").projectDir = - file("../../../notifications-permissions") - - include(":calendar-permissions") - project(":calendar-permissions").projectDir = file("../../../calendar-permissions") - - include(":resources") - project(":resources").projectDir = file("../../../resources") - - include(":resources-compose") - project(":resources-compose").projectDir = file("../../../resources-compose") - - include(":review") - project(":review").projectDir = file("../../../review") - - include(":system") - project(":system").projectDir = file("../../../system") - - include(":test-utils") - project(":test-utils").projectDir = file("../../../test-utils") + var modules = listOf( + "alerts", "architecture", "base", "architecture-compose", "bluetooth", "beacons", + "date-time-picker", "hud", "keyboard", "links", "location", "logging", + "base-permissions", "location-permissions", "bluetooth-permissions", + "contacts-permissions", "microphone-permissions", "storage-permissions", + "notifications-permissions", "calendar-permissions", + "resources", "resources-compose", "review", "system", "test-utils" + ) + modules.forEach { module -> + include(":$module") + project(":$module").projectDir = file("../../../$module") + } } "composite" -> { includeBuild("../../..") From 54e19d6435ea95746e3ab70df6e398a81cb15b24 Mon Sep 17 00:00:00 2001 From: Dennis Skokov Date: Mon, 9 May 2022 17:20:38 +0200 Subject: [PATCH 64/65] Removed as-root --- cloudbuild.yaml | 2 +- example/android/build.gradle | 30 +------- .../ios/Supporting Files/settings.gradle.kts | 14 ---- example/readme.md | 5 +- example/shared/build.gradle.kts | 74 ++++++------------- 5 files changed, 29 insertions(+), 96 deletions(-) diff --git a/cloudbuild.yaml b/cloudbuild.yaml index d3d412135..a69010e47 100644 --- a/cloudbuild.yaml +++ b/cloudbuild.yaml @@ -61,7 +61,7 @@ steps: - 'JAVA_TOOL_OPTIONS="-Xmx3g"' - 'GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.workers.max=8 -Dkotlin.incremental=false"' - 'BRANCH_NAME=$BRANCH_NAME' - - 'EXAMPLE_EMBEDDING_METHOD="as-root"' + - 'EXAMPLE_EMBEDDING_METHOD="composite"' dir: "example/ios/Supporting Files" waitFor: - localPublish diff --git a/example/android/build.gradle b/example/android/build.gradle index 959b292b2..97b7218f4 100644 --- a/example/android/build.gradle +++ b/example/android/build.gradle @@ -70,33 +70,9 @@ apply from: "../../gradle/android_compose.gradle" gradle.ext.component_type = gradle.ext.component_type_default dependencies { - - - if (gradle.ext.example_embedding_method == "as-root") { - implementation project(':shared') - implementation project(":base-permissions") - implementation project(":location-permissions") - implementation project(":bluetooth-permissions") - implementation project(":camera-permissions") - implementation project(":contacts-permissions") - implementation project(":microphone-permissions") - implementation project(":storage-permissions") - implementation project(":notifications-permissions") - implementation project(":calendar-permissions") - implementation project(":logging") - implementation project(":alerts") - implementation project(":hud") - implementation project(":architecture") - implementation project(":architecture-compose") - implementation project(":resources") - implementation project(":resources-compose") - } - else { - // if the example is the root we use a maven dependency instead of the project - implementation "com.splendo.kaluga:architecture-compose:$gradle.ext.library_version" - implementation "com.splendo.kaluga:resources-compose:$gradle.ext.library_version" - implementation project(':shared') - } + implementation "com.splendo.kaluga:architecture-compose:$gradle.ext.library_version" + implementation "com.splendo.kaluga:resources-compose:$gradle.ext.library_version" + implementation project(':shared') implementation "androidx.fragment:fragment-ktx:$gradle.androidx_fragment_version" implementation "com.google.android.gms:play-services-location:$gradle.play_services_version" diff --git a/example/ios/Supporting Files/settings.gradle.kts b/example/ios/Supporting Files/settings.gradle.kts index 1a161b7a1..24a4da1ff 100644 --- a/example/ios/Supporting Files/settings.gradle.kts +++ b/example/ios/Supporting Files/settings.gradle.kts @@ -44,20 +44,6 @@ apply("../../../gradle/ext.gradle") val ext = (gradle as ExtensionAware).extra when (ext["example_embedding_method"] ) { - "as-root" -> { - var modules = listOf( - "alerts", "architecture", "base", "architecture-compose", "bluetooth", "beacons", - "date-time-picker", "hud", "keyboard", "links", "location", "logging", - "base-permissions", "location-permissions", "bluetooth-permissions", - "contacts-permissions", "microphone-permissions", "storage-permissions", - "notifications-permissions", "calendar-permissions", - "resources", "resources-compose", "review", "system", "test-utils" - ) - modules.forEach { module -> - include(":$module") - project(":$module").projectDir = file("../../../$module") - } - } "composite" -> { includeBuild("../../..") } diff --git a/example/readme.md b/example/readme.md index 2d39309fc..6d68b4953 100644 --- a/example/readme.md +++ b/example/readme.md @@ -9,10 +9,7 @@ The example app can load the main components either through your (local) maven r The advantage of using a gradle module is that you can edit the source of components and run them in the example right away, without needing to publish them to maven first. -`kaluga.exampleEmbeddingMethod=composite` -By default maven is not used for resolving dependencies, instead the kaluga dependency included as composite build. -To enable using maven usage put the property `kaluga.exampleEmbeddingMethod=maven` in the `local.properties` file in the root of the project (this file is already generated by your IDE normally). -It is also possible to import the individual kaluga modules by using `as-root` option `kaluga.exampleEmbeddingMethod=as-root` +By default kaluga dependency is included as a composite build. You also can put the property `kaluga.exampleEmbeddingMethod=composite` in the `local.properties` file in the root of the project (this file is already generated by your IDE normally) to specify it explicitly. To enable maven use `kaluga.exampleEmbeddingMethod=maven`. You can also set the `kaluga.exampleMavenRepo` property to specify which maven repo to look in. By default this is `mavenLocal()` (this can also be used by explicitly setting the value `local`). For example to set this to the sonatype snapshot repository use: diff --git a/example/shared/build.gradle.kts b/example/shared/build.gradle.kts index dc81949b0..4954a037f 100644 --- a/example/shared/build.gradle.kts +++ b/example/shared/build.gradle.kts @@ -14,56 +14,30 @@ kotlin { val ext = (gradle as ExtensionAware).extra dependencies { - if (ext["example_embedding_method"] == "as-root") { - api(project(":alerts", "")) - api(project(":architecture", "")) - api(project(":base", "")) - api(project(":bluetooth", "")) - api(project(":beacons", "")) - api(project(":date-time-picker", "")) - api(project(":hud", "")) - api(project(":keyboard", "")) - api(project(":links", "")) - api(project(":location", "")) - api(project(":logging", "")) - api(project(":base-permissions", "")) - api(project(":location-permissions", "")) - api(project(":bluetooth-permissions", "")) - api(project(":camera-permissions", "")) - api(project(":contacts-permissions", "")) - api(project(":microphone-permissions", "")) - api(project(":storage-permissions", "")) - api(project(":notifications-permissions", "")) - api(project(":calendar-permissions", "")) - api(project(":resources", "")) - api(project(":review", "")) - api(project(":system", "")) - } else { - val libraryVersion = ext["library_version"] - api("com.splendo.kaluga:alerts:$libraryVersion") - api("com.splendo.kaluga:architecture:$libraryVersion") - api("com.splendo.kaluga:base:$libraryVersion") - api("com.splendo.kaluga:bluetooth:$libraryVersion") - api("com.splendo.kaluga:beacons:$libraryVersion") - api("com.splendo.kaluga:date-time-picker:$libraryVersion") - api("com.splendo.kaluga:hud:$libraryVersion") - api("com.splendo.kaluga:keyboard:$libraryVersion") - api("com.splendo.kaluga:links:$libraryVersion") - api("com.splendo.kaluga:location:$libraryVersion") - api("com.splendo.kaluga:logging:$libraryVersion") - api("com.splendo.kaluga:resources:$libraryVersion") - api("com.splendo.kaluga:review:$libraryVersion") - api("com.splendo.kaluga:system:$libraryVersion") - api("com.splendo.kaluga:base-permissions:$libraryVersion") - api("com.splendo.kaluga:location-permissions:$libraryVersion") - api("com.splendo.kaluga:bluetooth-permissions:$libraryVersion") - api("com.splendo.kaluga:camera-permissions:$libraryVersion") - api("com.splendo.kaluga:contacts-permissions:$libraryVersion") - api("com.splendo.kaluga:microphone-permissions:$libraryVersion") - api("com.splendo.kaluga:storage-permissions:$libraryVersion") - api("com.splendo.kaluga:notifications-permissions:$libraryVersion") - api("com.splendo.kaluga:calendar-permissions:$libraryVersion") - } + val libraryVersion = ext["library_version"] + api("com.splendo.kaluga:alerts:$libraryVersion") + api("com.splendo.kaluga:architecture:$libraryVersion") + api("com.splendo.kaluga:base:$libraryVersion") + api("com.splendo.kaluga:bluetooth:$libraryVersion") + api("com.splendo.kaluga:beacons:$libraryVersion") + api("com.splendo.kaluga:date-time-picker:$libraryVersion") + api("com.splendo.kaluga:hud:$libraryVersion") + api("com.splendo.kaluga:keyboard:$libraryVersion") + api("com.splendo.kaluga:links:$libraryVersion") + api("com.splendo.kaluga:location:$libraryVersion") + api("com.splendo.kaluga:logging:$libraryVersion") + api("com.splendo.kaluga:resources:$libraryVersion") + api("com.splendo.kaluga:review:$libraryVersion") + api("com.splendo.kaluga:system:$libraryVersion") + api("com.splendo.kaluga:base-permissions:$libraryVersion") + api("com.splendo.kaluga:location-permissions:$libraryVersion") + api("com.splendo.kaluga:bluetooth-permissions:$libraryVersion") + api("com.splendo.kaluga:camera-permissions:$libraryVersion") + api("com.splendo.kaluga:contacts-permissions:$libraryVersion") + api("com.splendo.kaluga:microphone-permissions:$libraryVersion") + api("com.splendo.kaluga:storage-permissions:$libraryVersion") + api("com.splendo.kaluga:notifications-permissions:$libraryVersion") + api("com.splendo.kaluga:calendar-permissions:$libraryVersion") } } } From 2e8f1efc7b61bd400905f1ec44e304f97898fcb9 Mon Sep 17 00:00:00 2001 From: Dennis Skokov Date: Tue, 10 May 2022 16:39:53 +0200 Subject: [PATCH 65/65] Delete cloud build yaml file --- cloudbuild.yaml | 84 ------------------------------------------------- 1 file changed, 84 deletions(-) delete mode 100644 cloudbuild.yaml diff --git a/cloudbuild.yaml b/cloudbuild.yaml deleted file mode 100644 index a69010e47..000000000 --- a/cloudbuild.yaml +++ /dev/null @@ -1,84 +0,0 @@ -steps: - - name: 'gcr.io/$PROJECT_ID/android:29' - id: assemble - args: ["./gradlew", "assemble"] - env: - - 'TERM=dumb' - - 'GRADLE_USER_HOME=/workspace/gradle_home' - - 'KONAN_DATA_DIR=/workspace/konan' - - 'JAVA_TOOL_OPTIONS="-Xmx3g"' - - 'GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.workers.max=8 -Dkotlin.incremental=false"' - - 'BRANCH_NAME=$BRANCH_NAME' - - - name: 'gcr.io/$PROJECT_ID/android:29' - id: check - args: ["./gradlew", "check"] - env: - - 'TERM=dumb' - # can only use one gradle home concurrently - - 'GRADLE_USER_HOME=/workspace/gradle_home_check' - - 'KONAN_DATA_DIR=/workspace/konan' - - 'JAVA_TOOL_OPTIONS="-Xmx3g"' - - 'GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.workers.max=8 -Dkotlin.incremental=false"' - - 'BRANCH_NAME=$BRANCH_NAME' - waitFor: - - assemble - - name: 'gcr.io/$PROJECT_ID/android:29' - id: compileExampleAndroidUsingModules - args: ["../../../gradlew", "--stacktrace", "-x", "compileKotlinIosx64", "assemble"] - env: - - 'GRADLE_USER_HOME=/workspace/gradle_home_example_modules' - - 'KONAN_DATA_DIR=/workspace/konan' - - 'TERM=dumb' - - 'JAVA_TOOL_OPTIONS="-Xmx3g"' - - 'GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.workers.max=8 -Dkotlin.incremental=false"' - - 'BRANCH_NAME=$BRANCH_NAME' - - 'EXAMPLE_EMBEDDING_METHOD="maven"' - dir: "example/ios/Supporting Files" - waitFor: - - check - - - name: 'gcr.io/$PROJECT_ID/android:29' - id: localPublish - args: ["./gradlew", "--stacktrace", "-Dmaven.repo.local=/workspace/m2", "publishToMavenLocal"] - env: - - 'GRADLE_USER_HOME=/workspace/gradle_home' - - 'KONAN_DATA_DIR=/workspace/konan' - - 'TERM=dumb' - - 'JAVA_TOOL_OPTIONS="-Xmx3g"' - - 'GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.workers.max=8 -Dkotlin.incremental=false"' - - 'BRANCH_NAME=$BRANCH_NAME' - waitFor: - - assemble - - - name: 'gcr.io/$PROJECT_ID/android:29' - id: compileExampleAndroidUsingM2 - args: ["../../../gradlew", "--stacktrace", "--project-cache-dir=gradle_example_project_m2","-Dmaven.repo.local=/workspace/m2", "-x", "compileKotlinIosx64", "assemble", ] - env: - - 'GRADLE_USER_HOME=/workspace/gradle_home_example_m2' - - 'KONAN_DATA_DIR=/workspace/konan' - - 'TERM=dumb' - - 'JAVA_TOOL_OPTIONS="-Xmx3g"' - - 'GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.workers.max=8 -Dkotlin.incremental=false"' - - 'BRANCH_NAME=$BRANCH_NAME' - - 'EXAMPLE_EMBEDDING_METHOD="composite"' - dir: "example/ios/Supporting Files" - waitFor: - - localPublish - - compileExampleAndroidUsingModules - -timeout: 3000s -options: - machineType: 'N1_HIGHCPU_8' - -# In future we have to save the build cache for faster builds: -# volumes: -# - name: 'build_cache' -# path: '/build_cache' -# - name: 'gcr.io/$PROJECT_ID/tar' -# id: compress_cache -# args: ['cpvzf', '/build_cache/cache.tgz', '-C', '/build_cache', '/build_cache/.gradle'] -# waitFor: ['build'] -# volumes: -# - name: 'build_cache' -# path: '/build_cache'