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..6135049bcc 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt @@ -16,6 +16,9 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyShortcut +import androidx.compose.ui.window.MenuBar import androidx.compose.ui.window.Window import androidx.compose.ui.window.rememberWindowState import coil3.ImageLoader @@ -47,6 +50,7 @@ import com.maxrave.simpmusic.utils.ComposeResUtils import com.maxrave.simpmusic.utils.NetworkFirstInterceptor import com.maxrave.simpmusic.utils.VersionManager import com.maxrave.simpmusic.viewModel.SharedViewModel +import com.maxrave.simpmusic.viewModel.UIEvent import com.maxrave.simpmusic.viewModel.changeLanguageNative import dev.nucleusframework.composenativetray.tray.api.Tray import dev.nucleusframework.core.runtime.SingleInstanceManager @@ -288,9 +292,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 +398,104 @@ 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) + } + // macOS menu bar with the usual Cmd shortcuts. Space/arrow keys are not bound here, + // because a menu accelerator would steal them from text fields. + if (isMacOS) { + MenuBar { + Menu("Playback") { + Item( + "Play/Pause", + shortcut = KeyShortcut(Key.P, meta = true), + ) { sharedViewModel.onUIEvent(UIEvent.PlayPause) } + Item( + "Next", + shortcut = KeyShortcut(Key.DirectionRight, meta = true), + ) { sharedViewModel.onUIEvent(UIEvent.Next) } + Item( + "Previous", + shortcut = KeyShortcut(Key.DirectionLeft, meta = true), + ) { sharedViewModel.onUIEvent(UIEvent.Previous) } + Separator() + Item( + "Shuffle", + shortcut = KeyShortcut(Key.S, meta = true, alt = true), + ) { sharedViewModel.onUIEvent(UIEvent.Shuffle) } + Item( + "Repeat", + shortcut = KeyShortcut(Key.R, meta = true, alt = true), + ) { sharedViewModel.onUIEvent(UIEvent.Repeat) } + Item( + "Like", + shortcut = KeyShortcut(Key.L, meta = true), + ) { sharedViewModel.onUIEvent(UIEvent.ToggleLike) } + } + Menu("Window") { + Item( + "Mini Player", + shortcut = KeyShortcut(Key.M, meta = true, alt = true), + ) { MiniPlayerManager.isOpen = !MiniPlayerManager.isOpen } + Item( + "Hide Window", + shortcut = KeyShortcut(Key.W, meta = true), + ) { isVisible = false } + } + } + } + // The window the user arranged (size, position, zoom) is remembered and put back after a + // minimise or a hide to the tray, which on macOS can bring an undecorated window back + // at another size. While minimized or hidden the menu bar and Dock are given back, but + // the fill itself is kept. + val arrangement = remember { com.maxrave.simpmusic.ui.component.WindowArrangement() } + DisposableEffect(window) { + if (!isMacOS) return@DisposableEffect onDispose { } + val fill = com.maxrave.simpmusic.ui.component.MacFillScreen + val tracker = + object : ComponentAdapter() { + override fun componentResized(event: ComponentEvent) { + arrangement.log("resized", window, throttle = true) + arrangement.note(window) + } + + override fun componentMoved(event: ComponentEvent) = arrangement.note(window) + } + val states = + object : WindowAdapter() { + override fun windowIconified(event: WindowEvent) { + arrangement.log("iconified", window) + fill.giveBackScreenEdges() + } + + override fun windowDeiconified(event: WindowEvent) { + arrangement.log("deiconified", window) + arrangement.putBack(window) + fill.takeScreenEdges() + } + } + window.addComponentListener(tracker) + window.addWindowListener(states) + onDispose { + window.removeComponentListener(tracker) + window.removeWindowListener(states) + } + } + LaunchedEffect(isVisible) { + if (!isMacOS) return@LaunchedEffect + arrangement.log(if (isVisible) "shown" else "hidden", window) + if (isVisible) { + arrangement.putBack(window) + com.maxrave.simpmusic.ui.component.MacFillScreen.takeScreenEdges() + } else { + com.maxrave.simpmusic.ui.component.MacFillScreen.giveBackScreenEdges() + } + } // 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 +568,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..332923df21 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) { @@ -152,7 +162,8 @@ fun CustomTitleBar( // Minimize button WindowControlButton( onClick = { - windowState.isMinimized = true + // Native miniaturize keeps a zoomed window zoomed; AWT's un-zooms it first. + if (!MacMiniaturize.minimize(window)) windowState.isMinimized = true }, backgroundColor = windowMinimiseButton, hoverColor = windowMinimiseButtonHover, @@ -164,10 +175,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..0f08571096 --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/MacFillScreen.kt @@ -0,0 +1,93 @@ +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 + } + } + + /** + * Gives the menu bar and Dock back while the window is minimized or hidden, WITHOUT leaving the + * fill: the window keeps its size, so it comes back as it was. + */ + fun giveBackScreenEdges() { + if (isFilled) setPresentationOptions(0L) + } + + /** Hides the menu bar and Dock again when a filled window comes back. */ + fun takeScreenEdges() { + if (isFilled) setPresentationOptions(HIDE_DOCK_AND_MENU_BAR) + } + + /** Called when the window is disposed 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 +} diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/MacMiniaturize.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/MacMiniaturize.kt new file mode 100644 index 0000000000..6c876de5bd --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/MacMiniaturize.kt @@ -0,0 +1,57 @@ +package com.maxrave.simpmusic.ui.component + +import androidx.compose.ui.awt.ComposeWindow +import com.maxrave.logger.Logger +import com.sun.jna.NativeLibrary +import com.sun.jna.Pointer +import java.awt.Window + +/** + * Minimizes a window with `-[NSWindow miniaturize:]`, the call the yellow button of any Mac app makes. + * + * Going through AWT (`extendedState = ICONIFIED`, which is what Compose's `WindowState.isMinimized` + * does) is not equivalent: for a zoomed window the JDK first un-zooms it and only then miniaturizes, + * so the window visibly shrinks to its small size and the Dock animation starts from that. Measured: + * 1470x860 -> 1249x731 about 0.3 s before the iconify event. Native miniaturize leaves the frame alone, + * so a zoomed window goes into the Dock zoomed and comes back zoomed. + */ +internal object MacMiniaturize { + private const val TAG = "MacMiniaturize" + + private class Natives { + private val objc = NativeLibrary.getInstance("objc") + private val system = NativeLibrary.getInstance("System") + val msgSend = objc.getFunction("objc_msgSend") + val dispatchAsync = system.getFunction("dispatch_async_f") + val mainQueue: Pointer = system.getGlobalVariableAddress("_dispatch_main_q") + val miniaturize: Pointer = objc.getFunction("sel_registerName").invokePointer(arrayOf("miniaturize:")) + } + + private val natives: Natives? by lazy { + if (!System.getProperty("os.name", "").contains("Mac", ignoreCase = true)) return@lazy null + runCatching { Natives() } + .onFailure { Logger.w(TAG, "Native miniaturize unavailable, minimizing through AWT: $it") } + .getOrNull() + } + + // One instance for the whole process: JNA frees a callback's native stub once its object is + // garbage collected, and the queued call runs after minimize() has returned. + private val work = + object : MacMainQueueWork { + override fun invoke(context: Pointer?) { + val n = natives ?: return + runCatching { n.msgSend.invokeVoid(arrayOf(context, n.miniaturize, null)) } + .onFailure { Logger.w(TAG, "miniaturize: failed: $it") } + } + } + + /** True when the call was queued; false off macOS or when it cannot be made (the caller falls back). */ + fun minimize(window: Window): Boolean { + val n = natives ?: return false + val handle = (window as? ComposeWindow)?.windowHandle ?: return false + if (handle == 0L) return false + return runCatching { + n.dispatchAsync.invokeVoid(arrayOf(n.mainQueue, Pointer(handle), work)) + }.isSuccess + } +} diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/WindowArrangement.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/WindowArrangement.kt new file mode 100644 index 0000000000..af0fb886cd --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/WindowArrangement.kt @@ -0,0 +1,59 @@ +package com.maxrave.simpmusic.ui.component + +import com.maxrave.logger.Logger +import java.awt.Frame +import java.awt.Rectangle + +/** + * Remembers where and how big the user left the main window, and puts it back after a minimise or a + * hide to the tray. AWT and Compose only track the size; nothing holds it, and an undecorated window + * on macOS can come back from the Dock at a different frame (or lose its zoomed state), which read + * as "it reset itself to the default size". + */ +internal class WindowArrangement { + private var bounds: Rectangle? = null + private var maximized = false + + private var lastResizeLogAt = 0L + + /** One log line per window event, so a reset can be read back from app.log. */ + fun log(event: String, window: Frame, throttle: Boolean = false) { + val now = System.currentTimeMillis() + if (throttle) { + if (now - lastResizeLogAt < 400) return + lastResizeLogAt = now + } + Logger.i( + TAG, + "$event bounds=${window.bounds} ext=${window.extendedState} showing=${window.isShowing} " + + "noted=$bounds notedMax=$maximized", + ) + } + + /** Records the current frame. Ignored while hidden or minimized, when the numbers mean nothing. */ + fun note(window: Frame) { + if (!window.isShowing) return + if (window.extendedState and Frame.ICONIFIED != 0) return + if (window.width <= 0 || window.height <= 0) return + bounds = window.bounds + maximized = window.extendedState and Frame.MAXIMIZED_BOTH == Frame.MAXIMIZED_BOTH + } + + /** + * Puts the window back as last noted, only when something moved it. A zoomed window is left + * alone: re-zooming after the restore made it visibly jump, and the zoom is no longer lost + * (see [MacMiniaturize]). + */ + fun putBack(window: Frame) { + val saved = bounds ?: return + if (maximized) return + if (window.bounds != saved) { + Logger.i(TAG, "Window came back as ${window.bounds}, restoring $saved") + window.bounds = saved + } + } + + private companion object { + const val TAG = "WindowArrangement" + } +}