Use native macOS window presentation for dock reopen and first show.

Enable AppKit document-window animation behavior and present via makeKeyAndOrderFront after Compose shows; avoid dock flash when the main window is already visible.
This commit is contained in:
2026-11-08 13:55:05 +03:00
Unverified
parent e6e3f6b49c
commit 56eb2daad0
20 changed files with 418 additions and 69 deletions
@@ -1,6 +1,8 @@
package ru.fromchat.desktop
import androidx.compose.ui.awt.ComposeWindow
import androidx.compose.ui.unit.dp
import javax.swing.SwingUtilities
import ru.fromchat.config.Settings
import ru.fromchat.ui.theme.Theme
import ru.fromchat.ui.theme.jvmPlatformSystemDarkTheme
@@ -61,3 +63,14 @@ internal fun applyDesktopEdgeToEdgeChrome(rootPane: JRootPane) {
rootPane.putClientProperty("apple.awt.transparentTitleBar", true)
rootPane.putClientProperty("apple.awt.windowTitleVisible", false)
}
/** Re-apply edge-to-edge client props once the Cocoa peer exists (cold open). */
internal fun installMacDesktopEdgeToEdgeChromeAfterOpen(window: ComposeWindow) {
if (!isMacOs()) return
applyDesktopEdgeToEdgeChrome(window.rootPane)
MacDesktopWindowPresentation.applySystemAnimationBehavior()
SwingUtilities.invokeLater {
applyDesktopEdgeToEdgeChrome(window.rootPane)
MacDesktopWindowPresentation.applySystemAnimationBehavior()
}
}
@@ -99,10 +99,12 @@ internal fun FrameWindowScope.DesktopRootSurface(
installWindowsNativeCaptionChrome(window)
applyWindowsRoundedCorners(window)
}
applyDesktopEdgeToEdgeChrome(window.rootPane)
dockIconImage?.let { image ->
window.iconImages = listOf(image)
applyDockIcon(image)
installMacDesktopEdgeToEdgeChromeAfterOpen(window)
if (!isMacOs()) {
dockIconImage?.let { image ->
window.iconImages = listOf(image)
applyDockIcon(image)
}
}
}
@@ -5,7 +5,9 @@ package ru.fromchat.desktop
*
* ## Window close → background (not quit)
* The red traffic-light / window close hides the main window and keeps the JVM process
* plus menu-bar tray alive (close-to-tray). Quit is only via tray Quit, File → Quit, or ⌘Q.
* plus menu-bar tray alive (close-to-tray). Dock reopen: activate only when already visible;
* otherwise AppKit document-window presentation (see MacDesktopWindowPresentation).
* Quit is only via tray Quit, File → Quit, or ⌘Q (persists sign-in unless incognito).
* Dock icon stays (NSApplicationActivationPolicyRegular) so macOS can show the Dock
* "Running in Background" indicator when no windows are visible.
*
@@ -0,0 +1,14 @@
package ru.fromchat.desktop
import java.awt.Window
/** Main Compose window handle for macOS dock / presentation heuristics. */
internal object MacDesktopWindowHost {
@Volatile
var mainWindow: Window? = null
fun isMainWindowShowing(): Boolean {
val window = mainWindow ?: return false
return window.isVisible && window.isShowing
}
}
@@ -0,0 +1,43 @@
package ru.fromchat.desktop
import javax.swing.SwingUtilities
internal object MacDesktopWindowPresentation {
fun applySystemAnimationBehavior() {
if (!isMacOs()) return
MacNotificationCenter.applySystemWindowAnimationBehavior()
}
/** First cold open: set animation behavior and activate; do not re-makeKey (breaks Skiko text input). */
fun onFirstComposeShow() {
if (!isMacOs()) return
SwingUtilities.invokeLater {
MacNotificationCenter.applySystemWindowAnimationBehavior()
MacNotificationCenter.activateApplication()
repairMainWindowKeyboardFocus()
}
}
/** Window was hidden (close-to-tray) and is visible again — use AppKit document presentation. */
fun presentAfterHidden() {
if (!isMacOs()) return
SwingUtilities.invokeLater {
MacNotificationCenter.applySystemWindowAnimationBehavior()
MacNotificationCenter.presentMainWindows()
repairMainWindowKeyboardFocus()
}
}
/** Best-effort restore AWT/Skiko keyboard focus after AppKit presentation. */
fun repairMainWindowKeyboardFocus() {
if (!isMacOs()) return
val window = MacDesktopWindowHost.mainWindow ?: return
window.toFront()
window.requestFocus()
MacNotificationCenter.repairMainWindowKeyboardFocus()
SwingUtilities.invokeLater {
window.requestFocus()
MacNotificationCenter.repairMainWindowKeyboardFocus()
}
}
}
@@ -594,6 +594,15 @@ fun main(args: Array<String>) {
DesktopNotifier.deliverPendingLaunch(notificationIdentifier)
}
fun handleMacDockReopen() {
if (!mac) return
if (windowVisible && MacDesktopWindowHost.isMainWindowShowing()) {
MacNotificationCenter.activateApplication()
return
}
showMainWindow()
}
LaunchedEffect(mac, windowVisible) {
if (!mac) return@LaunchedEffect
MacNotificationCenter.onActivated = { identifier ->
@@ -617,15 +626,6 @@ fun main(args: Array<String>) {
DesktopMenuCommands.emit(DesktopMenuCommand.OpenAbout)
}
/** Best-effort server logout (5s), then local wipe. Does not block the caller. */
fun startBackgroundLogoutThen(block: () -> Unit = {}) {
CoroutineScope(SupervisorJob() + Dispatchers.Swing).launch {
runCatching { ApiClient.logoutBestEffort() }
resetPreAuthDraft()
block()
}
}
/**
* Incognito window close: drop in-memory auth now, wipe disk off the EDT, remount on show.
*/
@@ -645,6 +645,22 @@ fun main(args: Array<String>) {
}
}
/**
* Exit the desktop app. Incognito always wipes local auth; standard sessions stay on disk
* so the next launch is still signed in (same as close-to-tray).
*/
fun quitDesktopApplication(block: () -> Unit = {}) {
if (IncognitoMode.active) {
endIncognitoSessionImmediatelyThen(block)
return
}
resetPreAuthDraft()
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
runCatching { WebSocketManager.disconnect() }
}
block()
}
/** Hide window, keep process + tray (close-to-background). Else quit. */
fun requestCloseToBackgroundOrQuit() {
if (traySupported) {
@@ -665,7 +681,7 @@ fun main(args: Array<String>) {
} else if (IncognitoMode.active) {
endIncognitoSessionImmediatelyThen { exitApplication() }
} else {
startBackgroundLogoutThen { exitApplication() }
quitDesktopApplication { exitApplication() }
}
}
@@ -682,26 +698,17 @@ fun main(args: Array<String>) {
desktop.setQuitHandler { _, response ->
windowVisible = false
DesktopSingleInstance.release()
if (IncognitoMode.active) {
endIncognitoSessionImmediatelyThen {
response.performQuit()
exitApplication()
}
} else {
CoroutineScope(SupervisorJob() + Dispatchers.Swing).launch {
runCatching { ApiClient.logoutBestEffort() }
resetPreAuthDraft()
response.performQuit()
exitApplication()
}
quitDesktopApplication {
response.performQuit()
exitApplication()
}
}
}
// Dock click while window is hidden → show again (macOS AppReopened).
// Dock click: show when hidden; if already on screen, only activate (no visibility flash).
if (mac) {
desktop.addAppEventListener(
AppReopenedListener {
SwingUtilities.invokeLater { showMainWindow() }
SwingUtilities.invokeLater { handleMacDockReopen() }
},
)
}
@@ -722,11 +729,7 @@ fun main(args: Array<String>) {
Separator()
Item(quit) {
windowVisible = false
if (IncognitoMode.active) {
endIncognitoSessionImmediatelyThen { exitApplication() }
} else {
startBackgroundLogoutThen { exitApplication() }
}
quitDesktopApplication { exitApplication() }
}
},
)
@@ -743,11 +746,7 @@ fun main(args: Array<String>) {
onAbout = { openAbout() },
onQuit = {
windowVisible = false
if (IncognitoMode.active) {
endIncognitoSessionImmediatelyThen { exitApplication() }
} else {
startBackgroundLogoutThen { exitApplication() }
}
quitDesktopApplication { exitApplication() }
},
)
}
@@ -784,19 +783,37 @@ fun main(args: Array<String>) {
}
event.key == Key.Q -> {
windowVisible = false
if (IncognitoMode.active) {
endIncognitoSessionImmediatelyThen { exitApplication() }
} else {
startBackgroundLogoutThen { exitApplication() }
}
quitDesktopApplication { exitApplication() }
true
}
else -> false
}
},
) {
val composeWindowShouldShow = contentReady && (windowVisible || !traySupported)
var hadComposeWindowShown by remember { mutableStateOf(false) }
var previousComposeWindowShouldShow by remember { mutableStateOf(false) }
LaunchedEffect(composeWindowShouldShow) {
if (!mac) {
previousComposeWindowShouldShow = composeWindowShouldShow
return@LaunchedEffect
}
val becameVisible = composeWindowShouldShow && !previousComposeWindowShouldShow
when {
becameVisible && !hadComposeWindowShown -> {
hadComposeWindowShown = true
MacDesktopWindowPresentation.onFirstComposeShow()
}
becameVisible && hadComposeWindowShown -> {
MacDesktopWindowPresentation.presentAfterHidden()
}
}
previousComposeWindowShouldShow = composeWindowShouldShow
}
LaunchedEffect(window, appName, windowChrome) {
window.title = appName
installMacDesktopEdgeToEdgeChromeAfterOpen(window)
windowChrome.toAwtColor().also {
window.background = it
window.contentPane.background = it
@@ -809,14 +826,18 @@ fun main(args: Array<String>) {
installWindowsNativeCaptionChrome(window)
applyWindowsRoundedCorners(window)
}
applyDesktopEdgeToEdgeChrome(window.rootPane)
dockIconImage?.let { image ->
window.iconImages = listOf(image)
applyDockIcon(image)
if (!mac) {
dockIconImage?.let { image ->
window.iconImages = listOf(image)
applyDockIcon(image)
}
}
}
DisposableEffect(window) {
if (mac) {
MacDesktopWindowHost.mainWindow = window
}
installDesktopWindowExceptionHandler(window)
AppForeground.setForeground(true)
fun syncWindowFocus(focused: Boolean) {
@@ -831,6 +852,9 @@ fun main(args: Array<String>) {
val listener = object : java.awt.event.WindowAdapter() {
override fun windowActivated(e: java.awt.event.WindowEvent?) {
syncWindowFocus(true)
if (mac) {
MacDesktopWindowPresentation.repairMainWindowKeyboardFocus()
}
}
override fun windowDeactivated(e: java.awt.event.WindowEvent?) {
@@ -839,6 +863,9 @@ fun main(args: Array<String>) {
override fun windowGainedFocus(e: java.awt.event.WindowEvent?) {
syncWindowFocus(true)
if (mac) {
MacDesktopWindowPresentation.repairMainWindowKeyboardFocus()
}
}
override fun windowLostFocus(e: java.awt.event.WindowEvent?) {
@@ -853,6 +880,9 @@ fun main(args: Array<String>) {
window.addWindowListener(listener)
window.addWindowFocusListener(listener)
onDispose {
if (mac && MacDesktopWindowHost.mainWindow === window) {
MacDesktopWindowHost.mainWindow = null
}
window.removeWindowListener(listener)
window.removeWindowFocusListener(listener)
}
@@ -885,7 +915,7 @@ fun main(args: Array<String>) {
},
onQuit = {
windowVisible = false
startBackgroundLogoutThen { exitApplication() }
quitDesktopApplication { exitApplication() }
},
)
}
@@ -1219,6 +1249,11 @@ internal fun applyDockIcon(image: BufferedImage?) {
Logger.w("DesktopIcon", "applyDockIcon skipped — image is null")
return
}
// Bundled apps use CFBundleIconFile / -Xdock:icon (liquid-glass .icns). Raster override flattens the Dock.
if (isMacOs()) {
Logger.i("DesktopIcon", "macOS: leaving native dock icon (not overriding with classpath raster)")
return
}
runCatching {
if (!Taskbar.isTaskbarSupported()) {
@@ -466,3 +466,103 @@ JNIEXPORT void JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeRegi
if (url == nil) return;
LSRegisterURL((__bridge CFURLRef)url, true);
}
static BOOL fromchatIsMainTitledWindow(NSWindow *window) {
return (window.styleMask & NSWindowStyleMaskTitled) != 0;
}
static void fromchatApplyDocumentWindowAnimation(NSWindow *window) {
if (@available(macOS 10.12, *)) {
window.animationBehavior = NSWindowAnimationBehaviorDocumentWindow;
}
}
JNIEXPORT void JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeApplySystemWindowAnimationBehavior(
JNIEnv *env,
jclass cls
) {
fromchatRunOnMain(^{
for (NSWindow *window in [NSApp windows]) {
if (!fromchatIsMainTitledWindow(window)) continue;
fromchatApplyDocumentWindowAnimation(window);
}
});
}
JNIEXPORT void JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativePresentMainWindows(
JNIEnv *env,
jclass cls
) {
fromchatRunOnMain(^{
[NSApp activateIgnoringOtherApps:YES];
for (NSWindow *window in [NSApp windows]) {
if (!fromchatIsMainTitledWindow(window)) continue;
fromchatApplyDocumentWindowAnimation(window);
if (window.isMiniaturized) {
[window deminiaturize:nil];
continue;
}
if (!window.isVisible || !window.isKeyWindow) {
[window makeKeyAndOrderFront:nil];
} else {
// Re-makeKey on an already visible key window resets Skiko's first responder;
// typing in Compose text fields fails until the window is iconified and restored.
[window orderFront:nil];
}
}
});
}
JNIEXPORT void JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeActivateApplication(
JNIEnv *env,
jclass cls
) {
fromchatRunOnMain(^{
[NSApp activateIgnoringOtherApps:YES];
NSWindow *key = [NSApp keyWindow];
if (key != nil) {
[key makeKeyAndOrderFront:nil];
return;
}
for (NSWindow *window in [NSApp windows]) {
if (window.isVisible && (window.styleMask & NSWindowStyleMaskTitled)) {
[window makeKeyAndOrderFront:nil];
break;
}
}
});
}
static NSView *fromchatKeyboardHostView(NSWindow *window) {
NSView *content = [window contentView];
if (content == nil) return nil;
for (NSView *child in [[content subviews] reverseObjectEnumerator]) {
if ([child acceptsFirstResponder]) return child;
}
return content;
}
JNIEXPORT void JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeRepairMainWindowKeyboardFocus(
JNIEnv *env,
jclass cls
) {
fromchatRunOnMain(^{
[NSApp activateIgnoringOtherApps:YES];
NSWindow *target = [NSApp keyWindow];
if (target == nil || !fromchatIsMainTitledWindow(target)) {
for (NSWindow *window in [NSApp windows]) {
if (!fromchatIsMainTitledWindow(window) || !window.isVisible) continue;
target = window;
if (!window.isKeyWindow) {
[window makeKeyAndOrderFront:nil];
}
break;
}
}
if (target == nil) return;
NSView *host = fromchatKeyboardHostView(target);
if (host != nil) {
[target makeFirstResponder:host];
}
});
}
@@ -860,6 +860,8 @@ inline fun String.decodeWindows1251() = String(
@get:ChecksSdkIntAtLeast(api = Build.VERSION_CODES.S)
actual val materialYouAvailable get() = Build.VERSION.SDK_INT >= 31
actual val expressiveStepFieldsFocusableDuringPagerMotion get() = false
private fun String?.trimIfNotBlank(): String? =
this?.trim()?.takeIf { it.isNotEmpty() }
@@ -5,11 +5,12 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import ru.fromchat.api.local.messages.nowMessageTimestampIso
import ru.fromchat.api.local.messages.sortMessagesForChatDisplay
import ru.fromchat.api.schema.messages.Message
/** Local-only centered notices (encryption mode changes). Also persisted to the message DB. */
object EncryptionModeNoticeStore {
const val SERVICE_USER_ID = -9001
const val SERVICE_USER_ID = 0
private val _noticesByConversation = MutableStateFlow<Map<String, List<Message>>>(emptyMap())
private val _revision = MutableStateFlow(0)
@@ -45,7 +46,7 @@ object EncryptionModeNoticeStore {
current
} else {
inserted = message
current + (conversationId to (existing + message).sortedBy { it.timestamp })
current + (conversationId to sortMessagesForChatDisplay(existing + message))
}
}
if (inserted != null) _revision.update { it + 1 }
@@ -55,13 +56,31 @@ object EncryptionModeNoticeStore {
fun noticesFor(conversationId: String): List<Message> =
_noticesByConversation.value[conversationId].orEmpty()
/** Rebuild in-memory notices after cold start from rows already in SQLite. */
fun registerPersistedNotices(conversationId: String, messages: List<Message>) {
val service = messages.filter { it.isCenteredServiceNotice() }
if (service.isEmpty()) return
var changed = false
_noticesByConversation.update { current ->
val existing = current[conversationId].orEmpty()
val byId = LinkedHashMap<Int, Message>()
for (msg in existing) byId[msg.id] = msg
for (msg in service) {
if (byId.putIfAbsent(msg.id, msg) == null) changed = true
}
if (!changed) return@update current
current + (conversationId to sortMessagesForChatDisplay(byId.values.toList()))
}
if (changed) _revision.update { it + 1 }
}
fun mergeIntoTimeline(conversationId: String, messages: List<Message>): List<Message> {
val notices = noticesFor(conversationId)
if (notices.isEmpty()) return messages
val byId = LinkedHashMap<Int, Message>()
for (msg in messages) byId[msg.id] = msg
for (notice in notices) byId.putIfAbsent(notice.id, notice)
return byId.values.sortedBy { it.timestamp }
return sortMessagesForChatDisplay(byId.values.toList())
}
fun clearAll() {
@@ -70,4 +89,5 @@ object EncryptionModeNoticeStore {
}
}
fun Message.isCenteredServiceNotice(): Boolean = user_id == EncryptionModeNoticeStore.SERVICE_USER_ID
fun Message.isCenteredServiceNotice(): Boolean =
user_id == EncryptionModeNoticeStore.SERVICE_USER_ID
@@ -167,9 +167,24 @@ object InstanceEncryptionStore {
suspend fun ensureActivePolicy(): InstanceEncryptionSnapshot {
_active.value?.let { return it }
restoreActiveFromDiskCache()?.let { return it }
return refreshActiveFromNetwork() ?: error("Instance encryption policy unavailable")
}
private suspend fun restoreActiveFromDiskCache(): InstanceEncryptionSnapshot? {
val config = ServerConfig.serverConfig.value ?: Settings.readServerConfig()
val instanceId = Settings.lastKnownServerInstanceId.trim()
if (instanceId.isBlank()) return null
val snapshot = InstanceEncryptionCache.snapshotForConfig(instanceId, config) ?: return null
mutex.withLock {
if (_active.value == null) {
_active.value = snapshot
Logger.i(TAG, "restored encryption policy from disk: ${snapshot.mode} v${snapshot.version}")
}
}
return _active.value
}
fun modeMismatchWarning(
cached: InstanceEncryptionSnapshot?,
live: InstanceEncryptionSnapshot,
@@ -5,6 +5,7 @@ import ru.fromchat.api.local.messages.conversationIdForDm
import ru.fromchat.api.local.messages.conversationIdForGroup
import ru.fromchat.api.local.messages.dmOtherUserIdFromConversationId
import ru.fromchat.api.local.messages.groupIdFromConversationId
import ru.fromchat.api.instance.isCenteredServiceNotice
import ru.fromchat.api.schema.messages.Message
/**
@@ -24,6 +25,9 @@ object CacheValidator {
currentUserId: Int?,
dmPeerUserId: Int? = dmOtherUserIdFromConversationId(conversationId),
): Boolean {
if (message.isCenteredServiceNotice()) {
return groupIdFromConversationId(conversationId) == null && dmPeerUserId != null
}
val groupId = groupIdFromConversationId(conversationId)
if (groupId != null) {
return groupId == GENERAL_PUBLIC_GROUP_ID && message.user_id > 0
@@ -12,6 +12,7 @@ import kotlinx.serialization.json.Json
import ru.fromchat.logging.Logger
import ru.fromchat.api.ApiClient
import ru.fromchat.api.instance.EncryptionModeNoticeStore
import ru.fromchat.api.instance.isCenteredServiceNotice
import ru.fromchat.api.local.messages.ChatListPreviewPendingIndicator
import ru.fromchat.api.local.messages.ChatListPreviewState
import ru.fromchat.api.local.messages.ChatListPreviewStrings
@@ -284,7 +285,7 @@ object MessageCacheStore {
/** Durable local-only centered service notice (e.g. encryption mode change). */
suspend fun upsertLocalServiceNotice(conversationId: String, message: Message) {
if (message.user_id != EncryptionModeNoticeStore.SERVICE_USER_ID) return
if (!message.isCenteredServiceNotice()) return
val convId = conversationId.trim()
if (convId.isEmpty()) return
val iid = instanceId()
@@ -830,9 +831,11 @@ object MessageCacheStore {
suspend fun purgePendingNotFromUser(userId: Int) {
val iid = instanceId()
withContext(messageDatabaseDispatcher) {
val serviceUserId = EncryptionModeNoticeStore.SERVICE_USER_ID.toLong()
val foreign = db.messageDatabaseQueries
.selectForeignPendingMessages(iid, userId.toLong())
.executeAsList()
.filter { it.userId != serviceUserId }
foreign.forEach { row ->
val cid = row.clientMessageId?.trim().orEmpty()
if (cid.isNotEmpty()) {
@@ -1091,8 +1094,25 @@ object MessageCacheStore {
private suspend fun clearConversationMessages(conversationId: String) {
val iid = instanceId()
Logger.d("MessageCache", "clearConversationMessages convId=$conversationId")
val preserved = loadPersistedServiceNotices(iid, conversationId)
withContext(messageDatabaseDispatcher) {
db.messageDatabaseQueries.deleteMessagesForConversation(iid, conversationId)
preserved.forEach { notice ->
db.messageDatabaseQueries.upsertMessage(
instanceId = iid,
id = notice.id.toLong(),
conversationId = conversationId,
userId = notice.user_id.toLong(),
content = notice.content,
timestamp = notice.timestamp,
isRead = 1L,
isEdited = 0L,
replyToId = null,
clientMessageId = null,
deletedFlag = 0L,
sendStatus = "sent",
)
}
}
}
@@ -1153,7 +1173,7 @@ object MessageCacheStore {
replyToId = resolveReplyToIdForPersistence(msg, existing?.replyToId),
clientMessageId = msg.client_message_id,
deletedFlag = 0L,
sendStatus = if (msg.id < 0) "pending" else "sent"
sendStatus = sendStatusForPersistence(msg),
)
}
}
@@ -1399,6 +1419,24 @@ object MessageCacheStore {
}
}
private suspend fun loadPersistedServiceNotices(
instanceId: String,
conversationId: String,
): List<Message> = withContext(messageDatabaseDispatcher) {
if (instanceId.isBlank() || conversationId.isBlank()) return@withContext emptyList()
db.messageDatabaseQueries
.selectMessagesByConversation(instanceId, conversationId)
.executeAsList()
.map { it.toAppMessage() }
.filter { it.isCenteredServiceNotice() }
}
private fun sendStatusForPersistence(msg: Message): String = when {
msg.isCenteredServiceNotice() -> "sent"
msg.id < 0 -> "pending"
else -> "sent"
}
private fun resolveReplyToIdForPersistence(msg: Message, existingReplyToId: Long? = null): Long? {
return msg.reply_to?.id?.toLong()
?: msg.replyToId?.toLong()
@@ -1488,6 +1526,7 @@ object MessageCacheStore {
messages.map { hydrateAttachmentPreviewFromDisk(it) }
private fun storedMessageContent(msg: Message): String = when {
msg.isCenteredServiceNotice() -> msg.content
msg.id < 0 -> encodeOptimisticOutboundMessage(msg)
!msg.files.isNullOrEmpty() && msg.dmEnvelope != null -> encodePersistedDmMessage(msg)
!msg.files.isNullOrEmpty() -> encodePersistedPublicMessage(msg)
@@ -1530,6 +1569,12 @@ object MessageCacheStore {
}
val validated = CacheValidator.filterMessages(conversationId, messages, self)
val iid = instanceId()
val preservedNotices = if (replaceAll) {
loadPersistedServiceNotices(iid, conversationId)
} else {
emptyList()
}
val toPersist = (validated + preservedNotices).distinctBy { it.id }
val beforeCount = withContext(messageDatabaseDispatcher) {
db.messageDatabaseQueries
.selectMessagesByConversation(iid, conversationId)
@@ -1539,7 +1584,8 @@ object MessageCacheStore {
Logger.d(
"MessageCache",
"replaceMessages convId=$conversationId replaceAll=$replaceAll " +
"incoming=${messages.size} validated=${validated.size} rowsBefore=$beforeCount",
"incoming=${messages.size} validated=${validated.size} " +
"preservedNotices=${preservedNotices.size} rowsBefore=$beforeCount",
)
withContext(messageDatabaseDispatcher) {
val existingRows = db.messageDatabaseQueries
@@ -1552,7 +1598,7 @@ object MessageCacheStore {
if (replaceAll) {
db.messageDatabaseQueries.transaction {
db.messageDatabaseQueries.deleteMessagesForConversation(iid, conversationId)
validated.forEach { msg: Message ->
toPersist.forEach { msg: Message ->
db.messageDatabaseQueries.upsertMessage(
instanceId = iid,
id = msg.id.toLong(),
@@ -1568,13 +1614,13 @@ object MessageCacheStore {
replyToId = resolveReplyToIdForPersistence(msg, existingReplyToIds[msg.id]),
clientMessageId = msg.client_message_id,
deletedFlag = 0L,
sendStatus = if (msg.id < 0) "pending" else "sent",
sendStatus = sendStatusForPersistence(msg),
)
}
}
} else {
// Merge into existing rows — partial UI snapshots must not wipe full history.
validated.forEach { msg: Message ->
toPersist.forEach { msg: Message ->
upsertSingle(conversationId, msg)
}
}
@@ -1,14 +1,16 @@
package ru.fromchat.api.local.messages
import ru.fromchat.api.instance.isCenteredServiceNotice
import ru.fromchat.api.schema.messages.Message
/**
* Chat list order: confirmed messages by time, then outgoing queued (negative id) at the bottom.
* Pending rows sort by enqueue sequence (monotonic negative id), not hash or wall-clock.
* Centered service notices use negative synthetic ids but belong in the confirmed timeline by time.
*/
internal fun sortMessagesForChatDisplay(messages: List<Message>): List<Message> {
if (messages.size <= 1) return messages
val (pending, confirmed) = messages.partition { it.id < 0 }
val (pending, confirmed) = messages.partition { it.id < 0 && !it.isCenteredServiceNotice() }
val confirmedComparator = compareBy<Message>(
{ messageSortEpochMillis(it) },
{ it.id.toLong() },
@@ -100,6 +100,7 @@ abstract class ChatPanel(
addMessageMutex.withLock {
batchStateUpdates {
updateState { current ->
EncryptionModeNoticeStore.registerPersistedNotices(current.id, messages)
val panelSnap = panelMessagesForDbMerge()
val merged = mergeDatabaseMessagesWithPanelState(
panelSnap,
@@ -37,10 +37,14 @@ import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import ru.fromchat.AppForeground
import ru.fromchat.utils.expressiveStepFieldsFocusableDuringPagerMotion
import ru.fromchat.utils.ImeKeyboardPhase
import kotlinx.coroutines.delay
import ru.fromchat.utils.keyboardPhase
import ru.fromchat.utils.rememberImeMotion
import ru.fromchat.utils.toPx
import androidx.compose.runtime.collectAsState
import kotlin.math.roundToInt
/** Lazy list item indices for [ExpressiveStepFlowScaffold] haze layout. */
@@ -75,9 +79,12 @@ fun expressiveStepSubmitKeyboardActions(onSubmit: () -> Unit): KeyboardActions =
@Composable
fun ExpressiveStepAutoFocusEffect(focusRequester: FocusRequester) {
val autoFocus = LocalExpressiveStepAutoFocusPrimary.current
LaunchedEffect(autoFocus) {
if (autoFocus) {
val windowFocused by AppForeground.isWindowFocused.collectAsState()
LaunchedEffect(autoFocus, windowFocused) {
if (!autoFocus || !windowFocused) return@LaunchedEffect
repeat(3) { attempt ->
focusRequester.requestFocus()
if (attempt < 2) delay(80L * (attempt + 1))
}
}
}
@@ -110,7 +117,7 @@ fun Modifier.trackImeScrollTarget(
var focused by remember { mutableStateOf(false) }
focusProperties {
canFocus = focusEnabled
canFocus = focusEnabled || expressiveStepFieldsFocusableDuringPagerMotion
}.onFocusChanged { state ->
val wasFocused = focused
focused = state.isFocused
@@ -168,6 +168,9 @@ operator fun PaddingValues.plus(other: PaddingValues) = PaddingValues(
expect val materialYouAvailable: Boolean
/** Desktop JVM skips the expressive-step pager focus gate (no touch-IME race). */
expect val expressiveStepFieldsFocusableDuringPagerMotion: Boolean
inline fun <T> T.require( message: String, condition: (T) -> Boolean): T {
require(condition(this)) { message }
return this
@@ -121,13 +121,13 @@ LIMIT :limit;
selectPendingMessagesByConversation:
SELECT *
FROM message
WHERE instanceId = ? AND conversationId = ? AND deletedFlag = 0 AND id < 0
WHERE instanceId = ? AND conversationId = ? AND deletedFlag = 0 AND id < 0 AND userId != 0
ORDER BY timestamp ASC;
selectLatestPendingMessageByConversation:
SELECT *
FROM message
WHERE instanceId = ? AND conversationId = ? AND deletedFlag = 0 AND id < 0
WHERE instanceId = ? AND conversationId = ? AND deletedFlag = 0 AND id < 0 AND userId != 0
ORDER BY timestamp DESC
LIMIT 1;
@@ -302,20 +302,20 @@ WHERE instanceId = ? AND type = 'dm' AND lastMessageId IS NULL AND id NOT IN (
selectForeignPendingMessages:
SELECT *
FROM message
WHERE instanceId = ? AND id < 0 AND deletedFlag = 0 AND userId != ?;
WHERE instanceId = ? AND id < 0 AND deletedFlag = 0 AND userId != ? AND userId != 0;
selectAllPendingMessagesForInstance:
SELECT *
FROM message
WHERE instanceId = ? AND id < 0 AND deletedFlag = 0;
WHERE instanceId = ? AND id < 0 AND deletedFlag = 0 AND userId != 0;
deleteAllPendingMessagesForInstance:
DELETE FROM message
WHERE instanceId = ? AND id < 0;
WHERE instanceId = ? AND id < 0 AND userId != 0;
deletePendingMessagesNotFromUser:
DELETE FROM message
WHERE instanceId = ? AND id < 0 AND userId != ?;
WHERE instanceId = ? AND id < 0 AND userId != ? AND userId != 0;
updateConversationArchived:
UPDATE conversation
@@ -21,6 +21,8 @@ actual fun ToggleNavScrimEffect(enabled: Boolean) {}
actual fun DialogEdgeToEdgeEffect() {}
actual val materialYouAvailable get() = false
actual val expressiveStepFieldsFocusableDuringPagerMotion get() = false
inline fun htons(short: UShort) = if (isLittleEndian) _OSSwapInt16(short) else short
inline fun htonl(data: UInt) = if (isLittleEndian) _OSSwapInt32(data) else data
inline fun htonll(data: ULong) = if (isLittleEndian) _OSSwapInt64(data) else data
@@ -68,6 +68,30 @@ object MacNotificationCenter {
runCatching { nativeResignActive() }
}
/** Use AppKit document-window presentation so show/hide use the system animation behavior. */
fun applySystemWindowAnimationBehavior() {
if (!available) return
runCatching { nativeApplySystemWindowAnimationBehavior() }
}
/** After the main window was hidden (close-to-tray), present with native makeKeyAndOrderFront. */
fun presentMainWindows() {
if (!available) return
runCatching { nativePresentMainWindows() }
}
/** Dock click while a window is already on screen — activate without toggling visibility. */
fun activateApplication() {
if (!available) return
runCatching { nativeActivateApplication() }
}
/** Re-attach AppKit first responder so Skiko/Compose text fields accept keys after presentation. */
fun repairMainWindowKeyboardFocus() {
if (!available) return
runCatching { nativeRepairMainWindowKeyboardFocus() }
}
/** Lets the real frontmost app own activation so Notification Center uses banners. */
fun yieldActivationIfNotFrontmost() {
if (!available) return
@@ -269,4 +293,16 @@ object MacNotificationCenter {
@JvmStatic
private external fun nativeDebugInfo(): String
@JvmStatic
private external fun nativeApplySystemWindowAnimationBehavior()
@JvmStatic
private external fun nativePresentMainWindows()
@JvmStatic
private external fun nativeActivateApplication()
@JvmStatic
private external fun nativeRepairMainWindowKeyboardFocus()
}
@@ -13,6 +13,8 @@ actual fun DialogEdgeToEdgeEffect() {}
actual val materialYouAvailable get() = false
actual val expressiveStepFieldsFocusableDuringPagerMotion get() = true
actual fun currentDeviceInfo(): CurrentDeviceInfo =
CurrentDeviceInfo(
osName = System.getProperty("os.name")?.trim()?.takeIf { it.isNotEmpty() },