Meshtastic-Android/app/src/main/java/com/geeksville/mesh/model/UIState.kt

377 lines
14 KiB
Kotlin
Raw Normal View History

/*
2025-01-02 06:50:26 -03:00
* Copyright (c) 2025 Meshtastic LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
2020-02-17 13:34:52 -08:00
package com.geeksville.mesh.model
import android.app.Application
2020-03-17 11:35:19 -07:00
import android.net.Uri
2020-02-18 12:22:45 -08:00
import android.os.RemoteException
2025-08-20 18:49:06 -04:00
import androidx.compose.material3.SnackbarDuration
2025-05-17 11:39:53 -05:00
import androidx.compose.material3.SnackbarHostState
2025-08-20 18:49:06 -04:00
import androidx.compose.material3.SnackbarResult
2022-04-22 17:22:06 -03:00
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
2022-09-15 22:24:04 -03:00
import androidx.lifecycle.asLiveData
2020-09-23 22:47:45 -04:00
import androidx.lifecycle.viewModelScope
import com.geeksville.mesh.AdminProtos
import com.geeksville.mesh.AppOnlyProtos
import com.geeksville.mesh.ChannelProtos
import com.geeksville.mesh.ChannelProtos.ChannelSettings
2022-09-12 00:26:12 -03:00
import com.geeksville.mesh.ConfigProtos.Config
import com.geeksville.mesh.LocalOnlyProtos.LocalConfig
2022-11-22 22:01:37 -03:00
import com.geeksville.mesh.LocalOnlyProtos.LocalModuleConfig
import com.geeksville.mesh.MeshProtos
import com.geeksville.mesh.channel
import com.geeksville.mesh.channelSet
import com.geeksville.mesh.channelSettings
import com.geeksville.mesh.config
import com.geeksville.mesh.copy
import com.geeksville.mesh.repository.radio.MeshActivity
import com.geeksville.mesh.repository.radio.RadioInterfaceService
import com.geeksville.mesh.service.MeshServiceNotifications
import dagger.hilt.android.lifecycle.HiltViewModel
2020-09-23 22:47:45 -04:00
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.shareIn
2024-05-27 09:56:26 -03:00
import kotlinx.coroutines.flow.stateIn
2020-09-23 22:47:45 -04:00
import kotlinx.coroutines.launch
import org.meshtastic.core.data.repository.FirmwareReleaseRepository
import org.meshtastic.core.data.repository.MeshLogRepository
import org.meshtastic.core.data.repository.NodeRepository
import org.meshtastic.core.data.repository.QuickChatActionRepository
import org.meshtastic.core.data.repository.RadioConfigRepository
2025-09-24 16:23:05 -04:00
import org.meshtastic.core.database.entity.MyNodeEntity
import org.meshtastic.core.database.entity.QuickChatAction
import org.meshtastic.core.database.entity.asDeviceVersion
import org.meshtastic.core.database.model.Node
2025-09-23 15:52:09 -04:00
import org.meshtastic.core.datastore.UiPreferencesDataSource
import org.meshtastic.core.model.util.toChannelSet
2025-09-30 16:55:56 -04:00
import org.meshtastic.core.service.IMeshService
import org.meshtastic.core.service.ServiceRepository
import org.meshtastic.core.strings.R
import timber.log.Timber
import javax.inject.Inject
// Given a human name, strip out the first letter of the first three words and return that as the
// initials for
// that user, ignoring emojis. If the original name is only one word, strip vowels from the original
// name and if the result is 3 or more characters, use the first three characters. If not, just take
// the first 3 characters of the original name.
fun getInitials(fullName: String): String {
val maxInitialLength = 4
val minWordCountForInitials = 2
val name = fullName.trim().withoutEmojis()
val words = name.split(Regex("\\s+")).filter { it.isNotEmpty() }
val initials =
when (words.size) {
in 0 until minWordCountForInitials -> {
val nameWithoutVowels =
if (name.isNotEmpty()) {
name.first() + name.drop(1).filterNot { c -> c.lowercase() in "aeiou" }
} else {
""
}
if (nameWithoutVowels.length >= maxInitialLength) nameWithoutVowels else name
}
2025-05-17 11:39:53 -05:00
else -> words.map { it.first() }.joinToString("")
}
return initials.take(maxInitialLength)
}
2020-03-15 16:30:12 -07:00
private fun String.withoutEmojis(): String = filterNot { char -> char.isSurrogate() }
/**
* Builds a [Channel] list from the difference between two [ChannelSettings] lists. Only changes are included in the
* resulting list.
*
* @param new The updated [ChannelSettings] list.
* @param old The current [ChannelSettings] list (required when disabling unused channels).
* @return A [Channel] list containing only the modified channels.
*/
internal fun getChannelList(new: List<ChannelSettings>, old: List<ChannelSettings>): List<ChannelProtos.Channel> =
buildList {
for (i in 0..maxOf(old.lastIndex, new.lastIndex)) {
if (old.getOrNull(i) != new.getOrNull(i)) {
add(
channel {
role =
when (i) {
0 -> ChannelProtos.Channel.Role.PRIMARY
in 1..new.lastIndex -> ChannelProtos.Channel.Role.SECONDARY
else -> ChannelProtos.Channel.Role.DISABLED
}
index = i
settings = new.getOrNull(i) ?: channelSettings {}
},
)
}
}
}
2025-05-17 11:39:53 -05:00
data class Contact(
val contactKey: String,
val shortName: String,
val longName: String,
val lastMessageTime: String?,
val lastMessageText: String?,
val unreadCount: Int,
val messageCount: Int,
val isMuted: Boolean,
2025-05-20 16:05:40 -05:00
val isUnmessageable: Boolean,
val nodeColors: Pair<Int, Int>? = null,
)
@Suppress("LongParameterList", "LargeClass", "UnusedPrivateProperty")
@HiltViewModel
class UIViewModel
@Inject
constructor(
private val app: Application,
private val nodeDB: NodeRepository,
private val radioConfigRepository: RadioConfigRepository,
private val serviceRepository: ServiceRepository,
radioInterfaceService: RadioInterfaceService,
meshLogRepository: MeshLogRepository,
2022-08-11 16:43:26 +01:00
private val quickChatActionRepository: QuickChatActionRepository,
firmwareReleaseRepository: FirmwareReleaseRepository,
2025-09-23 15:52:09 -04:00
private val uiPreferencesDataSource: UiPreferencesDataSource,
private val meshServiceNotifications: MeshServiceNotifications,
) : ViewModel() {
2020-09-23 22:47:45 -04:00
2025-09-23 15:52:09 -04:00
val theme: StateFlow<Int> = uiPreferencesDataSource.theme
2025-05-17 11:39:53 -05:00
val firmwareEdition = meshLogRepository.getMyNodeInfo().map { nodeInfo -> nodeInfo?.firmwareEdition }
val clientNotification: StateFlow<MeshProtos.ClientNotification?> = serviceRepository.clientNotification
fun clearClientNotification(notification: MeshProtos.ClientNotification) {
serviceRepository.clearClientNotification()
meshServiceNotifications.clearClientNotification(notification)
}
/**
* Emits events for mesh network send/receive activity. This is a SharedFlow to ensure all events are delivered,
* even if they are the same.
*/
val meshActivity: SharedFlow<MeshActivity> =
radioInterfaceService.meshActivity.shareIn(viewModelScope, SharingStarted.Eagerly, 0)
2025-05-17 11:39:53 -05:00
data class AlertData(
val title: String,
val message: String? = null,
val html: String? = null,
val onConfirm: (() -> Unit)? = null,
val onDismiss: (() -> Unit)? = null,
val choices: Map<String, () -> Unit> = emptyMap(),
2025-05-17 11:39:53 -05:00
)
private val _currentAlert: MutableStateFlow<AlertData?> = MutableStateFlow(null)
val currentAlert = _currentAlert.asStateFlow()
fun showAlert(
title: String,
message: String? = null,
html: String? = null,
onConfirm: (() -> Unit)? = {},
dismissable: Boolean = true,
choices: Map<String, () -> Unit> = emptyMap(),
2025-05-17 11:39:53 -05:00
) {
_currentAlert.value =
AlertData(
title = title,
message = message,
html = html,
onConfirm = {
onConfirm?.invoke()
dismissAlert()
2025-05-17 11:39:53 -05:00
},
onDismiss = { if (dismissable) dismissAlert() },
choices = choices,
2025-05-17 11:39:53 -05:00
)
}
private fun dismissAlert() {
_currentAlert.value = null
}
val meshService: IMeshService?
get() = serviceRepository.meshService
2023-02-02 17:13:44 -03:00
private val localConfig = MutableStateFlow<LocalConfig>(LocalConfig.getDefaultInstance())
val config
get() = localConfig.value
2022-06-20 22:46:45 -03:00
private val _moduleConfig = MutableStateFlow<LocalModuleConfig>(LocalModuleConfig.getDefaultInstance())
2022-11-22 22:01:37 -03:00
val moduleConfig: StateFlow<LocalModuleConfig> = _moduleConfig
val module
get() = _moduleConfig.value
2022-11-22 22:01:37 -03:00
private val _channels = MutableStateFlow(channelSet {})
val channels: StateFlow<AppOnlyProtos.ChannelSet>
get() = _channels
2022-09-12 19:07:30 -03:00
2025-05-17 11:39:53 -05:00
val quickChatActions
get() =
quickChatActionRepository
.getAllActions()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
2022-08-11 16:43:26 +01:00
// hardware info about our local device (can be null)
val myNodeInfo: StateFlow<MyNodeEntity?>
get() = nodeDB.myNodeInfo
val ourNodeInfo: StateFlow<Node?>
get() = nodeDB.ourNodeInfo
2025-08-20 18:49:06 -04:00
val snackBarHostState = SnackbarHostState()
fun showSnackBar(text: Int) = showSnackBar(app.getString(text))
2025-08-20 18:49:06 -04:00
fun showSnackBar(
text: String,
actionLabel: String? = null,
withDismissAction: Boolean = false,
duration: SnackbarDuration = if (actionLabel == null) SnackbarDuration.Short else SnackbarDuration.Indefinite,
onActionPerformed: (() -> Unit) = {},
onDismissed: (() -> Unit) = {},
) = viewModelScope.launch {
snackBarHostState.showSnackbar(text, actionLabel, withDismissAction, duration).run {
when (this) {
SnackbarResult.ActionPerformed -> onActionPerformed()
SnackbarResult.Dismissed -> onDismissed()
}
}
}
2020-04-07 17:42:31 -07:00
init {
serviceRepository.errorMessage
.filterNotNull()
.onEach {
showAlert(
title = app.getString(R.string.client_notification),
message = it,
onConfirm = { serviceRepository.clearErrorMessage() },
dismissable = false,
)
}
.launchIn(viewModelScope)
radioConfigRepository.localConfigFlow.onEach { config -> localConfig.value = config }.launchIn(viewModelScope)
radioConfigRepository.moduleConfigFlow
.onEach { config -> _moduleConfig.value = config }
.launchIn(viewModelScope)
radioConfigRepository.channelSetFlow
.onEach { channelSet -> _channels.value = channelSet }
.launchIn(viewModelScope)
Timber.d("ViewModel created")
2020-04-07 17:42:31 -07:00
}
private val _sharedContactRequested: MutableStateFlow<AdminProtos.SharedContact?> = MutableStateFlow(null)
val sharedContactRequested: StateFlow<AdminProtos.SharedContact?>
get() = _sharedContactRequested.asStateFlow()
fun setSharedContactRequested(sharedContact: AdminProtos.SharedContact?) {
_sharedContactRequested.value = sharedContact
}
// Connection state to our radio device
val connectionState
get() = serviceRepository.connectionState
private val _requestChannelSet = MutableStateFlow<AppOnlyProtos.ChannelSet?>(null)
val requestChannelSet: StateFlow<AppOnlyProtos.ChannelSet?>
get() = _requestChannelSet
2022-05-17 17:29:21 -03:00
fun requestChannelUrl(url: Uri) = runCatching { _requestChannelSet.value = url.toChannelSet() }
.onFailure { ex ->
Timber.e(ex, "Channel url error")
showSnackBar(R.string.channel_invalid)
}
2022-05-17 17:29:21 -03:00
val latestStableFirmwareRelease = firmwareReleaseRepository.stableRelease.mapNotNull { it?.asDeviceVersion() }
/** Called immediately after activity observes requestChannelUrl */
2022-05-17 17:29:21 -03:00
fun clearRequestChannelUrl() {
_requestChannelSet.value = null
2022-05-17 17:29:21 -03:00
}
2022-09-12 00:26:12 -03:00
var region: Config.LoRaConfig.RegionCode
2022-09-18 18:35:13 -03:00
get() = config.lora.region
set(value) {
2022-09-12 00:26:12 -03:00
updateLoraConfig { it.copy { region = value } }
2021-02-05 21:29:28 -08:00
}
override fun onCleared() {
super.onCleared()
Timber.d("ViewModel cleared")
}
private inline fun updateLoraConfig(crossinline body: (Config.LoRaConfig) -> Config.LoRaConfig) {
2022-09-12 00:26:12 -03:00
val data = body(config.lora)
2022-10-11 16:27:36 -03:00
setConfig(config { lora = data })
2022-09-12 00:26:12 -03:00
}
// Set the radio config (also updates our saved copy in preferences)
2022-10-11 16:27:36 -03:00
fun setConfig(config: Config) {
try {
meshService?.setConfig(config.toByteArray())
} catch (ex: RemoteException) {
Timber.e(ex, "Set config error")
}
2021-02-27 11:44:05 +08:00
}
fun addQuickChatAction(action: QuickChatAction) =
viewModelScope.launch(Dispatchers.IO) { quickChatActionRepository.upsert(action) }
2022-08-11 16:43:26 +01:00
fun deleteQuickChatAction(action: QuickChatAction) =
viewModelScope.launch(Dispatchers.IO) { quickChatActionRepository.delete(action) }
fun updateActionPositions(actions: List<QuickChatAction>) {
viewModelScope.launch(Dispatchers.IO) {
2022-08-16 12:25:40 +01:00
for (position in actions.indices) {
quickChatActionRepository.setItemPosition(actions[position].uuid, position)
}
}
}
val tracerouteResponse: LiveData<String?>
get() = serviceRepository.tracerouteResponse.asLiveData()
fun clearTracerouteResponse() {
serviceRepository.clearTracerouteResponse()
}
2025-09-23 15:52:09 -04:00
val appIntroCompleted: StateFlow<Boolean> = uiPreferencesDataSource.appIntroCompleted
fun onAppIntroCompleted() {
2025-09-23 15:52:09 -04:00
uiPreferencesDataSource.setAppIntroCompleted(true)
}
}