2
0

compositor.gradle.kts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. /*
  2. * Copyright (c) Milan Jurkulák 2026.
  3. * Contact:
  4. * e: mimoccc@gmail.com
  5. * e: mj@mjdev.org
  6. * w: https://mjdev.org
  7. */
  8. import org.jetbrains.kotlin.gradle.tasks.CInteropProcess
  9. plugins {
  10. // kotlin + serialization come from the root build classpath (declared apply-false there)
  11. kotlin("multiplatform")
  12. kotlin("plugin.serialization")
  13. }
  14. // identity from the shared version catalog (gradle/libs.versions.toml)
  15. val catalog = extensions.getByType<VersionCatalogsExtension>().named("libs")
  16. group = catalog.findVersion("app-pkg-name").get().requiredVersion
  17. version = catalog.findVersion("app-pkg-version").get().requiredVersion
  18. val nativeDir = project.file("native")
  19. val protocolsDir = layout.buildDirectory.dir("generated/protocols")
  20. val shimDir = layout.buildDirectory.dir("shim")
  21. // pkg-config is queried lazily and never fails configuration,
  22. // so the JVM desktop build stays usable on machines without wlroots
  23. fun pkgConfig(vararg args: String): List<String> = runCatching {
  24. val process = ProcessBuilder(listOf("pkg-config") + args)
  25. .redirectErrorStream(false)
  26. .start()
  27. val out = process.inputStream.bufferedReader().readText()
  28. if (process.waitFor() != 0) emptyList()
  29. else out.trim().split(Regex("\\s+")).filter { it.isNotBlank() }
  30. }.getOrElse { emptyList() }
  31. // cairo is added for server-side window decorations (the compositor renders the
  32. // GNOME-style titlebar + buttons into a cairo image surface used as a wlr_buffer)
  33. val wlrPackages = arrayOf("wlroots-0.18", "wayland-server", "xkbcommon", "pixman-1", "cairo")
  34. val wlrCflags: List<String>
  35. get() = pkgConfig("--cflags", *wlrPackages)
  36. val wlrLibs: List<String>
  37. get() = pkgConfig("--libs", *wlrPackages).ifEmpty {
  38. listOf("-lwlroots-0.18", "-lwayland-server", "-lxkbcommon", "-lcairo")
  39. }
  40. // the kotlin/native bundled linker does not search the system lib dirs
  41. val systemLibDirs = listOf(
  42. "/usr/lib/x86_64-linux-gnu",
  43. "/usr/lib",
  44. "/usr/local/lib",
  45. ).filter { file(it).isDirectory }.map { "-L$it" }
  46. val generateProtocols = tasks.register<Exec>("generateProtocols") {
  47. group = "mjdev"
  48. description = "Generates wayland protocol headers used by the compositor shim."
  49. val outDir = protocolsDir.get().asFile
  50. val xdgShellXml = "/usr/share/wayland-protocols/stable/xdg-shell/xdg-shell.xml"
  51. inputs.files(xdgShellXml).optional()
  52. outputs.dir(outDir)
  53. commandLine(
  54. "bash", "-c",
  55. "mkdir -p '$outDir' && " +
  56. "wayland-scanner server-header '$xdgShellXml' '$outDir/xdg-shell-protocol.h'"
  57. )
  58. }
  59. val compileShim = tasks.register<Exec>("compileShim") {
  60. group = "mjdev"
  61. description = "Compiles the C shim over wlroots into a static library."
  62. dependsOn(generateProtocols)
  63. // capture everything as local values at configuration time so the doFirst closure
  64. // never reaches back into the build script (required for configuration-cache safety)
  65. val shimC = nativeDir.resolve("shim.c")
  66. val shimH = nativeDir.resolve("shim.h")
  67. val outDir = shimDir.get().asFile
  68. val protoDir = protocolsDir.get().asFile
  69. val includeDir = nativeDir
  70. val cflags = wlrCflags.joinToString(" ")
  71. inputs.files(shimC, shimH)
  72. outputs.file(outDir.resolve("libmjcshim.a"))
  73. doFirst {
  74. commandLine(
  75. "bash", "-c",
  76. "mkdir -p '$outDir' && " +
  77. "cc -O2 -fPIC -DWLR_USE_UNSTABLE -std=c11 " +
  78. "-I'$protoDir' -I'$includeDir' $cflags " +
  79. "-c '$shimC' -o '$outDir/shim.o' && " +
  80. "ar rcs '$outDir/libmjcshim.a' '$outDir/shim.o'"
  81. )
  82. }
  83. // placeholder, replaced in doFirst (Exec requires a commandLine at configuration)
  84. commandLine("true")
  85. }
  86. kotlin {
  87. linuxX64 {
  88. compilations.getByName("main") {
  89. cinterops.create("shim") {
  90. defFile(nativeDir.resolve("shim.def"))
  91. packageName("mjdev.compositor.shim")
  92. includeDirs(nativeDir)
  93. }
  94. }
  95. binaries {
  96. executable("mjdevc") {
  97. entryPoint = "eu.mjdev.compositor.main"
  98. // link against the system glibc instead of the old bundled
  99. // sysroot, system libs (wlroots & co) need modern symbols
  100. val gccVersion = file("/usr/lib/gcc/x86_64-linux-gnu")
  101. .listFiles()?.map { it.name }?.maxByOrNull { it.toIntOrNull() ?: 0 }
  102. if (gccVersion != null) {
  103. freeCompilerArgs += listOf(
  104. "-Xoverride-konan-properties=" +
  105. "targetSysRoot.linux_x64=/;" +
  106. "libGcc.linux_x64=/usr/lib/gcc/x86_64-linux-gnu/$gccVersion;" +
  107. "crtFilesLocation.linux_x64=usr/lib/x86_64-linux-gnu"
  108. )
  109. }
  110. linkerOpts(systemLibDirs)
  111. linkerOpts(shimDir.get().asFile.resolve("libmjcshim.a").absolutePath)
  112. linkerOpts(wlrLibs)
  113. // the shim queries GL_RENDERER via EGL to decide hardware vs software GL for the
  114. // shell (SKIKO_RENDER_API), so link the EGL + GLES2 dispatchers explicitly.
  115. linkerOpts("-lEGL", "-lGLESv2")
  116. }
  117. }
  118. }
  119. sourceSets {
  120. getByName("linuxX64Main") {
  121. dependencies {
  122. implementation(catalog.findLibrary("kotlinx-serialization-json").get())
  123. }
  124. }
  125. }
  126. }
  127. // the static shim library must exist before linking the executable; it is passed via
  128. // linkerOpts (an absolute path), which Kotlin/Native does not track — so register it as an
  129. // explicit input, otherwise editing shim.c rebuilds the .a but never relinks the binary
  130. // (you would keep running a stale executable).
  131. tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinNativeLink>().configureEach {
  132. dependsOn(compileShim)
  133. inputs.file(shimDir.map { it.file("libmjcshim.a") })
  134. .withPropertyName("mjcShimLibrary")
  135. }
  136. // note: cinterop parses only the self contained shim.h,
  137. // generated wayland protocol headers are needed just for compileShim
  138. tasks.register<Copy>("stageSession") {
  139. group = "mjdev"
  140. description = "Stages the compositor binary and session files for installation."
  141. dependsOn("linkMjdevcReleaseExecutableLinuxX64")
  142. from(layout.buildDirectory.file("bin/linuxX64/mjdevcReleaseExecutable/mjdevc.kexe")) {
  143. rename { "mjdevc" }
  144. }
  145. from(rootProject.file("session/mjdev-session"))
  146. from(rootProject.file("session/mjdev.desktop"))
  147. into(layout.buildDirectory.dir("session-install"))
  148. }
  149. // Privileged install steps for the compositor + wayland session. Installs the binary, the
  150. // session launcher and the wayland-sessions entry, and removes the stale 2024 X11
  151. // "mjdev-desktop" session that shadows ours (same display name) and breaks login. Lines are
  152. // built at configuration time (staged paths are static) so the Exec stays config-cache safe.
  153. // built at configuration time (staged paths are static) so referencing the result from doLast
  154. // stays configuration-cache safe (the function itself is never captured in the task action).
  155. // the wayland runtime stack mjdevc needs — from the version catalog (single source of truth,
  156. // shared with the deb Depends and make-iso.sh), never hardcoded here.
  157. val compositorRuntimeDeps: String = libs.versions.app.compositor.runtime.deps.get()
  158. fun sessionInstallLines(staged: File): List<String> = listOf(
  159. "#!/bin/sh",
  160. "set -e",
  161. // runtime stack the compositor needs but a clean / GNOME box lacks (GNOME uses mutter,
  162. // not wlroots). dpkg can't resolve these, so apt-install them explicitly. libwlroots-0.18
  163. // pulls libdrm/libgbm/libinput/libseat/libxkbcommon/libwayland/libdisplay-info/libliftoff;
  164. // xwayland = X display for the AWT-based Compose shell; libgl1-mesa-dri = the GL/EGL driver
  165. // (incl. llvmpipe software fallback). Without these mjdevc fails to even load -> black screen.
  166. "apt-get update || true",
  167. "apt-get install --no-install-recommends -y $compositorRuntimeDeps seatd || " +
  168. "echo 'WARN: apt could not install the wayland runtime stack (offline or non-debian?) — the desktop may not start'",
  169. // the compositor opens /dev/dri/card0 + the seatd socket (group video); seatd must run and
  170. // the logged-in user must be in video/input/render (+ seat if present) or the session is black.
  171. "systemctl enable --now seatd 2>/dev/null || true",
  172. "_u=\"\$(getent passwd \"\${PKEXEC_UID:-\${SUDO_UID:-1000}}\" | cut -d: -f1)\"",
  173. "[ -n \"\$_u\" ] && usermod -aG video,input,render \"\$_u\" 2>/dev/null || true",
  174. "getent group seat >/dev/null 2>&1 && [ -n \"\$_u\" ] && usermod -aG seat \"\$_u\" 2>/dev/null || true",
  175. "install -Dm755 '${staged.resolve("mjdevc")}' /usr/local/bin/mjdevc",
  176. "install -Dm755 '${staged.resolve("mjdev-session")}' /usr/local/bin/mjdev-session",
  177. "install -Dm644 '${staged.resolve("mjdev.desktop")}' /usr/share/wayland-sessions/mjdev.desktop",
  178. "rm -f /usr/share/xsessions/mjdev-desktop.desktop " +
  179. "/usr/share/gnome-session/sessions/mjdev-desktop.session " +
  180. "/usr/share/applications/mjdev-desktop-mjdev-desktop.desktop",
  181. )
  182. // sudo can't read a password from the Gradle daemon (no TTY), so these tasks don't exec it —
  183. // they stage everything, write a self-contained install script under build/, and print the one
  184. // sudo command for the user to run in their own terminal.
  185. tasks.register("installSession") {
  186. group = "mjdev"
  187. description = "Stages the compositor + wayland session, prints the sudo install command."
  188. dependsOn("stageSession")
  189. val staged = layout.buildDirectory.dir("session-install").get().asFile
  190. val lines = sessionInstallLines(staged)
  191. doLast {
  192. val script = staged.resolve("install.sh")
  193. script.writeText(lines.joinToString("\n") + "\n")
  194. println("Session staged. Install it (single sudo prompt) with:")
  195. println(" sudo sh '${script.absolutePath}'")
  196. }
  197. }
  198. // Complete (re)install: compositor + wayland session + the desktop app .deb (the session's
  199. // shell, /opt/mjdev-desktop), and the stale-session cleanup — one script run as root via a
  200. // pkexec (polkit) authentication dialog. pkexec needs no TTY (unlike sudo), so it works from
  201. // the detached Gradle daemon and prompts graphically; if it's missing we print the sudo command.
  202. tasks.register<Exec>("installDesktop") {
  203. group = "mjdev"
  204. description = "Builds compositor + session + app .deb and installs it via a pkexec authentication dialog."
  205. dependsOn("stageSession", ":desktopApp:packageReleaseDeb", ":packageFullDeb")
  206. val staged = layout.buildDirectory.dir("session-install").get().asFile
  207. val lines = sessionInstallLines(staged)
  208. // desktopApp overrides compose outputBaseDir to <root>/packages, so the .deb is written
  209. // to packages/main-release/deb (not desktopApp/build/compose/binaries/…)
  210. val debDir = rootProject.rootDir.resolve("packages/main-release/deb")
  211. isIgnoreExitValue = false
  212. doFirst {
  213. val deb = debDir.listFiles { f -> f.extension == "deb" }?.firstOrNull()
  214. ?: error("desktop .deb not found in $debDir — run :desktopApp:packageReleaseDeb")
  215. val script = staged.resolve("install-desktop.sh")
  216. // install the deb via apt so its Depends (the wayland runtime stack baked in by
  217. // packageFullDeb) are resolved; fall back to dpkg + apt -f if the apt form is unavailable.
  218. val installDeb = "apt-get install --no-install-recommends -y '${deb.absolutePath}' || " +
  219. "{ dpkg -i '${deb.absolutePath}' || true; apt-get install -f -y; }"
  220. script.writeText((lines + installDeb).joinToString("\n") + "\n")
  221. // pkexec pops a graphical polkit auth dialog and runs the script as root; needs a polkit
  222. // agent in the session but no terminal. Fall back to a printed sudo command if absent.
  223. val pkexec = listOf("/usr/bin/pkexec", "/usr/local/bin/pkexec")
  224. .firstOrNull { File(it).canExecute() }
  225. if (pkexec != null) {
  226. println("Installing the mjdev desktop — approve the authentication dialog…")
  227. commandLine(pkexec, "sh", script.absolutePath)
  228. } else {
  229. println("pkexec not found. Install the desktop (single sudo prompt) with:")
  230. println(" sudo sh '${script.absolutePath}'")
  231. commandLine("true")
  232. }
  233. }
  234. commandLine("true")
  235. }
  236. tasks.register<Exec>("runNested") {
  237. group = "mjdev"
  238. description = "Runs the compositor nested inside the current Wayland session."
  239. dependsOn("linkMjdevcDebugExecutableLinuxX64")
  240. val shellCmd = (project.findProperty("shellCmd") as String?)
  241. val binary = layout.buildDirectory
  242. .file("bin/linuxX64/mjdevcDebugExecutable/mjdevc.kexe")
  243. .get().asFile.absolutePath
  244. // x11 backend -> the host window manager decorates the nested window (frame + close +
  245. // move); 16:9 nested output (the compositor locks it against resize)
  246. environment("WLR_BACKENDS", "x11")
  247. environment("MJDEVC_OUTPUT", "1280x720")
  248. doFirst {
  249. // host X11 auth for the nested wlroots x11 backend, resolved at execution time:
  250. // the detached Gradle daemon often lacks a valid XAUTHORITY, and mutter writes a
  251. // per-session, randomly-suffixed auth file under XDG_RUNTIME_DIR
  252. environment("DISPLAY", System.getenv("DISPLAY") ?: ":0")
  253. val xauthCandidates = buildList {
  254. System.getenv("XAUTHORITY")?.let { add(File(it)) }
  255. System.getenv("XDG_RUNTIME_DIR")?.let { dir ->
  256. File(dir).listFiles()?.forEach { f ->
  257. if (f.name.startsWith(".mutter-Xwaylandauth.")) add(f)
  258. }
  259. }
  260. add(File(System.getProperty("user.home"), ".Xauthority"))
  261. }
  262. xauthCandidates.firstOrNull { it.isFile }?.let { environment("XAUTHORITY", it.absolutePath) }
  263. val args = mutableListOf(binary)
  264. if (shellCmd != null) {
  265. args += listOf("--shell-cmd", shellCmd)
  266. }
  267. commandLine(args)
  268. }
  269. commandLine("true")
  270. }
  271. // Runs the Compose desktop app as the shell client inside the nested compositor.
  272. // The desktop app is packaged with its own JRE (createDistributable) and launched via
  273. // XWayland, so it shows up as a window managed by mjdevc (fixed 16:9, movable, closable).
  274. tasks.register<Exec>("runNestedDesktop") {
  275. group = "mjdev"
  276. description = "Runs the mjdev desktop app as a client inside the nested compositor."
  277. dependsOn("linkMjdevcDebugExecutableLinuxX64", ":desktopApp:createDistributable")
  278. val binary = layout.buildDirectory
  279. .file("bin/linuxX64/mjdevcDebugExecutable/mjdevc.kexe")
  280. .get().asFile.absolutePath
  281. // desktopApp overrides outputBaseDir to <root>/packages, so createDistributable
  282. // writes the app image to packages/main/app/<name>/bin/<name> (not build/compose/…)
  283. val appDir = rootProject.rootDir.resolve("packages/main/app")
  284. // x11 backend -> host-decorated nested window (frame + close + move); fixed 16:9 output
  285. environment("WLR_BACKENDS", "x11")
  286. environment("MJDEVC_OUTPUT", "1280x720")
  287. doFirst {
  288. // host X11 auth for the nested wlroots x11 backend, resolved at execution time:
  289. // the detached Gradle daemon often lacks a valid XAUTHORITY, and mutter writes a
  290. // per-session, randomly-suffixed auth file under XDG_RUNTIME_DIR
  291. environment("DISPLAY", System.getenv("DISPLAY") ?: ":0")
  292. val xauthCandidates = buildList {
  293. System.getenv("XAUTHORITY")?.let { add(File(it)) }
  294. System.getenv("XDG_RUNTIME_DIR")?.let { dir ->
  295. File(dir).listFiles()?.forEach { f ->
  296. if (f.name.startsWith(".mutter-Xwaylandauth.")) add(f)
  297. }
  298. }
  299. add(File(System.getProperty("user.home"), ".Xauthority"))
  300. }
  301. xauthCandidates.firstOrNull { it.isFile }?.let { environment("XAUTHORITY", it.absolutePath) }
  302. val launcher = appDir.walkTopDown()
  303. .firstOrNull { it.isFile && it.parentFile?.name == "bin" && it.canExecute() }
  304. ?: error("desktop launcher not found under $appDir — run :desktopApp:createDistributable")
  305. commandLine(binary, "--shell-cmd", launcher.absolutePath)
  306. }
  307. commandLine("true")
  308. }