fix: move card favourite star to bottom-right so it no longer overlaps the overflow button (v0.3.3.4)
build / Assemble debug APK (push) Failing after 9s

This commit is contained in:
Incido Developer committed 2026-08-17 12:59:10 +12:00
1 parent 5b82d2a9fe
commit 089926377c
44 files changed
+5490 -140

No files matched your search

@@ -7,12 +7,31 @@ import org.incido.data.entity.MyObjectBox
/**
* Singleton holder for the process-wide [BoxStore]. Initialised once from
* the Application/Activity context.
*
* v0.3.2.0 — kept an `encryptionKey` parameter for forward compatibility,
* but the open-source ObjectBox 4.0.3 distribution doesn't expose a
* public `encryptionKey(byte[])` method on [io.objectbox.BoxStoreBuilder].
* At-rest encryption is only available in ObjectBox Sync / Pro; the
* `:composeApp` `ObjectBoxKeyProvider` keeps the wrapping logic
* ready for when the API becomes available (or for migration to the
* commercial build). For now the store always opens unencrypted.
*/
object ObjectBoxStore {
@Volatile
private var instance: BoxStore? = null
fun init(context: Context): BoxStore =
/**
* Initialise the singleton [BoxStore]. Idempotent — repeated calls
* return the existing instance.
*
* @param context application context
* @param encryptionKey reserved for future at-rest encryption support
* (currently a no-op — ObjectBox 4.0.3 OSS doesn't expose the
* API). The key is wrapped via Android Keystore by
* `ObjectBoxKeyProvider` and ready to plug in.
*/
@Suppress("UNUSED_PARAMETER")
fun init(context: Context, encryptionKey: ByteArray? = null): BoxStore =
instance ?: synchronized(this) {
instance ?: MyObjectBox.builder()
.androidContext(context.applicationContext)
@@ -20,6 +39,17 @@ object ObjectBoxStore {
.also { instance = it }
}
/**
* Close + drop the singleton. Reserved for future use when
* toggling encryption requires re-opening the store with a new key.
*/
fun reset() {
synchronized(this) {
instance?.close()
instance = null
}
}
fun get(): BoxStore =
instance ?: error("ObjectBoxStore not initialised — call init(context) first")
}
@@ -0,0 +1,53 @@
package org.incido.data.entity
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import io.objectbox.annotation.Index
import org.incido.domain.model.NoteAttachment
/**
* v0.3.1.0 — One uploaded file (photo, document, etc.) attached to a
* note. File **bytes** live directly in the database (ObjectBox
* stores `ByteArray` columns natively) so the entire note + its
* attachments are backed up and restored as a single unit, with no
* filesystem paths to keep in sync.
*
* [bytes] is intentionally NOT part of [NoteAttachment] in the
* domain layer — list snapshots stay cheap because they don't load
* the (potentially large) blob. Callers fetch bytes on demand via
* [org.incido.domain.repository.NoteRepository.getAttachmentBytes].
*/
@Entity
data class NoteAttachmentEntity(
@Id var id: Long = 0,
@Index var noteId: Long = 0,
var mimeType: String = "",
var displayName: String = "",
var createdAt: Long = 0,
var sizeBytes: Long = 0,
var bytes: ByteArray = ByteArray(0),
)
internal fun NoteAttachmentEntity.toDomain(): NoteAttachment = NoteAttachment(
id = id,
noteId = noteId,
mimeType = mimeType,
displayName = displayName,
createdAt = createdAt,
sizeBytes = sizeBytes,
)
/**
* Inverse mapper from the domain layer — used when the editor or
* the share-into flow persists a freshly-imported attachment. The
* [id] field is left at 0L so ObjectBox assigns a fresh id on put.
*/
internal fun NoteAttachment.toEntity(): NoteAttachmentEntity = NoteAttachmentEntity(
id = 0L,
noteId = noteId,
mimeType = mimeType,
displayName = displayName,
createdAt = createdAt,
sizeBytes = sizeBytes,
bytes = ByteArray(0), // never serialised from the domain — bytes are set explicitly in the impl
)
@@ -1,16 +1,26 @@
package org.incido.data.repository
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import androidx.exifinterface.media.ExifInterface
import io.objectbox.BoxStore
import io.objectbox.kotlin.boxFor
import io.objectbox.query.QueryBuilder
import io.objectbox.reactive.DataSubscription
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.concurrent.Callable
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.incido.data.entity.HashtagEntity
import org.incido.data.entity.HashtagEntity_
import org.incido.data.entity.NoteAttachmentEntity
import org.incido.data.entity.NoteAttachmentEntity_
import org.incido.data.entity.NoteEntity
import org.incido.data.entity.NoteEntity_
import org.incido.data.entity.NoteHashtagCrossRef
@@ -20,6 +30,7 @@ import org.incido.data.entity.toEntity
import org.incido.domain.model.Hashtag
import org.incido.domain.model.HashtagUsage
import org.incido.domain.model.Note
import org.incido.domain.model.NoteAttachment
import org.incido.domain.repository.NoteRepository
/**
@@ -42,6 +53,8 @@ class NoteRepositoryImpl(
private val noteBox = boxStore.boxFor<NoteEntity>()
private val tagBox = boxStore.boxFor<HashtagEntity>()
private val xrefBox = boxStore.boxFor<NoteHashtagCrossRef>()
/** v0.3.1.0 — attachment rows (bytes stored inline as ByteArray). */
private val attachmentBox = boxStore.boxFor<NoteAttachmentEntity>()
// ---------------------------------------------------------------------
// List / observation streams
@@ -77,17 +90,42 @@ class NoteRepositoryImpl(
awaitClose { sub.cancel() }
}.flowOn(Dispatchers.Default)
override fun observeHashtagsByRecentUse(): Flow<List<HashtagUsage>> = callbackFlow {
// ObjectBox fires its observer with the full current query state
// immediately on subscribe, so the observer alone is the source
// of truth — no manual trySend that would race the subscription
// and double the work of the snapshot.
val sub = noteBox.query().build().subscribe().observer { _ ->
trySend(hashtagUsageSnapshot())
}
override fun searchFavorites(query: String): Flow<List<Note>> = callbackFlow {
trySend(snapshotFavoritesSearch(query))
val sub = noteBox.query().build().subscribe().observer { trySend(snapshotFavoritesSearch(query)) }
awaitClose { sub.cancel() }
}.flowOn(Dispatchers.Default)
override fun searchUntagged(query: String): Flow<List<Note>> = callbackFlow {
trySend(snapshotUntaggedSearch(query))
val sub = noteBox.query().build().subscribe().observer { trySend(snapshotUntaggedSearch(query)) }
awaitClose { sub.cancel() }
}.flowOn(Dispatchers.Default)
override fun observeHashtagsByRecentUse(): Flow<List<HashtagUsage>> = callbackFlow {
// The snapshot reads from noteBox + xrefBox + tagBox, so we must
// subscribe to ALL three — otherwise a change that only touches
// tagBox (new hashtag) or xrefBox (new cross-ref) is missed.
// The first observer fire from any of the three gives us the
// initial snapshot, so no manual pre-subscribe trySend is needed.
// We hold the Query objects (not the Subscription handles) so we
// can release the underlying native handle when the flow ends.
// In ObjectBox 4.0.3 `Query<T>` implements `java.io.Closeable`
// — the way to tear it down is `.close()`, not `.cancel()`.
val noteQuery = noteBox.query().build()
val tagQuery = tagBox.query().build()
val xrefQuery = xrefBox.query().build()
val emit: (Any) -> Unit = { _ -> trySend(hashtagUsageSnapshot()) }
noteQuery.subscribe().observer(emit)
tagQuery.subscribe().observer(emit)
xrefQuery.subscribe().observer(emit)
awaitClose {
noteQuery.close()
tagQuery.close()
xrefQuery.close()
}
}.flowOn(Dispatchers.Default)
override fun observeAllHashtags(): Flow<List<String>> = callbackFlow {
trySend(allHashtagsSnapshot().sorted())
val sub = noteBox.query().build().subscribe().observer {
@@ -110,6 +148,83 @@ class NoteRepositoryImpl(
awaitClose { sub.cancel() }
}.flowOn(Dispatchers.Default)
override fun observeAttachments(noteId: Long): Flow<List<NoteAttachment>> = callbackFlow {
trySend(attachmentsByNoteId()[noteId].orEmpty())
val query = attachmentBox.query()
.equal(NoteAttachmentEntity_.noteId, noteId)
.build()
query.subscribe().observer { trySend(attachmentsByNoteId()[noteId].orEmpty()) }
awaitClose { query.close() }
}.flowOn(Dispatchers.Default)
override suspend fun getAttachmentBytes(id: Long): ByteArray? {
return attachmentBox.get(id)?.bytes
}
override suspend fun addAttachment(
noteId: Long,
bytes: ByteArray,
mimeType: String,
displayName: String,
): Long {
// v0.3.1.2 — honour the EXIF Orientation tag on inbound images
// (camera intent usually writes landscape pixels + an EXIF
// rotation). Done at storage time so every render path
// (editor thumbnail, card thumbnail, full-screen viewer) sees
// the photo the right way up. Non-images pass through unchanged.
val storedBytes: ByteArray = if (mimeType.startsWith("image/")) {
withContext(Dispatchers.IO) { normalizeImageOrientation(bytes) }
} else {
bytes
}
val entity = NoteAttachmentEntity(
noteId = noteId,
mimeType = mimeType,
displayName = displayName,
createdAt = System.currentTimeMillis(),
sizeBytes = storedBytes.size.toLong(),
bytes = storedBytes,
)
return attachmentBox.put(entity)
}
/**
* v0.3.1.2 — rotate [bytes] to match the EXIF Orientation tag, then
* re-encode as JPEG so the stored bytes have no orientation flag
* (downstream renderers — editor thumbnail, card thumbnail, viewer
* — all decode raw pixels without honouring EXIF, so we bake the
* rotation into the bitmap at storage time). Returns the input
* unchanged when the orientation is normal, the bitmap can't be
* decoded, or the rotation fails for any reason.
*/
private fun normalizeImageOrientation(bytes: ByteArray): ByteArray {
val bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return bytes
val angle = ExifInterface(ByteArrayInputStream(bytes))
.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
.let {
when (it) {
ExifInterface.ORIENTATION_ROTATE_90 -> 90f
ExifInterface.ORIENTATION_ROTATE_180 -> 180f
ExifInterface.ORIENTATION_ROTATE_270 -> 270f
else -> 0f
}
}
if (angle == 0f) return bytes
val matrix = Matrix().apply { postRotate(angle) }
val rotated = Bitmap.createBitmap(bmp, 0, 0, bmp.width, bmp.height, matrix, true)
bmp.recycle()
val out = ByteArrayOutputStream().use { baos ->
rotated.compress(Bitmap.CompressFormat.JPEG, 92, baos)
rotated.recycle()
baos.toByteArray()
}
return out
}
override suspend fun removeAttachment(id: Long) {
attachmentBox.remove(id)
}
// ---------------------------------------------------------------------
// Writes
// ---------------------------------------------------------------------
@@ -134,6 +249,14 @@ class NoteRepositoryImpl(
if (orphanXrefs.isNotEmpty()) {
xrefBox.remove(*orphanXrefs.map { it.id }.toLongArray())
}
// v0.3.1.0: cascade to attachments so we don't leak blobs.
val orphanAttachments: List<NoteAttachmentEntity> = attachmentBox.query()
.equal(NoteAttachmentEntity_.noteId, id)
.build()
.find()
if (orphanAttachments.isNotEmpty()) {
attachmentBox.remove(*orphanAttachments.map { it.id }.toLongArray())
}
}
override suspend fun setFavorite(id: Long, isFavorite: Boolean) {
@@ -143,7 +266,53 @@ class NoteRepositoryImpl(
noteBox.put(entity)
}
/**
* Persist [note] and reconcile its hashtag set inside a single
* ObjectBox transaction. See [NoteRepository.saveNoteWithHashtags]
* for why atomicity matters (drawer Recent-Tags refresh bug fixed
* in v0.3.0.5).
*/
override suspend fun saveNoteWithHashtags(
note: Note,
hashtagsToAdd: Set<String>,
hashtagsToRemove: Set<String>,
): Note {
val now = System.currentTimeMillis()
val toPersist = if (note.id == 0L) {
note.copy(createdAt = now, updatedAt = now).toEntity()
} else {
note.copy(updatedAt = now).toEntity()
}
// callInTx batches all puts into one transaction, so the per-box
// observers subscribed by observeHashtagsByRecentUse fire ONCE at
// commit time with the final committed state. Without this, the
// tagBox observer could fire between the tagBox.put and the
// xrefBox.put, leaving the snapshot stuck on emptyList().
return boxStore.callInTx(Callable {
val assignedId = noteBox.put(toPersist)
val saved = noteBox.get(assignedId)?.toDomain()
?: note.copy(id = assignedId)
hashtagsToRemove.forEach { removeHashtagInternal(saved.id, it) }
hashtagsToAdd.forEach { addHashtagInternal(saved.id, it) }
saved
})
}
override suspend fun addHashtag(noteId: Long, name: String) {
addHashtagInternal(noteId, name)
}
override suspend fun removeHashtag(noteId: Long, name: String) {
removeHashtagInternal(noteId, name)
}
/**
* Synchronous helper so the implementation can call it from inside
* `boxStore.callInTx { ... }` (which expects a non-suspending
* Callable). The public [addHashtag] / [removeHashtag] methods also
* delegate here for a single source of truth.
*/
private fun addHashtagInternal(noteId: Long, name: String) {
val normalised = Hashtag.normalise(name)
if (!normalised.matches(Regex("^[a-z0-9][a-z0-9._-]{0,30}$"))) return
@@ -169,7 +338,7 @@ class NoteRepositoryImpl(
xrefBox.put(NoteHashtagCrossRef(noteId = noteId, hashtagId = tag.id))
}
override suspend fun removeHashtag(noteId: Long, name: String) {
private fun removeHashtagInternal(noteId: Long, name: String) {
val normalised = Hashtag.normalise(name)
val tag: HashtagEntity = tagBox.query()
.equal(HashtagEntity_.name, normalised, QueryBuilder.StringOrder.CASE_INSENSITIVE)
@@ -202,14 +371,34 @@ class NoteRepositoryImpl(
}
}
/**
* v0.3.1.0 — same shape as [hashtagsByNoteId], but for attachments.
* Returns `noteId -> List<NoteAttachment>` (metadata only — no bytes)
* sorted by [NoteAttachment.createdAt] ascending. Used by
* [decorate] to populate `Note.attachments` for list / search
* snapshots without touching the blob column.
*/
private fun attachmentsByNoteId(): Map<Long, List<NoteAttachment>> {
val all: List<NoteAttachmentEntity> = attachmentBox.all
if (all.isEmpty()) return emptyMap()
return all
.map { it.toDomain() }
.groupBy { it.noteId }
.mapValues { (_, rows) -> rows.sortedBy { it.createdAt } }
}
private fun decorate(entities: List<NoteEntity>): List<Note> {
val tags = hashtagsByNoteId()
val attachments = attachmentsByNoteId()
return entities.sortedWith(
compareByDescending<NoteEntity> { it.isFavorite }
.thenByDescending { it.updatedAt }
).map { e ->
val base = e.toDomain()
base.copy(hashtags = tags[e.id].orEmpty())
base.copy(
hashtags = tags[e.id].orEmpty(),
attachments = attachments[e.id].orEmpty(),
)
}
}
@@ -259,6 +448,71 @@ class NoteRepositoryImpl(
return decorate(untaggedEntities)
}
/**
* Context-aware search across favourites only. Blank [query]
* degrades to [snapshotFavorites]. Otherwise runs the same
* content + hashtag-name matching as [snapshotSearch] and
* intersects with `isFavorite = true`.
*/
private fun snapshotFavoritesSearch(query: String): List<Note> {
val q = query.trim()
if (q.isEmpty()) return snapshotFavorites()
val allIds: Set<Long> = snapshotSearchMatchingNoteIds(q)
if (allIds.isEmpty()) return emptyList()
val entities: List<NoteEntity> = allIds.mapNotNull { id -> noteBox.get(id) }
.filter { it.isFavorite }
return decorate(entities)
}
/**
* Context-aware search across untagged notes only. Blank [query]
* degrades to [snapshotUntagged]. Otherwise runs the content
* matching from [snapshotSearch] and intersects with notes that
* have zero hashtags (tag matching is irrelevant for untagged).
*/
private fun snapshotUntaggedSearch(query: String): List<Note> {
val q = query.trim()
if (q.isEmpty()) return snapshotUntagged()
val noteIdsWithTags: Set<Long> = xrefBox.all.mapTo(HashSet(xrefBox.all.size)) { it.noteId }
val contentMatches: List<Long> = noteBox.query()
.contains(NoteEntity_.content, q, QueryBuilder.StringOrder.CASE_INSENSITIVE)
.build()
.find()
.map { it.id }
val matching: List<NoteEntity> = contentMatches
.mapNotNull { id -> noteBox.get(id) }
.filter { it.id !in noteIdsWithTags }
return decorate(matching)
}
/**
* Shared content + tag-name matcher used by [snapshotSearch] and
* [snapshotFavoritesSearch]. Returns the set of matching note ids.
*/
private fun snapshotSearchMatchingNoteIds(query: String): Set<Long> {
// Match against content (contains, case-insensitive).
val contentMatches: List<Long> = noteBox.query()
.contains(NoteEntity_.content, query, QueryBuilder.StringOrder.CASE_INSENSITIVE)
.build()
.find()
.map { it.id }
// Match against hashtag names (case-insensitive exact equality).
val matchingTag: HashtagEntity? = tagBox.query()
.equal(HashtagEntity_.name, query, QueryBuilder.StringOrder.CASE_INSENSITIVE)
.build()
.findFirst()
val tagMatches: List<Long> = if (matchingTag == null) emptyList() else {
xrefBox.query()
.equal(NoteHashtagCrossRef_.hashtagId, matchingTag.id)
.build()
.find()
.map { it.noteId }
}
return (contentMatches + tagMatches).toSet()
}
private fun snapshotForHashtag(name: String): List<Note> {
val normalised = Hashtag.normalise(name)
val tag: HashtagEntity = tagBox.query()
@@ -278,7 +532,11 @@ class NoteRepositoryImpl(
private fun noteByIdSnapshot(id: Long): Note? {
val entity = noteBox.get(id) ?: return null
val tags = hashtagsByNoteId()[id].orEmpty()
return entity.toDomain().copy(hashtags = tags)
val attachments = attachmentsByNoteId()[id].orEmpty()
return entity.toDomain().copy(
hashtags = tags,
attachments = attachments,
)
}
/** Build [HashtagUsage] for every distinct tag, sorted by lastUsedAt DESC. */