forked from processing/processing4
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPreferences.kt
More file actions
208 lines (175 loc) · 7.31 KB
/
Preferences.kt
File metadata and controls
208 lines (175 loc) · 7.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package processing.app
import androidx.compose.runtime.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.dropWhile
import kotlinx.coroutines.launch
import processing.utils.Settings
import java.io.File
import java.io.InputStream
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.StandardWatchEventKinds
import java.nio.file.WatchEvent
import java.util.*
/*
The ReactiveProperties class extends the standard Java Properties class
to provide reactive capabilities using Jetpack Compose's mutableStateMapOf.
This allows UI components to automatically update when preference values change.
*/
class ReactiveProperties : Properties() {
val snapshotStateMap = mutableStateMapOf<String, String>()
override fun setProperty(key: String, value: String) {
super.setProperty(key, value)
snapshotStateMap[key] = value
}
override fun getProperty(key: String): String? {
return snapshotStateMap[key] ?: super.getProperty(key)
}
operator fun get(key: String): String? = getProperty(key)
operator fun set(key: String, value: String) {
setProperty(key, value)
}
}
/*
A CompositionLocal to provide access to the ReactiveProperties instance
throughout the composable hierarchy.
*/
val LocalPreferences = compositionLocalOf<ReactiveProperties> { error("No preferences provided") }
const val PREFERENCES_FILE_NAME = "preferences.txt"
const val DEFAULTS_FILE_NAME = "defaults.txt"
/*
This composable function sets up a preferences provider that manages application settings.
It initializes the preferences from a file, watches for changes to that file, and saves
any updates back to the file. It uses a ReactiveProperties class to allow for reactive
updates in the UI when preferences change.
usage:
PreferencesProvider {
// Your app content here
}
to access preferences:
val preferences = LocalPreferences.current
val someSetting = preferences["someKey"] ?: "defaultValue"
preferences["someKey"] = "newValue"
This will automatically save to the preferences file and update any UI components
that are observing that key.
to override the preferences file (for testing, etc)
System.setProperty("processing.app.preferences.file", "/path/to/your/preferences.txt")
to override the debounce time (in milliseconds)
System.setProperty("processing.app.preferences.debounce", "200")
*/
@OptIn(FlowPreview::class)
@Composable
fun PreferencesProvider(content: @Composable () -> Unit) {
val preferencesFileOverride: File? = System.getProperty("processing.app.preferences.file")?.let { File(it) }
val preferencesDebounceOverride: Long? = System.getProperty("processing.app.preferences.debounce")?.toLongOrNull()
val settingsFolder = Settings.getFolder()
val preferencesFile = preferencesFileOverride ?: settingsFolder.resolve(PREFERENCES_FILE_NAME)
if (!preferencesFile.exists()) {
preferencesFile.mkdirs()
preferencesFile.createNewFile()
}
remember {
// check if the file has backward slashes
if (preferencesFile.readText().contains("\\")) {
val correctedText = preferencesFile.readText().replace("\\", "/")
preferencesFile.writeText(correctedText)
}
}
val update = watchFile(preferencesFile)
val properties = remember(preferencesFile, update) {
ReactiveProperties().apply {
val defaultsStream = ClassLoader.getSystemResourceAsStream(DEFAULTS_FILE_NAME)
?: InputStream.nullInputStream()
defaultsStream
.reader(Charsets.UTF_8)
.use { reader ->
load(reader)
}
preferencesFile
.inputStream()
.reader(Charsets.UTF_8)
.use { reader ->
load(reader)
}
}
}
val initialState = remember(properties) { properties.snapshotStateMap.toMap() }
// Listen for changes to the preferences and save them to file
LaunchedEffect(properties) {
snapshotFlow { properties.snapshotStateMap.toMap() }
.dropWhile { it == initialState }
.debounce(preferencesDebounceOverride ?: 100)
.collect {
// Save the preferences to file, sorted alphabetically
preferencesFile.outputStream().use { output ->
output.write(
properties.entries
.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.key.toString() })
.joinToString("\n") { (key, value) -> "$key=$value" }
.toByteArray()
)
// Reload legacy Preferences
Preferences.init()
output.close()
}
}
}
CompositionLocalProvider(LocalPreferences provides properties) {
content()
}
}
/*
This composable function watches a specified file for modifications. When the file is modified,
it updates a state variable with the latest WatchEvent. This can be useful for triggering UI updates
or other actions in response to changes in the file.
To watch the file at the fasted speed (for testing) set the following system property:
System.setProperty("processing.app.watchfile.forced", "true")
*/
@Composable
fun watchFile(file: File): Any? {
val forcedWatch: Boolean = System.getProperty("processing.app.watchfile.forced").toBoolean()
val scope = rememberCoroutineScope()
var event by remember(file) { mutableStateOf<WatchEvent<*>?>(null) }
DisposableEffect(file) {
val fileSystem = FileSystems.getDefault()
val watcher = fileSystem.newWatchService()
var active = true
// In forced mode we just poll the last modified time of the file
// This is not efficient but works better for testing with temp files
val toWatch = { file.lastModified() }
var state = toWatch()
val path = file.toPath()
val parent = path.parent
val key = parent.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY)
scope.launch(Dispatchers.IO) {
while (active) {
if (forcedWatch) {
if (toWatch() == state) continue
state = toWatch()
event = object : WatchEvent<Path> {
override fun count(): Int = 1
override fun context(): Path = file.toPath().fileName
override fun kind(): WatchEvent.Kind<Path> = StandardWatchEventKinds.ENTRY_MODIFY
override fun toString(): String = "ForcedEvent(${context()})"
}
continue
} else {
for (modified in key.pollEvents()) {
if (modified.context() != path.fileName) continue
event = modified
}
delay(10)
}
}
}
onDispose {
active = false
key.cancel()
watcher.close()
}
}
return event
}