Skip to content

ProCraft for Android: An Android native painting app written in Rust

Rust

feat(gallery): artworks keep their place; held and dragged they move or stack, and a copy goes after its original

Josh0ac7c9280201
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.kt
index cb75037..48304d6 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
@@ -781,7 +781,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
refreshGallery()
}
}
- // the home screen's widget shows the newest artwork
+ // the home screen's widget shows the artwork worked on last
viewModelScope.launch(Dispatchers.IO) { io.github.artcraftandroid.procraft.gallery.RecentArtworkWidget.refresh(getApplication<Application>()) }
}
@@ -1588,7 +1588,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
}
/**
- * The home screen's Recent artwork widget was tapped: the newest artwork opens, once the window
+ * The home screen's Recent artwork widget was tapped: the artwork worked on last opens, once the window
* has its size (the app may only now be starting); nothing if one is already open.
*/
fun openMostRecent() {
@@ -1670,6 +1670,28 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
}
}
+ /** [e] dragged to [to] in the gallery or stack showing (its place in the list without it). */
+ fun moveInGallery(e: io.github.artcraftandroid.procraft.gallery.GalleryEntry, to: Int) {
+ // at once, so the cells move as the finger lifts
+ val shown = galleryEntries.filter { it.dir != e.dir }.toMutableList()
+ shown.add(to.coerceIn(0, shown.size), e)
+ galleryEntries = shown
+ artworks = shown.filterIsInstance<Artwork>()
+ viewModelScope.launch {
+ withContext(Dispatchers.IO) { store.move(e, to) }
+ refreshGallery()
+ }
+ }
+
+ /** Artwork [a] dropped onto [onto] in the gallery: with an artwork it makes a stack, [a] first; a stack takes it in first. */
+ fun dropOnto(a: Artwork, onto: io.github.artcraftandroid.procraft.gallery.GalleryEntry) {
+ if (openStack != null || a.dir == onto.dir) return
+ viewModelScope.launch {
+ withContext(Dispatchers.IO) { store.putOnto(a, onto) }
+ refreshGallery()
+ }
+ }
+
fun renameArtwork(a: Artwork, name: String) {
if (name.isBlank()) return
viewModelScope.launch {
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/ArtworkStore.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/ArtworkStore.kt
index b976917..27ebebe 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/ArtworkStore.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/ArtworkStore.kt
@@ -19,50 +19,94 @@ data class Artwork(override val dir: File, override val name: String, val width:
val thumbnail: File get() = File(dir, "thumbnail.png")
}
-/** Artworks kept together: a folder holding their folders, newest first. */
+/** Artworks kept together: a folder holding their folders, in their own order. */
data class Stack(override val dir: File, override val name: String, val artworks: List<Artwork>) : GalleryEntry {
override val modified: Long get() = artworks.maxOfOrNull { it.modified } ?: dir.lastModified()
}
+/**
+ * Where things sit in the gallery (or a stack): an order of folder names kept beside them. New
+ * folders go first, newest first, and keep their place from then on: changing an artwork doesn't
+ * move it; only a drag does.
+ */
+internal object GalleryOrder {
+ /** The order of the folders [present] (name to time changed), given the order [saved] before. */
+ fun arrange(present: List<Pair<String, Long>>, saved: List<String>): List<String> {
+ val names = present.mapTo(HashSet()) { it.first }
+ val placed = saved.filter { it in names }.distinct()
+ val known = placed.toHashSet()
+ return present.filter { it.first !in known }.sortedByDescending { it.second }.map { it.first } + placed
+ }
+
+ /** [order] with [name] taken out and put back at [to] (its place in the order without it). */
+ fun moved(order: List<String>, name: String, to: Int): List<String> {
+ val rest = order.filter { it != name }
+ return rest.take(to.coerceIn(0, rest.size)) + name + rest.drop(to.coerceIn(0, rest.size))
+ }
+}
+
/** The artworks in the app's private storage, one folder each, some in stacks (a folder of them). */
class ArtworkStore(val root: File) {
init {
root.mkdirs()
}
- /** What is in [at] (the gallery, or a stack's folder), newest first; empty stacks go away. */
- fun list(at: File = root): List<GalleryEntry> = at.listFiles { f -> f.isDirectory }.orEmpty().mapNotNull { dir ->
- read(dir) ?: if (at == root) readStack(dir) else null
- }.sortedByDescending { it.modified }
+ /** What is in [at] (the gallery, or a stack's folder) in its order; empty stacks go away. */
+ fun list(at: File = root): List<GalleryEntry> {
+ val dirs = at.listFiles { f -> f.isDirectory }.orEmpty()
+ val entries = dirs.mapNotNull { dir -> read(dir) ?: if (at == root) readStack(dir) else null }.associateBy { it.dir.name }
+ return order(at, dirs, entries).mapNotNull(entries::get)
+ }
- /** The artwork changed last, in the gallery or a stack. */
- fun mostRecent(): Artwork? = when (val e = list().firstOrNull()) {
- is Artwork -> e
- is Stack -> e.artworks.firstOrNull()
- null -> null
+ /** Every folder in [at] in order, those that can't be read this moment (being written) too. */
+ private fun order(at: File): List<String> {
+ val dirs = at.listFiles { f -> f.isDirectory }.orEmpty()
+ return order(at, dirs, dirs.mapNotNull(::read).associateBy { it.dir.name })
}
+ /** The artwork changed last, in the gallery or a stack (each is saved when it is left). */
+ fun mostRecent(): Artwork? = list().flatMap {
+ when (it) {
+ is Artwork -> listOf(it)
+ is Stack -> it.artworks
+ }
+ }.maxByOrNull { it.modified }
+
fun newFolder(at: File = root): File = File(at, UUID.randomUUID().toString()).also { it.mkdirs() }
fun delete(a: Artwork) {
a.dir.deleteRecursively()
}
- /** A copy beside the original, named "<name> copy" (the copy's title is set by the caller when opened). */
+ /** A copy under the same name, right after the original. */
fun duplicate(a: Artwork): File {
- val copy = newFolder(a.dir.parentFile ?: root)
+ val at = a.dir.parentFile ?: root
+ val before = order(at)
+ val copy = newFolder(at)
a.dir.copyRecursively(copy, overwrite = true)
- File(copy, "artwork.json").let { f ->
- runCatching {
- val json = JSONObject(f.readText())
- json.put("name", "${a.name} copy")
- f.writeText(json.toString())
- }
- }
- copy.setLastModified(System.currentTimeMillis())
+ // not worked on yet: as recent as the original
+ File(copy, "artwork.json").setLastModified(a.modified)
+ writeOrder(at, GalleryOrder.moved(before + copy.name, copy.name, before.indexOf(a.dir.name) + 1))
return copy
}
+ /** [e] moved to [to] in the gallery or stack it is in (its place in the order without it). */
+ fun move(e: GalleryEntry, to: Int) {
+ val at = e.dir.parentFile ?: return
+ writeOrder(at, GalleryOrder.moved(order(at), e.dir.name, to))
+ }
+
+ /** Artwork [a] (from the gallery) dropped onto [onto]: an artwork makes a stack with it there, [a] first; a stack takes it in first. */
+ fun putOnto(a: Artwork, onto: GalleryEntry) {
+ if (onto is Artwork) {
+ stack(listOf(a, onto), place = onto)
+ return
+ }
+ val inside = order(onto.dir)
+ if (!a.dir.renameTo(File(onto.dir, a.dir.name))) return
+ writeOrder(onto.dir, listOf(a.dir.name) + inside)
+ }
+
fun rename(a: Artwork, name: String) {
val f = File(a.dir, "artwork.json")
runCatching {
@@ -72,11 +116,21 @@ class ArtworkStore(val root: File) {
}
}
- /** A new stack in the gallery holding [artworks] (moved into it). */
- fun stack(artworks: List<Artwork>): File {
+ /**
+ * A new stack in the gallery holding [artworks] (moved into it), where [place] was: by default
+ * the first of them, and they keep the gallery's order; with [place], in the order given.
+ */
+ fun stack(artworks: List<Artwork>, place: Artwork? = null): File {
+ val before = order(root)
+ val names = artworks.map { it.dir.name }
+ val inside = if (place != null) names else before.filter { it in names }
+ val at = (place?.dir?.name ?: inside.firstOrNull())?.let(before::indexOf) ?: 0
val dir = newFolder(root)
File(dir, STACK_FILE).writeText(JSONObject().put("name", "Stack").toString())
for (a in artworks) a.dir.renameTo(File(dir, a.dir.name))
+ writeOrder(dir, inside)
+ val rest = before.filter { it !in names }
+ writeOrder(root, GalleryOrder.moved(rest + dir.name, dir.name, before.take(at.coerceAtLeast(0)).count { it !in names }))
return dir
}
@@ -106,8 +160,33 @@ class ArtworkStore(val root: File) {
return Stack(dir, name, artworks)
}
+ /** The order of the folders [dirs] in [at] ([entries] those read), kept up to date on disk. */
+ private fun order(at: File, dirs: Array<out File>, entries: Map<String, GalleryEntry>): List<String> {
+ val f = File(at, ORDER_FILE)
+ val saved = runCatching { f.readLines().filter { it.isNotBlank() } }.getOrDefault(emptyList())
+ // a folder being written keeps its place; if new, its folder's time places it
+ val order = GalleryOrder.arrange(dirs.map { it.name to (entries[it.name]?.modified ?: it.lastModified()) }, saved)
+ if (order != saved) writeOrder(at, order)
+ return order
+ }
+
+ private fun writeOrder(at: File, order: List<String>) {
+ runCatching {
+ val f = File(at, ORDER_FILE)
+ val next = File(at, "$ORDER_FILE.new")
+ next.writeText(order.joinToString("\n", postfix = "\n"))
+ if (!next.renameTo(f)) {
+ f.delete()
+ next.renameTo(f)
+ }
+ }
+ }
+
private companion object {
const val STACK_FILE = "stack.json"
+
+ /** The folders' order, one name a line, first first. */
+ const val ORDER_FILE = "order.txt"
}
}
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/DragOut.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/DragOut.kt
index 792da92..f6ad4f6 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/DragOut.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/DragOut.kt
@@ -125,11 +125,19 @@ fun pngToJpeg(png: File, jpg: File): Boolean {
return true
}
+/** What the gallery's own drags carry, so it can tell them from another app's. */
+class GalleryDrag(val entry: GalleryEntry)
+
+/** How opaque a dragged artwork's (or stack's) picture is. */
+private const val DRAG_PICTURE_ALPHA = 204
+
/**
- * Starts dragging artwork [a] (in the gallery at [root]) from [view] out to other apps: the
- * preferred file format, and the preferred picture format too when that file isn't a picture.
+ * Starts dragging artwork [a] (in the gallery at [root]) from [view]: out to other apps in the
+ * preferred file format (and the preferred picture format too when that file isn't a picture),
+ * and within the gallery. Its picture is the thumbnail at [width] x [height] pixels, a little
+ * see-through, held at [touch] (from its top left).
*/
-fun startArtworkDrag(view: View, a: Artwork, root: File): Boolean {
+fun startArtworkDrag(view: View, a: Artwork, root: File, width: Int, height: Int, touch: Point): Boolean {
val ctx = view.context
val prefs = ctx.getSharedPreferences("interface", Context.MODE_PRIVATE)
val file = CanvasViewModel.DRAG_FORMATS.getOrElse(prefs.getInt(CanvasViewModel.DRAG_FORMAT, 0)) { "ProCraft" }
@@ -137,24 +145,36 @@ fun startArtworkDrag(view: View, a: Artwork, root: File): Boolean {
val formats = if (file in CanvasViewModel.DRAG_IMAGE_FORMATS) listOf(file) else listOf(file, image)
val clip = ClipData(ClipDescription(a.name, formats.map(DragProvider::mime).toTypedArray()), ClipData.Item(DragProvider.uri(ctx, formats[0], a, root)))
formats.drop(1).forEach { clip.addItem(ClipData.Item(DragProvider.uri(ctx, it, a, root))) }
- val thumb = BitmapFactory.decodeFile(a.thumbnail.path)
- val shadow = object : View.DragShadowBuilder(view) {
- // the thumbnail, 160 dp on its long side, held at its middle
- private val side = 160f * ctx.resources.displayMetrics.density
- private val scale = thumb?.let { side / maxOf(it.width, it.height) } ?: 1f
-
- override fun onProvideShadowMetrics(size: Point, touch: Point) {
- val w = ((thumb?.width ?: 1) * scale).toInt().coerceAtLeast(1)
- val h = ((thumb?.height ?: 1) * scale).toInt().coerceAtLeast(1)
+ // opaque, so the picture keeps its own alpha rather than the system's
+ val flags = View.DRAG_FLAG_GLOBAL or View.DRAG_FLAG_GLOBAL_URI_READ or View.DRAG_FLAG_OPAQUE
+ return view.startDragAndDrop(clip, dragPicture(view, a.thumbnail, width, height, touch), GalleryDrag(a), flags)
+}
+
+/** Starts dragging stack [s] from [view], within the gallery only; its picture as an artwork's is, its top artwork's. */
+fun startStackDrag(view: View, s: Stack, width: Int, height: Int, touch: Point): Boolean {
+ val top = s.artworks.firstOrNull() ?: return false
+ return view.startDragAndDrop(null, dragPicture(view, top.thumbnail, width, height, touch), GalleryDrag(s), View.DRAG_FLAG_OPAQUE)
+}
+
+/** A dragged thing's picture: [thumbnail] at [width] x [height] pixels on white with rounded corners, a little see-through, held at [touch]. */
+private fun dragPicture(view: View, thumbnail: File, width: Int, height: Int, touch: Point): View.DragShadowBuilder {
+ val thumb = BitmapFactory.decodeFile(thumbnail.path)
+ val w = width.coerceAtLeast(1)
+ val h = height.coerceAtLeast(1)
+ val r = 8f * view.resources.displayMetrics.density
+ return object : View.DragShadowBuilder(view) {
+ override fun onProvideShadowMetrics(size: Point, at: Point) {
size.set(w, h)
- touch.set(w / 2, h / 2)
+ at.set(touch.x.coerceIn(0, w - 1), touch.y.coerceIn(0, h - 1))
}
override fun onDrawShadow(canvas: android.graphics.Canvas) {
- val t = thumb ?: return
- canvas.scale(scale, scale)
- canvas.drawBitmap(t, 0f, 0f, null)
+ val frame = android.graphics.RectF(0f, 0f, w.toFloat(), h.toFloat())
+ val layer = canvas.saveLayerAlpha(frame, DRAG_PICTURE_ALPHA)
+ canvas.clipPath(android.graphics.Path().apply { addRoundRect(frame, r, r, android.graphics.Path.Direction.CW) })
+ canvas.drawColor(android.graphics.Color.WHITE)
+ thumb?.let { canvas.drawBitmap(it, null, frame, android.graphics.Paint(android.graphics.Paint.FILTER_BITMAP_FLAG)) }
+ canvas.restoreToCount(layer)
}
}
- return view.startDragAndDrop(clip, shadow, null, View.DRAG_FLAG_GLOBAL or View.DRAG_FLAG_GLOBAL_URI_READ)
}
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/RecentArtworkWidget.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/RecentArtworkWidget.kt
index 6db159b..0f99597 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/RecentArtworkWidget.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/RecentArtworkWidget.kt
@@ -15,7 +15,7 @@ import io.github.artcraftandroid.procraft.R
import java.io.File
/**
- * The home screen's Recent artwork widget: the newest artwork's picture filling it (the app's mark
+ * The home screen's Recent artwork widget: the picture of the artwork worked on last filling it (the app's mark
* when there is none); a tap opens the app at that artwork.
*/
class RecentArtworkWidget : AppWidgetProvider() {
@@ -31,7 +31,7 @@ class RecentArtworkWidget : AppWidgetProvider() {
/** The longest side the picture is given at (the home screen holds it in memory). */
private const val PICTURE_MOST = 720
- /** Shows the newest artwork on every Recent artwork widget there is. */
+ /** Shows the artwork worked on last on every Recent artwork widget there is. */
fun refresh(context: Context) {
val manager = AppWidgetManager.getInstance(context)
val ids = runCatching { manager.getAppWidgetIds(ComponentName(context, RecentArtworkWidget::class.java)) }.getOrNull()
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GalleryScreen.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GalleryScreen.kt
index b94db48..4662c1b 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GalleryScreen.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GalleryScreen.kt
@@ -60,6 +60,10 @@ import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.ui.layout.positionInWindow
+import androidx.compose.ui.layout.positionInRoot
+import androidx.compose.foundation.draganddrop.dragAndDropTarget
+import androidx.compose.ui.draganddrop.toAndroidDragEvent
+import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.unit.IntSize
@@ -84,6 +88,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import io.github.artcraftandroid.procraft.canvas.CanvasViewModel
import io.github.artcraftandroid.procraft.gallery.Artwork
+import io.github.artcraftandroid.procraft.gallery.GalleryEntry
import io.github.artcraftandroid.procraft.gallery.CanvasPreset
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.snap
@@ -130,6 +135,9 @@ fun GalleryScreen(vm: CanvasViewModel) {
var deleting by remember { mutableStateOf<Artwork?>(null) }
// the artwork (by folder) whose actions a swipe left is showing
var swiped by remember { mutableStateOf<String?>(null) }
+ // a drag in the gallery: the artwork dragged, and the cell it would be stacked onto (by folder)
+ var dragging by remember { mutableStateOf<String?>(null) }
+ var dropOnto by remember { mutableStateOf<String?>(null) }
// Select: the artworks picked, by folder
var selecting by remember { mutableStateOf(false) }
val selected = remember { mutableStateListOf<String>() }
@@ -233,15 +241,56 @@ fun GalleryScreen(vm: CanvasViewModel) {
androidx.compose.runtime.CompositionLocalProvider(LocalCell provides cell) {
// the whole screen under the header, so artworks flying in from a stack lower down
// aren't clipped by a grid of one short row
+ val grid = if (stack == null) vm.galleryGrid else androidx.compose.foundation.lazy.grid.rememberLazyGridState()
LazyVerticalGrid(
- modifier = Modifier.fillMaxSize(),
- state = if (stack == null) vm.galleryGrid else androidx.compose.foundation.lazy.grid.rememberLazyGridState(),
+ modifier = Modifier.fillMaxSize().then(
+ galleryDrop(
+ grid, entries, cell, stacking = stack == null,
+ onOver = { dropOnto = it },
+ onEnded = {
+ dragging = null
+ dropOnto = null
+ },
+ onMove = vm::moveInGallery,
+ onStack = vm::dropOnto,
+ ),
+ ),
+ state = grid,
columns = GridCells.Fixed(columns),
contentPadding = PaddingValues(bottom = 24.dp),
) {
items(entries, key = { it.dir.name }) { entry ->
if (entry is io.github.artcraftandroid.procraft.gallery.Stack) {
- StackCell(entry, vm.galleryVersion, dim = selecting, onPlaced = { stackCellAt[entry.dir.name] = it }) {
+ val faint = androidx.compose.animation.core.animateFloatAsState(
+ if (dragging == entry.dir.name) DRAGGED_ALPHA else 1f, Motion.artworkLift(), label = "dragged",
+ )
+ val view = LocalView.current
+ val density = androidx.compose.ui.platform.LocalDensity.current
+ StackCell(
+ entry, vm.galleryVersion, dim = selecting, wash = dropOnto == entry.dir.name,
+ modifier = Modifier.animateItem(fadeInSpec = null, fadeOutSpec = null).graphicsLayer { alpha = faint.value },
+ onPlaced = { stackCellAt[entry.dir.name] = it },
+ onDrag = { touch ->
+ // its top artwork's picture, lifted, held where the finger is on it
+ val placed = stackCellAt[entry.dir.name]
+ val top = entry.artworks.firstOrNull()
+ if (!selecting && placed != null && top != null) {
+ val box = with(density) {
+ androidx.compose.ui.geometry.Rect(
+ placed.center.x - cell.width.toPx() / 2f, placed.top + 39.dp.toPx(),
+ placed.center.x + cell.width.toPx() / 2f, placed.top + 39.dp.toPx() + cell.thumb.toPx(),
+ )
+ }
+ val picture = fitted(box, top)
+ val held = (touch - picture.topLeft) * Motion.ARTWORK_LIFTED
+ val w = (picture.width * Motion.ARTWORK_LIFTED).toInt()
+ val h = (picture.height * Motion.ARTWORK_LIFTED).toInt()
+ if (io.github.artcraftandroid.procraft.gallery.startStackDrag(view, entry, w, h, android.graphics.Point(held.x.toInt(), held.y.toInt()))) {
+ dragging = entry.dir.name
+ }
+ }
+ },
+ ) {
if (!selecting) vm.showStack(entry)
}
return@items
@@ -253,15 +302,24 @@ fun GalleryScreen(vm: CanvasViewModel) {
val open = androidx.compose.animation.core.animateFloatAsState(
if (swiped == a.dir.name) 1f else 0f, Motion.swipeActions(), label = "swipe",
).value
- // held, its thumbnail shrinks, then lifts (to be dragged out), and settles when let go
+ // held, its thumbnail shrinks, then lifts (to be dragged), and settles when let go
val lift = remember { androidx.compose.animation.core.Animatable(1f) }
val cellScope = rememberCoroutineScope()
- Box(Modifier.flyIn(stackFrom, Motion.stackPushMove()).flyOut(stackFrom, leaving, Motion.stackPop())) {
+ // dragged, it stays behind faint
+ val faint = androidx.compose.animation.core.animateFloatAsState(
+ if (dragging == a.dir.name) DRAGGED_ALPHA else 1f, Motion.artworkLift(), label = "dragged",
+ )
+ // where the cell is in the window, for where the drag picture is held
+ val cellAt = remember { arrayOf(Offset.Zero) }
+ Box(Modifier.animateItem(fadeInSpec = null, fadeOutSpec = null).flyIn(stackFrom, Motion.stackPushMove()).flyOut(stackFrom, leaving, Motion.stackPop())) {
// across the whole column, so the thumbnail sits in its middle as a stack's does
Column(
- Modifier.fillMaxWidth().height(cell.pitch).graphicsLayer { alpha = 1f - SWIPED_FADE * open.coerceIn(0f, 1f) }.pointerInput(a, selecting, chosen) {
+ Modifier.fillMaxWidth().height(cell.pitch).onGloballyPositioned { cellAt[0] = it.positionInWindow() }.graphicsLayer {
+ alpha = (1f - SWIPED_FADE * open.coerceIn(0f, 1f)) * faint.value
+ }.pointerInput(a, selecting, chosen) {
// a tap opens it (or picks it), and on its name renames it; swiped left, its
- // actions show (right, they go); held and moved, it is dragged out to other apps
+ // actions show (right, they go); held and moved, it is dragged: within the
+ // gallery to move it or stack it, or out to other apps
awaitEachGesture {
val down = awaitFirstDown()
// a moment held before it shrinks, so a scroll starting on it leaves it be
@@ -307,7 +365,14 @@ fun GalleryScreen(vm: CanvasViewModel) {
c.consume()
if (!c.pressed) break
if ((c.position - down.position).getDistance() > viewConfiguration.touchSlop) {
- io.github.artcraftandroid.procraft.gallery.startArtworkDrag(view, a, vm.store.root)
+ // the picture as big as the lifted thumbnail, held where the finger is on it
+ val shown = vm.thumbAt[a.dir.name]
+ val scale = Motion.ARTWORK_LIFTED / lift.value
+ val w = ((shown?.width ?: cell.width.toPx()) * scale).toInt()
+ val h = ((shown?.height ?: cell.thumb.toPx()) * scale).toInt()
+ val touch = cellAt[0] + c.position - (shown?.topLeft ?: cellAt[0])
+ val held = android.graphics.Point((touch.x * scale).toInt(), (touch.y * scale).toInt())
+ if (io.github.artcraftandroid.procraft.gallery.startArtworkDrag(view, a, vm.store.root, w, h, held)) dragging = a.dir.name
break
}
}
@@ -327,7 +392,9 @@ fun GalleryScreen(vm: CanvasViewModel) {
contentAlignment = Alignment.BottomCenter,
) {
// where it is, for zooming into it, unless the gallery is zooming itself
- Thumbnail(a, vm.galleryVersion, if (selecting) chosen else null) { if (vm.galleryZoom == null) vm.thumbAt[a.dir.name] = it }
+ Thumbnail(a, vm.galleryVersion, if (selecting) chosen else null, wash = dropOnto == a.dir.name) {
+ if (vm.galleryZoom == null) vm.thumbAt[a.dir.name] = it
+ }
}
Text(
a.name,
@@ -736,6 +803,147 @@ private fun RenameArtwork(a: Artwork, version: Int, from: androidx.compose.ui.ge
/** How far a swiped artwork fades back under its actions. */
private const val SWIPED_FADE = 0.64f
+
+/** How faint an artwork's cell stays while it is dragged. */
+private const val DRAGGED_ALPHA = 0.3f
+
+/** The blue over an artwork (or stack) a dragged artwork would be stacked with. */
+private val DropWash = Color(0x800064DC)
+
+/** How near the grid's top or bottom a drag scrolls it, and how far each frame. */
+private val DragScrollEdge = 60.dp
+private val DragScrollStep = 12.dp
+
+/** Artwork [a]'s picture as it sits in its thumbnail's [box]: fitted, standing on the box's bottom. */
+private fun fitted(box: androidx.compose.ui.geometry.Rect, a: Artwork): androidx.compose.ui.geometry.Rect {
+ val ratio = if (a.width > 0 && a.height > 0) a.width.toFloat() / a.height else 0.75f
+ val w = if (ratio <= box.width / box.height) box.height * ratio else box.width
+ val h = w / ratio
+ return androidx.compose.ui.geometry.Rect(box.center.x - w / 2f, box.bottom - h, box.center.x + w / 2f, box.bottom)
+}
+
+/** Where a drag over the gallery's grid is: the cell it would be stacked onto, or else the slot it would go in. */
+private data class DropAt(val onto: String?, val slot: Int)
+
+/**
+ * Where point [p] (the grid's pixels) is over [entries] laid out in [grid]: over another's picture
+ * (the thumbnail as it sits in its box, or a stack's box) it is that one, when [stacking]; anywhere
+ * else the slot between cells it is nearest, before a cell's middle or after it.
+ */
+private fun dropAt(grid: androidx.compose.foundation.lazy.grid.LazyGridState, entries: List<GalleryEntry>, dragged: String, p: Offset, top: Float, box: androidx.compose.ui.geometry.Size, stacking: Boolean): DropAt? {
+ val items = grid.layoutInfo.visibleItemsInfo
+ for (info in items) {
+ val x = info.offset.x.toFloat()
+ val y = info.offset.y.toFloat()
+ if (p.x < x || p.x >= x + info.size.width || p.y < y || p.y >= y + info.size.height) continue
+ val e = entries.getOrNull(info.index) ?: return null
+ val left = x + (info.size.width - box.width) / 2f
+ val inBox = androidx.compose.ui.geometry.Rect(left, y + top, left + box.width, y + top + box.height)
+ val picture = if (e is Artwork) fitted(inBox, e) else inBox
+ if (stacking && e.dir.name != dragged && picture.contains(p)) return DropAt(e.dir.name, info.index)
+ return DropAt(null, if (p.x < x + info.size.width / 2f) info.index else info.index + 1)
+ }
+ // past the last cell: last
+ val last = items.lastOrNull() ?: return null
+ return if (last.index == entries.size - 1 && (p.y >= last.offset.y + last.size.height || (p.y >= last.offset.y && p.x >= last.offset.x + last.size.width))) DropAt(null, entries.size) else null
+}
+
+/**
+ * The gallery's grid taking the gallery's own drags: let go over another artwork's picture (or a
+ * stack's), the dragged artwork is stacked with it ([onOver] names it meanwhile), anywhere else it
+ * goes where it is let go. Near the grid's top or bottom the grid scrolls.
+ */
+@Composable
+private fun galleryDrop(
+ grid: androidx.compose.foundation.lazy.grid.LazyGridState,
+ entries: List<GalleryEntry>,
+ cell: CellSize,
+ stacking: Boolean,
+ onOver: (String?) -> Unit,
+ onEnded: () -> Unit,
+ onMove: (GalleryEntry, Int) -> Unit,
+ onStack: (Artwork, GalleryEntry) -> Unit,
+): Modifier {
+ val now = androidx.compose.runtime.rememberUpdatedState(entries)
+ val over = androidx.compose.runtime.rememberUpdatedState(onOver)
+ val ended = androidx.compose.runtime.rememberUpdatedState(onEnded)
+ val move = androidx.compose.runtime.rememberUpdatedState(onMove)
+ val stack = androidx.compose.runtime.rememberUpdatedState(onStack)
+ val density = androidx.compose.ui.platform.LocalDensity.current
+ val sizes = androidx.compose.runtime.rememberUpdatedState(
+ with(density) { Triple(39.dp.toPx(), androidx.compose.ui.geometry.Size(cell.width.toPx(), cell.thumb.toPx()), DragScrollEdge.toPx()) },
+ )
+ // the grid's place in the window and its height
+ val placed = remember { arrayOf(Offset.Zero, Offset.Zero) }
+ // -1 scrolling up, 1 down
+ var edge by remember { mutableIntStateOf(0) }
+ LaunchedEffect(edge) {
+ val step = with(density) { DragScrollStep.toPx() }
+ while (edge != 0) {
+ grid.scrollBy(edge * step)
+ androidx.compose.runtime.withFrameNanos { }
+ }
+ }
+ val target = remember(grid, stacking) {
+ object : androidx.compose.ui.draganddrop.DragAndDropTarget {
+ var at: DropAt? = null
+
+ fun dragged(e: androidx.compose.ui.draganddrop.DragAndDropEvent) = (e.toAndroidDragEvent().localState as? io.github.artcraftandroid.procraft.gallery.GalleryDrag)?.entry
+
+ fun track(e: androidx.compose.ui.draganddrop.DragAndDropEvent) {
+ val d = e.toAndroidDragEvent()
+ val entry = dragged(e) ?: return
+ val p = Offset(d.x, d.y) - placed[0]
+ val (top, box, near) = sizes.value
+ edge = when {
+ p.y < near -> -1
+ p.y > placed[1].y - near -> 1
+ else -> 0
+ }
+ at = dropAt(grid, now.value, entry.dir.name, p, top, box, stacking && entry is Artwork)
+ over.value(at?.onto)
+ }
+
+ override fun onEntered(event: androidx.compose.ui.draganddrop.DragAndDropEvent) = track(event)
+
+ override fun onMoved(event: androidx.compose.ui.draganddrop.DragAndDropEvent) = track(event)
+
+ override fun onExited(event: androidx.compose.ui.draganddrop.DragAndDropEvent) {
+ at = null
+ edge = 0
+ over.value(null)
+ }
+
+ override fun onDrop(event: androidx.compose.ui.draganddrop.DragAndDropEvent): Boolean {
+ val e = dragged(event) ?: return false
+ val drop = at ?: return true
+ val list = now.value
+ val onto = drop.onto?.let { name -> list.firstOrNull { it.dir.name == name } }
+ if (onto != null && e is Artwork) {
+ stack.value(e, onto)
+ } else {
+ val from = list.indexOfFirst { it.dir.name == e.dir.name }
+ val to = if (drop.slot > from) drop.slot - 1 else drop.slot
+ if (from >= 0 && to != from) move.value(e, to)
+ }
+ return true
+ }
+
+ override fun onEnded(event: androidx.compose.ui.draganddrop.DragAndDropEvent) {
+ at = null
+ edge = 0
+ ended.value()
+ }
+ }
+ }
+ return Modifier.onGloballyPositioned {
+ placed[0] = it.positionInRoot()
+ placed[1] = Offset(it.size.width.toFloat(), it.size.height.toFloat())
+ }.dragAndDropTarget(
+ shouldStartDragAndDrop = { it.toAndroidDragEvent().localState is io.github.artcraftandroid.procraft.gallery.GalleryDrag },
+ target = target,
+ )
+}
private val SwipePillWidth = 94.dp
private val SwipePillHeight = 56.dp
private val SwipePillFill get() = if (Pc.light) Color(0xFFF5F5F5) else Color(0xDB1C1C1C)
@@ -857,13 +1065,53 @@ private fun StackCell(
s: io.github.artcraftandroid.procraft.gallery.Stack,
version: Int,
dim: Boolean,
+ wash: Boolean,
+ modifier: Modifier,
onPlaced: (androidx.compose.ui.geometry.Rect) -> Unit,
+ onDrag: (Offset) -> Unit,
onOpen: () -> Unit,
) {
val top = s.artworks.firstOrNull() ?: return
val cell = LocalCell.current
+ val view = LocalView.current
+ // where the cell is in the window, for where the drag picture is held
+ val cellAt = remember { arrayOf(Offset.Zero) }
Column(
- Modifier.height(cell.pitch).onGloballyPositioned { onPlaced(it.boundsInWindow()) }.clickable(onClick = onOpen),
+ modifier.height(cell.pitch).onGloballyPositioned {
+ onPlaced(it.boundsInWindow())
+ cellAt[0] = it.positionInWindow()
+ }.pointerInput(s) {
+ // a tap opens it; held and moved, it is dragged ([onDrag], with the finger's place in the window)
+ awaitEachGesture {
+ val down = awaitFirstDown()
+ var up: androidx.compose.ui.input.pointer.PointerInputChange? = null
+ var moved = false
+ val held = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) {
+ while (up == null && !moved) {
+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break
+ if (!c.pressed) up = c else if ((c.position - down.position).getDistance() > viewConfiguration.touchSlop) moved = true
+ }
+ false
+ } ?: true
+ if (!held) {
+ up?.let {
+ it.consume()
+ onOpen()
+ }
+ return@awaitEachGesture
+ }
+ view.performHapticFeedback(android.view.HapticFeedbackConstants.LONG_PRESS)
+ while (true) {
+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break
+ c.consume()
+ if (!c.pressed) break
+ if ((c.position - down.position).getDistance() > viewConfiguration.touchSlop) {
+ onDrag(cellAt[0] + c.position)
+ break
+ }
+ }
+ }
+ },
horizontalAlignment = Alignment.CenterHorizontally,
) {
Box(Modifier.padding(top = 39.dp).size(cell.width, cell.thumb), contentAlignment = Alignment.BottomCenter) {
@@ -874,7 +1122,7 @@ private fun StackCell(
.clip(RoundedCornerShape(8.dp)).background(Color(0xFFF2F2F2)),
)
}
- Thumbnail(top, version)
+ Thumbnail(top, version, wash = wash)
}
Text(s.name, color = if (dim) Pc.GallerySize else Pc.GalleryText, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, modifier = Modifier.padding(top = 12.dp))
Text("${s.artworks.size} artworks", color = Pc.GallerySize, fontSize = 10.sp)
@@ -959,7 +1207,7 @@ private fun PreviewArrow(left: Boolean, modifier: Modifier, onClick: () -> Unit)
* a circle at its top right ([chosen]: filled blue with a tick).
*/
@Composable
-private fun Thumbnail(a: Artwork, version: Int, chosen: Boolean? = null, onPlaced: (androidx.compose.ui.geometry.Rect) -> Unit = {}) {
+private fun Thumbnail(a: Artwork, version: Int, chosen: Boolean? = null, wash: Boolean = false, onPlaced: (androidx.compose.ui.geometry.Rect) -> Unit = {}) {
val image by produceState<ImageBitmap?>(null, a.dir.path, a.modified, version) {
value = withContext(Dispatchers.IO) { BitmapFactory.decodeFile(a.thumbnail.path)?.asImageBitmap() }
}
@@ -983,6 +1231,8 @@ private fun Thumbnail(a: Artwork, version: Int, chosen: Boolean? = null, onPlace
.background(Color.White),
) {
image?.let { Image(it, contentDescription = a.name, contentScale = ContentScale.FillBounds, modifier = Modifier.fillMaxSize()) }
+ // blue while an artwork dragged over it would be stacked with it
+ if (wash) Box(Modifier.matchParentSize().background(DropWash))
// the marks fade in as Select starts, and out as it ends
FadingValue(chosen, Motion.selectMode()) { chosen, shown ->
Box(
diff --git a/apps/procraft-android/android/app/src/test/java/io/github/artcraftandroid/procraft/gallery/GalleryOrderTest.kt b/apps/procraft-android/android/app/src/test/java/io/github/artcraftandroid/procraft/gallery/GalleryOrderTest.kt
new file mode 100644
index 0000000..0e2f8c9
--- /dev/null
+++ b/apps/procraft-android/android/app/src/test/java/io/github/artcraftandroid/procraft/gallery/GalleryOrderTest.kt
@@ -0,0 +1,37 @@
+package io.github.artcraftandroid.procraft.gallery
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class GalleryOrderTest {
+ @Test
+ fun withNoOrderYetTheNewestComeFirst() {
+ val present = listOf("a" to 10L, "b" to 30L, "c" to 20L)
+ assertEquals(listOf("b", "c", "a"), GalleryOrder.arrange(present, emptyList()))
+ }
+
+ @Test
+ fun aChangedArtworkKeepsItsPlaceAndANewOneGoesFirst() {
+ // "a" was changed last, but it was placed already; "d" is new
+ val present = listOf("a" to 99L, "b" to 30L, "c" to 20L, "d" to 50L)
+ assertEquals(listOf("d", "c", "a", "b"), GalleryOrder.arrange(present, listOf("c", "a", "b")))
+ }
+
+ @Test
+ fun goneFoldersAndRepeatsLeaveTheOrder() {
+ val present = listOf("a" to 1L, "b" to 2L)
+ assertEquals(listOf("b", "a"), GalleryOrder.arrange(present, listOf("b", "x", "a", "b")))
+ }
+
+ @Test
+ fun aMoveTakesTheEntryOutAndPutsItBackAtItsNewPlace() {
+ val order = listOf("a", "b", "c", "d")
+ assertEquals(listOf("b", "c", "a", "d"), GalleryOrder.moved(order, "a", 2))
+ assertEquals(listOf("d", "a", "b", "c"), GalleryOrder.moved(order, "d", 0))
+ // past either end it goes to that end
+ assertEquals(listOf("b", "c", "d", "a"), GalleryOrder.moved(order, "a", 99))
+ assertEquals(listOf("c", "a", "b", "d"), GalleryOrder.moved(order, "c", -1))
+ // a name not there yet is put in
+ assertEquals(listOf("a", "e", "b", "c", "d"), GalleryOrder.moved(order, "e", 1))
+ }
+}