Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## [Unreleased]

### Fixed
- `OutOfMemoryError` on low-memory devices (0.19.19, Samsung A30 / Android 11, 192MB heap). Several unbounded allocations are now capped: the wallpaper and glyph-editor image imports decode sampled instead of full-resolution, the in-app browser destroys its WebView on exit instead of leaking it, `HttpRequest` actions drain at most 256KB of a response, and the shade refresh is debounced so notification bursts can't stack parcel-unpack churn. `largeHeap` is enabled for headroom on 3-4GB devices.

## [0.19.19]

### Fixed
Expand Down
1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
<application
android:name=".NothingModesApplication"
android:allowBackup="false"
android:largeHeap="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="Nothing Modes"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
Expand Down Expand Up @@ -123,6 +124,11 @@ class AutomationNotificationListener : NotificationListenerService() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return
val generation = refreshGeneration.incrementAndGet()
scope.launch {
// Debounce bursts: every post/remove schedules a refresh, and each
// one unparcels every active notification's extras. A chatty
// stream would otherwise keep the heap churning toward OOM;
// superseded generations still bail inside the mutex.
delay(REFRESH_DEBOUNCE_MS)
// Serialize refreshes: each one unparcels every active
// notification's extras, and concurrent runs would multiply the
// heap spike that OOMed on oversized parcels.
Expand Down Expand Up @@ -178,5 +184,6 @@ class AutomationNotificationListener : NotificationListenerService() {
const val EXTRA_SENDER = "notification_sender"
const val EXTRA_IS_GROUP = "notification_is_group"
const val EXTRA_CONVERSATION_ID = "notification_conversation_id"
private const val REFRESH_DEBOUNCE_MS = 500L
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1268,8 +1268,18 @@ class RealActionExecutor(
conn.outputStream.use { it.write(action.body.toByteArray()) }
}
val code = conn.responseCode
// Drain so the connection can be reused; body content is discarded.
(if (code < 400) conn.inputStream else conn.errorStream)?.use { it.readBytes() }
// Drain a bounded prefix — disconnect() follows, so extra
// draining buys nothing, and an unbounded readBytes() can
// OOM the process on a huge response body.
(if (code < 400) conn.inputStream else conn.errorStream)?.use { stream ->
val buf = ByteArray(8192)
var remaining = MAX_DRAIN_BYTES
while (remaining > 0) {
val n = stream.read(buf, 0, minOf(buf.size, remaining))
if (n < 0) break
remaining -= n
}
}
if (code in 200..299) {
ActionResult.Success
} else {
Expand Down Expand Up @@ -2173,6 +2183,7 @@ class RealActionExecutor(
private const val NOTIFICATION_ID_BASE = 2000
private const val VERIFY_ATTEMPTS = 4
private const val VERIFY_SETTLE_MS = 700L
private const val MAX_DRAIN_BYTES = 256 * 1024

/** Factory: creates a RealActionExecutor with all Android controllers. */
fun create(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package com.tdvorak.nothingmodes.ui.components
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
Expand Down Expand Up @@ -32,6 +31,7 @@ import com.tdvorak.nothingmodes.ui.theme.NothingEnumSelector
import com.tdvorak.nothingmodes.ui.theme.NothingInput
import com.tdvorak.nothingmodes.ui.theme.NothingPrimaryButton
import com.tdvorak.nothingmodes.ui.theme.NothingSpacing
import com.tdvorak.nothingmodes.ui.util.decodeSampledBitmap

/**
* Editor for [Action.SetWallpaper] that lets the user pick an image from the
Expand Down Expand Up @@ -117,10 +117,7 @@ private fun loadWallpaperThumbnail(
val uri = runCatching { Uri.parse(uriString) }.getOrNull() ?: return null

return runCatching {
context.contentResolver
.openInputStream(uri)
?.use { BitmapFactory.decodeStream(it) }
?.scaledToMax(512)
decodeSampledBitmap(context.contentResolver, uri, 1024)?.scaledToMax(512)
}.getOrNull()
?: runCatching {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.graphics.Typeface
import android.media.MediaMetadataRetriever
Expand Down Expand Up @@ -93,6 +92,7 @@ import com.tdvorak.nothingmodes.ui.theme.NothingSpacing
import com.tdvorak.nothingmodes.ui.theme.NothingTag
import com.tdvorak.nothingmodes.ui.theme.NothingTopBar
import com.tdvorak.nothingmodes.ui.theme.ThemeManager
import com.tdvorak.nothingmodes.ui.util.decodeSampledBitmap
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.launch
Expand Down Expand Up @@ -496,7 +496,7 @@ fun GlyphEditorScreen(
ImportType.GIF,
-> {
runCatching {
context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it) }
decodeSampledBitmap(context.contentResolver, uri, 1024)
}.getOrNull()
?: runCatching {
val source = ImageDecoder.createSource(context.contentResolver, uri)
Expand Down Expand Up @@ -545,7 +545,7 @@ fun GlyphEditorScreen(
if (uri != null) {
val bitmap =
runCatching {
context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it) }
decodeSampledBitmap(context.contentResolver, uri, 1024)
}.getOrNull()
if (bitmap != null) applyBitmap(bitmap) else Toast.makeText(context, "Could not load image", Toast.LENGTH_SHORT).show()
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -316,19 +316,39 @@ fun IntegratedBrowserScreen(
View(ctx)
}
},
// A WebView left alive keeps its renderer and page state —
// repeated browser visits otherwise pile up toward OOM.
onRelease = { (it as? WebView)?.destroy() },
)
}
}
}

private const val MAX_IMPORT_CHARS = 1_000_000

private suspend fun fetchText(url: String): String? =
withContext(Dispatchers.IO) {
runCatching {
val conn = URL(url).openConnection() as HttpURLConnection
conn.connectTimeout = 10_000
conn.readTimeout = 10_000
try {
conn.inputStream.bufferedReader().use { it.readText() }
conn.inputStream.bufferedReader().use { reader ->
val buffer = CharArray(8192)
val out = StringBuilder()
while (out.length < MAX_IMPORT_CHARS) {
val n = reader.read(buffer)
if (n < 0) break
out.append(buffer, 0, n)
}
// Cut off mid-document means the payload exceeded the cap —
// fail rather than hand truncated JSON to the importer.
if (out.length >= MAX_IMPORT_CHARS && reader.read() >= 0) {
null
} else {
out.toString()
}
}
} finally {
conn.disconnect()
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.tdvorak.nothingmodes.ui.util

import android.content.ContentResolver
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri

/**
* Decodes [uri] with `inSampleSize` so the result's long edge lands near
* [maxDim]. `BitmapFactory.decodeStream` alone materializes the full image —
* a modern photo or video frame can exceed the whole heap on low-RAM
* devices (OutOfMemoryError reports on a 192MB-heap Samsung A30).
*/
fun decodeSampledBitmap(
resolver: ContentResolver,
uri: Uri,
maxDim: Int,
): Bitmap? {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
var sample = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxDim) {
sample *= 2
}
val options = BitmapFactory.Options().apply { inSampleSize = sample }
return resolver.openInputStream(uri)?.use {
BitmapFactory.decodeStream(it, null, options)
}
}
Loading