2
0

compositor.gradle.kts 16 KB

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