-
-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathPreferences.kt
More file actions
73 lines (62 loc) · 2 KB
/
Copy pathPreferences.kt
File metadata and controls
73 lines (62 loc) · 2 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
package processing.app
import androidx.compose.runtime.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.InputStream
import java.nio.file.*
import java.util.Properties
const val PREFERENCES_FILE_NAME = "preferences.txt"
const val DEFAULTS_FILE_NAME = "defaults.txt"
fun PlatformStart(){
Platform.inst ?: Platform.init()
}
@Composable
fun loadPreferences(): Properties{
PlatformStart()
val settingsFolder = Platform.getSettingsFolder()
val preferencesFile = settingsFolder.resolve(PREFERENCES_FILE_NAME)
if(!preferencesFile.exists()){
preferencesFile.createNewFile()
}
watchFile(preferencesFile)
return Properties().apply {
load(ClassLoader.getSystemResourceAsStream(DEFAULTS_FILE_NAME) ?: InputStream.nullInputStream())
load(preferencesFile.inputStream())
}
}
@Composable
fun watchFile(file: File): Any? {
val scope = rememberCoroutineScope()
var event by remember(file) { mutableStateOf<WatchEvent<*>?> (null) }
DisposableEffect(file){
val fileSystem = FileSystems.getDefault()
val watcher = fileSystem.newWatchService()
var active = true
val path = file.toPath()
val parent = path.parent
val key = parent.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY)
scope.launch(Dispatchers.IO) {
while (active) {
for (modified in key.pollEvents()) {
if (modified.context() != path.fileName) continue
event = modified
}
}
}
onDispose {
active = false
key.cancel()
watcher.close()
}
}
return event
}
val LocalPreferences = compositionLocalOf<Properties> { error("No preferences provided") }
@Composable
fun PreferencesProvider(content: @Composable () -> Unit){
val preferences = loadPreferences()
CompositionLocalProvider(LocalPreferences provides preferences){
content()
}
}