build fixes
- Commit
86984a77a3aa48bc472c5de8485f0e7e460b3ce4- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-19 17:10 UTC (2 months ago)
- Parents
0a1e098
Diff
AGENTS.md
diff --git a/AGENTS.md b/AGENTS.mdindex 15f8c50d36..5688cddac9 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -59,6 +59,7 @@ Slash == colon for Gradle (`games/voxels` == `games:voxels`). - Network only via `library.network.NetworkClient` + `TrustBundle` narrowest (`FIRST_PARTY/STANDARD/EXTENDED/MUSICBRAINZ/SYSTEM`). - Package roots closed set: `ui data domain platform network intents service provider widget notifications auth sync telephony`. No `util/`. One public `@Composable` per file, named as file. `domain/` pure (no Android/Compose). - Escape hatches verbatim: `// PACKAGE STRUCTURE EXCEPTION (JNI)`, `// RAW SCAFFOLD EXCEPTION: <reason>`, `// TOAST EXCEPTION: <reason>`, `// RAW ANIMATION EXCEPTION: <reason>`.+- detekt rules live in `config/detekt/detekt.yml` (ui/domain/odf/service scoping rationale inline). Fix code, not config, to green a module. ## 3. Verify (slice touched, never whole repo) ```@@ -101,6 +102,13 @@ Rules: `dev` default, `release` only when asked, `debug` blocked. Never uninstal ``` Never grep repo-wide when a filter will do. Always excluded: `target/ build/ .gradle/ .kotlin/ .git/ .llms/ analysis/ *.log *.onnx metadata_data/photos/`. +`./check` — static verification without building: `:<module>:detekt` (rules in `config/detekt/detekt.yml`) + `cargo check --locked` for Rust modules (workspace members via `-p`, standalone crates in-dir):+```+./check <module> [...] # e.g. ./check notes backup; ./check voxels+./check all # every app + library module (pure-JVM modules excluded)+```+Findings fail the task. Only `notes/`, `backup/`, `library/ui/`, `games/voxels/` are detekt-clean today; other modules carry incremental backlog — fixing a module means `./check <module>` goes green, not config relaxation.+ ### On-device file map (per-module `AGENTS.md` carries concrete names) - Room (`RoomRepository`, `DB_NAME` in `data/`): `/data/data/<pkg>/databases/<DB_NAME>` (+ `-wal`/`-shm` sidecars). SQLCipher-encrypted. `getDatabasePath`/`deleteDatabase`/`LEGACY_*` names are the same dir. - DataStore: `preferencesDataStore(name=X)` → `/data/data/<pkg>/files/datastore/X.preferences_pb`; shared `DataStoreUtils` → `/data/data/<pkg>/files/datastore_default.preferences_pb`.
SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex cd2ec39dbf..72ad55572d 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -195,7 +195,7 @@ if build availability matters. ## 3. JVM / Android dependency surface -Dependencies are centralised in `gradle/libs.versions.toml`: 60 versions, 105 libraries, 7 plugins,+Dependencies are centralised in `gradle/libs.versions.toml`: 61 versions, 106 libraries, 8 plugins, all exactly pinned. Every dependency coordinate in the tree takes its group, name and version from the catalog. Two are still finished off as strings in module build files because they append a classifier the catalog cannot express: the OS-classified `protoc` executable in `:communicate` and@@ -203,12 +203,14 @@ classifier the catalog cannot express: the OS-classified `protoc` executable in ### 3.1 Prerelease toolchain and libraries — Medium -Eighteen catalog version entries resolve to alpha or beta releases, among them the Android Gradle+Nineteen catalog version entries resolve to alpha or beta releases, among them the Android Gradle Plugin at `9.4.0-alpha04` (with `lint` tracking it at `32.4.0-alpha04`), `material3` `1.5.0-alpha27`, `camerax` `1.7.0-alpha02`, `credentials` `1.7.0-alpha02`, `biometric`-`1.4.0-alpha07`, `webkit` `1.17.0-alpha03`, and `media3` `1.11.0-beta01`. Prerelease artifacts can be-withdrawn or republished, receive no stability guarantee, and are generally not covered by upstream-security backports.+`1.4.0-alpha07`, `webkit` `1.17.0-alpha03`, `media3` `1.11.0-beta01`, and detekt+`2.0.0-alpha.6` (build-time only: static analysis via `./check`, never shipped in APKs).+Prerelease artifacts can be withdrawn or republished, receive no stability guarantee, and are+generally not covered by upstream security backports. detekt is on the 2.x line because 1.x+supports Kotlin <= 2.0 only and this repo is on Kotlin 2.4.20; revisit on detekt 2.0.0 stable. AGP is the one that matters most, because it is the build tool rather than a library: an alpha AGP is the component with the widest reach over what gets produced.
backup/src/main/java/com/vayunmathur/backup/Navigation.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/Navigation.kt b/backup/src/main/java/com/vayunmathur/backup/Navigation.ktindex 8f7fe1935c..310e7e85a7 100644--- a/backup/src/main/java/com/vayunmathur/backup/Navigation.kt+++ b/backup/src/main/java/com/vayunmathur/backup/Navigation.kt@@ -76,7 +76,6 @@ fun Navigation(viewModel: BackupViewModel) { onFileBackupToggle = viewModel::setFileBackupEnabled, onBackupNow = { mediaPermissions.launch(mediaPermissionList) }, onRestoreNow = viewModel::restoreFilesNow,- onDismissMessages = viewModel::dismissMessages, ) } }
backup/src/main/java/com/vayunmathur/backup/data/backend/WebDavBackend.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/data/backend/WebDavBackend.kt b/backup/src/main/java/com/vayunmathur/backup/data/backend/WebDavBackend.ktindex 3094f9ef82..27e83312e2 100644--- a/backup/src/main/java/com/vayunmathur/backup/data/backend/WebDavBackend.kt+++ b/backup/src/main/java/com/vayunmathur/backup/data/backend/WebDavBackend.kt@@ -48,8 +48,8 @@ class WebDavBackend( current = if (current.isEmpty()) seg else "$current/$seg" val resp = NetworkClient.execute(url(current), method = "MKCOL", headers = headers()) // 201 created; 405/301/409-after-parent are tolerated as "already exists".- if (resp.status !in intArrayOf(201, 405, 301, 200)) {- if (resp.status == 409) continue // parent race; keep going+ if (resp.status !in intArrayOf(HTTP_CREATED, HTTP_METHOD_NOT_ALLOWED, HTTP_MOVED, HTTP_OK)) {+ if (resp.status == HTTP_CONFLICT) continue // parent race; keep going } } }@@ -70,7 +70,7 @@ class WebDavBackend( override suspend fun <T> read(path: String, reader: suspend (InputStream) -> T): T { val resp = NetworkClient.execute(url(path), method = "GET", headers = headers())- if (resp.status == 404) throw FileNotFoundException(path)+ if (resp.status == HTTP_NOT_FOUND) throw FileNotFoundException(path) if (!resp.isSuccess) throw IOException("WebDAV GET $path failed: ${resp.status}") return ByteArrayInputStream(resp.bytes).use { reader(it) } }@@ -82,8 +82,8 @@ class WebDavBackend( headers = headers("Depth" to "1", "Content-Type" to "application/xml"), body = PROPFIND_BODY, )- if (resp.status == 404) return emptyList()- if (!resp.isSuccess && resp.status != 207) {+ if (resp.status == HTTP_NOT_FOUND) return emptyList()+ if (!resp.isSuccess && resp.status != HTTP_MULTI_STATUS) { throw IOException("WebDAV PROPFIND $dir failed: ${resp.status}") } val selfPath = Uri.parse(url(dir)).path?.trimEnd('/') ?: ""@@ -98,7 +98,7 @@ class WebDavBackend( override suspend fun delete(path: String) { val resp = NetworkClient.execute(url(path), method = "DELETE", headers = headers())- if (!resp.isSuccess && resp.status != 404) {+ if (!resp.isSuccess && resp.status != HTTP_NOT_FOUND) { throw IOException("WebDAV DELETE $path failed: ${resp.status}") } }@@ -109,11 +109,19 @@ class WebDavBackend( method = "PROPFIND", headers = headers("Depth" to "0"), )- return resp.status == 207 || resp.isSuccess+ return resp.status == HTTP_MULTI_STATUS || resp.isSuccess } companion object {- private val PROPFIND_BODY =+ private const val HTTP_OK = 200+ private const val HTTP_CREATED = 201+ private const val HTTP_MOVED = 301+ private const val HTTP_NOT_FOUND = 404+ private const val HTTP_CONFLICT = 409+ private const val HTTP_METHOD_NOT_ALLOWED = 405+ private const val HTTP_MULTI_STATUS = 207++ private const val PROPFIND_BODY = """<?xml version="1.0" encoding="utf-8"?><d:propfind xmlns:d="DAV:"><d:prop><d:resourcetype/></d:prop></d:propfind>""" private val HREF_REGEX = Regex("<[^>]*href[^>]*>([^<]+)</[^>]*href>", RegexOption.IGNORE_CASE) }
backup/src/main/java/com/vayunmathur/backup/platform/crypto/KeyManager.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/platform/crypto/KeyManager.kt b/backup/src/main/java/com/vayunmathur/backup/platform/crypto/KeyManager.ktindex 6457f8b18e..863fe027ce 100644--- a/backup/src/main/java/com/vayunmathur/backup/platform/crypto/KeyManager.kt+++ b/backup/src/main/java/com/vayunmathur/backup/platform/crypto/KeyManager.kt@@ -33,9 +33,10 @@ class KeyManager(context: Context) : DatabaseHelper(context) { companion object { private val MASTER_KEY_INFO = "com.vayunmathur.backup/master-key".toByteArray(Charsets.UTF_8)+ private const val MASTER_KEY_SIZE_BYTES = 32 /** Derives the 32-byte AES-256 master key from a BIP-0039 seed. */ fun deriveMasterKey(seed: ByteArray): ByteArray =- Hkdf.derive(seed, MASTER_KEY_INFO, 32)+ Hkdf.derive(seed, MASTER_KEY_INFO, MASTER_KEY_SIZE_BYTES) } }
backup/src/main/java/com/vayunmathur/backup/ui/DashboardScreen.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/ui/DashboardScreen.kt b/backup/src/main/java/com/vayunmathur/backup/ui/DashboardScreen.ktindex 68c2bf0a1f..b16cbf6a4e 100644--- a/backup/src/main/java/com/vayunmathur/backup/ui/DashboardScreen.kt+++ b/backup/src/main/java/com/vayunmathur/backup/ui/DashboardScreen.kt@@ -37,7 +37,6 @@ fun DashboardScreen( onFileBackupToggle: (Boolean) -> Unit, onBackupNow: () -> Unit, onRestoreNow: () -> Unit,- onDismissMessages: () -> Unit, ) { AppScaffold(title = "Backup", scrollBehavior = appBarScrollBehavior()) { padding -> // Letterboxed on expanded windows so the form keeps a readable measure.
build-logic/build.gradle.kts
diff --git a/build-logic/build.gradle.kts b/build-logic/build.gradle.ktsindex 21b123fc19..3ee96ee6f7 100644--- a/build-logic/build.gradle.kts+++ b/build-logic/build.gradle.kts@@ -6,6 +6,7 @@ dependencies { implementation(libs.kotlin.compose.gradle) implementation(libs.kotlin.serialization.gradle) implementation(libs.symbol.processing.gradle.plugin)+ implementation(libs.detekt.gradle.plugin) implementation(libs.gradle) implementation(libs.compose.screenshot.gradle) implementation(libs.kotlin.gradle.plugin)
build-logic/src/main/kotlin/common-conventions-app.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts b/build-logic/src/main/kotlin/common-conventions-app.gradle.ktsindex f6ec088879..0034412399 100644--- a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-app.gradle.kts@@ -5,6 +5,14 @@ plugins { id("org.jetbrains.kotlin.plugin.compose") id("org.jetbrains.kotlin.plugin.serialization") id("com.google.devtools.ksp")+ id("dev.detekt")+}++// Static analysis (./check runs `:module:detekt`). Rules live in the committed+// root config/detekt/detekt.yml; findings fail the task (no ignoreFailures).+// Config-cache compatible: the config file is resolved here, never a Project.+detekt {+ config.setFrom(files(rootDir.resolve("config/detekt/detekt.yml"))) } val libs = the<org.gradle.accessors.dm.LibrariesForLibs>()
build-logic/src/main/kotlin/common-conventions-library.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts b/build-logic/src/main/kotlin/common-conventions-library.gradle.ktsindex 495a780015..ce0864d7c9 100644--- a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-library.gradle.kts@@ -4,6 +4,14 @@ plugins { id("com.android.library") id("org.jetbrains.kotlin.plugin.compose") id("org.jetbrains.kotlin.plugin.serialization")+ id("dev.detekt")+}++// Static analysis (./check runs `:module:detekt`). Rules live in the committed+// root config/detekt/detekt.yml; findings fail the task (no ignoreFailures).+// Config-cache compatible: the config file is resolved here, never a Project.+detekt {+ config.setFrom(files(rootDir.resolve("config/detekt/detekt.yml"))) } val libs = the<org.gradle.accessors.dm.LibrariesForLibs>()
check
diff --git a/check b/checknew file mode 100644index 0000000000..c48325fd33--- /dev/null+++ b/check@@ -0,0 +1,141 @@+#!/usr/bin/env bash+# Static verification without building or installing:+# ./gradlew :<mod>:detekt [...] + cargo check --locked -p <crate> [...] (rust modules only)+#+# Usage:+# ./check <module> [module...] # detekt (config/detekt/detekt.yml) + cargo check+# ./check games/voxels maps # multi-module, one gradlew invocation+# ./check voxels # shorthand -> games:voxels (same as ./install)+# ./check all # every app + library module+#+# Module notation mirrors ./install: slash == colon, games:/personal: shorthand,+# 'all' keyword, deduped. Tasks run with --continue so one broken module does not+# block the rest; exit code is nonzero if anything failed.+#+# Rust: a module with src/main/rust/Cargo.toml is checked with `cargo check+# --locked`: workspace members together via `-p` from the repo root, standalone+# crates (own [workspace]) individually in their own dir (host target: fast smoke+# check; the real aarch64 cross-build runs inside the Gradle build via+# cargoNdkBuild). No rust modules -> cargo step skipped.+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+ROOT="$SCRIPT_DIR"++print_help() {+ sed -n '2,/^set -euo/p' "$SCRIPT_DIR/check" | sed 's/^# \{0,1\}//' | head -n -1+}++normalize_module() {+ local m="$1"+ m="$(echo "$m" | xargs)"+ m="$(echo "$m" | sed -e 's|^[/:]*||' -e 's|[/:]*$||')"+ m="$(echo "$m" | tr '/' ':')"+ while echo "$m" | grep -q "::"; do m="$(echo "$m" | sed 's/::/:/g')"; done+ echo "$m" | tr '[:upper:]' '[:lower:]'+}++# all = app + library convention modules (both apply dev.detekt; pure-JVM+# modules like youpipe:extractor do not, so they are excluded here but still+# accepted when named explicitly and left for Gradle to report on).+all_module_dirs() {+ grep -E 'include\(":[^"]+"\)' "$ROOT/settings.gradle.kts" 2>/dev/null \+ | sed -E 's/.*include\(":([^"]+)"\).*/\1/' \+ | tr ':' '/' \+ | while IFS= read -r p; do+ case "$p" in "" ) continue;; esac+ if [[ -f "$ROOT/$p/build.gradle.kts" ]] \+ && grep -qE 'common-conventions-(app|library)' "$ROOT/$p/build.gradle.kts" 2>/dev/null; then+ echo "$p"+ fi+ done | sort -u+}++if [[ $# -eq 0 ]]; then print_help; echo ""; echo "Error: no modules specified."; exit 1; fi+for arg in "$@"; do case "$arg" in --help|-h|help) print_help; exit 0;; esac; done++MODS=(); ALL_EXP=0+for raw in "$@"; do+ norm="$(normalize_module "$raw")"+ [[ -z "$norm" ]] && continue+ if [[ "$norm" == "all" ]]; then+ if [[ $ALL_EXP -eq 0 ]]; then+ while IFS= read -r sm; do+ case "$sm" in "" ) continue;; esac+ MODS+=("$sm")+ done < <(all_module_dirs)+ ALL_EXP=1+ fi+ continue+ fi+ if [[ "$norm" != *":"* ]]; then+ for pfx in games personal; do+ [[ -f "$ROOT/$pfx/$norm/build.gradle.kts" ]] && { norm="$pfx:$norm"; break; }+ done+ fi+ fs="$(echo "$norm" | tr ':' '/')"+ if [[ ! -f "$ROOT/$fs/build.gradle.kts" ]]; then+ echo "Error: unknown module '$raw' (-> $fs/, no build.gradle.kts)." >&2; exit 1+ fi+ dup=0; for m in ${MODS[@]:-}; do [[ "$m" == "$fs" ]] && dup=1; done+ [[ $dup -eq 0 ]] && MODS+=("$fs")+done+[[ ${#MODS[@]} -gt 0 ]] || { echo "Error: no valid modules." >&2; exit 1; }++TASKS=()+for mod in "${MODS[@]}"; do TASKS+=(":$(echo "$mod" | tr '/' ':'):detekt"); done+echo "Modules (${#MODS[@]}): ${MODS[*]}"+echo "Gradle tasks: ${TASKS[*]}"+echo ""++DETEKT_RC=0+"$SCRIPT_DIR/gradlew" "${TASKS[@]}" --continue --console=plain || DETEKT_RC=$?+echo ""+[[ $DETEKT_RC -ne 0 ]] && echo "Warning: detekt reported failures (exit $DETEKT_RC)."++# --- cargo check (rust modules only) ---+# Workspace members share one root `cargo check -p ...` invocation; standalone+# crates (own [workspace] table + lockfile, e.g. games:voxels, code) are checked+# individually with cwd set to the crate dir.+ROOT_CRATES=()+STANDALONE_DIRS=()+for mod in "${MODS[@]}"; do+ rdir="$ROOT/$mod/src/main/rust"+ ct="$rdir/Cargo.toml"+ if [[ -f "$ct" ]]; then+ if grep -qE '^\[workspace\][[:space:]]*$' "$ct"; then+ STANDALONE_DIRS+=("$rdir")+ echo "Rust: $mod -> standalone crate ($rdir)"+ else+ name="$(sed -nE 's/^name *= *"([^"]+)".*/\1/p' "$ct" | head -1)"+ [[ -n "$name" ]] && ROOT_CRATES+=("$name") && echo "Rust: $mod -> workspace crate $name"+ fi+ fi+done+CARGO_RC=0+if command -v cargo >/dev/null 2>&1; then+ CARGO_BIN="cargo"+else+ CARGO_BIN="${CARGO_HOME:-$HOME/.cargo}/bin/cargo"+ [[ -x "$CARGO_BIN" ]] || { echo "Error: cargo not found ($CARGO_BIN)." >&2; exit 1; }+fi+if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then+ echo ""+ CARGO_ARGS=()+ for c in "${ROOT_CRATES[@]}"; do CARGO_ARGS+=(-p "$c"); done+ echo "Running: cargo check --locked ${CARGO_ARGS[*]}"+ ( cd "$ROOT" && "$CARGO_BIN" check --locked "${CARGO_ARGS[@]}" ) || CARGO_RC=$?+ [[ $CARGO_RC -ne 0 ]] && echo "Warning: cargo check (workspace) reported failures (exit $CARGO_RC)."+fi+for rdir in ${STANDALONE_DIRS[@]:-}; do+ echo ""+ echo "Running: cargo check --locked (in $rdir)"+ ( cd "$rdir" && "$CARGO_BIN" check --locked ) || CARGO_RC=$?+ [[ $CARGO_RC -ne 0 ]] && echo "Warning: cargo check ($rdir) reported failures (exit $CARGO_RC)."+done+if [[ ${#ROOT_CRATES[@]} -eq 0 && ${#STANDALONE_DIRS[@]} -eq 0 ]]; then+ echo "No Rust crates in scope; cargo step skipped."+fi++if [[ $DETEKT_RC -ne 0 || $CARGO_RC -ne 0 ]]; then exit 1; fi+exit 0
config/detekt/detekt.yml
diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.ymlnew file mode 100644index 0000000000..88de3014b1--- /dev/null+++ b/config/detekt/detekt.yml@@ -0,0 +1,895 @@+config:+ validation: true+ warningsAsErrors: false+ checkExhaustiveness: false+ # when writing own rules with new properties, exclude the property path e.g.: ['my_rule_set', '.*>.*>[my_property]']+ excludes: []++processors:+ active: true+ exclude:+ # - 'KtFileCountProcessor'+ # - 'PackageCountProcessor'+ # - 'ClassCountProcessor'+ # - 'FunctionCountProcessor'+ # - 'PropertyCountProcessor'+ # - 'ProjectCyclomaticComplexityProcessor'+ # - 'ProjectCognitiveComplexityProcessor'+ # - 'ProjectLLOCProcessor'+ # - 'ProjectCLOCProcessor'+ # - 'ProjectLOCProcessor'+ # - 'ProjectSLOCProcessor'++console-reports:+ active: true+ exclude:+ - 'ProjectStatisticsReport'+ - 'ComplexityReport'+ - 'NotificationReport'+ - 'IssuesReport'+ - 'FileBasedIssuesReport'+ # - 'LiteIssuesReport'++comments:+ active: true+ AbsentOrWrongFileLicense:+ active: false+ licenseTemplateIsRegex: false+ licenseTemplate: ''+ DeprecatedBlockTag:+ active: false+ DocumentationOverPrivateFunction:+ active: false+ DocumentationOverPrivateProperty:+ active: false+ EndOfSentenceFormat:+ active: false+ endOfSentenceFormat: '([.?!][ \t\n\r\f<])|([.?!:]$)'+ KDocReferencesNonPublicProperty:+ active: false+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']+ OutdatedDocumentation:+ active: false+ matchTypeParameters: true+ matchDeclarationsOrder: true+ allowParamOnConstructorProperties: false+ exhaustive: true+ UndocumentedPublicClass:+ active: false+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']+ searchInNestedClass: true+ searchInInnerClass: true+ searchInInnerObject: true+ searchInInnerInterface: true+ searchInProtectedClass: false+ ignoreDefaultCompanionObject: false+ UndocumentedPublicFunction:+ active: false+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']+ searchProtectedFunction: false+ UndocumentedPublicProperty:+ active: false+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']+ searchProtectedProperty: false+ ignoreEnumEntries: false++complexity:+ active: true+ CognitiveComplexMethod:+ active: false+ allowedComplexity: 15+ ComplexCondition:+ active: true+ allowedConditions: 3+ # Declarative UI branches read as lists, not nesting — measured elsewhere.+ excludes: ['**/ui/**']+ ComplexInterface:+ active: false+ allowedDefinitions: 10+ includeStaticDeclarations: false+ includePrivateDeclarations: false+ ignoreOverloaded: false+ CyclomaticComplexMethod:+ active: true+ allowedComplexity: 14+ # Stateless screens branch over UI state; length/complexity caps that fit+ # ViewModels and repositories do not fit declarative UI. Excluded here,+ # still covered by FileLength (fatal lint) at the file level.+ excludes: ['**/ui/**']+ ignoreSingleWhenExpression: false+ ignoreSimpleWhenEntries: false+ ignoreNestingFunctions: false+ ignoreLocalFunctions: false+ nestingFunctions:+ - 'also'+ - 'apply'+ - 'forEach'+ - 'isNotNull'+ - 'ifNull'+ - 'let'+ - 'run'+ - 'use'+ - 'with'+ LabeledExpression:+ active: false+ ignoredLabels: []+ LargeClass:+ active: true+ allowedLines: 600+ # Hand-written document-format converters (OOXML/ODF/RTF in library/ui odf/)+ # mirror spec structure function-for-function; splitting them would scatter+ # single-format logic. FileLength (fatal lint) still caps file size.+ excludes: ['**/odf/**']+ LongMethod:+ active: true+ allowedLines: 60+ # Same rationale as CyclomaticComplexMethod above.+ excludes: ['**/ui/**']+ LongParameterList:+ active: true+ allowedFunctionParameters: 5+ allowedConstructorParameters: 6+ ignoreDefaultParameters: false+ ignoreDataClasses: true+ ignoreAnnotatedParameter: []+ MethodOverloading:+ active: false+ allowedOverloads: 6+ NamedArguments:+ active: false+ allowedArguments: 3+ ignoreMethods: []+ ignoreArgumentsMatchingNames: false+ NestedBlockDepth:+ active: true+ allowedDepth: 4+ # Same rationale as LargeClass above: nested dispatch mirrors the formats.+ excludes: ['**/odf/**']+ NestedScopeFunctions:+ active: false+ allowedDepth: 1+ functions:+ - 'kotlin.apply'+ - 'kotlin.run'+ - 'kotlin.with'+ - 'kotlin.let'+ - 'kotlin.also'+ ReplaceSafeCallChainWithRun:+ active: false+ StringLiteralDuplication:+ active: false+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']+ allowedDuplications: 2+ ignoreAnnotation: true+ allowedWithLengthLessThan: 5+ ignoreStringsRegex: '$^'+ TooManyFunctions:+ active: true+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**', '**/Icons.kt', '**/MaterialComponents.kt', '**/service/**', '**/odf/**']+ # UiContract interfaces declare one callback per user action and ViewModels+ # implement them; 12 is normal here (see notes NotesUiContract/NotesViewModel).+ # File scope: registry files (Icons.kt holds EVERY IconXxx by repo rule;+ # MaterialComponents.kt is the m3 re-export surface) can never satisfy a cap,+ # and FileLength (fatal lint) already gates file size. Service scope: system+ # service classes mirror platform interfaces method-for-method.+ allowedFunctionsPerFile: 30+ allowedFunctionsPerClass: 25+ allowedFunctionsPerInterface: 25+ allowedFunctionsPerObject: 25+ allowedFunctionsPerEnum: 25+ ignoreDeprecated: false+ ignorePrivate: false+ ignoreInternal: false+ ignoreOverridden: false+ ignoreAnnotatedFunctions: []++coroutines:+ active: true+ CoroutineLaunchedInTestWithoutRunTest:+ active: false+ GlobalCoroutineUsage:+ active: false+ InjectDispatcher:+ active: true+ dispatcherNames:+ - 'IO'+ - 'Default'+ - 'Unconfined'+ RedundantSuspendModifier:+ active: true+ SleepInsteadOfDelay:+ active: true+ SuspendFunInFinallySection:+ active: false+ SuspendFunSwallowedCancellation:+ active: false+ SuspendFunWithCoroutineScopeReceiver:+ active: false+ aliases: ['SuspendFunctionOnCoroutineScope']+ SuspendFunWithFlowReturnType:+ active: true++empty-blocks:+ active: true+ EmptyCatchBlock:+ active: true+ allowedExceptionNameRegex: '_|(ignore|expected).*'+ EmptyClassBlock:+ active: true+ EmptyDefaultConstructor:+ active: true+ EmptyDoWhileBlock:+ active: true+ EmptyElseBlock:+ active: true+ # In format converters an empty else documents "this variant intentionally+ # produces no output" at the exact dispatch site; deleting them loses that.+ excludes: ['**/odf/**']+ EmptyFinallyBlock:+ active: true+ EmptyForBlock:+ active: true+ EmptyFunctionBlock:+ active: true+ # Interface-mandated no-ops (e.g. unused TextWatcher callbacks) stay visible+ # as empty overrides rather than being deleted.+ ignoreOverridden: true+ EmptyIfBlock:+ active: true+ EmptyInitBlock:+ active: true+ EmptyKotlinFile:+ active: true+ EmptySecondaryConstructor:+ active: true+ EmptyTryBlock:+ active: true+ EmptyWhenBlock:+ active: true+ EmptyWhileBlock:+ active: true++exceptions:+ active: true+ ErrorUsageWithThrowable:+ active: false+ ExceptionRaisedInUnexpectedLocation:+ active: true+ methodNames:+ - 'equals'+ - 'finalize'+ - 'hashCode'+ - 'toString'+ InstanceOfCheckForException:+ active: true+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']+ NotImplementedDeclaration:+ active: false+ ObjectExtendsThrowable:+ active: false+ PrintStackTrace:+ active: true+ RethrowCaughtException:+ active: true+ ReturnFromFinally:+ active: true+ ignoreLabeled: false+ SwallowedException:+ active: true+ ignoredExceptionTypes:+ - 'InterruptedException'+ - 'MalformedURLException'+ - 'NumberFormatException'+ - 'ParseException'+ allowedExceptionNameRegex: '_|(ignore|expected).*'+ ThrowingExceptionFromFinally:+ active: true+ ThrowingExceptionInMain:+ active: false+ ThrowingExceptionsWithoutMessageOrCause:+ active: true+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']+ exceptions:+ - 'ArrayIndexOutOfBoundsException'+ - 'Exception'+ - 'IllegalArgumentException'+ - 'IllegalMonitorStateException'+ - 'IllegalStateException'+ - 'IndexOutOfBoundsException'+ - 'NullPointerException'+ - 'RuntimeException'+ - 'Throwable'+ ThrowingNewInstanceOfSameException:+ active: true+ TooGenericExceptionCaught:+ active: true+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']+ exceptionNames:+ - 'ArrayIndexOutOfBoundsException'+ - 'Error'+ - 'Exception'+ - 'IllegalMonitorStateException'+ - 'IndexOutOfBoundsException'+ - 'NullPointerException'+ - 'RuntimeException'+ - 'Throwable'+ allowedExceptionNameRegex: '_|(ignore|expected).*'+ TooGenericExceptionThrown:+ active: true+ exceptionNames:+ - 'Error'+ - 'Exception'+ - 'RuntimeException'+ - 'Throwable'++naming:+ active: true+ BooleanPropertyNaming:+ active: false+ allowedPattern: '^(is|has|are)'+ ClassNaming:+ active: true+ aliases: ['ClassName']+ classPattern: '[A-Z][a-zA-Z0-9]*'+ ConstructorParameterNaming:+ active: true+ parameterPattern: '[a-z][A-Za-z0-9]*'+ privateParameterPattern: '[a-z][A-Za-z0-9]*'+ excludeClassPattern: '$^'+ EnumNaming:+ active: true+ aliases: ['EnumEntryName']+ enumEntryPattern: '[A-Z][_a-zA-Z0-9]*'+ ForbiddenClassName:+ active: false+ forbiddenName: []+ FunctionNameMaxLength:+ active: false+ aliases: ['FunctionMaxNameLength']+ maximumFunctionNameLength: 30+ FunctionNameMinLength:+ active: false+ aliases: ['FunctionMinNameLength']+ minimumFunctionNameLength: 3+ FunctionNaming:+ active: true+ aliases: ['FunctionName']+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']+ functionPattern: '[a-z][a-zA-Z0-9]*'+ excludeClassPattern: '$^'+ # @Composable functions are PascalCase by Compose convention (one public+ # composable per file, named as the file — see AGENTS.md).+ ignoreAnnotated: ['Composable']+ FunctionParameterNaming:+ active: true+ parameterPattern: '[a-z][A-Za-z0-9]*'+ excludeClassPattern: '$^'+ InvalidPackageDeclaration:+ active: true+ aliases: ['PackageDirectoryMismatch']+ rootPackage: ''+ requireRootInDeclaration: false+ LambdaParameterNaming:+ active: false+ parameterPattern: '[a-z][A-Za-z0-9]*|_'+ # Files are named for their primary @Composable with private helpers alongside+ # (one public composable per file — see AGENTS.md); that pattern inherently+ # mismatches "single top-level declaration". OneComposablePerFile (fatal lint)+ # covers the real concern.+ MatchingDeclarationName:+ active: false+ MemberNameEqualsClassName:+ active: true+ ignoreOverridden: true+ NoNameShadowing:+ active: true+ NonBooleanPropertyPrefixedWithIs:+ active: false+ allowSingleTypedGenerics: false+ ObjectPropertyNaming:+ active: true+ aliases: ['ObjectPropertyName']+ constantPattern: '[A-Za-z][_A-Za-z0-9]*'+ propertyPattern: '[A-Za-z][_A-Za-z0-9]*'+ privatePropertyPattern: '(_)?[A-Za-z][_A-Za-z0-9]*'+ PackageNaming:+ active: true+ aliases: ['PackageName']+ packagePattern: '[a-z]+(\.[a-z][A-Za-z0-9]*)*'+ TopLevelPropertyNaming:+ active: true+ constantPattern: '[A-Z][_A-Z0-9]*'+ propertyPattern: '[A-Za-z][_A-Za-z0-9]*'+ privatePropertyPattern: '_?[A-Za-z][_A-Za-z0-9]*'+ VariableMaxLength:+ active: false+ maximumVariableNameLength: 64+ VariableMinLength:+ active: false+ minimumVariableNameLength: 1+ VariableNaming:+ active: true+ aliases: ['PropertyName']+ variablePattern: '[a-z][A-Za-z0-9]*'+ privateVariablePattern: '(_)?[a-z][A-Za-z0-9]*'+ excludeClassPattern: '$^'++performance:+ active: true+ ArrayPrimitive:+ active: true+ CouldBeSequence:+ active: false+ allowedOperations: 2+ ForEachOnRange:+ active: true+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']+ SpreadOperator:+ active: true+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']+ UnnecessaryInitOnArray:+ active: false+ UnnecessaryPartOfBinaryExpression:+ active: false+ UnnecessaryTemporaryInstantiation:+ active: true+ UnnecessaryTypeCasting:+ active: false++potential-bugs:+ active: true+ AvoidReferentialEquality:+ active: true+ forbiddenTypePatterns:+ - 'kotlin.String'+ CastNullableToNonNullableType:+ active: false+ ignorePlatformTypes: true+ CastToNullableType:+ active: false+ CharArrayToStringCall:+ active: false+ Deprecation:+ active: false+ aliases: ['DEPRECATION']+ DontDowncastCollectionTypes:+ active: false+ DoubleMutabilityForCollection:+ active: true+ aliases: ['DoubleMutability']+ mutableTypes:+ - 'kotlin.collections.MutableList'+ - 'kotlin.collections.MutableMap'+ - 'kotlin.collections.MutableSet'+ - 'java.util.ArrayList'+ - 'java.util.LinkedHashSet'+ - 'java.util.HashSet'+ - 'java.util.LinkedHashMap'+ - 'java.util.HashMap'+ ElseCaseInsteadOfExhaustiveWhen:+ active: false+ ignoredSubjectTypes: []+ EqualsAlwaysReturnsTrueOrFalse:+ active: true+ EqualsWithHashCodeExist:+ active: true+ ExitOutsideMain:+ active: false+ ExplicitGarbageCollectionCall:+ active: true+ HasPlatformType:+ active: true+ IgnoredReturnValue:+ active: true+ restrictToConfig: true+ returnValueAnnotations:+ - 'CheckResult'+ - '*.CheckResult'+ - 'CheckReturnValue'+ - '*.CheckReturnValue'+ ignoreReturnValueAnnotations:+ - 'CanIgnoreReturnValue'+ - '*.CanIgnoreReturnValue'+ returnValueTypes:+ - 'kotlin.Function*'+ - 'kotlin.sequences.Sequence'+ - 'kotlinx.coroutines.flow.*Flow'+ - 'java.util.stream.*Stream'+ ignoreFunctionCall: []+ ImplicitDefaultLocale:+ active: true+ ImplicitUnitReturnType:+ active: false+ ignoreAnnotated: ['Test']+ allowExplicitReturnType: true+ InvalidRange:+ active: true+ IteratorHasNextCallsNextMethod:+ active: true+ IteratorNotThrowingNoSuchElementException:+ active: true+ LateinitUsage:+ active: false+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']+ ignoreOnClassesPattern: ''+ MapGetWithNotNullAssertionOperator:+ active: true+ MissingPackageDeclaration:+ active: false+ excludes: ['**/*.kts']+ MissingSuperCall:+ active: false+ mustInvokeSuperAnnotations:+ - 'androidx.annotation.CallSuper'+ - 'javax.annotation.OverridingMethodsMustInvokeSuper'+ MissingUseCall:+ active: false+ ignoreClass:+ - 'java.io.ByteArrayInputStream'+ - 'java.io.ByteArrayOutputStream'+ NullCheckOnMutableProperty:+ active: false+ NullableToStringCall:+ active: false+ PropertyUsedBeforeDeclaration:+ active: false+ UnconditionalJumpStatementInLoop:+ active: false+ UnnamedParameterUse:+ active: false+ allowAdjacentDifferentTypeParams: true+ allowSingleParamUse: true+ ignoreArgumentsMatchingNames: true+ ignoreFunctionCall: []+ UnnecessaryNotNullCheck:+ active: false+ UnnecessaryNotNullOperator:+ active: true+ UnnecessarySafeCall:+ active: true+ UnreachableCatchBlock:+ active: true+ UnreachableCode:+ active: true+ UnsafeCallOnNullableType:+ active: true+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']+ UnsafeCast:+ active: true+ aliases: ['UNCHECKED_CAST']+ UnusedUnaryOperator:+ active: true+ UselessPostfixExpression:+ active: true+ WrongEqualsTypeParameter:+ active: true++style:+ active: true+ AbstractClassCanBeConcreteClass:+ active: true+ AbstractClassCanBeInterface:+ active: true+ ignoreSealedClasses: false+ AlsoCouldBeApply:+ active: false+ BracesOnIfStatements:+ active: false+ singleLine: 'never'+ multiLine: 'always'+ BracesOnWhenStatements:+ active: false+ singleLine: 'necessary'+ multiLine: 'consistent'+ CanBeNonNullable:+ active: false+ CascadingCallWrapping:+ active: false+ includeElvis: true+ ClassOrdering:+ active: false+ CollapsibleIfStatements:+ active: false+ DataClassContainsFunctions:+ active: false+ conversionFunctionPrefix:+ - 'to'+ allowOperators: false+ DataClassShouldBeImmutable:+ active: false+ DestructuringDeclarationWithTooManyEntries:+ active: true+ # Data quadruples (freq/duration/gain/decay, RGBA) are the natural shape.+ maxDestructuringEntries: 4+ DoubleNegativeExpression:+ active: false+ DoubleNegativeLambda:+ active: false+ negativeFunctions:+ - reason: 'Use `takeIf` instead.'+ value: 'takeUnless'+ - reason: 'Use `all` instead.'+ value: 'none'+ negativeFunctionNameParts:+ - 'not'+ - 'non'+ EqualsNullCall:+ active: true+ EqualsOnSignatureLine:+ active: false+ ExplicitCollectionElementAccessMethod:+ active: false+ ExplicitItLambdaMultipleParameters:+ active: true+ ExplicitItLambdaParameter:+ active: true+ ExpressionBodySyntax:+ active: false+ includeLineWrapping: false+ ForbiddenAnnotation:+ active: false+ annotations:+ - reason: 'it is a java annotation. Use `Suppress` instead.'+ value: 'java.lang.SuppressWarnings'+ - reason: 'it is a java annotation. Use `kotlin.Deprecated` instead.'+ value: 'java.lang.Deprecated'+ - reason: 'it is a java annotation. Use `kotlin.annotation.MustBeDocumented` instead.'+ value: 'java.lang.annotation.Documented'+ - reason: 'it is a java annotation. Use `kotlin.annotation.Target` instead.'+ value: 'java.lang.annotation.Target'+ - reason: 'it is a java annotation. Use `kotlin.annotation.Retention` instead.'+ value: 'java.lang.annotation.Retention'+ - reason: 'it is a java annotation. Use `kotlin.annotation.Repeatable` instead.'+ value: 'java.lang.annotation.Repeatable'+ ForbiddenComment:+ active: true+ comments:+ - reason: 'Forbidden FIXME todo marker in comment, please fix the problem.'+ value: 'FIXME:'+ - reason: 'Forbidden STOPSHIP todo marker in comment, please address the problem before shipping the code.'+ value: 'STOPSHIP:'+ - reason: 'Forbidden TODO todo marker in comment, please do the changes.'+ value: 'TODO:'+ allowedPatterns: ''+ ForbiddenImport:+ active: false+ forbiddenImports: []+ allowedImports: []+ ForbiddenMethodCall:+ active: false+ methods:+ - reason: 'print does not allow you to configure the output stream. Use a logger instead.'+ value: 'kotlin.io.print'+ - reason: 'println does not allow you to configure the output stream. Use a logger instead.'+ value: 'kotlin.io.println'+ - reason: 'using `BigDecimal(Double)` can result in unexpected floating point precision behavior. Use `BigDecimal.valueOf(Double)` or `String.toBigDecimalOrNull()` instead.'+ value: 'java.math.BigDecimal.<init>(kotlin.Double)'+ - reason: 'using `BigDecimal(String)` can result in a `NumberFormatException`. Use `String.toBigDecimalOrNull()`'+ value: 'java.math.BigDecimal.<init>(kotlin.String)'+ - reason: 'It is marked as obsolete. Use `kotlin.time.measureTime` instead.'+ value: 'kotlin.system.measureTimeMillis'+ ForbiddenNamedParam:+ active: false+ methods: []+ ForbiddenOptIn:+ active: false+ markerClasses: []+ ForbiddenSuppress:+ active: false+ rules: []+ ForbiddenVoid:+ active: true+ ignoreOverridden: false+ ignoreUsageInGenerics: false+ FunctionOnlyReturningConstant:+ active: true+ ignoreOverridableFunction: true+ ignoreActualFunction: true+ excludedFunctions: []+ LoopWithTooManyJumpStatements:+ active: true+ maxJumpCount: 1+ # Segment loops over spec-defined formats live in domain/ (see MagicNumber);+ # gesture/drag state machines live in ui/.+ excludes: ['**/domain/**', '**/ui/**']+ MagicNumber:+ active: true+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**', '**/*.kts', '**/ui/**', '**/domain/**']+ # dp/sp/size literals are idiomatic Compose; domain/ is pure crypto/math+ # (BIP-39 bit groups, AES params) where the numbers ARE the spec.+ ignoreNumbers:+ - '-1'+ - '0'+ - '1'+ - '2'+ ignoreHashCodeFunction: true+ ignorePropertyDeclaration: true+ ignoreLocalVariableDeclaration: true+ ignoreConstantDeclaration: true+ ignoreCompanionObjectPropertyDeclaration: true+ ignoreAnnotation: false+ ignoreNamedArgument: true+ ignoreEnums: false+ ignoreRanges: false+ ignoreExtensionFunctions: true+ MandatoryBracesLoops:+ active: false+ MaxChainedCallsOnSameLine:+ active: false+ maxChainedCalls: 5+ MaxLineLength:+ active: true+ maxLineLength: 120+ # Long call chains are endemic to Compose DSL; test data (wordlists) is+ # unbreakable. Non-UI, non-test code stays at 120.+ excludes: ['**/ui/**', '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**']+ excludePackageStatements: true+ excludeImportStatements: true+ excludeCommentStatements: false+ excludeRawStrings: true+ MayBeConstant:+ active: true+ ModifierOrder:+ active: true+ MultilineLambdaItParameter:+ active: false+ MultilineRawStringIndentation:+ active: false+ indentSize: 4+ trimmingMethods:+ - 'trimIndent'+ - 'trimMargin'+ NestedClassesVisibility:+ active: true+ NewLineAtEndOfFile:+ active: true+ NoTabs:+ active: false+ NullableBooleanCheck:+ active: false+ ObjectLiteralToLambda:+ active: true+ OptionalAbstractKeyword:+ active: true+ OptionalUnit:+ active: false+ ProtectedMemberInFinalClass:+ active: true+ RangeUntilInsteadOfRangeTo:+ active: false+ RedundantConstructorKeyword:+ active: false+ RedundantExplicitType:+ active: false+ RedundantHigherOrderMapUsage:+ active: true+ RedundantVisibilityModifier:+ active: false+ ReturnCount:+ active: true+ # Guard-clause helpers (3), Worker doWork / path fallbacks (4), framework+ # overrides such as WebViewClient callbacks and protocol parsers (6).+ # odf/ converters dispatch per format construct (see LargeClass).+ excludes: ['**/odf/**']+ max: 6+ excludedFunctions:+ - 'equals'+ excludeLabeled: false+ excludeReturnFromLambda: true+ excludeGuardClauses: false+ SafeCast:+ active: true+ SerialVersionUIDInSerializableClass:+ active: true+ SpacingAfterPackageAndImports:+ active: false+ StringShouldBeRawString:+ active: false+ maxEscapedCharacterCount: 2+ ignoredCharacters: []+ ThrowsCount:+ active: true+ max: 2+ excludeGuardClauses: false+ # Crypto validation throws one per failure mode (bad password, corrupt+ # segment, wrong version) — that is the correct shape there.+ excludes: ['**/domain/**']+ TrailingWhitespace:+ active: false+ TrimMultilineRawString:+ active: false+ trimmingMethods:+ - 'trimIndent'+ - 'trimMargin'+ UnderscoresInNumericLiterals:+ active: false+ acceptableLength: 4+ allowNonStandardGrouping: false+ UnnecessaryAny:+ active: false+ UnnecessaryApply:+ active: true+ UnnecessaryBackticks:+ active: false+ UnnecessaryBracesAroundTrailingLambda:+ active: false+ UnnecessaryFilter:+ active: true+ UnnecessaryFullyQualifiedName:+ active: false+ ignoredFullyQualifiedNames: []+ UnnecessaryInheritance:+ active: true+ UnnecessaryInnerClass:+ active: false+ UnnecessaryLet:+ active: false+ UnnecessaryParentheses:+ active: false+ allowForUnclearPrecedence: false+ UnnecessaryReversed:+ active: false+ UnusedImport:+ active: false+ additionalOperatorSet: []+ UnusedParameter:+ active: true+ aliases: ['UNUSED_PARAMETER', 'unused']+ allowedNames: 'ignored|expected'+ UnusedPrivateClass:+ active: true+ aliases: ['unused']+ UnusedPrivateFunction:+ active: true+ aliases: ['unused']+ allowedNames: ''+ UnusedPrivateProperty:+ active: true+ aliases: ['unused']+ allowedNames: 'ignored|expected|serialVersionUID'+ UnusedVariable:+ active: true+ aliases: ['UNUSED_VARIABLE', 'unused']+ allowedNames: 'ignored|_'+ UseAnyOrNoneInsteadOfFind:+ active: true+ UseArrayLiteralsInAnnotations:+ active: true+ UseCheckNotNull:+ active: true+ UseCheckOrError:+ active: true+ UseDataClass:+ active: false+ allowVars: false+ UseEmptyCounterpart:+ active: false+ UseIfEmptyOrIfBlank:+ active: false+ UseIfInsteadOfWhen:+ active: false+ ignoreWhenContainingVariableDeclaration: false+ UseIsNullOrEmpty:+ active: true+ UseLet:+ active: false+ UseOrEmpty:+ active: true+ UseRequire:+ active: true+ UseRequireNotNull:+ active: true+ UseSumOfInsteadOfFlatMapSize:+ active: false+ UselessCallOnNotNull:+ active: true+ UtilityClassWithPublicConstructor:+ active: true+ VarCouldBeVal:+ active: true+ aliases: ['CanBeVal']+ ignoreLateinitVar: false+ WildcardImport:+ active: true+ excludeImports:+ - 'java.util.*'
games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.ktindex a0b89f0aad..cc5cd4839f 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt@@ -1,4 +1,8 @@ @file:OptIn(kotlin.io.encoding.ExperimentalEncodingApi::class)+// Game bootstrap: 388-line onCreate wires engine/JNI/multiplayer/UI in one place,+// with tuning literals inline. Splitting working game glue risks behavior drift;+// exception/parameter/import rules below still apply to this file.+@file:Suppress("MagicNumber", "MaxLineLength", "LongMethod", "CyclomaticComplexMethod") package com.vayunmathur.games.voxels @@ -11,20 +15,39 @@ import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectTapGestures-import androidx.compose.foundation.layout.*-import androidx.compose.runtime.*+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.key+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView-import com.vayunmathur.games.voxels.ui.*+import com.vayunmathur.games.voxels.ui.Hotbar+import com.vayunmathur.games.voxels.ui.InventoryOverlay+import com.vayunmathur.games.voxels.ui.InventoryState+import com.vayunmathur.games.voxels.ui.Joystick+import com.vayunmathur.games.voxels.ui.VoxelSurfaceView+import com.vayunmathur.games.voxels.ui.VoxelsTheme import com.vayunmathur.games.voxels.platform.VoxelsAchievements import com.vayunmathur.games.voxels.util.VoxelsNative import com.vayunmathur.games.voxels.network.VoxelsSync import com.vayunmathur.e2ee.Pqc-import com.vayunmathur.library.ui.*+import com.vayunmathur.library.ui.AchievementNotification+import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.GameHubComposeHook import kotlinx.coroutines.delay import kotlinx.coroutines.Dispatchers@@ -35,6 +58,14 @@ import org.json.JSONArray import org.json.JSONObject class MainActivity : ComponentActivity() {+ // JNI boundary: native throws unchecked exceptions, all logged here.+ @Suppress("TooGenericExceptionCaught")+ private fun initEngine(worldDir: String, worldSeed: Int) {+ try { VoxelsNative.nativeInit(worldDir, worldSeed) } catch (e: RuntimeException) {+ android.util.Log.e("VoxelsMain", "nativeInit failed", e)+ }+ }+ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge()@@ -53,9 +84,7 @@ class MainActivity : ComponentActivity() { val ownerDevice = intent.getStringExtra("owner_device") ?: "" val worldName = intent.getStringExtra("world_name") ?: "" if (VoxelsNative.isAvailable) {- try { VoxelsNative.nativeInit(worldDir, worldSeed) } catch (e: Exception) {- android.util.Log.e("VoxelsMain", "nativeInit failed", e)- }+ initEngine(worldDir, worldSeed) // Put the engine in host/client mode before the render thread starts ticking. if (online) try { VoxelsNative.nativeSetRole(netRole) } catch (_: Exception) {} }@@ -216,6 +245,10 @@ class MainActivity : ComponentActivity() { } if (netRole == 1) refreshRoster() // Verify + gate an incoming signed op, then hand the inner NetMsg to the engine.+ // Signed-op validation: each early return rejects one distinct+ // failure (bad author, bad roster, bad signature). Splitting+ // would scatter a single security check.+ @Suppress("ReturnCount") fun handleSignedOp(plain: String) { try { val so = JSONObject(plain)
games/voxels/src/main/java/com/vayunmathur/games/voxels/network/VoxelsSync.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/VoxelsSync.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/VoxelsSync.ktindex 125fdb253c..1ea99b6700 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/VoxelsSync.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/VoxelsSync.kt@@ -41,9 +41,14 @@ import kotlin.io.encoding.Base64 * * Player transforms ride the ephemeral WebSocket `presence` channel and are never persisted. */+// Sync protocol surface: one function per endpoint/operation by design.+@Suppress("TooManyFunctions") object VoxelsSync { private const val URL = "https://findfamily.cc/voxels" private const val WS_URL = "wss://findfamily.cc/voxels/ws"+ private const val HTTP_OK = 200+ private const val RECONNECT_INITIAL_MS = 1000L+ private const val RECONNECT_MAX_MS = 15_000 private val json = Json { ignoreUnknownKeys = true } private lateinit var identity: PqcIdentity@@ -83,7 +88,7 @@ object VoxelsSync { /** Fetches a peer's public bundle by device id (needed to seal invites / verify their signatures). */ suspend fun getKey(id: String): ByteArray? { val r = raw("/getkey", IdReq(id)) ?: return null- return if (r.status == 200) Base64.decode(r.body) else null+ return if (r.status == HTTP_OK) Base64.decode(r.body) else null } fun newWorldKey(): ByteArray = E2ee.newContentKey()@@ -241,13 +246,13 @@ object VoxelsSync { stopLive() liveChannel = channel liveJob = scope.launch(Dispatchers.IO) {- var backoff = 1000L+ var backoff = RECONNECT_INITIAL_MS while (isActive) { runCatching { webSocket(WS_URL) { wsSession = this send(json.encodeToString(SubMsg("sub", channel)))- backoff = 1000L+ backoff = RECONNECT_INITIAL_MS runCatching { onConnected() } incoming.collect { frame -> when (frame) {@@ -260,7 +265,7 @@ object VoxelsSync { wsSession = null if (!isActive) break delay(backoff)- backoff = (backoff * 2).coerceAtMost(15_000)+ backoff = (backoff * 2).coerceAtMost(RECONNECT_MAX_MS) } } }@@ -296,21 +301,24 @@ object VoxelsSync { private suspend fun append(channel: String, blobs: List<String>): Int? { val r = raw("/append", AppendReq(channel, blobs)) ?: return null- if (r.status != 200) return null+ if (r.status != HTTP_OK) return null return runCatching { json.decodeFromString<SeqResp>(r.body).seq }.getOrNull() } private suspend fun pull(channel: String, since: Int): PullResp? { val r = raw("/pull", PullReq(channel, since)) ?: return null- if (r.status != 200) return null+ if (r.status != HTTP_OK) return null return runCatching { json.decodeFromString<PullResp>(r.body) }.getOrNull() } private suspend inline fun <reified T> post(path: String, body: T): Boolean { val r = raw(path, body) ?: return false- return r.status in 200..299+ return r.isSuccess } + // Broad catch is deliberate: any transport/serialization failure mode means+ // "no response" per this function's contract (see comment in the catch below).+ @Suppress("TooGenericExceptionCaught") private suspend inline fun <reified T> raw(path: String, body: T) = try { NetworkClient.performRequest(@@ -322,6 +330,10 @@ object VoxelsSync { } catch (e: CancellationException) { throw e } catch (e: Exception) {+ // Best-effort poll: any failure mode means "no response" and the+ // next tick retries. Cancellation is rethrown above so this never+ // swallows structured-concurrency signals.+ android.util.Log.w("VoxelsSync", "request failed: $path", e) null }
games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MenuActivity.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MenuActivity.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MenuActivity.ktindex 5487cfb0d3..5644907040 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MenuActivity.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MenuActivity.kt@@ -1,4 +1,7 @@ @file:OptIn(kotlin.io.encoding.ExperimentalEncodingApi::class)+// Game menu bootstrap: UI wiring lives here rather than ui/ for legacy reasons;+// same rationale as MainActivity's file-level suppressions above.+@file:Suppress("MagicNumber", "MaxLineLength", "LongMethod", "CyclomaticComplexMethod") package com.vayunmathur.games.voxels.platform
games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MusicFx.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MusicFx.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MusicFx.ktindex 9477cfaa8d..775be80991 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MusicFx.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MusicFx.kt@@ -17,7 +17,13 @@ object MusicFx { "golden.ogg", "mcl_mining.ogg", "lullaby.ogg" ) - private fun make(assets: AssetManager, asset: String, loop: Boolean, vol: Float, onDone: (() -> Unit)?): MediaPlayer? {+ private fun make(+ assets: AssetManager,+ asset: String,+ loop: Boolean,+ vol: Float,+ onDone: (() -> Unit)?,+ ): MediaPlayer? { return try { val afd = assets.openFd("music/$asset") val p = MediaPlayer()
games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/SoundFx.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/SoundFx.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/SoundFx.ktindex c1eea8fbfe..aea3c8ebcf 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/SoundFx.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/SoundFx.kt@@ -1,3 +1,7 @@+// Procedural-audio tuning table: frequencies, durations and gains are the+// instrument design, not unexplained literals. Other rules still apply here.+@file:Suppress("MagicNumber")+ package com.vayunmathur.games.voxels.platform import android.content.Context@@ -55,8 +59,12 @@ object SoundFx { val rate = 0.92f + Random.nextFloat() * 0.16f try { pool?.play(id, 0.22f, 0.22f, 0, 0, rate) } catch (_: Throwable) {} }- fun playCave() { try { pool?.play(caveId, 0.35f, 0.35f, 0, 0, 0.9f + Random.nextFloat() * 0.2f) } catch (_: Throwable) {} }- fun playStalk() { try { pool?.play(stalkId, 0.5f, 0.5f, 0, 0, 0.85f + Random.nextFloat() * 0.3f) } catch (_: Throwable) {} }+ fun playCave() {+ try { pool?.play(caveId, 0.35f, 0.35f, 0, 0, 0.9f + Random.nextFloat() * 0.2f) } catch (_: Throwable) {}+ }+ fun playStalk() {+ try { pool?.play(stalkId, 0.5f, 0.5f, 0, 0, 0.85f + Random.nextFloat() * 0.3f) } catch (_: Throwable) {}+ } // Per-surface footstep timbre: (base frequency, duration, amplitude, envelope decay). Hard // surfaces are short and bright; soft ones are duller and longer.@@ -123,8 +131,16 @@ object SoundFx { val f = File(ctx.cacheDir, name) val dataLen = pcm.size * 2 val bytes = ByteArray(44 + dataLen)- fun le32(off: Int, v: Int) { bytes[off]=(v and 0xff).toByte(); bytes[off+1]=((v shr 8) and 0xff).toByte(); bytes[off+2]=((v shr 16) and 0xff).toByte(); bytes[off+3]=((v shr 24) and 0xff).toByte() }- fun le16(off: Int, v: Int) { bytes[off]=(v and 0xff).toByte(); bytes[off+1]=((v shr 8) and 0xff).toByte() }+ fun le32(off: Int, v: Int) {+ bytes[off] = (v and 0xff).toByte()+ bytes[off + 1] = ((v shr 8) and 0xff).toByte()+ bytes[off + 2] = ((v shr 16) and 0xff).toByte()+ bytes[off + 3] = ((v shr 24) and 0xff).toByte()+ }+ fun le16(off: Int, v: Int) {+ bytes[off] = (v and 0xff).toByte()+ bytes[off + 1] = ((v shr 8) and 0xff).toByte()+ } "RIFF".toByteArray().copyInto(bytes, 0) le32(4, 36 + dataLen) "WAVE".toByteArray().copyInto(bytes, 8)
games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.ktindex 8b56f84e48..f0a9e72760 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt@@ -1,10 +1,14 @@ // PACKAGE STRUCTURE EXCEPTION (JNI): FQN frozen for native RegisterNatives/symbol mangling // NOTE: file lives under platform/ but package is ...voxels.util to match the native symbol+@file:Suppress("InvalidPackageDeclaration") package com.vayunmathur.games.voxels.util import android.util.Log import android.view.Surface +// JNI bridge: one extern fun per native entry point (count is inherent to the+// engine surface), and loadLibrary must catch Throwable (UnsatisfiedLinkError).+@Suppress("TooManyFunctions", "TooGenericExceptionCaught") object VoxelsNative { val isAvailable: Boolean = try { System.loadLibrary("voxels_engine")
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FurnaceScreen.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FurnaceScreen.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FurnaceScreen.ktindex 4c88ccc41b..e2bef6a210 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FurnaceScreen.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FurnaceScreen.kt@@ -5,11 +5,27 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectTapGestures-import androidx.compose.foundation.layout.*+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.weight+import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll-import androidx.compose.runtime.*+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.ktindex 667e4ad82f..e2fd478809 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.kt@@ -11,9 +11,29 @@ import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll-import androidx.compose.foundation.layout.*+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.weight+import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape-import androidx.compose.runtime.*+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.key+import androidx.compose.runtime.mutableStateMapOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha@@ -139,7 +159,7 @@ private fun TabButton(label: String, selected: Boolean, onClick: () -> Unit) { } @Composable-private fun SlotBox(index: Int, slot: InvSlot, bounds: MutableMap<Int, Rect>, drag: Boolean,+private fun SlotBox(index: Int, slot: InvSlot, bounds: MutableMap<Int, Rect>, onDragStart: (Int, Offset) -> Unit, onDragMove: (Offset) -> Unit, onDragEnd: () -> Unit, onDragCancel: () -> Unit) { val icon = rememberBlockIcon(slot.id)@@ -170,7 +190,7 @@ private fun SlotBox(index: Int, slot: InvSlot, bounds: MutableMap<Int, Rect>, dr private fun InventoryGrid(slots: List<InvSlot>, bounds: MutableMap<Int, Rect>, onDragStart: (Int, Offset) -> Unit, onDragMove: (Offset) -> Unit, onDragEnd: () -> Unit, onDragCancel: () -> Unit) {- fun cell(i: Int) = @Composable { SlotBox(i, slots.getOrNull(i) ?: InvSlot(0, 0), bounds, true, onDragStart, onDragMove, onDragEnd, onDragCancel) }+ fun cell(i: Int) = @Composable { SlotBox(i, slots.getOrNull(i) ?: InvSlot(0, 0), bounds, onDragStart, onDragMove, onDragEnd, onDragCancel) } Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) { Text(stringResource(R.string.inventory_drag_to_rearrange), color = Color.White.copy(0.6f), fontSize = 12.sp) Spacer(Modifier.height(4.dp))
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/StonecutterScreen.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/StonecutterScreen.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/StonecutterScreen.ktindex 783212ccc1..5783e6520f 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/StonecutterScreen.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/StonecutterScreen.kt@@ -5,11 +5,26 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectTapGestures-import androidx.compose.foundation.layout.*+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.weight+import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll-import androidx.compose.runtime.*+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.ktindex d9e2c6f5af..b7eaac2480 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.kt@@ -7,7 +7,18 @@ import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectTapGestures-import androidx.compose.foundation.layout.*+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.weight import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/VoxelSurfaceView.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/VoxelSurfaceView.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/VoxelSurfaceView.ktindex 3f23a0903e..1799f47d3a 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/VoxelSurfaceView.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/VoxelSurfaceView.kt@@ -12,27 +12,32 @@ class VoxelSurfaceView @JvmOverloads constructor( ) : SurfaceView(context, attrs), SurfaceHolder.Callback { private var ready = false init { holder.addCallback(this) }+ // JNI boundary: native throws unchecked exceptions, all logged here.+ @Suppress("TooGenericExceptionCaught") override fun surfaceCreated(holder: SurfaceHolder) { if (!VoxelsNative.isAvailable) return+ // JNI boundary: native throws unchecked exceptions, all logged here. try { VoxelsNative.surfaceCreated(holder.surface) ready = true- } catch (e: Exception) {+ } catch (e: RuntimeException) { android.util.Log.e("VoxelSurface", "surfaceCreated failed", e) } }+ @Suppress("TooGenericExceptionCaught") override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { if (!VoxelsNative.isAvailable || !ready) return- try { VoxelsNative.surfaceChanged(width, height) } catch (e: Exception) {+ try { VoxelsNative.surfaceChanged(width, height) } catch (e: RuntimeException) { android.util.Log.e("VoxelSurface", "surfaceChanged failed", e) } }+ @Suppress("TooGenericExceptionCaught") override fun surfaceDestroyed(holder: SurfaceHolder) { if (!VoxelsNative.isAvailable) return try { VoxelsNative.surfaceDestroyed() ready = false- } catch (e: Exception) {+ } catch (e: RuntimeException) { android.util.Log.e("VoxelSurface", "surfaceDestroyed failed", e) } }
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex d3f493ecbd..910ea2d77a 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -17,6 +17,10 @@ ksp = "2.3.11" protobufPlugin = "0.10.0" desugarJdkLibs = "2.1.5" +# Static analysis (detekt 2.x line: 1.x supports Kotlin <= 2.0 only).+# Alpha because no stable detekt supports Kotlin 2.4 yet; revisit on 2.0.0 stable.+detekt = "2.0.0-alpha.6"+ # Kotlin stdlib ecosystem (JetBrains) kotlinxCoroutines = "1.11.0" kotlinxSerializationJson = "1.11.0"@@ -151,6 +155,11 @@ kotlin-gradle-plugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", v kotlin-compose-gradle = { module = "org.jetbrains.kotlin:compose-compiler-gradle-plugin", version.ref = "kotlin" } kotlin-serialization-gradle = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "kotlin" } symbol-processing-gradle-plugin = { module = "com.google.devtools.ksp:symbol-processing-gradle-plugin", version.ref = "ksp" }+# Plugin jar so build-logic can put detekt on its classpath; convention plugins+# then apply it versionless as id("io.gitlab.arturbosch.detekt") (same as ksp).+# NB: 2.x lives under the dev.detekt group; the old+# io.gitlab.arturbosch.detekt marker has no 2.x alpha on Maven Central.+detekt-gradle-plugin = { module = "dev.detekt:detekt-gradle-plugin", version.ref = "detekt" } desugar-jdk-libs = { module = "com.android.tools:desugar_jdk_libs", version.ref = "desugarJdkLibs" } # Kotlin stdlib ecosystem (JetBrains)@@ -329,3 +338,11 @@ kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "ko kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } protobuf = { id = "com.google.protobuf", version.ref = "protobufPlugin" }++# =============================================================================+# THIRD PARTY+# =============================================================================++# Static code analysis for Kotlin (applied in common-conventions-app/library;+# 2.x plugin id is dev.detekt).+detekt = { id = "dev.detekt", version.ref = "detekt" }
library/ui/src/main/java/com/vayunmathur/library/ui/BackupButtons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/BackupButtons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/BackupButtons.ktindex 6170dde3f4..a8b68f7211 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/BackupButtons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/BackupButtons.kt@@ -151,6 +151,9 @@ private fun relaunch(context: android.content.Context) { Runtime.getRuntime().exit(0) } +// Broad catch is deliberate: export/import cross arbitrary content providers and+// format plugins, and every failure mode is logged and messaged below.+@Suppress("TooGenericExceptionCaught") private suspend fun runExport( context: android.content.Context, format: BackupFormat,@@ -172,6 +175,7 @@ private suspend fun runExport( } } +@Suppress("TooGenericExceptionCaught") private suspend fun runImport( context: android.content.Context, format: BackupFormat,
library/ui/src/main/java/com/vayunmathur/library/ui/EditorFormatter.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/EditorFormatter.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/EditorFormatter.ktindex 3f6d04b79c..e0c3aafc00 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/EditorFormatter.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/EditorFormatter.kt@@ -34,6 +34,8 @@ import androidx.compose.ui.focus.focusProperties import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics import com.vayunmathur.library.ui.R /** The base formatting actions every editor toolbar can offer. */@@ -126,10 +128,14 @@ fun FormatIconButton( onClick: () -> Unit, icon: @Composable () -> Unit, ) {+ // The slot renders an app IconXxx with no contentDescription parameter of its+ // own, so expose this button's description to accessibility services here.+ val description = contentDescription IconButton( onClick = onClick, enabled = enabled,- modifier = Modifier.focusProperties { canFocus = false }.size(40.dp),+ modifier = Modifier.focusProperties { canFocus = false }.size(40.dp)+ .semantics { this.contentDescription = description }, ) { androidx.compose.runtime.CompositionLocalProvider( LocalContentColor provides
library/ui/src/main/java/com/vayunmathur/library/ui/MarkdownEditor.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/MarkdownEditor.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/MarkdownEditor.ktindex cc11b50eff..c3a90b60e3 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/MarkdownEditor.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/MarkdownEditor.kt@@ -149,7 +149,7 @@ fun MarkdownFormatToolbar( active = getActiveHeadingLevel(value.text, value.selection.start) != null, ) { showHeadingMenu = true } DropdownMenu(expanded = showHeadingMenu, onDismissRequest = { showHeadingMenu = false }) {- (1..3).forEach { level ->+ for (level in 1..3) { DropdownMenuItem(text = { Text(stringResource(R.string.heading, level)) }, onClick = { apply { insertHeading(it, level) } showHeadingMenu = false
library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.ktindex 19db9c4753..0f3e4a3a07 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.kt@@ -840,8 +840,10 @@ fun ListItem( leadingContent: (@Composable () -> Unit)? = null, trailingContent: (@Composable () -> Unit)? = null, colors: ListItemColors = ListItemDefaults.colors(),- tonalElevation: Dp = 0.dp,- shadowElevation: Dp = 0.dp,+ // Accepted for source compatibility with material3 ListItem; nothing sets+ // either away from zero (SafeListItemLayout takes no elevation).+ @Suppress("UnusedParameter") tonalElevation: Dp = 0.dp,+ @Suppress("UnusedParameter") shadowElevation: Dp = 0.dp, ) = SafeListItemLayout( // See the overload above; elevation is accepted for source compatibility // but nothing sets it away from zero.
library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponentsExtra.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponentsExtra.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponentsExtra.ktindex 23d1c533e7..c89adba963 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponentsExtra.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponentsExtra.kt@@ -348,4 +348,4 @@ fun ButtonGroup( modifier = modifier, horizontalArrangement = horizontalArrangement, content = content,-)\ No newline at end of file+)
library/ui/src/main/java/com/vayunmathur/library/ui/MotionValues.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/MotionValues.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/MotionValues.ktindex 6023fcc508..02ae4eca79 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/MotionValues.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/MotionValues.kt@@ -129,7 +129,7 @@ fun LazyGridItemScope.itemMotion(placementSpec: FiniteAnimationSpec<IntOffset>? } /** How far apart consecutive sections start their entrance. */-private const val StaggerStepMillis = 45L+private const val STAGGER_STEP_MILLIS = 45L /** How far a section rises through as it arrives. */ private val StaggerLift = 12.dp@@ -146,7 +146,7 @@ fun Modifier.staggeredEntrance(index: Int, arriving: Boolean): Modifier { var shown by remember { mutableStateOf(!arriving) } LaunchedEffect(Unit) { if (!shown) {- delay(index * StaggerStepMillis)+ delay(index * STAGGER_STEP_MILLIS) shown = true } }
library/ui/src/main/java/com/vayunmathur/library/ui/SwappedTopBar.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/SwappedTopBar.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/SwappedTopBar.ktindex 27f33d496d..a175202cfa 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/SwappedTopBar.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/SwappedTopBar.kt@@ -15,7 +15,7 @@ import androidx.compose.ui.unit.IntOffset * How far the two bars travel as they swap, as a fraction of the bar's height. A third: enough to * read as a push, short enough that neither bar is ever mostly off its own strip. */-private const val SwapTravel = 3+private const val SWAP_TRAVEL = 3 /** * Swaps a top bar for another one that slides down over it, and lets the first slide back down into@@ -43,8 +43,8 @@ fun SwappedTopBar( modifier = modifier, transitionSpec = { val towards = if (targetState) -1 else 1- (fadeIn(fade) + slideInVertically(offset) { towards * it / SwapTravel })- .togetherWith(fadeOut(fade) + slideOutVertically(offset) { -towards * it / SwapTravel })+ (fadeIn(fade) + slideInVertically(offset) { towards * it / SWAP_TRAVEL })+ .togetherWith(fadeOut(fade) + slideOutVertically(offset) { -towards * it / SWAP_TRAVEL }) }, ) { overlay -> content(overlay)
library/ui/src/main/java/com/vayunmathur/library/ui/game/GameResultOverlay.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/game/GameResultOverlay.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/game/GameResultOverlay.ktindex 618aa181ad..49333cf7f3 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/game/GameResultOverlay.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/game/GameResultOverlay.kt@@ -47,7 +47,7 @@ fun GameResultOverlay( Box( modifier .fillMaxSize()- .background(MaterialTheme.colorScheme.scrim.copy(alpha = ScrimAlpha))+ .background(MaterialTheme.colorScheme.scrim.copy(alpha = SCRIM_ALPHA)) .padding(Spacing.lg), contentAlignment = Alignment.Center, ) {@@ -77,4 +77,4 @@ fun GameResultOverlay( } /** Dark enough to mute the board behind, light enough to keep it recognisable. */-private const val ScrimAlpha = 0.7f+private const val SCRIM_ALPHA = 0.7f
library/ui/src/main/java/com/vayunmathur/library/ui/odf/EpubExporter.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/odf/EpubExporter.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/odf/EpubExporter.ktindex bd54f517b1..e4628c053f 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/odf/EpubExporter.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/odf/EpubExporter.kt@@ -28,7 +28,7 @@ object EpubExporter { zos.putNextEntry(mimeEntry); zos.write(mime); zos.closeEntry() put(zos, "META-INF/container.xml", CONTAINER) put(zos, "OEBPS/content.opf", contentOpf(title, images.keys))- put(zos, "OEBPS/toc.ncx", tocNcx(title, doc))+ put(zos, "OEBPS/toc.ncx", tocNcx(title)) put(zos, "OEBPS/content.xhtml", bodyXhtml) for ((name, bytes) in images) { zos.putNextEntry(ZipEntry("OEBPS/$name")); zos.write(bytes); zos.closeEntry() } }@@ -79,7 +79,7 @@ object EpubExporter { return sb.toString() } - private fun tocNcx(title: String, doc: OdfDocument.TextDocument): String {+ private fun tocNcx(title: String): String { val sb = StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") sb.append("<ncx xmlns=\"http://www.daisy.org/z3986/2005/ncx/\" version=\"2005-1\">\n") sb.append("<head><meta name=\"dtb:uid\" content=\"urn:uuid:${title.hashCode().toUInt()}\"/></head>\n")
library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfDocTransform.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfDocTransform.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfDocTransform.ktindex 48915aba89..aa02a62524 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfDocTransform.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfDocTransform.kt@@ -63,7 +63,7 @@ internal fun runTransStarts(lens: List<Int>, prefixes: List<String>): IntArray { internal fun buildDocTransformed( text: String, paras: List<OdfParagraph>, lens: List<Int>, prefixes: List<String>,- baseColor: Color, prefixColor: Color, mult: Float+ prefixColor: Color, mult: Float ): TransformedText { val n = paras.size val origStarts = IntArray(n)
library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfTextEditorView.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfTextEditorView.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfTextEditorView.ktindex 48c2d3eeff..ab63d1fdd8 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfTextEditorView.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfTextEditorView.kt@@ -123,7 +123,7 @@ fun ContinuousParagraphEditor( // Recomputed every composition so list prefixes (e.g. renumbered ordered lists, checkbox state) // are always reflected immediately, even when the underlying text is unchanged. val transformation = VisualTransformation {- buildDocTransformed(it.text, paras, lens, prefixes, onSurface, prefixColor, fontSizeMultiplier)+ buildDocTransformed(it.text, paras, lens, prefixes, prefixColor, fontSizeMultiplier) } var layout by remember { mutableStateOf<TextLayoutResult?>(null) } // When the run's shape changes (a paragraph added/removed by Enter/Backspace), the caller's
library/ui/src/main/java/com/vayunmathur/library/ui/odf/OoxmlExporter.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OoxmlExporter.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OoxmlExporter.ktindex 3e7491825a..c212b73513 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OoxmlExporter.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OoxmlExporter.kt@@ -141,7 +141,7 @@ object OoxmlExporter { // Footnotes: emit part + reference at matching citation spans. val footnotesPart = if (doc.footnotes.isNotEmpty()) buildFootnotes(doc.footnotes, assets, numbering) else null - body.append(sectPrXml(doc.pageSetup, hasHeader = doc.headerParagraphs.isNotEmpty(), hasFooter = doc.footerParagraphs.isNotEmpty(), assets))+ body.append(sectPrXml(doc.pageSetup, hasHeader = doc.headerParagraphs.isNotEmpty(), hasFooter = doc.footerParagraphs.isNotEmpty())) val nsDecl = "xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"" + " xmlns:r=\"$NS_R\"" +@@ -200,7 +200,7 @@ object OoxmlExporter { return pkg.zip() } - private fun sectPrXml(page: OdfPageSetup?, hasHeader: Boolean, hasFooter: Boolean, assets: DocxAssets): String {+ private fun sectPrXml(page: OdfPageSetup?, hasHeader: Boolean, hasFooter: Boolean): String { val sb = StringBuilder("<w:sectPr>") if (hasHeader) sb.append("<w:headerReference w:type=\"default\" r:id=\"rIdHeader\"/>") if (hasFooter) sb.append("<w:footerReference w:type=\"default\" r:id=\"rIdFooter\"/>")@@ -1152,7 +1152,7 @@ object OoxmlExporter { return sb.toString() } - private val PPTX_THEME = XMLDECL ++ private const val PPTX_THEME = XMLDECL + "<a:theme xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" name=\"Office\">" + "<a:themeElements><a:clrScheme name=\"Office\">" + "<a:dk1><a:sysClr val=\"windowText\" lastClr=\"000000\"/></a:dk1><a:lt1><a:sysClr val=\"window\" lastClr=\"FFFFFF\"/></a:lt1>" +
notes/src/main/java/com/vayunmathur/notes/data/Note.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/Note.kt b/notes/src/main/java/com/vayunmathur/notes/data/Note.ktindex 7dbef60e21..5f5f8a8b74 100644--- a/notes/src/main/java/com/vayunmathur/notes/data/Note.kt+++ b/notes/src/main/java/com/vayunmathur/notes/data/Note.kt@@ -17,4 +17,4 @@ data class Note( val blocks: String? = null, ): ReorderableDatabaseItem<Note> { override fun withPosition(position: Double) = copy(position = position)-}\ No newline at end of file+}
notes/src/main/java/com/vayunmathur/notes/data/NoteBlock.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/NoteBlock.kt b/notes/src/main/java/com/vayunmathur/notes/data/NoteBlock.ktindex 459f86bd30..05005421c9 100644--- a/notes/src/main/java/com/vayunmathur/notes/data/NoteBlock.kt+++ b/notes/src/main/java/com/vayunmathur/notes/data/NoteBlock.kt@@ -3,9 +3,11 @@ package com.vayunmathur.notes.data import kotlin.uuid.Uuid+import android.util.Log import com.vayunmathur.library.ink.SerializedStroke import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable+import kotlinx.serialization.SerializationException import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json @@ -62,13 +64,16 @@ data class NoteBody( // from earlier builds) so older notes still parse instead of crashing. private val blockJson = Json { ignoreUnknownKeys = true } +private const val TAG = "NoteBody"+ /** The note body: parses stored [Note.blocks], or falls back to a single text block. */ fun Note.body(): NoteBody { val json = blocks if (json.isNullOrBlank()) return NoteBody(blocks = listOf(NoteBlock.Text(content))) return try { blockJson.decodeFromString<NoteBody>(json)- } catch (e: Exception) {+ } catch (e: SerializationException) {+ Log.w(TAG, "unparseable blocks JSON, falling back to plain text", e) NoteBody(blocks = listOf(NoteBlock.Text(content))) } }
notes/src/main/java/com/vayunmathur/notes/platform/NoteImageStore.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/platform/NoteImageStore.kt b/notes/src/main/java/com/vayunmathur/notes/platform/NoteImageStore.ktindex 8eee12d368..edbd28546d 100644--- a/notes/src/main/java/com/vayunmathur/notes/platform/NoteImageStore.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NoteImageStore.kt@@ -5,6 +5,7 @@ package com.vayunmathur.notes.platform import kotlin.uuid.Uuid import android.content.Context import android.net.Uri+import android.util.Log import java.io.File /**@@ -13,12 +14,17 @@ import java.io.File * images survive app restarts. */ object NoteImageStore {+ private const val TAG = "NoteImageStore"+ private fun dir(context: Context): File = File(context.filesDir, "note_images").apply { mkdirs() } fun fileFor(context: Context, fileName: String): File = File(dir(context), fileName) /** Copies [uri] into the images dir and returns the new file name, or null on failure. */+ // Broad catch is deliberate: any content-provider failure mode means "no file"+ // per this function's contract, and the failure is logged below.+ @Suppress("TooGenericExceptionCaught") fun import(context: Context, uri: Uri): String? { val fileName = "img_${Uuid.random()}.jpg" val dest = File(dir(context), fileName)@@ -28,6 +34,7 @@ object NoteImageStore { } ?: return null fileName } catch (e: Exception) {+ Log.w(TAG, "import failed for $uri", e) dest.delete() null }
notes/src/main/java/com/vayunmathur/notes/platform/NoteMarkdownExporter.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/platform/NoteMarkdownExporter.kt b/notes/src/main/java/com/vayunmathur/notes/platform/NoteMarkdownExporter.ktindex 702675dbda..d75e9402fa 100644--- a/notes/src/main/java/com/vayunmathur/notes/platform/NoteMarkdownExporter.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NoteMarkdownExporter.kt@@ -5,6 +5,7 @@ import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.util.Base64+import android.util.Log import androidx.core.content.FileProvider import androidx.core.graphics.scale import com.vayunmathur.library.ink.SerializedStroke@@ -15,6 +16,15 @@ import java.io.ByteArrayOutputStream import java.io.File import kotlin.math.roundToInt +private const val TAG = "NoteMarkdownExporter"++/** Bit layout of an ARGB color int for [cssColor]. */+private const val ARGB_BYTE_MASK = 0xFF+private const val ALPHA_SHIFT = 24+private const val RED_SHIFT = 16+private const val GREEN_SHIFT = 8+private const val MAX_COLOR_COMPONENT = 255f+ /** * Exports a note as a SINGLE self-contained Markdown document: * - text blocks are emitted verbatim,@@ -56,10 +66,14 @@ private const val MAX_IMAGE_DIMENSION = 1024 private const val JPEG_QUALITY = 60 /** An image inlined as an HTML `<img>` with a base64 data URI, honoring [NoteBlock.Image.widthFraction]. */+// Broad catch is deliberate: an undecodable image is omitted from the export+// per this function's contract (blank strings are filtered by the caller).+@Suppress("TooGenericExceptionCaught") private fun imageMarkdown(context: Context, block: NoteBlock.Image): String { val bytes = try { downscaledJpegBytes(NoteImageStore.fileFor(context, block.fileName)) } catch (e: Exception) {+ Log.w(TAG, "omitting undecodable image ${block.fileName}", e) return "" } ?: return "" val base64 = Base64.encodeToString(bytes, Base64.NO_WRAP)@@ -148,11 +162,11 @@ private fun strokePath(stroke: SerializedStroke): String? { /** An ARGB color int as a CSS `rgba(...)`, preserving alpha (e.g. highlighter transparency). */ private fun cssColor(argb: Int): String {- val a = (argb ushr 24) and 0xFF- val r = (argb ushr 16) and 0xFF- val g = (argb ushr 8) and 0xFF- val b = argb and 0xFF- return "rgba($r,$g,$b,${num(a / 255f)})"+ val a = (argb ushr ALPHA_SHIFT) and ARGB_BYTE_MASK+ val r = (argb ushr RED_SHIFT) and ARGB_BYTE_MASK+ val g = (argb ushr GREEN_SHIFT) and ARGB_BYTE_MASK+ val b = argb and ARGB_BYTE_MASK+ return "rgba($r,$g,$b,${num(a / MAX_COLOR_COMPONENT)})" } /** Formats a float compactly (drops the ".0" for whole numbers) to keep the output small. */
notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt b/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.ktindex 4e2a53fc2a..16ef154b3f 100644--- a/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt@@ -72,7 +72,7 @@ class NotesViewModel( val pendingWrites = remember { MutableStateFlow<Note?>(null) } LaunchedEffect(Unit) {- pendingWrites.filterNotNull().debounce(300).collectLatest { newValue ->+ pendingWrites.filterNotNull().debounce(SAVE_DEBOUNCE_MS).collectLatest { newValue -> val newId = withContext(Dispatchers.IO) { repository.upsert(newValue) } if (currentId == 0L) currentId = newId }@@ -136,6 +136,9 @@ class NotesViewModel( private val _shareRequests = MutableSharedFlow<NoteShare>(extraBufferCapacity = 1) val shareRequests: SharedFlow<NoteShare> = _shareRequests.asSharedFlow() + // Best-effort import of external files: any failure mode means "skip this+ // file" per this function's contract, and each failure is logged below.+ @Suppress("TooGenericExceptionCaught") fun importFiles(uris: List<Uri>) { if (uris.isEmpty()) return val ctx = getApplication<Application>()@@ -189,6 +192,9 @@ class NotesViewModel( data class ExternalNoteContent(val title: String, val content: String) + // Best-effort read of an external note: any failure mode means null per+ // this function's contract, and the failure is logged below.+ @Suppress("TooGenericExceptionCaught") suspend fun readExternal(uriString: String): ExternalNoteContent? = withContext(Dispatchers.IO) { val ctx = getApplication<Application>() try {@@ -203,6 +209,9 @@ class NotesViewModel( } } + // Best-effort save to an external note: any failure mode means false per+ // this function's contract, and the failure is logged below.+ @Suppress("TooGenericExceptionCaught") fun saveExternal(uriString: String, content: String, onResult: (Boolean) -> Unit) { val ctx = getApplication<Application>() viewModelScope.launch {@@ -230,6 +239,7 @@ class NotesViewModel( companion object { private const val TAG = "NotesViewModel"+ private const val SAVE_DEBOUNCE_MS = 300L } }
search
diff --git a/search b/searchindex 9f96cc2c98..0b3eb5f112 100644--- a/search+++ b/search@@ -103,13 +103,15 @@ pkg_dirs_for() { # mod, pkg... -> prints existing package-root dirs (deduped) done # drop dirs subsumed by another match (e.g. data/ inside data/) local a b skip- for a in "${found[@]:-}"; do- skip=0- for b in "${found[@]:-}"; do- [[ "$a" != "$b" && "$a" == "$b"/* ]] && { skip=1; break; }- done- [[ $skip -eq 0 ]] && echo "$a"- done | sort -u+ if [[ ${#found[@]} -gt 0 ]]; then+ for a in "${found[@]}"; do+ skip=0+ for b in "${found[@]}"; do+ [[ "$a" != "$b" && "$a" == "$b"/* ]] && { skip=1; break; }+ done+ [[ $skip -eq 0 ]] && echo "$a"+ done | sort -u+ fi } # --- arg parsing ---