Skip to content

Instantly share code, notes, and snippets.

@cgruber
Last active November 21, 2024 06:34
Show Gist options
  • Save cgruber/8a10a54daaab4761fcfd92cf5e5ce1ef to your computer and use it in GitHub Desktop.
Save cgruber/8a10a54daaab4761fcfd92cf5e5ce1ef to your computer and use it in GitHub Desktop.
Constrain Compose Desktop Window to a minimum size.
//
// Copyright (c) Christian Gruber, All Rights Reserved
//
// Licensed for use under any of simplified BSD 2-clause, BSD, MIT, or Apache licenses,
// at the licensee's discretion.
//
// I'd release it to the public domain, except that prevents its use in some commercial
// environments due to the US having a broken copyright system. So there it is. Liberally
// licensed as I can make it.
// An example of constraining a Window to a minimum size in Jetpack Compose Desktop
//
// Disclaimer: Once it worked, I stopped thinking about it - there may be a terser or
// cleaner logic, or a nice reusable utility to be extracted here.
//
// Also, I’m assuming that the window you’re resizing has focus. That may not be theoretically
// always true, but I think it’s usually true. If it turns out to not to be, selecting the
// window to set size may be a problem.
//
// Known limitations:
// - I've only tried this on MacOS - no idea if this behaves differently on different platforms
// - When resizing the left or top side, if you keep resizing, it'll start moving the window.
// I'm pretty sure that can be fixed by tracking position and restoring position when you set
// the size. My guess is the resize event makes the window smaller, but you're moving the side
// that the origin is computed from, so setting size sets it from that new left or top, which
// has, because of the resize, shifted position.
const val MIN_HEIGHT = 200
const val MIN_WIDTH = 300
fun main() = Window(
title = "Compose for Desktop",
size = IntSize(600, 400),
events = WindowEvents(
onResize = { size ->
val width = if (size.width < MIN_WIDTH) MIN_WIDTH else size.width
val height = if (size.height < MIN_HEIGHT) MIN_HEIGHT else size.height
if (width != size.width || height != size.height) {
// Don't bother setting if it's not below the constraints.
AppManager.focusedWindow?.setSize(width, height)
}
}
)
) {
//...
}
@sigmadeltasoftware
Copy link

For future reference:

Window(
  onCloseRequest = ::exitApplication
) {
  window.minimumSize = Dimension(800, 600)
  …
}

@xoanaraujo
Copy link

window.minimumSize = Dimension(800, 600) works on Ubuntu 22.04.4 LTS

@robertlevonyan
Copy link

this doesn't work on mac, any ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment