Skip to content

Commit

Permalink
add warning dialog at startup if a newer data version is used with an…
Browse files Browse the repository at this point in the history
… old app version
  • Loading branch information
sunny-chung committed Feb 17, 2024
1 parent 7bcbc72 commit bf0d6ef
Show file tree
Hide file tree
Showing 10 changed files with 308 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import com.sunnychung.application.multiplatform.hellohttp.manager.SingleInstance
import com.sunnychung.application.multiplatform.hellohttp.network.GrpcTransportClient
import com.sunnychung.application.multiplatform.hellohttp.network.WebSocketTransportClient
import com.sunnychung.application.multiplatform.hellohttp.repository.ApiSpecificationCollectionRepository
import com.sunnychung.application.multiplatform.hellohttp.repository.OperationalRepository
import com.sunnychung.application.multiplatform.hellohttp.repository.ProjectCollectionRepository
import com.sunnychung.application.multiplatform.hellohttp.repository.RequestCollectionRepository
import com.sunnychung.application.multiplatform.hellohttp.repository.ResponseCollectionRepository
Expand Down Expand Up @@ -42,6 +43,7 @@ object AppContext {
val ResponseCollectionRepository = ResponseCollectionRepository()
val ApiSpecificationCollectionRepository = ApiSpecificationCollectionRepository()
val UserPreferenceRepository = UserPreferenceRepository()
val OperationalRepository = OperationalRepository()

val DialogViewModel = DialogViewModel()
val ErrorMessagePromptViewModel = ErrorMessagePromptViewModel()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,30 @@
package com.sunnychung.application.multiplatform.hellohttp

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.AlertDialog
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
import com.jayway.jsonpath.Configuration
Expand All @@ -17,14 +33,18 @@ import com.jayway.jsonpath.spi.json.JacksonJsonProvider
import com.jayway.jsonpath.spi.json.JsonProvider
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider
import com.jayway.jsonpath.spi.mapper.MappingProvider
import com.sunnychung.application.multiplatform.hellohttp.document.OperationalDI
import com.sunnychung.application.multiplatform.hellohttp.document.UserPreferenceDI
import com.sunnychung.application.multiplatform.hellohttp.error.MultipleProcessError
import com.sunnychung.application.multiplatform.hellohttp.model.Version
import com.sunnychung.application.multiplatform.hellohttp.platform.isMacOs
import com.sunnychung.application.multiplatform.hellohttp.ux.AppView
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import net.harawata.appdirs.AppDirsFactory
import java.awt.Dimension
import java.io.File
import java.util.concurrent.atomic.AtomicInteger
import kotlin.system.exitProcess

fun main() {
Expand All @@ -36,43 +56,130 @@ fun main() {
AppContext.SingleInstanceProcessService.apply { dataDir = File(appDir) }.enforce()
} catch (e: MultipleProcessError) {
application {
Window(title = "Hello HTTP", onCloseRequest = { exitProcess(1) } ) {
Window(title = "Hello HTTP", onCloseRequest = { exitProcess(1) }) {
AlertDialog(
onDismissRequest = { exitProcess(1) },
text = { Text("Another instance of Hello HTTP is running. Please close that process before starting another one.") },
confirmButton = { Text(text = "Close", modifier = Modifier.clickable { exitProcess(1) }.padding(10.dp)) },
confirmButton = {
Text(
text = "Close",
modifier = Modifier.clickable { exitProcess(1) }.padding(10.dp)
)
},
)
}
}
exitProcess(1)
}
println("Preparing to start")
AppContext.PersistenceManager.initialize()
AppContext.AutoBackupManager.backupNow()
val preference = AppContext.UserPreferenceRepository.read(UserPreferenceDI())!!.preference
AppContext.UserPreferenceViewModel.setColorTheme(preference.colourTheme)
}
// json path initialization
Configuration.setDefaults(object : Configuration.Defaults {
override fun jsonProvider(): JsonProvider = JacksonJsonProvider()
override fun options(): MutableSet<Option> = mutableSetOf()
override fun mappingProvider(): MappingProvider = JacksonMappingProvider()
})
application {
Window(
title = "Hello HTTP",
onCloseRequest = ::exitApplication,
icon = painterResource("image/appicon.svg"),
state = rememberWindowState(width = 1024.dp, height = 560.dp)
) {
with(LocalDensity.current) {
window.minimumSize = if (isMacOs()) {
Dimension(800, 450)

val dataVersion = AppContext.OperationalRepository.read(OperationalDI())!!.data.appVersion.let { Version(it) }
val appVersion = AppContext.MetadataManager.version.let { Version(it) }

val prepareCounter = AtomicInteger(0)

application {
var isContinue by remember { mutableStateOf<Boolean?>(null) }
var isPrepared by remember { mutableStateOf(false) }
if (isContinue == null) {
if (dataVersion > appVersion) {
DataLossWarningDialogWindow(
dataVersion = dataVersion.versionName,
appVersion = appVersion.versionName
) {
isContinue = it
}
} else {
isContinue = true
}
}
if (isContinue == false) {
println("Exit")
exitApplication()
} else if (isContinue == true) {
LaunchedEffect(Unit) {
println("Preparing after continue")
if (prepareCounter.addAndGet(1) > 1) {
throw RuntimeException("Prepare more than once")
}

AppContext.OperationalRepository.read(OperationalDI())
.also {
it!!.data.appVersion = appVersion.versionName
AppContext.OperationalRepository.awaitUpdate(OperationalDI())
}
AppContext.AutoBackupManager.backupNow()
val preference = AppContext.UserPreferenceRepository.read(UserPreferenceDI())!!.preference
AppContext.UserPreferenceViewModel.setColorTheme(preference.colourTheme)

// json path initialization
Configuration.setDefaults(object : Configuration.Defaults {
override fun jsonProvider(): JsonProvider = JacksonJsonProvider()
override fun options(): MutableSet<Option> = mutableSetOf()
override fun mappingProvider(): MappingProvider = JacksonMappingProvider()
})

delay(500L)
isPrepared = true
}

if (isPrepared) {
Window(
title = "Hello HTTP",
onCloseRequest = ::exitApplication,
icon = painterResource("image/appicon.svg"),
state = rememberWindowState(width = 1024.dp, height = 560.dp)
) {
with(LocalDensity.current) {
window.minimumSize = if (isMacOs()) {
Dimension(800, 450)
} else {
Dimension(800.dp.roundToPx(), 450.dp.roundToPx())
}
}
AppView()
}
} else {
Dimension(800.dp.roundToPx(), 450.dp.roundToPx())
// dummy window to prevent application exit before the main window is loaded
Window(
title = "Hello HTTP",
icon = painterResource("image/appicon.svg"),
visible = false,
onCloseRequest = {}
) {}
}
}
}
}
}

@Composable
fun DataLossWarningDialogWindow(dataVersion: String, appVersion: String, onUserRespond: (Boolean) -> Unit) {
Window(
title = "Hello HTTP",
icon = painterResource("image/appicon.svg"),
onCloseRequest = { onUserRespond(false) },
resizable = false,
state = rememberWindowState(position = WindowPosition(Alignment.Center), width = 500.dp, height = 240.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(12.dp)
) {
Text(
"The version of this application ($appVersion) is older than your user data version " +
"($dataVersion). Continue using this application may lose some of your data (e.g. data " +
"for features that are only available in newer versions). Please upgrade this " +
"application if possible.\n\nContinue to use this old version?"
)
Spacer(modifier = Modifier.height(20.dp))
Row(horizontalArrangement = Arrangement.spacedBy(20.dp)) {
Button(onClick = { onUserRespond(true) }) { Text("Continue. Accept possible data loss.") }
Button(onClick = { onUserRespond(false) }) { Text("Exit") }
}
}
AppView()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ interface Identifiable {
sealed class DocumentIdentifier(val type: PersistenceDocumentType)

enum class PersistenceDocumentType {
ProjectAndEnvironments, Requests, Responses, ApiSpecifications, UserPreference
ProjectAndEnvironments, Requests, Responses, ApiSpecifications, UserPreference, Operational
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.sunnychung.application.multiplatform.hellohttp.document

import com.sunnychung.application.multiplatform.hellohttp.annotation.DocumentRoot
import com.sunnychung.application.multiplatform.hellohttp.annotation.Persisted
import com.sunnychung.application.multiplatform.hellohttp.model.OperationalInfo
import kotlinx.serialization.Serializable

@DocumentRoot
@Persisted
@Serializable
data class OperationalDocument(override val id: OperationalDI, var data: OperationalInfo) : Document<OperationalDI>

@Persisted
@Serializable
class OperationalDI : DocumentIdentifier(type = PersistenceDocumentType.Operational) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
return true
}

override fun hashCode(): Int {
return javaClass.hashCode()
}

override fun toString(): String {
return "OperationalDI()"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ package com.sunnychung.application.multiplatform.hellohttp.manager

import com.sunnychung.application.multiplatform.hellohttp.AppContext
import com.sunnychung.application.multiplatform.hellohttp.document.DocumentIdentifier
import com.sunnychung.application.multiplatform.hellohttp.document.OperationalDI
import com.sunnychung.application.multiplatform.hellohttp.document.OperationalDocument
import com.sunnychung.application.multiplatform.hellohttp.document.ProjectAndEnvironmentsDI
import com.sunnychung.application.multiplatform.hellohttp.document.ProjectCollection
import com.sunnychung.application.multiplatform.hellohttp.document.UserPreferenceDI
import com.sunnychung.application.multiplatform.hellohttp.document.UserPreferenceDocument
import com.sunnychung.application.multiplatform.hellohttp.model.ColourTheme
import com.sunnychung.application.multiplatform.hellohttp.model.OperationalInfo
import com.sunnychung.application.multiplatform.hellohttp.model.UserPreference
import com.sunnychung.application.multiplatform.hellohttp.util.uuidString
import kotlinx.coroutines.sync.Mutex
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
Expand Down Expand Up @@ -69,6 +73,15 @@ class PersistenceManager {
colourTheme = ColourTheme.Dark
))
}
AppContext.OperationalRepository.readOrCreate(OperationalDI()) { id ->
OperationalDocument(
id = id,
data = OperationalInfo(
appVersion = AppContext.MetadataManager.version,
installationId = uuidString(),
)
)
}
}


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.sunnychung.application.multiplatform.hellohttp.model

import com.sunnychung.application.multiplatform.hellohttp.annotation.Persisted
import kotlinx.serialization.Serializable

@Persisted
@Serializable
data class OperationalInfo(
var appVersion: String,
var installationId: String,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.sunnychung.application.multiplatform.hellohttp.model

class Version(val versionName: String) : Comparable<Version> {
private val components = versionName.split("[\\.-]+".toRegex())
override operator fun compareTo(other: Version): Int {
(0 .. maxOf(components.lastIndex, other.components.lastIndex)).forEach { i ->
val compareResult = this.numericComponent(i).compareTo(other.numericComponent(i))
if (compareResult != 0) {
return compareResult
}
}
return 0
}

override fun equals(other: Any?): Boolean {
if (other !is Version) return false
return compareTo(other) == 0
}

fun numericComponent(index: Int): Int {
return if (index > components.lastIndex) {
0
} else {
components[index].toIntOrNull() ?: -1
}
}

override fun toString(): String = versionName
}
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,11 @@ sealed class BaseCollectionRepository<T : Document<ID>, ID : DocumentIdentifier>
}
}

suspend fun awaitUpdate(identifier: ID) {
notifyUpdated(identifier)
update(identifier)
}

open suspend fun delete(identifier: ID) {
withLock(identifier) {
with(persistenceManager) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.sunnychung.application.multiplatform.hellohttp.repository

import com.sunnychung.application.multiplatform.hellohttp.document.OperationalDI
import com.sunnychung.application.multiplatform.hellohttp.document.OperationalDocument
import kotlinx.serialization.serializer

class OperationalRepository : BaseCollectionRepository<OperationalDocument, OperationalDI>(serializer()) {
override fun relativeFilePath(id: OperationalDI): String = "operational.db"
}
Loading

0 comments on commit bf0d6ef

Please sign in to comment.