Skip to content

Commit

Permalink
Make sure Dogcat executes on BG thread, collectors run on UI
Browse files Browse the repository at this point in the history
  • Loading branch information
NorseDreki committed Feb 2, 2024
1 parent a35cb34 commit 08da01b
Show file tree
Hide file tree
Showing 13 changed files with 72 additions and 108 deletions.
5 changes: 3 additions & 2 deletions src/commonMain/kotlin/dogcat/Dogcat.kt
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ class Dogcat(
val userId = shell.appIdFor(packageName)

filters.apply(ByPackage(packageName, userId))
Logger.d("Startup with foreground app, resolved to package '$packageName' and user ID '$userId'")
Logger.d("${context()} Startup with foreground app, resolved to package '$packageName' and user ID '$userId'")
}

is PickAppPackage -> {
Expand All @@ -100,7 +100,7 @@ class Dogcat(
}

is PickAllApps -> {
Logger.d("Startup with no package filters")
Logger.d("${context()} Startup with no package filters")
}
}

Expand All @@ -119,6 +119,7 @@ class Dogcat(

filters.applied,

//merge with heartbeat
deviceName,

shell.heartbeat()
Expand Down
5 changes: 4 additions & 1 deletion src/commonMain/kotlin/dogcat/DogcatException.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
package dogcat

class DogcatException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
class DogcatException(
message: String,
cause: Throwable? = null
) : RuntimeException(message, cause)
1 change: 0 additions & 1 deletion src/commonMain/kotlin/dogcat/LogLineParser.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ interface LogLineParser {
fun parse(line: String) : LogLine
}


class LogcatBriefParser : LogLineParser {
private val briefPattern = """^([A-Z])/(.+?)\( *(\d+)\): (.*?)$""".toRegex()

Expand Down
24 changes: 9 additions & 15 deletions src/commonMain/kotlin/dogcat/LogLines.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dogcat

import bufferedTransform
import dogcat.LogFilter.Substring
import dogcat.state.DefaultAppliedFiltersState
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
Expand All @@ -13,7 +14,6 @@ class LogLines(
private val filtersState: DefaultAppliedFiltersState,
private val shell: Shell,
private val dispatcherCpu: CoroutineDispatcher,
private val dispatcherIo: CoroutineDispatcher,
) {
private val handler = CoroutineExceptionHandler { _, t -> Logger.d("!!!!!!11111111 CATCH! ${t.message}\r") }
private lateinit var scope: CoroutineScope
Expand All @@ -23,12 +23,10 @@ class LogLines(
if (restartSource) {
if (this::scope.isInitialized) {
Logger.d("${context()} !!!!! cancelling scope ${scope.coroutineContext[Job]}")
withContext(dispatcherCpu) {

scope.cancel()
}
scope.cancel()
}
scope = CoroutineScope(dispatcherIo + handler + Job())
scope = CoroutineScope(dispatcherCpu + handler + Job())
sharedLines = createSharedLines()
Logger.d("${context()} created shared lines in capture $sharedLines")
}
Expand All @@ -39,25 +37,21 @@ class LogLines(
Logger.d("${context()} Applied filters flat map concat")
it.values.asFlow()
}
.filterIsInstance<LogFilter.Substring>()
.filterIsInstance<Substring>()
//never called, always restarted
.distinctUntilChanged { old, new ->
Logger.d("] Distinct? $old $new")
old.substring == new.substring
}
.flatMapLatest { filter ->
Logger.d("${context()} flat map shared lines")
val f = sharedLines
.filter { it.contains(filter.substring, ignoreCase = true) }
.onEach {
//logger.Logger.d("${context()} !!!!!!!!!!!! '${filter.substring}' $restartSource Shared lines flat map latest")
}

f
}
.map {
lineParser.parse(it)
}
//.filterIsInstance<Brief>()
.bufferedTransform(
{ buffer, item ->
when (item) {
Expand All @@ -72,11 +66,12 @@ class LogLines(
else -> true
}
}

else -> false
}
}

is Unparseable -> false // Pass through Unparseable items
else -> false
}
},
{ buffer, item ->
Expand All @@ -88,14 +83,14 @@ class LogLines(
Brief(item.level, "", item.owner, item.message)
}
}

is Unparseable -> item // Pass through Unparseable items
else -> item
}
}
)
.withIndex()
.onEach {
if (i < 75) {
if (i < 15) {
Logger.d("${context()} csl ${it.index}")
i++
}
Expand Down Expand Up @@ -132,7 +127,6 @@ class LogLines(
DogcatConfig.MAX_LOG_LINES,
)
.onSubscription { Logger.d("${context()} Subscribing to shareIn") }

.onCompletion { Logger.d("${context()} (3) COMPLETED Subscription to shareIn") }
}
}
8 changes: 3 additions & 5 deletions src/nativeMain/kotlin/AdbShell.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@ import kotlinx.coroutines.*
import kotlinx.coroutines.channels.ClosedReceiveChannelException
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import logger.Logger
import logger.context
Expand Down Expand Up @@ -119,6 +118,7 @@ class AdbShell(
.catch { cause ->
Logger.d("||||||||||||||||||||||||||||||||||||||||||||||||||| Flow was cancelled, cleaning up resources...")
}
.flowOn(dispatcherIo)
}

override fun heartbeat(): Flow<Boolean> = flow {
Expand All @@ -134,14 +134,12 @@ class AdbShell(
?.first()

val running = name?.contains("running") ?: false

//Logger.d("${context()} !Emulator $name")

emit(running)

delay(1000L)
}
}
.flowOn(dispatcherIo)

override suspend fun appIdFor(packageName: String): String {
val appIdContext =
Expand Down
2 changes: 1 addition & 1 deletion src/nativeMain/kotlin/FileLogger.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class FileLogger : CanLog {
?: throw RuntimeException("Was not able to open log file for writing.")

override fun d(line: String) {
fprintf(file, "$line$LINE_SEPARATOR")
fprintf(file, "$line$\n")
fflush(file)
}

Expand Down
2 changes: 1 addition & 1 deletion src/nativeMain/kotlin/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ fun main(args: Array<String>) {
//he key takeaway is that if you call launch on a custom CoroutineScope, any CoroutineExceptionHandler provided
// directly to the CoroutineScope constructor or to launch will be executed when an exception is thrown within the launched coroutine.
val appJob = CoroutineScope(ui).launch(handler) {
val appModule = AppModule(ui)
val appModule = AppModule()

with(appModule) {
Logger.set(fileLogger)
Expand Down
12 changes: 5 additions & 7 deletions src/nativeMain/kotlin/di/AppModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@ import ui.status.StatusPresenter
import userInput.DefaultInput
import userInput.Input

class AppModule(
private val uiDispatcher: CoroutineDispatcher
) {
class AppModule {

private val appModule = DI.Module("app") {
bindSingleton<CanLog> {
if (BuildConfig.DEBUG) {
Expand All @@ -38,16 +37,15 @@ class AppModule(
instance(),
instance(),
instance(),
instance(),
instance()
)
}
bindSingleton<StatusPresenter> { StatusPresenter(instance(), instance(), instance(), uiDispatcher) }
bindSingleton<StatusPresenter> { StatusPresenter(instance(), instance(), instance()) }
bindSingleton<LogLinesPresenter> {
LogLinesPresenter(
instance(),
instance(),
instance(),
uiDispatcher
instance()
)
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/nativeMain/kotlin/di/DogcatModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ object DogcatModule {
internal val dogcatModule = DI.Module("dogcat") {
bindSingleton<DefaultAppliedFiltersState> { DefaultAppliedFiltersState() }
bindSingleton<LogLineParser> { LogcatBriefParser() }
bindSingleton<LogLines> { LogLines(instance(), instance(), instance(), Dispatchers.Default, Dispatchers.IO) }
bindSingleton<LogLines> { LogLines(instance(), instance(), instance(), Dispatchers.Default) }
bindSingleton<Dogcat> { Dogcat(instance(), instance(), instance()) }
bindSingleton<Shell> { AdbShell(Dispatchers.IO) }
}
Expand Down
11 changes: 2 additions & 9 deletions src/nativeMain/kotlin/ui/logLines/LogLineExtensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ suspend fun LogLinesView.processLogLine(
) {
if (it.value is Unparseable) {
printTag("")
//use System.line ending
waddstr(pad, " ".repeat(1 + 3 + 1))
//account for end of line in the same way as in wrapline
waddstr(pad, (it.value as Unparseable).line + "\n")
Expand Down Expand Up @@ -49,9 +48,6 @@ suspend fun LogLinesView.processLogLine(
}
}


//refresh()

if (autoscroll) {
//handle a case when current lines take less than a screen
//end()
Expand Down Expand Up @@ -94,8 +90,7 @@ private fun LogLinesView.wrapLine(

val width = position.endX
val header = AppConfig.DEFAULT_TAG_WIDTH + 1 + 3 + 1// space, level, space
val line = message.replace(r, " ") // Replace control characters and escape sequences with spaces
//val line = message.replace("\t", " ") //prevent escape characters leaking
val line = message.replace(r, " ")
val wrapArea = width - header
var buf = ""
var current = 0
Expand All @@ -106,7 +101,6 @@ private fun LogLinesView.wrapLine(
val next = min(current + wrapArea, line.length)
buf += line.substring(current, next)
if (next < line.length) {
//buf += "\n"
count += 1
buf += " ".repeat(header) //
}
Expand All @@ -116,11 +110,10 @@ private fun LogLinesView.wrapLine(
val sx = getmaxx(pad)

val s = if ((buf.length + header) % sx == 0) {
//Logger.d("${buf.length} $message")
buf
} else {
buf + "\n"
}

return s to count //+ "\n\r"
return s to count
}
Loading

0 comments on commit 08da01b

Please sign in to comment.