ProCraft for Android: An Android native painting app written in Rust
Rust
fix(brushes): keep the brush library in a file, not preferences
Josh0ea26faf9140
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.ktindex ebc95aa..98563c2 100644--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt@@ -445,8 +445,12 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {var transformBox by mutableStateOf<TransformBox?>(null)private setprivate val transformPrefs = app.getSharedPreferences("transform", android.content.Context.MODE_PRIVATE)- /** The brush library as edited, kept between artworks and launches. */+ /** The brushes in use and what has shipped, kept between artworks and launches. */private val brushPrefs = app.getSharedPreferences("brushes", android.content.Context.MODE_PRIVATE)+ /** The brush library as edited, in a file: brought-in brushes' images make it too big for preferences. */+ private val brushLibraryFile = File(app.filesDir, "brushes/library.json")+ /** Writes of the library, one at a time. */+ private val brushLibraryWrites = Mutex()var transformKind by mutableStateOf(enumPref(TRANSFORM_KIND, TransformKind.FREEFORM))private setvar interpolation by mutableStateOf(enumPref(INTERPOLATION, Interpolation.BILINEAR))@@ -1877,19 +1881,22 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {* takes half a second, so callers off the main thread do this before [start].*/private fun loadBrushes(s: CanvasSession) {- // the library as kept, else edits kept by earlier versions- val kept = brushPrefs.getString(BRUSH_LIBRARY, null)- val loaded = kept != null && s.loadBrushLibrary(kept)+ // the library as kept (in its file; earlier versions kept it in preferences: moved once), else+ // edits kept by earlier versions+ var loaded = brushLibraryFile.exists() && s.loadBrushLibraryFile(brushLibraryFile.path)+ if (!loaded) {+ val kept = brushPrefs.getString(BRUSH_LIBRARY, null)+ loaded = kept != null && s.loadBrushLibrary(kept)+ if (loaded && s.saveBrushLibraryFile(brushLibraryFile.path)) brushPrefs.edit().remove(BRUSH_LIBRARY).apply()+ }if (!loaded) brushPrefs.getString(BRUSH_CHANGES, null)?.let { s.applyBrushChanges(it) }// brushes and sets shipped since the library was kept join it, onceval seen = brushPrefs.getString(BRUSHES_SEEN, null)?.split(',')?.mapNotNull { it.toUIntOrNull() } ?: FIRST_SHIPPEDval shipped = if (loaded) s.addShippedBrushes(seen) else s.shippedBrushCounts()if (shipped != seen || !brushPrefs.contains(BRUSHES_SEEN)) {- brushPrefs.edit().apply {- // kept with them, or the next start would load the library without them- if (loaded) putString(BRUSH_LIBRARY, s.savedBrushLibrary())- putString(BRUSHES_SEEN, shipped.joinToString(","))- }.apply()+ // kept with them, or the next start would load the library without them+ if (loaded) s.saveBrushLibraryFile(brushLibraryFile.path)+ brushPrefs.edit().putString(BRUSHES_SEEN, shipped.joinToString(",")).apply()}// the brushes in use as they were left (they go by place in the kept library)if (loaded) brushPrefs.getString(BRUSH_CHOICES, null)?.let { s.loadBrushChoices(it) }@@ -3144,7 +3151,8 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {readSliders()previews.clear()shadedNames.clear()- brushPrefs.edit().putString(BRUSH_LIBRARY, s.savedBrushLibrary()).putString(BRUSH_CHOICES, s.savedBrushChoices()).apply()+ keepBrushLibrary(s)+ brushPrefs.edit().putString(BRUSH_CHOICES, s.savedBrushChoices()).apply()}fun duplicateBrush(b: BrushInfo) {@@ -3716,7 +3724,15 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {val value = if (size) this.size else opacityif (notchAt(size, value) != null) s.removeSliderNotch(size, value) else s.addSliderNotch(size, value)readNotches()- brushPrefs.edit().putString(BRUSH_LIBRARY, s.savedBrushLibrary()).apply()+ keepBrushLibrary(s)+ }++ /** Keeps the library as it is now in its file, off the main thread. */+ private fun keepBrushLibrary(s: CanvasSession) {+ viewModelScope.launch(Dispatchers.IO) {+ // each write takes the library as it is when it runs, so the last one is the latest+ brushLibraryWrites.withLock { runCatching { s.saveBrushLibraryFile(brushLibraryFile.path) } }+ }}private fun readNotches() {@@ -5824,6 +5840,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {GlitchKind.DIVERGE to listOf(0.98f, -0.5f, 0.85f, 0.5f),)const val BRUSH_CHANGES = "changes"+ /** Where earlier versions kept the library (now in a file). */const val BRUSH_LIBRARY = "library"/** How big the studio's Shape and Grain Source rows show their image (pixels across). */const val SOURCE_ROW_PX = 88diff --git a/apps/procraft-android/src/brush_library.rs b/apps/procraft-android/src/brush_library.rsindex 2e3f0fb..690347b 100644--- a/apps/procraft-android/src/brush_library.rs+++ b/apps/procraft-android/src/brush_library.rs@@ -606,6 +606,29 @@ impl CanvasSession {serde_json::to_string(&sets).unwrap_or_default()}+ /// Keeps the library in the file at `path` (its folder made if missing), replaced whole: it+ /// can be large, with the images of brushes brought in. False if it couldn't be written.+ pub fn save_brush_library_file(&self, path: String) -> bool {+ let json = self.saved_brush_library();+ let path = std::path::Path::new(&path);+ if let Some(dir) = path.parent() {+ let _ = std::fs::create_dir_all(dir);+ }+ let written = crate::project::write_atomically(path, |p| {+ std::fs::write(p, json.as_bytes()).map_err(|e| crate::project::file_error("keeping the brushes", e))+ });+ if let Err(e) = &written {+ log::error!("{e}");+ }+ written.is_ok()+ }++ /// Puts back a library kept with [`Self::save_brush_library_file`]; false, changing nothing,+ /// if there is none or it can't be read.+ pub fn load_brush_library_file(&self, path: String) -> bool {+ std::fs::read_to_string(&path).is_ok_and(|json| self.load_brush_library(json))+ }+/// Puts back a library kept with [`Self::saved_brush_library`]; false, changing nothing, if it/// can't be read.pub fn load_brush_library(&self, json: String) -> bool {diff --git a/apps/procraft-android/src/tests.rs b/apps/procraft-android/src/tests.rsindex 72003b4..b74e117 100644--- a/apps/procraft-android/src/tests.rs+++ b/apps/procraft-android/src/tests.rs@@ -777,9 +777,14 @@ fn an_imported_brush_shows_its_own_preview_until_changed() {(p.rgba[((50 * w + 5) * 4 + 3) as usize], p.rgba[((10 * w + 160) * 4 + 3) as usize])};assert_eq!(alpha(&s), (255, 0));- // kept with the library, and written back out as it came+ // kept with the library (in a file of its own), and written back out as it camelet Some(other) = session(100, 100) else { return };- assert!(other.load_brush_library(s.saved_brush_library()));+ let dir = std::env::temp_dir().join(format!("procraft-library-{}", std::process::id()));+ let kept = dir.join("brushes").join("library.json").to_string_lossy().into_owned();+ assert!(s.save_brush_library_file(kept.clone()));+ assert!(other.load_brush_library_file(kept.clone()));+ let _ = std::fs::remove_dir_all(&dir);+ assert!(!other.load_brush_library_file(kept), "none kept");assert_eq!(alpha(&other), (255, 0));let out = brushfile::read(&s.brush_as_file(set, 0).unwrap()).unwrap();assert_eq!(out.thumbnail.as_deref(), Some(thumbnail.as_slice()));