Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / build-logic / src / main / kotlin / LauncherIconGen.kt

LauncherIconGen.kt139 lines · 5.5 KiBRaw
1import org.gradle.api.DefaultTask
2import org.gradle.api.GradleException
3import org.gradle.api.file.DirectoryProperty
4import org.gradle.api.provider.Property
5import org.gradle.api.tasks.Input
6import org.gradle.api.tasks.Internal
7import org.gradle.api.tasks.OutputDirectory
8import org.gradle.api.tasks.TaskAction
9import java.net.URI
10
11// DSL for declaring which Material Symbol an app's launcher icon is built from:
12//
13// launcherIcon {
14// symbol = "calendar_month"
15// }
16//
17// `common-conventions-app` reads this and generates the app's adaptive-icon
18// foreground vector at build time, so no ic_launcher_foreground.xml is committed.
19interface LauncherIconExtension {
20 /** Material Symbols name, e.g. "calendar_month" (the `materialsymbolsoutlined` style). */
21 val symbol: Property<String>
22
23 /**
24 * Fraction of the 960 viewport the symbol occupies within the adaptive-icon
25 * safe zone. Defaults to 0.58; lower values render a smaller glyph with more
26 * padding. The translate is derived so the glyph stays centered.
27 */
28 val scale: Property<Double>
29}
30
31// Downloads the outlined Material Symbol at [ref], wraps its path in the standard
32// adaptive-icon foreground vector, and writes it into an AGP-managed generated res
33// directory. Raw symbol XML is cached under [cacheDir] so `clean` builds and
34// offline rebuilds don't re-hit the network.
35abstract class GenerateLauncherIconTask : DefaultTask() {
36 @get:Input
37 abstract val symbol: Property<String>
38
39 @get:Input
40 abstract val ref: Property<String>
41
42 @get:Input
43 abstract val scale: Property<Double>
44
45 @get:Internal
46 abstract val cacheDir: DirectoryProperty
47
48 @get:OutputDirectory
49 abstract val outputDir: DirectoryProperty
50
51 @TaskAction
52 fun generate() {
53 val sym = symbol.orNull
54 ?: throw GradleException(
55 "No launcher icon symbol set for ${path.substringBeforeLast(':')}. " +
56 "Declare one in build.gradle.kts:\n\n launcherIcon {\n symbol = \"calendar_month\"\n }\n"
57 )
58 val gitRef = ref.get()
59 val raw = fetchRawSymbol(sym, gitRef)
60 val pathData = PATH_DATA.find(raw)?.groupValues?.get(1)
61 ?: throw GradleException("Could not find android:pathData in Material Symbol '$sym' (ref $gitRef)")
62
63 val drawableDir = outputDir.get().asFile.resolve("drawable").apply { mkdirs() }
64 drawableDir.resolve("ic_launcher_foreground.xml").writeText(wrap(pathData))
65
66 // Emit the adaptive-icon wrapper too, so no ic_launcher.xml is committed per app.
67 // It references the generated foreground, the standard monochrome layer, and the
68 // per-app @color/ic_launcher_background (still declared in each app's values).
69 val mipmapDir = outputDir.get().asFile.resolve("mipmap-anydpi-v26").apply { mkdirs() }
70 mipmapDir.resolve("ic_launcher.xml").writeText(ADAPTIVE_ICON)
71 mipmapDir.resolve("ic_launcher_round.xml").writeText(ADAPTIVE_ICON)
72 }
73
74 private fun fetchRawSymbol(sym: String, gitRef: String): String {
75 val cached = cacheDir.get().asFile.resolve(gitRef).resolve("${sym}_24px.xml")
76 if (cached.isFile && cached.length() > 0) return cached.readText()
77
78 val url =
79 "https://raw.githubusercontent.com/google/material-design-icons/$gitRef" +
80 "/symbols/android/$sym/materialsymbolsoutlined/${sym}_24px.xml"
81 val text = try {
82 URI(url).toURL().openStream().bufferedReader().use { it.readText() }
83 } catch (e: Exception) {
84 throw GradleException(
85 "Failed to download Material Symbol '$sym' from $url. " +
86 "Check the symbol name and network access.",
87 e,
88 )
89 }
90 if (!text.contains("pathData")) {
91 throw GradleException("Material Symbol '$sym' not found at ref $gitRef (url: $url)")
92 }
93 cached.parentFile.mkdirs()
94 cached.writeText(text)
95 return text
96 }
97
98 private fun wrap(pathData: String): String {
99 val s = scale.get()
100 val translate = (VIEWPORT - VIEWPORT * s) / 2.0
101 return """
102 |<vector xmlns:android="http://schemas.android.com/apk/res/android"
103 | android:width="108dp"
104 | android:height="108dp"
105 | android:viewportWidth="960"
106 | android:viewportHeight="960"
107 | android:tint="#000000">
108 | <group android:scaleX="${fmt(s)}"
109 | android:scaleY="${fmt(s)}"
110 | android:translateX="${fmt(translate)}"
111 | android:translateY="${fmt(translate)}">
112 | <path
113 | android:fillColor="@android:color/white"
114 | android:pathData="$pathData"/>
115 | </group>
116 |</vector>
117 |
118 """.trimMargin()
119 }
120
121 private fun fmt(v: Double): String {
122 val s = v.toString()
123 return if (s.endsWith(".0")) s.dropLast(2) else s
124 }
125
126 private companion object {
127 const val VIEWPORT = 960.0
128 val PATH_DATA = Regex("""android:pathData="([^"]*)"""")
129 val ADAPTIVE_ICON = """
130 |<?xml version="1.0" encoding="utf-8"?>
131 |<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
132 | <background android:drawable="@color/ic_launcher_background"/>
133 | <foreground android:drawable="@drawable/ic_launcher_foreground"/>
134 | <monochrome android:drawable="@drawable/ic_launcher_foreground"/>
135 |</adaptive-icon>
136 |
137 """.trimMargin()
138 }
139}