From 64e2bdbc5e29c8467d5b05df52415e51afd0a090 Mon Sep 17 00:00:00 2001 From: Pham Thanh Tu Date: Sat, 14 Nov 2026 21:06:48 +0700 Subject: [PATCH] fix(desktop): fit the window and shell to a MacBook screen Window: it opened off-centre and past the screen edges. The minimum size was multiplied by the display scale, but AWT sizes are already in points, so Retina turned 900x560 into 1800x1120, larger than the screen, and AWT grew the window to it. The minimum is now 900x560, the opening size is 85% of the usable area, and the position is centred. Green button: it only zoomed to the usable area. macOS native full screen does not resize a borderless window, so the window is sized to the screen from code instead (MacFillScreen), with the menu bar and Dock hidden through NSApplication presentationOptions. Double-clicking the title bar still zooms. Corners are square while the window touches the screen edges. Shell: on a narrow window the sidebar folds on its own without rewriting the stored preference, the side Now Playing panel yields to the fullscreen player below 960dp and keeps a floor for the content beside it, and the floating mini player capsule shrinks with the window instead of spilling past the sidebar edge. Co-Authored-By: Claude Sonnet 5.5 --- .../kotlin/com/maxrave/simpmusic/App.kt | 87 ++++++++++++++----- .../simpmusic/ui/component/DesktopSidebar.kt | 19 +++- .../maxrave/simpmusic/ui/screen/MiniPlayer.kt | 60 ++++++++----- .../ui/screen/library/LibraryScreen.kt | 11 ++- .../com/maxrave/simpmusic/DesktopApp.kt | 37 +++++++- .../simpmusic/ui/component/CustomTitleBar.kt | 28 ++++-- .../simpmusic/ui/component/MacFillScreen.kt | 80 +++++++++++++++++ 7 files changed, 262 insertions(+), 60 deletions(-) create mode 100644 composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/MacFillScreen.kt diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt index 1dba3cac8b..b44f223574 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt @@ -20,7 +20,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width -import androidx.compose.foundation.layout.wrapContentWidth +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll @@ -73,6 +73,7 @@ import com.maxrave.simpmusic.expect.openUrl import com.maxrave.simpmusic.expect.ui.layerBackdrop import com.maxrave.simpmusic.expect.ui.rememberBackdrop import com.maxrave.simpmusic.extension.copy +import com.maxrave.simpmusic.extension.getScreenSizeInfo import com.maxrave.simpmusic.ui.component.AppBottomNavigationBar import com.maxrave.simpmusic.ui.component.AppNavigationRail import com.maxrave.simpmusic.ui.component.DesktopSidebar @@ -82,6 +83,7 @@ import com.maxrave.simpmusic.ui.component.LocalNowPlayingOpen import com.maxrave.simpmusic.ui.component.LocalUserStarted import com.maxrave.simpmusic.ui.icon.ArrowForwardIos import com.maxrave.simpmusic.ui.icon.SimpIcons +import com.maxrave.simpmusic.ui.screen.DesktopCapsuleMaxWidth import com.maxrave.simpmusic.ui.navigation.destination.home.AnalyticsDestination import com.maxrave.simpmusic.ui.navigation.destination.home.HomeDestination import com.maxrave.simpmusic.ui.navigation.destination.home.NotificationDestination @@ -143,6 +145,18 @@ import simpmusic.composeapp.generated.resources.update_message import simpmusic.composeapp.generated.resources.yes import kotlin.time.ExperimentalTime +/** Below this width the Desktop sidebar folds so Home / Library keep a usable column. */ +private const val DESKTOP_SIDEBAR_AUTO_COLLAPSE_WIDTH_DP = 1100 + +/** + * Below this width the side Now Playing panel yields to the fullscreen player overlay — a 13" + * MacBook in split view cannot host sidebar + content + 35% player at once. + */ +private const val DESKTOP_SIDE_NOW_PLAYING_MIN_WIDTH_DP = 960 + +/** Floor left for the content panel beside an open Desktop Now Playing card. */ +private val DESKTOP_MIN_CONTENT_BESIDE_NP = 360.dp + @OptIn(ExperimentalMaterial3Api::class, ExperimentalTime::class, ExperimentalFoundationApi::class) @Composable fun App( @@ -508,6 +522,19 @@ fun App( } val isTablet = windowSize.isWidthAtLeastBreakpoint(WIDTH_DP_MEDIUM_LOWER_BOUND) val isTabletLandscape = isTablet && currentOrientation() == Orientation.LANDSCAPE + // Desktop shell on a MacBook (split view, zoomed, or a half-screen window) needs its own + // breakpoints: the Material tablet ones alone still leave an expanded 280dp sidebar and a + // 35% Now Playing panel fighting over the leftover strip. + val desktopWindowWidthDp = if (isDesktopShell) getScreenSizeInfo().wDP else Int.MAX_VALUE + val forceSidebarCollapsed = isDesktopShell && desktopWindowWidthDp < DESKTOP_SIDEBAR_AUTO_COLLAPSE_WIDTH_DP + // Whether this window *can* host the side Now Playing card (width + orientation). Fullscreen + // gates the card separately so a landscape fullscreen session does not fall through to the + // overlay the way a too-narrow Desktop window should. + val canHostSideNowPlaying = + isTablet && + isTabletLandscape && + (!isDesktopShell || desktopWindowWidthDp >= DESKTOP_SIDE_NOW_PLAYING_MIN_WIDTH_DP) + val useSideNowPlaying = canHostSideNowPlaying && !isInFullscreen AppTheme( themeMode = themeMode, @@ -645,20 +672,20 @@ fun App( bottom = 4.dp, ) } else { - // Floating capsule, Apple Music style: a fixed size so it never - // stretches to the window width, and no haze at all — the capsule - // paints its own liquid glass. Layering haze underneath blurs the - // same pixels twice and reads as a dark smear, not glass. - // padding BEFORE height: the other way round the bottom margin - // eats into the 72dp and the capsule ends up 52dp tall. - // 60dp is the floor for this layout: the content row is centred - // on the capsule's axis and the 16dp progress box hangs off the - // bottom, so the height has to cover the taller of the artwork - // (32dp) and the two text lines (~33dp), plus that 16dp, plus a - // gap. Going lower means shrinking the artwork again. + // Floating capsule, Apple Music style. Cap at the full three-cluster + // width and fill what the content strip has left, so a resized + // MacBook window shrinks the pill instead of letting it spill past + // the sidebar / Now Playing edge. No haze — the capsule paints its + // own liquid glass; layering haze underneath blurs the same pixels + // twice and reads as a dark smear. padding BEFORE height: the other + // way round the bottom margin eats into the 60dp. That height is the + // floor: artwork 32dp / two text lines ~33dp, plus the 16dp progress + // box hung off the bottom. Modifier - .wrapContentWidth() + .padding(horizontal = 20.dp) .padding(bottom = 20.dp) + .widthIn(max = DesktopCapsuleMaxWidth) + .fillMaxWidth() .height(60.dp) }, backdrop = backdrop, @@ -710,6 +737,7 @@ fun App( containerColor = desktopPanel, showAnalyticsTab = showAnalyticsTab, showMixForYouTab = showMixForYouTab, + forceCollapsed = forceSidebarCollapsed, // No end padding: the content panel's own 8dp is the gap between the two. modifier = Modifier.padding(start = 8.dp, top = 8.dp, bottom = 8.dp), ) { klass -> @@ -789,7 +817,7 @@ fun App( tabletMiniPlayer(Modifier.padding(innerPadding).align(Alignment.BottomCenter)) } } - if (isTablet && isTabletLandscape && !isInFullscreen) { + if (useSideNowPlaying) { AnimatedVisibility( isShowNowPlaylistScreen, enter = expandHorizontally() + fadeIn(), @@ -798,17 +826,30 @@ fun App( Row( Modifier .fillMaxHeight() - // The width Now Playing has always had: `fillMaxWidth(0.35f)` of what the - // 80dp NavigationRail left in this Row. The rail and the sidebar now sit - // inside the weighted Box, so that share is taken by hand from the Row's - // own width; otherwise it would follow the sidebar. On Desktop it is 8dp - // less, the spacer it no longer has, so the card keeps its exact size. + // Preferred width is still `fillMaxWidth(0.35f)` of what the + // 80dp NavigationRail left in this Row. On a narrow Desktop + // window that share is clamped so the content panel keeps at + // least [DESKTOP_MIN_CONTENT_BESIDE_NP], otherwise the Home + // cards and the capsule crush into a strip. .layout { measurable, constraints -> - val width = + val full = constraints.maxWidth + val preferred = ( - ((constraints.maxWidth - 80.dp.roundToPx()) * 0.35f).roundToInt() - + ((full - 80.dp.roundToPx()) * 0.35f).roundToInt() - if (isDesktopShell) 8.dp.roundToPx() else 0 - ).coerceIn(0, constraints.maxWidth) + ) + val width = + if (isDesktopShell) { + val sidebarDp = if (forceSidebarCollapsed) 72 else 280 + val reservedLeft = + (sidebarDp + 8).dp.roundToPx() + + DESKTOP_MIN_CONTENT_BESIDE_NP.roundToPx() + + 16.dp.roundToPx() + val maxNp = (full - reservedLeft).coerceAtLeast(280.dp.roundToPx()) + preferred.coerceIn(280.dp.roundToPx(), maxNp) + } else { + preferred + }.coerceIn(0, full) val placeable = measurable.measure(constraints.copy(minWidth = width, maxWidth = width)) layout(placeable.width, placeable.height) { placeable.placeRelative(0, 0) } }, @@ -860,7 +901,7 @@ fun App( } } - if (isShowNowPlaylistScreen && !isTabletLandscape) { + if (isShowNowPlaylistScreen && !canHostSideNowPlaying) { ForceDarkContent { NowPlayingScreen( navController = navController, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/DesktopSidebar.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/DesktopSidebar.kt index e2c653edf7..503f69ee6e 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/DesktopSidebar.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/DesktopSidebar.kt @@ -153,6 +153,12 @@ fun DesktopSidebar( showAnalyticsTab: Boolean, showMixForYouTab: Boolean, modifier: Modifier = Modifier, + /** + * When the window is too narrow for a 280dp library column (MacBook split view / resized), + * fold visually without rewriting the stored preference — widening the window restores it. + * The user can still expand while forced; that override clears once the window is wide again. + */ + forceCollapsed: Boolean = false, viewModel: LibrarySidebarViewModel = koinViewModel(), reloadDestinationIfNeeded: (KClass<*>) -> Unit = { _ -> }, ) { @@ -197,7 +203,12 @@ fun DesktopSidebar( // The library sources are one-shot reads, not observed queries, so the list is read again whenever // the user moves between screens, which is where a like, follow or new playlist happens. LaunchedEffect(currentBackStackEntry?.id) { viewModel.refresh() } - val collapsed by viewModel.collapsed.collectAsStateWithLifecycle() + val collapsedPref by viewModel.collapsed.collectAsStateWithLifecycle() + var expandWhileForced by rememberSaveable { mutableStateOf(false) } + LaunchedEffect(forceCollapsed) { + if (!forceCollapsed) expandWhileForced = false + } + val collapsed = (collapsedPref || forceCollapsed) && !(forceCollapsed && expandWhileForced) val overview by viewModel.overview.collectAsStateWithLifecycle() val libraryItems by viewModel.items.collectAsStateWithLifecycle() val playingQueueId by viewModel.playingQueueId.collectAsStateWithLifecycle() @@ -349,7 +360,11 @@ fun DesktopSidebar( onToggle = { searching = false query = "" - viewModel.setCollapsed(!collapsed) + if (forceCollapsed) { + expandWhileForced = !expandWhileForced + } else { + viewModel.setCollapsed(!collapsedPref) + } }, onStartSearch = { searching = true }, onQueryChange = { query = it }, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/MiniPlayer.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/MiniPlayer.kt index 50acc48db2..142374541c 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/MiniPlayer.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/MiniPlayer.kt @@ -33,6 +33,7 @@ import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsHoveredAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -45,6 +46,7 @@ import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.layout.wrapContentWidth @@ -154,6 +156,13 @@ import kotlin.math.roundToLong private const val TAG = "MiniPlayer" +/** + * Widest the Desktop floating capsule grows to: transport 200 + dividers + track 300 + action + * cluster. Callers cap with [widthIn] so a narrower MacBook window / split view shrinks it instead + * of letting it spill past the content panel. + */ +internal val DesktopCapsuleMaxWidth = 822.dp + @OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class) @Composable fun MiniPlayer( @@ -644,13 +653,14 @@ fun MiniPlayer( ) } // Apple Music-style floating capsule: transport on the left, the track and its slim - // progress slider in the middle, the action cluster on the right. Size and placement come - // from the caller (App.kt), so the capsule keeps a fixed width and floats over content. - // Without glass it is an opaque theme surface, the Android flat card's colour; a haze blur - // instead gives a dark smear rather than a floating pill. + // progress slider in the middle, the action cluster on the right. The caller (App.kt) caps + // width at [DesktopCapsuleMaxWidth] and fills what is left of the content strip, so a + // resized MacBook window shrinks the capsule instead of letting it overflow. Without glass + // it is an opaque theme surface; a haze blur instead gives a dark smear rather than a + // floating pill. val capsuleShape = RoundedCornerShape(50) val density = LocalDensity.current - Box( + BoxWithConstraints( modifier .then( if (useGlassSurface) { @@ -664,8 +674,15 @@ fun MiniPlayer( }, contentAlignment = Alignment.Center, ) { + // Drop secondary chrome before the track title: PiP first, then queue. Controls and + // mute/close stay — a capsule that cannot pause is useless. + val showPipButton = maxWidth >= 700.dp + val showQueueButton = maxWidth >= 560.dp + val controlsWidth = if (maxWidth < 520.dp) 160.dp else 200.dp + val dividerPad = if (maxWidth < 600.dp) 8.dp else 14.dp Row( Modifier + .fillMaxWidth() .fillMaxHeight() // No vertical padding: the progress line is bottom-aligned inside its own 16dp // touch box, so the line already floats 8dp above whatever the bottom edge is. @@ -678,7 +695,7 @@ fun MiniPlayer( // button, so it consumes whatever width it is handed. The old layout kept it in check // with Column(width = 600.dp); inside a capsule it must be boxed to a fixed width or // it spreads across the whole bar and pushes the other two clusters out of view. - Box(Modifier.width(200.dp)) { + Box(Modifier.width(controlsWidth)) { PlayerControlLayout( controllerState, isSmallSize = true, @@ -693,7 +710,7 @@ fun MiniPlayer( } } VerticalDivider( - modifier = Modifier.height(28.dp).padding(horizontal = 14.dp), + modifier = Modifier.height(28.dp).padding(horizontal = dividerPad), color = textColor.copy(alpha = 0.2f), ) // The whole track cluster is the hover target, not the progress line itself: @@ -717,7 +734,8 @@ fun MiniPlayer( Box( modifier = Modifier - .width(300.dp) + .weight(1f) + .widthIn(min = 100.dp) .fillMaxHeight() .hoverable(trackInteraction), ) { @@ -965,7 +983,7 @@ fun MiniPlayer( ) } VerticalDivider( - modifier = Modifier.height(28.dp).padding(horizontal = 14.dp), + modifier = Modifier.height(28.dp).padding(horizontal = dividerPad), color = textColor.copy(alpha = 0.2f), ) Row(verticalAlignment = Alignment.CenterVertically) { @@ -978,19 +996,21 @@ fun MiniPlayer( sharedViewModel.onUIEvent(UIEvent.ToggleLike) } } - IconButton( - onClick = { - showQueueBottomSheet = true - }, - ) { - Icon( - imageVector = SimpIcons.QueueMusic, - tint = textColor, - contentDescription = "", - ) + if (showQueueButton) { + IconButton( + onClick = { + showQueueBottomSheet = true + }, + ) { + Icon( + imageVector = SimpIcons.QueueMusic, + tint = textColor, + contentDescription = "", + ) + } } // Desktop mini player button (JVM only) - if (getPlatform() == Platform.Desktop) { + if (getPlatform() == Platform.Desktop && showPipButton) { IconButton(onClick = { toggleMiniPlayer() }) { Icon( imageVector = SimpIcons.PictureInPictureAlt, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryScreen.kt index 872df955ad..06cbe400e9 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryScreen.kt @@ -67,6 +67,7 @@ import com.maxrave.simpmusic.extension.copy import com.maxrave.simpmusic.extension.isScrollingUp import com.maxrave.simpmusic.extension.ultraThinBarStyle import com.maxrave.simpmusic.getPlatform +import com.maxrave.simpmusic.ui.screen.DesktopCapsuleMaxWidth import com.maxrave.simpmusic.ui.component.AddToPlaylistModalBottomSheet import com.maxrave.simpmusic.ui.component.Chip import com.maxrave.simpmusic.ui.component.CreateLocalPlaylistSheet @@ -597,10 +598,8 @@ fun LibraryScreen( } /** - * How wide the Your Library tab may get on Desktop: the floating capsule player's own width plus - * the 10dp gutter every row of this list already carries, so the cards' edges land on the - * capsule's. The capsule has no width constant of its own — `MiniPlayer`'s Desktop row sums to - * 16 + 200 (controls) + 29 (divider) + 300 (track) + 29 (divider) + 232 (heart cell 40 + four - * 48dp icon buttons) + 16 = 822dp — so this must follow if that row changes. + * How wide the Your Library tab may get on Desktop: the floating capsule player's own max width + * plus the 10dp gutter every row of this list already carries, so the cards' edges land on the + * capsule's. See [DesktopCapsuleMaxWidth]. */ -private val YOUR_LIBRARY_MAX_WIDTH = 842.dp +private val YOUR_LIBRARY_MAX_WIDTH = DesktopCapsuleMaxWidth + 20.dp diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt index 7e217f18ff..3499342026 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt @@ -288,9 +288,25 @@ fun runDesktopApp(args: Array = emptyArray()) { governedApplication { // Main Window + // 1500dp is wider than most MacBook screens (1440-1512dp), and the default position is + // the platform's own, so the window opened off-centre with an edge past the screen. + // Size it from the usable area (minus menu bar and Dock), then centre it there. + val initialWindowSize = + remember { + val usable = + runCatching { + java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().maximumWindowBounds + }.getOrNull() + // 85% of the usable area leaves a margin on every side; never below the + // window's own minimum (900x560), never above the design size. + val width = usable?.let { (it.width * 0.85f).toInt().coerceIn(900, 1500) } ?: 1500 + val height = usable?.let { (it.height * 0.85f).toInt().coerceIn(560, 860) } ?: 860 + DpSize(width.dp, height.dp) + } val windowState = rememberWindowState( - size = DpSize(1500.dp, 860.dp), + position = androidx.compose.ui.window.WindowPosition.Aligned(androidx.compose.ui.Alignment.Center), + size = initialWindowSize, ) var isVisible by remember { mutableStateOf(true) } val showNotificationPermissionDialog by @@ -378,6 +394,18 @@ fun runDesktopApp(args: Array = emptyArray()) { state = windowState, visible = isVisible, ) { + // Floor for a usable Desktop shell on a MacBook: below this the sidebar + content + + // capsule fight for space even after auto-collapse. AWT sizes are already in logical + // units (points), so the display scale must NOT be applied: multiplied by Retina's 2x + // this floor became 1800x1120, larger than a MacBook screen (1470x956), and AWT grew + // the window to it — past every edge of the screen. + LaunchedEffect(Unit) { + window.minimumSize = java.awt.Dimension(900, 560) + } + // Hiding to the tray while filling the screen must give the menu bar and Dock back. + LaunchedEffect(isVisible) { + if (!isVisible && isMacOS) com.maxrave.simpmusic.ui.component.MacFillScreen.release(window) + } // Returning from macOS System Settings is the only reliable time to learn whether the // user enabled notifications after denying the one-shot system prompt. DisposableEffect(window) { @@ -450,7 +478,12 @@ fun runDesktopApp(args: Array = emptyArray()) { Modifier .fillMaxSize() .then( - if (!nativeTitleBar) { + // Square corners once the window reaches the screen edges: a rounded + // clip there only shows the wallpaper in the four corners. + if (!nativeTitleBar && + !com.maxrave.simpmusic.ui.component.MacFillScreen.isFilled && + windowState.placement == androidx.compose.ui.window.WindowPlacement.Floating + ) { Modifier.clip(RoundedCornerShape(12.dp)) } else { Modifier diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/CustomTitleBar.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/CustomTitleBar.kt index f66f2bb789..12215fd59f 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/CustomTitleBar.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/CustomTitleBar.kt @@ -19,6 +19,7 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -67,7 +68,9 @@ fun CustomTitleBar( containerColor: Color = Color.Black, titleColor: Color = Color.White, ) { - var isMaximized by remember { mutableStateOf(windowState.placement == WindowPlacement.Maximized) } + // "Enlarged" covers both zoom (Maximized) and the fill-screen mode (MacFillScreen): either + // way the green button's next action is to restore. + var isMaximized by remember { mutableStateOf(windowState.placement != WindowPlacement.Floating) } // Track drag start position var dragStartX by remember { mutableStateOf(0) } @@ -75,9 +78,12 @@ fun CustomTitleBar( // Update isMaximized when window state changes LaunchedEffect(windowState.placement) { - isMaximized = windowState.placement == WindowPlacement.Maximized + isMaximized = windowState.placement != WindowPlacement.Floating } + // Leaving through the tray or a close request must not leave the menu bar hidden. + DisposableEffect(window) { onDispose { MacFillScreen.release(window) } } + Box( modifier = modifier @@ -88,10 +94,12 @@ fun CustomTitleBar( detectTapGestures( onDoubleTap = { // Double-click to maximize/restore - if (windowState.placement == WindowPlacement.Maximized) { - windowState.placement = WindowPlacement.Floating - } else { - windowState.placement = WindowPlacement.Maximized + when { + // Fill-screen is left with the green button, as in other apps. + MacFillScreen.isFilled -> Unit + windowState.placement == WindowPlacement.Floating -> + windowState.placement = WindowPlacement.Maximized + else -> windowState.placement = WindowPlacement.Floating } }, ) @@ -111,6 +119,8 @@ fun CustomTitleBar( onDrag = { change, _ -> change.consume() if (nativeDrag) return@detectDragGestures + // A window filling the screen has nowhere to be dragged to. + if (MacFillScreen.isFilled) return@detectDragGestures val mouseLocation = MouseInfo.getPointerInfo()?.location ?: return@detectDragGestures // If maximized, restore before moving if (windowState.placement == WindowPlacement.Maximized) { @@ -164,10 +174,14 @@ fun CustomTitleBar( // Maximize/Restore button WindowControlButton( onClick = { + // macOS convention: the green button fills the whole screen (menu bar and + // Dock hidden), while double-clicking the title bar only zooms. Maximized + // stops at the usable area, so it never covered the whole screen. if (windowState.placement == WindowPlacement.Maximized) { windowState.placement = WindowPlacement.Floating } else { - windowState.placement = WindowPlacement.Maximized + MacFillScreen.toggle(window) + isMaximized = MacFillScreen.isFilled } }, backgroundColor = windowMaximiseButton, diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/MacFillScreen.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/MacFillScreen.kt new file mode 100644 index 0000000000..42434449bf --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/MacFillScreen.kt @@ -0,0 +1,80 @@ +package com.maxrave.simpmusic.ui.component + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.maxrave.logger.Logger +import com.sun.jna.NativeLibrary +import com.sun.jna.Pointer +import java.awt.Rectangle +import java.awt.Window + +/** + * Makes the custom-title-bar window cover its whole screen, the way the green button does in other + * Mac apps. macOS native full screen (`toggleFullScreen:`, what `WindowPlacement.Fullscreen` calls) + * hides the menu bar but does not resize a borderless window, which stayed at its old size on a + * black Space. So the window is sized to the screen from code instead, and the menu bar and Dock + * are hidden with `NSApplication.presentationOptions`. + */ +internal object MacFillScreen { + private const val TAG = "MacFillScreen" + + // NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar. AppKit + // rejects hiding the menu bar unless the Dock is hidden too. + private const val HIDE_DOCK_AND_MENU_BAR = (1L shl 0) or (1L shl 2) + + private var restoreBounds: Rectangle? = null + + /** Compose state, so the window shell can square its corners while the screen is filled. */ + var isFilled by mutableStateOf(false) + private set + + fun toggle(window: Window) { + val saved = restoreBounds + if (saved == null) { + restoreBounds = window.bounds + isFilled = true + window.bounds = window.graphicsConfiguration.bounds + setPresentationOptions(HIDE_DOCK_AND_MENU_BAR) + } else { + restoreBounds = null + isFilled = false + setPresentationOptions(0L) + window.bounds = saved + } + } + + /** Called when the window is hidden or closed while filled, so the menu bar does not stay hidden. */ + fun release(window: Window) { + if (restoreBounds != null) toggle(window) + } + + private fun setPresentationOptions(options: Long) { + runCatching { + val objc = NativeLibrary.getInstance("objc") + val system = NativeLibrary.getInstance("System") + val msgSend = objc.getFunction("objc_msgSend") + val sel = objc.getFunction("sel_registerName") + val appClass = objc.getFunction("objc_getClass").invokePointer(arrayOf("NSApplication")) + val shared = sel.invokePointer(arrayOf("sharedApplication")) + val setOptions = sel.invokePointer(arrayOf("setPresentationOptions:")) + val app = msgSend.invokePointer(arrayOf(appClass, shared)) + // AppKit state belongs on the main thread, not the AWT one. + val work = + object : MacMainQueueWork { + override fun invoke(context: Pointer?) { + runCatching { msgSend.invokeVoid(arrayOf(app, setOptions, options)) } + .onFailure { Logger.w(TAG, "setPresentationOptions failed: $it") } + } + } + keepAlive = work + system.getFunction("dispatch_async_f").invokeVoid( + arrayOf(system.getGlobalVariableAddress("_dispatch_main_q"), null, work), + ) + }.onFailure { Logger.w(TAG, "Could not change presentation options: $it") } + } + + // JNA frees a callback's native stub once its object is garbage collected, and the queued call + // runs after this function returns. + @Volatile private var keepAlive: MacMainQueueWork? = null +}