Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/*
* This file is part of AndroidIDE.
*
* AndroidIDE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidIDE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidIDE. If not, see <https://www.gnu.org/licenses/>.
*/

package com.itsaky.androidide.fragments.output

import kotlinx.coroutines.channels.Channel

/**
* Thread-safe pending build output with fixed memory and batch budgets.
*
* Inputs are indivisible unless one exceeds [maxPendingChars], in which case only its newest tail
* is retained. Older pending output is evicted first, while batches preserve the retained order.
*/
internal class BuildOutputBuffer(
private val maxPendingChars: Int = DEFAULT_MAX_PENDING_CHARS,
private val maxBatchChars: Int = DEFAULT_MAX_BATCH_CHARS,
) {
data class Batch(
val text: String,
val sessionToken: Int,
val sourceChars: Int,
val omittedLines: Long,
)

private sealed interface Entry {
val sessionToken: Int

data class Text(
val value: String,
override val sessionToken: Int,
) : Entry

data class Omission(
var lineCount: Long,
var sourceChars: Int,
override val sessionToken: Int,
) : Entry
}

private val entries = ArrayDeque<Entry>()
private val available = Channel<Unit>(Channel.CONFLATED)
private val lock = Any()
private var retainedChars = 0

internal val pendingChars: Int
get() = synchronized(lock) { retainedChars }

init {
require(maxPendingChars > 0) { "maxPendingChars must be positive" }
require(maxBatchChars > 0) { "maxBatchChars must be positive" }
}

fun offer(
text: String,
sessionToken: Int,
) {
if (text.isEmpty()) return
val normalized = if (text.endsWith('\n')) text else "$text\n"
synchronized(lock) {
val existingOmission = entries.firstOrNull() as? Entry.Omission
if (existingOmission != null) entries.removeFirst()

var retained = normalized
var omittedLines = existingOmission?.lineCount ?: 0
var omittedChars = existingOmission?.sourceChars ?: 0
if (retained.length > maxPendingChars) {
val droppedPrefix = retained.dropLast(maxPendingChars)
omittedLines += lineCount(droppedPrefix)
omittedChars = saturatedAdd(omittedChars, droppedPrefix.length)
retained = retained.takeLast(maxPendingChars)
}
while (retainedChars > maxPendingChars - retained.length) {
val evicted = entries.removeFirst() as Entry.Text
retainedChars -= evicted.value.length
omittedLines += lineCount(evicted.value)
omittedChars = saturatedAdd(omittedChars, evicted.value.length)
}

if (omittedLines > 0) {
entries.addFirst(Entry.Omission(omittedLines, omittedChars, sessionToken))
}
entries.addLast(Entry.Text(retained, sessionToken))
retainedChars += retained.length
available.trySend(Unit)
}
}

suspend fun takeBatch(): Batch {
while (true) {
available.receive()
val batch = synchronized(lock) { takeAvailableBatch() }
if (batch != null) return batch
}
}

fun clear() {
synchronized(lock) {
entries.clear()
retainedChars = 0
while (available.tryReceive().isSuccess) {
// Discard stale wakeups from the cleared build session.
}
}
}

private fun takeAvailableBatch(): Batch? {
if (entries.isEmpty()) return null
val sessionToken = entries.first().sessionToken
val batch = StringBuilder(minOf(retainedChars, maxBatchChars))
var sourceChars = 0
var omittedLines = 0L
while (entries.isNotEmpty()) {
val entry = entries.first()
if (entry.sessionToken != sessionToken) break
if (entry is Entry.Text && batch.isNotEmpty() && batch.length + entry.value.length > maxBatchChars) break

entries.removeFirst()
when (entry) {
is Entry.Text -> {
batch.append(entry.value)
retainedChars -= entry.value.length
sourceChars = saturatedAdd(sourceChars, entry.value.length)
}

is Entry.Omission -> {
omittedLines += entry.lineCount
sourceChars = saturatedAdd(sourceChars, entry.sourceChars)
}
}
}
if (entries.isNotEmpty()) available.trySend(Unit)
return Batch(batch.toString(), sessionToken, sourceChars, omittedLines)
}

private fun lineCount(text: String): Long = text.count { it == '\n' }.toLong() + if (text.endsWith('\n')) 0 else 1

private fun saturatedAdd(
left: Int,
right: Int,
): Int = (left.toLong() + right).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()

companion object {
private const val DEFAULT_MAX_PENDING_CHARS = 256 * 1024
private const val DEFAULT_MAX_BATCH_CHARS = 32 * 1024
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ import com.itsaky.androidide.utils.dpToPx
import com.itsaky.androidide.utils.flashInfo
import com.itsaky.androidide.viewmodel.BuildOutputViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.drop
Expand All @@ -62,7 +60,9 @@ class BuildOutputFragment :

override val currentEditor: IDEEditor? get() = editor

private val logChannel = Channel<String>(Channel.UNLIMITED)
// Fixed pending budget: a flooding build drops its oldest queued lines behind one omission
// marker instead of holding an unlimited backlog in memory until the editor catches up.
private val outputBuffer = BuildOutputBuffer(maxBatchChars = MAX_BATCH_CHARS)

private var searchLayout: EditorSearchLayout? = null
private var filterBar: LogFilterBarController? = null
Expand Down Expand Up @@ -353,9 +353,8 @@ class BuildOutputFragment :
// Avoid forcing the activityViewModels lazy init (which calls requireActivity())
// when the fragment is detached, otherwise an IllegalStateException is thrown.
if (!isAdded || activity == null) return
while (logChannel.tryReceive().isSuccess) {
// Discard: these lines belong to the session being cleared.
}
// Discard: these lines belong to the session being cleared.
outputBuffer.clear()
// Invalidate in-flight flushes before deleting content, so a batch drained from the
// channel earlier cannot re-seed the cleared session.
sessionGeneration++
Expand All @@ -381,35 +380,7 @@ class BuildOutputFragment :

fun appendOutput(output: String?) {
if (!output.isNullOrEmpty()) {
logChannel.trySend(output)
}
}

/**
* Ensures the string ends with a newline character (`\n`).
* Useful for maintaining correct formatting when concatenating log lines.
*/
private fun String.ensureNewline(): String = if (endsWith('\n')) this else "$this\n"

/**
* Immediately drains (consumes) all available messages from the channel into the [buffer].
*
* This is a **non-blocking** operation that enables batching, grouping hundreds of pending lines
* into a single memory operation to avoid saturating the UI queue.
*/
private fun ReceiveChannel<String>.drainTo(buffer: StringBuilder) {
// Bounded: the main thread word-wraps each batch in one appendBatch call, so draining a
// flooding build in one go stalled it into an ANR (WordwrapLayout.afterInsert). The rest
// stays queued for the next batch.
if (buffer.length >= MAX_BATCH_CHARS) return
var result = tryReceive()
while (result.isSuccess) {
val line = result.getOrNull()
if (!line.isNullOrEmpty()) {
buffer.append(line.ensureNewline())
}
if (buffer.length >= MAX_BATCH_CHARS) return
result = tryReceive()
outputBuffer.offer(output, sessionGeneration)
}
}

Expand All @@ -420,21 +391,15 @@ class BuildOutputFragment :
* 2. Wakes up and drains the entire queue (Batching).
* 3. Sends the complete block to the UI in a single pass.
*/
private suspend fun processLogs() =
with(StringBuilder()) {
for (firstLine in logChannel) {
val sessionGenAtDrain = sessionGeneration
val editorGenAtDrain = editorContentGeneration
append(firstLine.ensureNewline())
logChannel.drainTo(this)

if (isNotEmpty()) {
val batchText = toString()
clear()
flushToEditor(batchText, sessionGenAtDrain, editorGenAtDrain)
}
}
private suspend fun processLogs() {
while (true) {
val batch = outputBuffer.takeBatch()
val editorGenAtDrain = editorContentGeneration
// A batch queued before clearOutput() belongs to the previous build.
if (batch.sessionToken != sessionGeneration) continue
flushToEditor(batch.text, batch.omittedLines, batch.sessionToken, editorGenAtDrain)
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/**
* Performs the safe UI update on the Main Thread.
Expand All @@ -448,6 +413,7 @@ class BuildOutputFragment :
*/
private suspend fun flushToEditor(
text: String,
omittedLines: Long,
sessionGen: Int,
editorGen: Int,
) {
Expand All @@ -456,13 +422,16 @@ class BuildOutputFragment :
if (sessionGen != sessionGeneration) return

// The editor shows only the lines matching the current filter; the file keeps them all.
// The omission marker is shown whatever the filter, so dropped output is never silent.
val omissionMarker = if (omittedLines > 0) formatOmissionMarker(omittedLines) else ""
val visibleText =
BuildOutputViewModel.filterLines(
text,
buildOutputViewModel.filterText.value,
buildOutputViewModel.showTimestamps.value,
buildOutputViewModel.showDeltas.value,
)
omissionMarker +
BuildOutputViewModel.filterLines(
text,
buildOutputViewModel.filterText.value,
buildOutputViewModel.showTimestamps.value,
buildOutputViewModel.showDeltas.value,
)
if (visibleText.isEmpty()) {
return
}
Expand Down Expand Up @@ -529,6 +498,13 @@ class BuildOutputFragment :
* until they ANR'd. Trims the editor's own (already filtered) text rather than re-reading the
* session file, whose writer can lag the editor. Call on the main thread under [editorContentMutex].
*/
private fun formatOmissionMarker(lineCount: Long): String {
val quantity = lineCount.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
return resources
.getQuantityString(R.plurals.msg_build_output_lines_omitted, quantity, lineCount)
.plus('\n')
}

private fun IDEEditor.trimToWindow() {
if (isReleased) return
val tail = BuildOutputViewModel.editorTail(text) ?: return
Expand Down
Loading