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
2 changes: 2 additions & 0 deletions .github/workflows/e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -337,9 +337,11 @@ jobs:
disable-animations: true
emulator-boot-timeout: 600
script: |
set -e
eval $(opam env)
export LOGSEQ_OPAM_SWITCH="$(opam switch show)"
export DUNE="$(command -v dune)"
./android/gradlew -p android :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.logseq.logseq.AndroidNavigationChromeLayoutTest
./scripts/test-android-e2e.sh "$ANDROID_MODULE"

- name: Upload Maestro debug artifacts
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ class AndroidFeedbackRecordingTest(private val scenario: String) {
assertEquals("NLP date-time input uses the device's local time", expected.toString(), scheduled.getString("editorValue"))
}
"language" -> {
mount(1); host("settings", """{"appearance":"system","language":"system","systemLanguage":"zh-CN","spellCheck":true,"autoCorrection":true,"sidebarTabs":[],"baseURL":"http://127.0.0.1:1","version":"QA","revision":"feedback"}""")
mount(1); host("settings", """{"appearance":"system","language":"system","systemLanguage":"zh-CN","spellCheck":true,"autoCorrection":true,"taskRemindersEnabled":false,"taskRemindersStatus":"","sidebarTabs":[],"baseURL":"http://127.0.0.1:1","version":"QA","revision":"feedback"}""")
ui.onNodeWithTag("button.sidebar").performClick(); pause()
ui.onNodeWithTag("button.sidebar.settings").performClick(); pause()
if (verify) ui.onNodeWithText("设置").assertExists()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package com.logseq.logseq

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
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.material3.MaterialExpressiveTheme
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.assertHeightIsAtLeast
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.getUnclippedBoundsInRoot
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performClick
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.logseq.logseq.runtime.LogseqNativeBridge
import com.logseq.logseq.runtime.LuiPatchFilter
import com.logseq.logseq.runtime.dispatchLuiEvent
import com.logseq.logseq.runtime.logseqIconResolver
import com.logseq.logseq.ui.LogseqTheme
import com.logseq.logseq.ui.extensions.NavigationChromeLayout
import com.logseq.logseq.ui.extensions.logseqExtensionRegistry
import dev.lui.LuiBackend
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class AndroidNavigationChromeLayoutTest {
@get:Rule val ui = createComposeRule()
private var bridge: LogseqNativeBridge? = null

@After fun closeBridge() { bridge?.let { ui.runOnIdle { it.close() } } }

private fun checkChrome(occupies: Boolean) {
ui.setContent {
Box(Modifier.fillMaxSize().testTag("screen")) {
NavigationChromeLayout(occupies,
content = { Box(Modifier.fillMaxSize().testTag("content")) },
chrome = {
// BoxWithConstraints rejects intrinsic measurement. Its
// child also models the chrome's vertical grow modifiers.
BoxWithConstraints(Modifier.fillMaxWidth()) {
Box(Modifier.fillMaxHeight().height(56.dp).testTag("chrome"))
}
})
}
}
val screen = ui.onNodeWithTag("screen").getUnclippedBoundsInRoot()
val content = ui.onNodeWithTag("content").getUnclippedBoundsInRoot()
val chrome = ui.onNodeWithTag("chrome").getUnclippedBoundsInRoot()
assertEquals(56f, (chrome.bottom - chrome.top).value, 1f)
assertEquals(screen.bottom.value, chrome.bottom.value, 1f)
assertEquals((if (occupies) chrome.top else screen.bottom).value, content.bottom.value, 1f)
}

@Test fun overlayChromeMeasuresSubcomposedContentAtNaturalHeight() = checkChrome(false)
@Test fun insetChromeMeasuresSubcomposedContentAtNaturalHeight() = checkChrome(true)

@Test fun captureChromeKeepsItsHeightAndOpensComposer() {
lateinit var native: LogseqNativeBridge
val backend = LuiBackend(onEvent = { dispatchLuiEvent(it, native) },
extensions = logseqExtensionRegistry { it }, icons = logseqIconResolver)
val filter = LuiPatchFilter(backend)
native = LogseqNativeBridge(onPatch = { filter.applyJson(it) })
bridge = native
val root = native.initialize(authenticationCode = 3)
filter.applyJson(native.applySnapshot("""{"ok":true,"result":{
"graphName":"Chrome layout test","selectedGraphId":"chrome-layout-test",
"isGraphUnlocked":true,"outlinerRows":[]}}"""))
ui.setContent {
MaterialExpressiveTheme(colorScheme = LogseqTheme.lightScheme, typography = LogseqTheme.typography) {
Box(Modifier.fillMaxSize()) { backend.Content(root) }
}
}
ui.onNodeWithTag("pane.journals").assertHeightIsAtLeast(120.dp)
ui.onNodeWithTag("button.search").assertIsDisplayed().assertHeightIsAtLeast(48.dp)
ui.onNodeWithTag("button.composer.expand").assertIsDisplayed().assertHeightIsAtLeast(48.dp).performClick()
ui.onNodeWithTag("field.composer").assertIsDisplayed()
ui.onNodeWithTag("button.send").assertIsDisplayed()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ class AndroidNodePropertiesTest {
val snapshot = InstrumentationRegistry.getInstrumentation().context.assets
.open("node-properties.json").bufferedReader().use { it.readText() }
filter.applyJson(bridge.applySnapshot(snapshot))
val settingsPatch = bridge.applyHostUpdate("settings", """{"appearance":"dark","language":"en","spellCheck":true,"autoCorrection":true,"sidebarTabs":[],"baseURL":"https://api.logseq.io","version":"test","revision":"test"}""")
val settingsPatch = bridge.applyHostUpdate("settings", """{"appearance":"dark","language":"en","spellCheck":true,"autoCorrection":true,"taskRemindersEnabled":false,"taskRemindersStatus":"","sidebarTabs":[],"baseURL":"https://api.logseq.io","version":"test","revision":"test"}""")
settingsPatch.takeIf { it.isNotEmpty() }?.let { filter.applyJson(it) }
bridge.applyHostUpdate("graph-loading", "false").takeIf { it.isNotEmpty() }?.let { filter.applyJson(it) }
ui.setContent {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class AndroidTagSearchRegressionTest {
bridge = LogseqNativeBridge(onPatch = { if (it.isNotEmpty()) filter.applyJson(it) })
val root = bridge.initialize(authenticationCode = 3)
filter.applyJson(bridge.applySnapshot(response.toString()))
bridge.applyHostUpdate("settings", """{"appearance":"light","language":"$language","systemLanguage":"en","spellCheck":true,"autoCorrection":true,"sidebarTabs":[],"baseURL":"https://api.logseq.io","version":"test","revision":"test"}""")
bridge.applyHostUpdate("settings", """{"appearance":"light","language":"$language","systemLanguage":"en","spellCheck":true,"autoCorrection":true,"taskRemindersEnabled":false,"taskRemindersStatus":"","sidebarTabs":[],"baseURL":"https://api.logseq.io","version":"test","revision":"test"}""")
.takeIf { it.isNotEmpty() }?.let(filter::applyJson)
bridge.applyHostUpdate("graph-loading", "false").takeIf { it.isNotEmpty() }?.let(filter::applyJson)
ui.setContent {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ internal data class AndroidHostSettings(
"systemLanguage" to java.util.Locale.getDefault().toLanguageTag(),
"spellCheck" to spellCheck,
"autoCorrection" to autoCorrection,
"taskRemindersEnabled" to false,
"taskRemindersStatus" to "",
"sidebarTabs" to sidebarTabs,
"baseURL" to baseUrl,
"version" to version,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -301,35 +301,34 @@ private fun NavigationBoundary(context: LuiExtensionContext) {
if (childIds.size == 2) {
// Second child is the bottom chrome. Hoist it out of the content
// column like iOS's safeAreaInset/overlay so the composer's
// internal `grow` props can't starve the journal. Unbounded
// height keeps it at natural size without querying intrinsic
// measurements unsupported by subcomposed LUI layouts.
if (occupies) {
Column(Modifier.fillMaxSize()) {
Box(Modifier.weight(1f)) { NavigationContent(context, childIds[0], dismissesComposer) }
Box(Modifier.wrapContentHeight(unbounded = true)) {
context.child(childIds[1])
}
}
} else {
Box(Modifier.fillMaxSize()) {
Column(Modifier.fillMaxSize()) { NavigationContent(context, childIds[0], dismissesComposer) }
Box(
Modifier
.align(Alignment.BottomCenter)
.wrapContentHeight(unbounded = true),
) {
context.child(childIds[1])
}
}
}
// internal `grow` props can't starve the journal.
NavigationChromeLayout(occupies,
content = { NavigationContent(context, childIds[0], dismissesComposer) },
chrome = { context.child(childIds[1]) })
} else {
context.Children()
}
}
}
}

@Composable
internal fun NavigationChromeLayout(occupies: Boolean, content: @Composable () -> Unit, chrome: @Composable () -> Unit) {
// Unbounded height keeps grow modifiers from claiming the screen without
// asking for intrinsics, which subcomposed controls do not support.
if (occupies) {
Column(Modifier.fillMaxSize()) {
Box(Modifier.weight(1f)) { content() }
Box(Modifier.wrapContentHeight(unbounded = true)) { chrome() }
}
} else {
Box(Modifier.fillMaxSize()) {
Column(Modifier.fillMaxSize()) { content() }
Box(Modifier.align(Alignment.BottomCenter).wrapContentHeight(unbounded = true)) { chrome() }
}
}
}

@Composable
private fun NavigationContent(context: LuiExtensionContext, contentId: Long, dismissesComposer: Boolean) {
val focus = LocalFocusManager.current
Expand Down
136 changes: 97 additions & 39 deletions apple/Sources/Logseq/GraphSyncCoordinator.swift
Original file line number Diff line number Diff line change
@@ -1,12 +1,41 @@
import Foundation
import os

actor GraphSyncCoordinator {
typealias ForegroundOperation = @MainActor @Sendable (String) async -> Void
typealias BackgroundOperation = @MainActor @Sendable () async -> Bool
typealias BackgroundExpirationCleanup = @MainActor @Sendable () async -> Void

fileprivate final class BackgroundRun: Sendable {
struct State: Sendable {
var callers: Set<UUID> = []
var expiration: Task<Task<Bool, Never>?, Never>?
}
let task: Task<Bool, Never>
let cleanup: BackgroundExpirationCleanup
let state = OSAllocatedUnfairLock(initialState: State())

init(task: Task<Bool, Never>, cleanup: @escaping BackgroundExpirationCleanup) {
self.task = task
self.cleanup = cleanup
}
}

// A caller keeps its expiration result even after the shared run finishes.
// Repeated cancellation/OS expiration must await the same cleanup and may
// never look up a later run by a global "current background" slot.
final class BackgroundRequest: Sendable {
fileprivate struct State: Sendable {
var expired = false
var expiration: Task<Task<Bool, Never>?, Never>?
var run: BackgroundRun?
}
fileprivate let id = UUID()
fileprivate let state = OSAllocatedUnfairLock(initialState: State())
}

private var foregroundTask: Task<Void, Never>?
private var backgroundTask: Task<Bool, Never>?
private var backgroundGeneration = UUID()
private var backgroundRun: BackgroundRun?
private var networkAvailable = true
private var desiredForeground: (graphID: String, operation: ForegroundOperation)?

Expand Down Expand Up @@ -40,7 +69,7 @@ actor GraphSyncCoordinator {
operation: @escaping ForegroundOperation
) async {
let previousForeground = foregroundTask
let activeBackground = backgroundTask
let activeBackground = backgroundRun?.task
previousForeground?.cancel()
foregroundTask = Task {
if let activeBackground {
Expand Down Expand Up @@ -74,51 +103,80 @@ actor GraphSyncCoordinator {
await foregroundTask.value
}

func runBackground(operation: @escaping BackgroundOperation) async -> Bool {
guard !Task.isCancelled else { return false }
if let backgroundTask {
return await backgroundTask.value
}

let previousForeground = foregroundTask
foregroundTask = nil
previousForeground?.cancel()
let generation = UUID()
backgroundGeneration = generation
let task = Task {
if let previousForeground {
await previousForeground.value
func runBackground(
request: BackgroundRequest = BackgroundRequest(),
expirationCleanup: @escaping BackgroundExpirationCleanup = {},
operation: @escaping BackgroundOperation
) async -> Bool {
guard !Task.isCancelled, !request.state.withLock({ $0.expired }) else { return false }
if backgroundRun == nil {
let previousForeground = foregroundTask
foregroundTask = nil
previousForeground?.cancel()
let task = Task {
if let previousForeground {
await previousForeground.value
}
guard !Task.isCancelled else { return false }
return await operation()
}
guard !Task.isCancelled else { return false }
return await operation()
backgroundRun = BackgroundRun(task: task, cleanup: expirationCleanup)
}
backgroundTask = task
let run = backgroundRun!
request.state.withLock { $0.run = run }
_ = run.state.withLock { $0.callers.insert(request.id) }
let result = await withTaskCancellationHandler {
await task.value
await run.task.value
} onCancel: {
task.cancel()
request.state.withLock { $0.expired = true }
Task { _ = await self.expireBackground(request: request) }
}
if backgroundGeneration == generation {
backgroundTask = nil
if Task.isCancelled || request.state.withLock({ $0.expired }) {
_ = await expireBackground(request: request)
} else {
_ = run.state.withLock { $0.callers.remove(request.id) }
}
return result
if backgroundRun === run { backgroundRun = nil }
return result && !Task.isCancelled && !request.state.withLock { $0.expired }
}

func cancelBackground() async {
guard let backgroundTask else { return }
self.backgroundTask = nil
backgroundGeneration = UUID()
backgroundTask.cancel()
_ = await backgroundTask.value
// Expiring one coalesced waiter releases only that waiter's budget. The
// final waiter cancels the captured run, drains its reminder writes, and
// returns that exact network task for teardown after OS completion.
func expireBackground(request: BackgroundRequest) async -> Task<Bool, Never>? {
if let expiration = request.state.withLock({ $0.expiration }) {
return await expiration.value
}
// The request retains its exact run after normal completion. An OS
// expiration may already have claimed the budget while its actor call
// is queued; it must still drain that run, never a newer global slot.
let expiration = request.state.withLock { $0.run }.map { run in
run.state.withLock { state -> Task<Task<Bool, Never>?, Never> in
state.callers.remove(request.id)
guard state.callers.isEmpty else { return Task { nil } }
if let expiration = state.expiration { return expiration }
run.task.cancel()
let task = run.task
let cleanup = run.cleanup
let expiration = Task<Task<Bool, Never>?, Never> {
await cleanup()
return task
}
state.expiration = expiration
return expiration
}
} ?? Task { nil }
request.state.withLock {
$0.expired = true
$0.expiration = expiration
}
return await expiration.value
}
}

@MainActor final class BackgroundTaskCompletion {
private var finished = false

func finish(success: Bool, completion: (Bool) -> Void) {
guard !finished else { return }
finished = true
completion(success)
func cancelBackground() async {
guard let run = backgroundRun else { return }
backgroundRun = nil
run.task.cancel()
_ = await run.task.value
}
}
Loading
Loading