compositor.gradle.kts 17 KB

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