Implement native window frame toggle

Signed-off-by: denis0001-dev <denis0001.dev@ya.ru>
This commit is contained in:
2026-10-15 14:53:43 +03:00
Unverified
parent 66077905ae
commit f97d523d22
10 changed files with 371 additions and 168 deletions
@@ -13,8 +13,20 @@ internal fun isWindowsOs(): Boolean =
internal fun isLinuxOs(): Boolean =
System.getProperty("os.name").orEmpty().lowercase().contains("linux")
/** Undecorated Compose window with in-app title bar (Windows and Linux; macOS uses native chrome). */
internal fun usesCustomDesktopFrame(): Boolean = isWindowsOs() || isLinuxOs()
/**
* True when the OS-drawn window frame is in use instead of the in-app custom title bar.
* macOS always has native chrome. On Windows and Linux the Appearance → "Native window
* frame" setting switches the window between the custom (undecorated) and the OS frame;
* it is disabled by default, on Linux it auto-enables when the window manager is Hyprland
* (see [ru.fromchat.desktop.initNativeFrameDefaults]).
*/
internal fun usesNativeDesktopFrame(): Boolean = isMacOs() || DesktopWindowSettings.nativeFrame
/**
* Undecorated Compose window with in-app title bar (Windows and Linux by default).
* macOS uses native chrome; Hyprland auto-enables the native frame (see above).
*/
internal fun usesCustomDesktopFrame(): Boolean = !isMacOs() && !DesktopWindowSettings.nativeFrame
internal fun isWindowsArm64(): Boolean {
if (!isWindowsOs()) return false
@@ -12,6 +12,7 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
@@ -309,6 +310,8 @@ fun main(args: Array<String>) {
}
if (!DesktopSingleInstance.acquireOrForward(args)) return
DesktopProtocolRegistration.register()
// Detect the WM (Hyprland → native frame) before the window is created.
initNativeFrameDefaults()
if (isWindowsOs()) {
if (isWindowsArm64()) {
System.setProperty("skiko.rendering.angle.enabled", "true")
@@ -352,7 +355,25 @@ fun main(args: Array<String>) {
val mac = remember { isMacOs() }
val windows = remember { isWindowsOs() }
val customFrame = remember { usesCustomDesktopFrame() }
// AWT forbids changing window decorations once a frame is displayable, so a frame
// mode change recreates the window: this key is read once per mount, and the
// `key()` below remounts the whole Window (fresh ComposeWindow, same windowState)
// when the setting changes. Geometry is preserved via DesktopWindowPrefs
// persistence and the shared `windowState`.
var nativeFrame by remember { mutableStateOf(DesktopWindowSettings.nativeFrame) }
// The remount below loses composition state, so after a frame-mode change we reland
// on the Appearance screen instead of restoring any UI state (keeps the toggle
// simple: no AWT state transfer).
var nativeFrameReland by remember { mutableStateOf(false) }
val onNativeFrameChange: (Boolean) -> Unit = {
nativeFrame = it
nativeFrameReland = true
}
DisposableEffect(Unit) {
DesktopWindowSettings.addNativeFrameListener(onNativeFrameChange)
onDispose { DesktopWindowSettings.removeNativeFrameListener(onNativeFrameChange) }
}
val customFrame = !mac && !nativeFrame
val windowIcon = remember {
dockIconImage?.toPainter() ?: loadAppIconPainter(tray = false)
}
@@ -581,178 +602,183 @@ fun main(args: Array<String>) {
}
}
Window(
onCloseRequest = { requestCloseToBackgroundOrQuit() },
title = appName,
state = windowState,
visible = contentReady && (windowVisible || !traySupported),
icon = windowIcon,
undecorated = customFrame,
onPreviewKeyEvent = { event ->
// macOS: MenuBar KeyShortcuts handle these. Win/Linux: no menu bar.
if (mac || event.type != KeyEventType.KeyDown || !event.isCtrlPressed) {
return@Window false
}
when {
!event.isShiftPressed && event.key == Key.N -> {
if (!isLoggedIn) return@Window false
showMainWindow()
DesktopMenuCommands.emit(DesktopMenuCommand.NewChat)
true
}
!event.isShiftPressed && event.key == Key.F -> {
if (!isLoggedIn) return@Window false
showMainWindow()
DesktopMenuCommands.emit(DesktopMenuCommand.SearchConversations)
true
}
event.isShiftPressed && event.key == Key.S -> {
showMainWindow()
DesktopMenuCommands.emit(DesktopMenuCommand.EnterChatListSelection)
true
}
event.isShiftPressed && event.key == Key.A -> {
openAbout()
true
}
event.isShiftPressed && event.key == Key.N -> {
showMainWindow()
true
}
event.key == Key.M -> {
windowState.isMinimized = true
true
}
event.key == Key.Q -> {
exitApplication()
true
}
else -> false
}
},
) {
LaunchedEffect(window, appName, windowChrome) {
window.title = appName
windowChrome.toAwtColor().also {
window.background = it
window.contentPane.background = it
if (customFrame && windows) {
updateWindowsNativeCaptionBackground(window, it)
}
}
if (customFrame && windows) {
installWindowsNativeCaptionChrome(window)
applyWindowsRoundedCorners(window)
}
applyDesktopEdgeToEdgeChrome(window.rootPane)
dockIconImage?.let { image ->
window.iconImages = listOf(image)
applyDockIcon(image)
}
}
DisposableEffect(window) {
installDesktopWindowExceptionHandler(window)
AppForeground.setForeground(true)
fun syncWindowFocus(focused: Boolean) {
DesktopAppVisibility.isWindowFocused = focused
AppForeground.setWindowFocused(focused)
if (!focused) MacNotificationCenter.resignActive()
Logger.i(
"DesktopAppVisibility",
"focus=$focused active=${window.isActive} awtFocused=${window.isFocused}",
)
}
val listener = object : java.awt.event.WindowAdapter() {
override fun windowActivated(e: java.awt.event.WindowEvent?) {
syncWindowFocus(true)
}
override fun windowDeactivated(e: java.awt.event.WindowEvent?) {
syncWindowFocus(false)
}
override fun windowGainedFocus(e: java.awt.event.WindowEvent?) {
syncWindowFocus(true)
}
override fun windowLostFocus(e: java.awt.event.WindowEvent?) {
syncWindowFocus(false)
}
override fun windowIconified(e: java.awt.event.WindowEvent?) {
syncWindowFocus(false)
}
}
syncWindowFocus(window.isActive && window.isFocused)
window.addWindowListener(listener)
window.addWindowFocusListener(listener)
onDispose {
window.removeWindowListener(listener)
window.removeWindowFocusListener(listener)
}
}
if (mac) {
FromChatMenuBar(
isLoggedIn = isLoggedIn,
onNewChat = {
showMainWindow()
DesktopMenuCommands.emit(DesktopMenuCommand.NewChat)
},
onSearchConversations = {
showMainWindow()
DesktopMenuCommands.emit(DesktopMenuCommand.SearchConversations)
},
onSelectChats = {
showMainWindow()
DesktopMenuCommands.emit(DesktopMenuCommand.EnterChatListSelection)
},
onShow = { showMainWindow() },
onMinimize = { windowState.isMinimized = true },
onZoom = {
windowState.placement =
if (windowState.placement == WindowPlacement.Maximized) {
WindowPlacement.Floating
} else {
WindowPlacement.Maximized
key(nativeFrame) {
Window(
onCloseRequest = { requestCloseToBackgroundOrQuit() },
title = appName,
state = windowState,
visible = contentReady && (windowVisible || !traySupported),
icon = windowIcon,
undecorated = customFrame,
onPreviewKeyEvent = { event ->
// macOS: MenuBar KeyShortcuts handle these. Win/Linux: no menu bar.
if (mac || event.type != KeyEventType.KeyDown || !event.isCtrlPressed) {
return@Window false
}
when {
!event.isShiftPressed && event.key == Key.N -> {
if (!isLoggedIn) return@Window false
showMainWindow()
DesktopMenuCommands.emit(DesktopMenuCommand.NewChat)
true
}
!event.isShiftPressed && event.key == Key.F -> {
if (!isLoggedIn) return@Window false
showMainWindow()
DesktopMenuCommands.emit(DesktopMenuCommand.SearchConversations)
true
}
event.isShiftPressed && event.key == Key.S -> {
showMainWindow()
DesktopMenuCommands.emit(DesktopMenuCommand.EnterChatListSelection)
true
}
event.isShiftPressed && event.key == Key.A -> {
openAbout()
true
}
event.isShiftPressed && event.key == Key.N -> {
showMainWindow()
true
}
event.key == Key.M -> {
windowState.isMinimized = true
true
}
event.key == Key.Q -> {
exitApplication()
true
}
else -> false
}
},
onQuit = { exitApplication() },
)
}
CompositionLocalProvider(
LocalExtraStatusBarTop provides when {
mac -> 28.dp
customFrame -> WindowsTitleBarHeight
else -> 0.dp
},
) {
Box(
Modifier
.fillMaxSize()
.background(windowChrome),
) {
App(onContentReady = { contentReady = true })
if (customFrame) {
MaterialTheme(colorScheme = getColorScheme(desktopAppDarkTheme(), dynamicColor = false)) {
WindowsDesktopTitleBar(
title = appName,
windowIcon = windowIcon,
window = window,
windowState = windowState,
onCloseRequest = { requestCloseToBackgroundOrQuit() },
modifier = Modifier
.align(Alignment.TopStart)
.fillMaxWidth()
.zIndex(10_000f),
LaunchedEffect(window, appName, windowChrome) {
window.title = appName
windowChrome.toAwtColor().also {
window.background = it
window.contentPane.background = it
if (customFrame && windows) {
updateWindowsNativeCaptionBackground(window, it)
}
}
if (customFrame && windows) {
installWindowsNativeCaptionChrome(window)
applyWindowsRoundedCorners(window)
}
applyDesktopEdgeToEdgeChrome(window.rootPane)
dockIconImage?.let { image ->
window.iconImages = listOf(image)
applyDockIcon(image)
}
}
DisposableEffect(window) {
installDesktopWindowExceptionHandler(window)
AppForeground.setForeground(true)
fun syncWindowFocus(focused: Boolean) {
DesktopAppVisibility.isWindowFocused = focused
AppForeground.setWindowFocused(focused)
if (!focused) MacNotificationCenter.resignActive()
Logger.i(
"DesktopAppVisibility",
"focus=$focused active=${window.isActive} awtFocused=${window.isFocused}",
)
}
val listener = object : java.awt.event.WindowAdapter() {
override fun windowActivated(e: java.awt.event.WindowEvent?) {
syncWindowFocus(true)
}
override fun windowDeactivated(e: java.awt.event.WindowEvent?) {
syncWindowFocus(false)
}
override fun windowGainedFocus(e: java.awt.event.WindowEvent?) {
syncWindowFocus(true)
}
override fun windowLostFocus(e: java.awt.event.WindowEvent?) {
syncWindowFocus(false)
}
override fun windowIconified(e: java.awt.event.WindowEvent?) {
syncWindowFocus(false)
}
}
syncWindowFocus(window.isActive && window.isFocused)
window.addWindowListener(listener)
window.addWindowFocusListener(listener)
onDispose {
window.removeWindowListener(listener)
window.removeWindowFocusListener(listener)
}
}
if (mac) {
FromChatMenuBar(
isLoggedIn = isLoggedIn,
onNewChat = {
showMainWindow()
DesktopMenuCommands.emit(DesktopMenuCommand.NewChat)
},
onSearchConversations = {
showMainWindow()
DesktopMenuCommands.emit(DesktopMenuCommand.SearchConversations)
},
onSelectChats = {
showMainWindow()
DesktopMenuCommands.emit(DesktopMenuCommand.EnterChatListSelection)
},
onShow = { showMainWindow() },
onMinimize = { windowState.isMinimized = true },
onZoom = {
windowState.placement =
if (windowState.placement == WindowPlacement.Maximized) {
WindowPlacement.Floating
} else {
WindowPlacement.Maximized
}
},
onQuit = { exitApplication() },
)
}
CompositionLocalProvider(
LocalExtraStatusBarTop provides when {
mac -> 28.dp
customFrame -> WindowsTitleBarHeight
else -> 0.dp
},
) {
Box(
Modifier
.fillMaxSize()
.background(windowChrome),
) {
App(
startAtAppearance = nativeFrameReland,
onContentReady = { contentReady = true },
)
if (customFrame) {
MaterialTheme(colorScheme = getColorScheme(desktopAppDarkTheme(), dynamicColor = false)) {
WindowsDesktopTitleBar(
title = appName,
windowIcon = windowIcon,
window = window,
windowState = windowState,
onCloseRequest = { requestCloseToBackgroundOrQuit() },
modifier = Modifier
.align(Alignment.TopStart)
.fillMaxWidth()
.zIndex(10_000f),
)
}
}
}
}
}
}
}
}
}
@@ -0,0 +1,7 @@
package ru.fromchat.ui.main.settings
actual fun isDesktopNativeFrameSupported(): Boolean = false
actual fun isDesktopNativeFrameEnabled(): Boolean = false
actual fun setDesktopNativeFrameEnabled(enabled: Boolean) = Unit
@@ -343,6 +343,8 @@
<string name="settings_category_appearance_d">Тема и Material You</string>
<string name="appearance_nav_bar_style">Стиль панели навигации</string>
<string name="appearance_nav_bar_style_d">Как выглядит нижняя панель навигации</string>
<string name="appearance_window_frame">Системная рамка окна</string>
<string name="appearance_window_frame_d">Использовать рамку окна от системы вместо встроенной панели заголовка. Окно будет открыто заново.</string>
<string name="appearance_nav_bar_traditional">Классическая</string>
<string name="appearance_nav_bar_floating">Плавающая</string>
<string name="appearance_nav_bar_show_titles">Показывать названия вкладок</string>
@@ -375,6 +375,8 @@
<string name="settings_category_appearance_d">Theme and Material You</string>
<string name="appearance_nav_bar_style">Navigation bar style</string>
<string name="appearance_nav_bar_style_d">How the bottom navigation bar looks</string>
<string name="appearance_window_frame">Native window frame</string>
<string name="appearance_window_frame_d">Use the OS-drawn window frame instead of the built-in title bar. The window will reopen.</string>
<string name="appearance_nav_bar_traditional">Traditional</string>
<string name="appearance_nav_bar_floating">Floating</string>
<string name="appearance_nav_bar_show_titles">Show tab titles</string>
@@ -47,6 +47,7 @@ import com.pr0gramm3r101.utils.rememberSystemBarsController
import com.pr0gramm3r101.utils.widthSizeClass
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.JsonElement
@@ -122,6 +123,7 @@ import ru.fromchat.ui.components.LocalPaneHazeState
import ru.fromchat.ui.components.ScreenSurface
import dev.chrisbanes.haze.rememberHazeState
import ru.fromchat.utils.NetworkConnectivity
import kotlin.time.Duration.Companion.milliseconds
val LocalNavController = compositionLocalOf<NavController> { error("NavController not provided") }
@@ -234,6 +236,8 @@ fun App(
startAtDmConversationUserId: Int? = null,
startAtProfileUserId: Int? = null,
startAtProfileUsername: String? = null,
/** Desktop: after a window frame-mode remount, reland on the Appearance screen (no UI state restored). */
startAtAppearance: Boolean = false,
profileLookupErrorMessage: String? = null,
onProfileLookupErrorMessageConsumed: () -> Unit = {},
/** Desktop: fired once [startDestination] is known so the window can show after bootstrap. */
@@ -449,6 +453,40 @@ fun App(
}
}
// Reland on the Appearance screen after a frame-mode remount. No UI state is
// restored, so this is the only way back to the screen the user was on.
// Must not navigate before the detail graph exists: on a fresh mount the first
// composition has no graph on the controllers yet, and getGraph() throws.
val relandRootEntry by navController.currentBackStackEntryAsState()
// Consumed once per composition: a remount recreates this `remember`, so the
// reland never re-fires on later root-stack changes (e.g. back from Appearance).
var relandDone by remember { mutableStateOf(false) }
LaunchedEffect(startDestination, startAtAppearance, relandRootEntry) {
if (startDestination == null || startDestination == "welcome") {
return@LaunchedEffect
}
if (relandDone || !startAtAppearance || relandRootEntry?.destination?.route != "chat") {
return@LaunchedEffect
}
val controller = if (isDesktopListDetail) {
pendingMainTab = MAIN_PAGE_SETTINGS
settingsDetailNavController
} else {
navController
}
// The detail NavHost composes in the same first frame as startDestination;
// retry until its graph exists and the navigation lands.
while (true) {
if (runCatching {
controller.navigateReplacingMainDetail(SettingsRoutes.Appearance)
}.isSuccess) {
relandDone = true
break
}
delay(50.milliseconds)
}
}
LaunchedEffect(startDestination) {
if (startDestination == null || startDestination == "welcome") {
return@LaunchedEffect
@@ -17,6 +17,7 @@ import androidx.compose.material.icons.rounded.DarkMode
import androidx.compose.material.icons.rounded.LightMode
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material.icons.rounded.Tab
import androidx.compose.material.icons.rounded.ViewInAr
import androidx.compose.material.icons.rounded.Wallpaper
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
@@ -46,6 +47,8 @@ import ru.fromchat.appearance_nav_bar_show_titles_d
import ru.fromchat.appearance_nav_bar_style
import ru.fromchat.appearance_nav_bar_style_d
import ru.fromchat.appearance_nav_bar_traditional
import ru.fromchat.appearance_window_frame
import ru.fromchat.appearance_window_frame_d
import ru.fromchat.as_system
import ru.fromchat.config.NavBarStyle
import ru.fromchat.config.Settings
@@ -75,6 +78,8 @@ fun AppearanceScreen(onBack: () -> Unit) {
}
var enterToSendSwitch by remember { mutableStateOf(Settings.enterToSend) }
var themeChipIndex by remember { mutableIntStateOf(Settings.theme.ordinal) }
val nativeFrameSupported = isDesktopNativeFrameSupported()
var nativeFrameSwitch by remember { mutableStateOf(isDesktopNativeFrameEnabled()) }
Scaffold(
containerColor = MaterialTheme.colorScheme.background,
@@ -127,6 +132,19 @@ fun AppearanceScreen(onBack: () -> Unit) {
Icon(Icons.AutoMirrored.Rounded.KeyboardReturn, null)
}
)
if (nativeFrameSupported) {
SwitchListItem(
headline = stringResource(Res.string.appearance_window_frame),
supportingText = stringResource(Res.string.appearance_window_frame_d),
checked = nativeFrameSwitch,
onCheckedChange = {
nativeFrameSwitch = it
setDesktopNativeFrameEnabled(it)
},
divider = true,
leadingContent = { Icon(Icons.Rounded.ViewInAr, null) }
)
}
ListItem(
headline = stringResource(Res.string.theme),
leadingContent = { Icon(Icons.Rounded.Brush, null) },
@@ -220,3 +238,10 @@ fun AppearanceScreen(onBack: () -> Unit) {
}
}
}
/** True on desktop, where the window frame can be switched to the OS-drawn one. */
expect fun isDesktopNativeFrameSupported(): Boolean
expect fun isDesktopNativeFrameEnabled(): Boolean
expect fun setDesktopNativeFrameEnabled(enabled: Boolean)
@@ -0,0 +1,7 @@
package ru.fromchat.ui.main.settings
actual fun isDesktopNativeFrameSupported(): Boolean = false
actual fun isDesktopNativeFrameEnabled(): Boolean = false
actual fun setDesktopNativeFrameEnabled(enabled: Boolean) = Unit
@@ -0,0 +1,72 @@
package ru.fromchat.desktop
import java.util.prefs.Preferences
/**
* Desktop main-window frame preference.
*
* `nativeFrame`: when true the window is decorated by the OS (native title bar / frame)
* instead of the in-app custom chrome. Absent → platform default (false, i.e. custom
* frame) — Hyprland on Linux is the exception: its default is `true` (auto-enabled on
* first launch, see [ru.fromchat.desktop.initNativeFrameDefaults] and the auto-enable
* in [Main.kt]).
*
* Stored in the same prefs node as [DesktopNotificationSettings].
*/
object DesktopWindowSettings {
private const val PREF_NODE = "ru/fromchat/desktop"
private const val KEY_NATIVE_FRAME = "window_native_frame"
/** Live listeners (Main.kt) so the frame switch applies without a restart. */
private val nativeFrameListeners = mutableListOf<(Boolean) -> Unit>()
var nativeFrame: Boolean
get() = preferences().getBoolean(KEY_NATIVE_FRAME, false)
set(value) {
preferences().putBoolean(KEY_NATIVE_FRAME, value)
}
fun addNativeFrameListener(listener: (Boolean) -> Unit) {
nativeFrameListeners.add(listener)
}
fun removeNativeFrameListener(listener: (Boolean) -> Unit) {
nativeFrameListeners.remove(listener)
}
fun notifyNativeFrameChanged(value: Boolean) {
for (listener in nativeFrameListeners.toList()) {
runCatching { listener(value) }
}
}
private fun preferences(): Preferences =
Preferences.userRoot().node(PREF_NODE)
}
/**
* Hyprland runs on Wayland where undecorated client-side decoration is unreliable, so the
* native frame is automatically enabled there. Runs once before the first window is shown;
* the choice stays in prefs from then on (the user can flip it in Appearance settings).
*/
fun initNativeFrameDefaults() {
if (DesktopWindowSettings.nativeFrame) return // explicit user choice already stored
if (!isLinuxOs()) return
if (detectHyprland()) {
DesktopWindowSettings.nativeFrame = true
}
}
/** True when the active window manager is Hyprland (via `hyprctl`, best effort). */
internal fun detectHyprland(): Boolean =
isLinuxOs() && runCatching {
val process = ProcessBuilder("hyprctl", "monitor")
.redirectErrorStream(true)
.start()
val exitValue = process.waitFor()
val output = process.inputStream.bufferedReader().readText().trim()
exitValue == 0 && output.isNotEmpty()
}.getOrDefault(false)
private fun isLinuxOs(): Boolean =
System.getProperty("os.name").orEmpty().lowercase().contains("linux")
@@ -0,0 +1,12 @@
package ru.fromchat.ui.main.settings
import ru.fromchat.desktop.DesktopWindowSettings
actual fun isDesktopNativeFrameSupported(): Boolean = true
actual fun isDesktopNativeFrameEnabled(): Boolean = DesktopWindowSettings.nativeFrame
actual fun setDesktopNativeFrameEnabled(enabled: Boolean) {
DesktopWindowSettings.nativeFrame = enabled
DesktopWindowSettings.notifyNativeFrameChanged(enabled)
}