-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerate-AndroidStudioProject.ps1
More file actions
300 lines (280 loc) · 15.3 KB
/
Generate-AndroidStudioProject.ps1
File metadata and controls
300 lines (280 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
param(
[string]$BuildDir = "build-ide",
[string]$AndroidBuildDir = "build-android",
[string]$NdkPath,
[switch]$SkipHostConfigure = $true,
[string]$ProjucerPath,
[string]$JucerFile = "AudioAnalyzer.jucer",
[switch]$UseRootCMake,
[switch]$RequireProjucerGradle
)
$ErrorActionPreference = "Stop"
$Root = Split-Path -Path $MyInvocation.MyCommand.Path -Parent
$Source = $Root
$Build = Join-Path $Root $BuildDir
$AndroidBuild = Join-Path $Root $AndroidBuildDir
# [0/3] Try JUCE Projucer export (headless) if a Projucer path is provided
if ($RequireProjucerGradle -and (-not ($ProjucerPath -and (Test-Path $ProjucerPath)) )) {
Write-Host "-RequireProjucerGradle specified but ProjucerPath is missing or invalid." -ForegroundColor Red
exit 3
}
if ($ProjucerPath -and (Test-Path $ProjucerPath)) {
$jucer = if ([System.IO.Path]::IsPathRooted($JucerFile)) { $JucerFile } else { Join-Path $Root $JucerFile }
if (-not (Test-Path $jucer)) {
Write-Host "Projucer specified but .jucer not found at '$jucer'" -ForegroundColor Yellow
} else {
Write-Host "[0/3] Exporting Android Studio project via Projucer (--resave)" -ForegroundColor Cyan
& "$ProjucerPath" --resave "$jucer"
# Regardless of exit code, search for a generated Gradle project (some GUI apps don't set exit codes)
Start-Sleep -Milliseconds 200
$gradleHit = $null
# 0) Try to read targetFolder from the .jucer (exporter output can be customized)
$preferredDirs = @()
try {
$jucerXml = [xml](Get-Content -Raw $jucer)
# Collect any exporter nodes that look like Android
$exporters = @()
$exporters += $jucerXml.SelectNodes('//EXPORTFORMATS/*[@targetFolder]')
foreach ($ex in $exporters) {
$tag = $ex.Name
$tf = $ex.Attributes['targetFolder']?.Value
if ([string]::IsNullOrWhiteSpace($tf)) { continue }
# Heuristic: only consider Android exporters
if ($tag -match 'ANDROID') {
$tfPath = if ([System.IO.Path]::IsPathRooted($tf)) { $tf } else { Join-Path (Split-Path -Parent $jucer) $tf }
$preferredDirs += $tfPath
}
}
} catch { }
# 1) Also include common defaults under ./Builds/
$preferredDirs += @(
(Join-Path $Root 'Builds/Android'),
(Join-Path $Root 'Builds/AndroidStudio')
)
foreach ($pd in $preferredDirs) {
if (Test-Path $pd) {
$sg = Get-ChildItem -Path $pd -Filter 'settings.gradle*' -File -ErrorAction SilentlyContinue | Select-Object -First 1
if ($sg) {
$gradleHit = $sg
break
}
}
}
# 2) Fallback to a repo-wide search (allowing other layouts)
if (-not $gradleHit) {
$gradleFiles = @()
$gradleFiles += Get-ChildItem -Path $Root -Recurse -Filter "settings.gradle" -ErrorAction SilentlyContinue
$gradleFiles += Get-ChildItem -Path $Root -Recurse -Filter "settings.gradle.kts" -ErrorAction SilentlyContinue
$candidates = $gradleFiles | Where-Object { $_.FullName -match '(?i)Android' -or $_.DirectoryName -match '(?i)Builds' } | Select-Object -Unique
# Prefer those that also contain a gradlew or gradlew.bat alongside
foreach ($s in $candidates) {
$dir = Split-Path -Parent $s.FullName
if ((Test-Path (Join-Path $dir 'gradlew.bat')) -or (Test-Path (Join-Path $dir 'gradlew'))) { $gradleHit = $s; break }
}
if (-not $gradleHit -and $candidates) { $gradleHit = $candidates | Select-Object -First 1 }
}
if ($gradleHit) {
$proj = Split-Path -Parent $gradleHit.FullName
Write-Host "`nAndroid Studio Gradle project generated by Projucer at:" -ForegroundColor Green
Write-Host $proj
# Optionally patch the generated project to point externalNativeBuild at the repo's root CMake
if ($UseRootCMake) {
Write-Host "Patching Gradle externalNativeBuild to use root CMakeLists.txt (opt-in)" -ForegroundColor DarkCyan
function Patch-GradleCMakePath {
param([string]$GradleDir,[string]$RootCmake)
$appGradle = Join-Path $GradleDir 'app/build.gradle'
$appGradleKts = Join-Path $GradleDir 'app/build.gradle.kts'
$rootCMakeFwd = ($RootCmake -replace '\\','/')
function Patch-Groovy([string]$txt) {
# 1) Replace file("...CMakeLists.txt") form
$new = [Regex]::Replace($txt, 'path\s*=\s*file\([^)]*CMakeLists\.txt\)', ('path = file("{0}")' -f $rootCMakeFwd))
if ($new -ne $txt) { return $new }
# 2) Replace path "...CMakeLists.txt" (single or double quotes)
$new = [Regex]::Replace($txt, 'path\s+["\x27][^"\x27]*CMakeLists\.txt["\x27]', ('path "{0}"' -f $rootCMakeFwd))
if ($new -ne $txt) { return $new }
# 3) If cmake block exists without a path, inject one at the top of the cmake block
if ($txt -match '(?s)externalNativeBuild\s*\{\s*cmake\s*\{') {
$new = [Regex]::Replace($txt, '(?s)(externalNativeBuild\s*\{\s*cmake\s*\{)', ('$1`n path "{0}"' -f $rootCMakeFwd), 1)
if ($new -ne $txt) { return $new }
}
return $null
}
function Patch-Kts([string]$txt) {
# 1) Replace path = file("...CMakeLists.txt") form
$new = [Regex]::Replace($txt, 'path\s*=\s*file\([^)]*CMakeLists\.txt\)', ('path = file("{0}")' -f $rootCMakeFwd))
if ($new -ne $txt) { return $new }
# 2) Replace path "...CMakeLists.txt" (rare in kts but handle anyway)
$new = [Regex]::Replace($txt, 'path\s+["\x27][^"\x27]*CMakeLists\.txt["\x27]', ('path "{0}"' -f $rootCMakeFwd))
if ($new -ne $txt) { return $new }
# 3) Inject if cmake block exists
if ($txt -match '(?s)externalNativeBuild\s*\{\s*cmake\s*\{') {
$new = [Regex]::Replace($txt, '(?s)(externalNativeBuild\s*\{\s*cmake\s*\{)', ('$1`n path = file("{0}")' -f $rootCMakeFwd), 1)
if ($new -ne $txt) { return $new }
}
return $null
}
if (Test-Path $appGradle) {
$txt = Get-Content -Raw $appGradle
# If already correct, short-circuit
if ($txt -match [Regex]::Escape($rootCMakeFwd)) { return $true }
$res = Patch-Groovy $txt
if ($res) {
Set-Content -NoNewline -Path $appGradle -Value $res
Write-Host "Updated $appGradle to point to $rootCMakeFwd" -ForegroundColor DarkGreen
return $true
}
}
if (Test-Path $appGradleKts) {
$txt = Get-Content -Raw $appGradleKts
if ($txt -match [Regex]::Escape($rootCMakeFwd)) { return $true }
$res = Patch-Kts $txt
if ($res) {
Set-Content -NoNewline -Path $appGradleKts -Value $res
Write-Host "Updated $appGradleKts to point to $rootCMakeFwd" -ForegroundColor DarkGreen
return $true
}
}
return $false
}
$patched = Patch-GradleCMakePath -GradleDir $proj -RootCmake (Join-Path $Source 'CMakeLists.txt')
if (-not $patched) { Write-Host "No externalNativeBuild path updated; check app/build.gradle(.kts)." -ForegroundColor Yellow }
}
Write-Host "`nOpen this folder in Android Studio (File > Open)." -ForegroundColor Green
exit 0
} else {
if ($LASTEXITCODE) { Write-Host "Projucer --resave exit code: $LASTEXITCODE" -ForegroundColor DarkGray }
if ($RequireProjucerGradle) {
Write-Host "Projucer export did not produce a Gradle project and -RequireProjucerGradle is set; aborting." -ForegroundColor Red
exit 2
}
Write-Host "Projucer completed (or returned no exit code) but no Gradle project was found. Ensure the Android exporter is enabled in the .jucer. Falling back to CMake/NDK flow." -ForegroundColor Yellow
}
}
}
if (-not $SkipHostConfigure) {
Write-Host "[1/3] Configuring CMake project (host)" -ForegroundColor Cyan
cmake -S $Source -B $Build
if ($LASTEXITCODE -ne 0) {
throw "CMake configure failed with exit code $LASTEXITCODE"
}
} else {
Write-Host "[1/3] Skipping host configure (use -SkipHostConfigure:\$false to enable)" -ForegroundColor DarkGray
}
Write-Host "[2/3] Generating Android CMake build (to emit Gradle project)" -ForegroundColor Cyan
# Try to locate the Android NDK
function Get-AndroidNdkPath {
param([string]$Override)
if ($Override -and (Test-Path $Override)) { return $Override }
if ($env:ANDROID_NDK_ROOT -and (Test-Path $env:ANDROID_NDK_ROOT)) { return $env:ANDROID_NDK_ROOT }
if ($env:ANDROID_NDK_HOME -and (Test-Path $env:ANDROID_NDK_HOME)) { return $env:ANDROID_NDK_HOME }
$sdkRoots = @()
foreach ($v in 'ANDROID_SDK_ROOT','ANDROID_HOME') {
$val = [System.Environment]::GetEnvironmentVariable($v)
if ($val -and (Test-Path $val)) { $sdkRoots += $val }
}
if ($env:LOCALAPPDATA) {
$sdkRoots += (Join-Path $env:LOCALAPPDATA 'Android/Sdk')
}
if ($env:ProgramData) {
$sdkRoots += (Join-Path $env:ProgramData 'Android/Sdk')
}
$sdkRoots = $sdkRoots | Where-Object { $_ -and (Test-Path $_) } | Select-Object -Unique
foreach ($sdk in $sdkRoots) {
$ndkDir = Join-Path $sdk 'ndk'
if (Test-Path $ndkDir) {
$candidates = Get-ChildItem -Path $ndkDir -Directory -ErrorAction SilentlyContinue | Sort-Object Name -Descending
if ($candidates -and $candidates.Count -gt 0) { return $candidates[0].FullName }
}
$bundle = Join-Path $sdk 'ndk-bundle'
if (Test-Path $bundle) { return $bundle }
}
return $null
}
$ndk = Get-AndroidNdkPath -Override $NdkPath
if ($ndk) {
Write-Host "Using Android NDK: $ndk" -ForegroundColor DarkGray
$toolchain = Join-Path $ndk "build/cmake/android.toolchain.cmake"
if (-not (Test-Path $toolchain)) { throw "Android toolchain not found at $toolchain" }
# Prefer Ninja; locate it via PATH or Android SDK cmake packages
function Find-NinjaPath {
try { $v = & ninja --version 2>$null; if ($LASTEXITCODE -eq 0) { return 'ninja' } } catch {}
$sdkRoots = @()
foreach ($v in 'ANDROID_SDK_ROOT','ANDROID_HOME') {
$val = [System.Environment]::GetEnvironmentVariable($v)
if ($val -and (Test-Path $val)) { $sdkRoots += $val }
}
if ($env:LOCALAPPDATA) { $sdkRoots += (Join-Path $env:LOCALAPPDATA 'Android/Sdk') }
$sdkRoots = $sdkRoots | Where-Object { $_ -and (Test-Path $_) } | Select-Object -Unique
foreach ($sdk in $sdkRoots) {
$cmakeDir = Join-Path $sdk 'cmake'
if (Test-Path $cmakeDir) {
$versions = Get-ChildItem -Path $cmakeDir -Directory -ErrorAction SilentlyContinue | Sort-Object Name -Descending
foreach ($ver in $versions) {
$ninja = Join-Path $ver.FullName 'bin/ninja.exe'
if (Test-Path $ninja) { return $ninja }
}
}
}
return $null
}
$ninjaPath = Find-NinjaPath
$generatorArgs = @()
if ($ninjaPath) {
$ninjaDir = Split-Path -Parent $ninjaPath
if ($ninjaPath -ne 'ninja') { $env:PATH = "$ninjaDir;$env:PATH" }
$generatorArgs = @('-G','Ninja', "-DCMAKE_MAKE_PROGRAM=$ninjaPath")
Write-Host "Using Ninja at: $ninjaPath" -ForegroundColor DarkGray
} else {
Write-Host "Ninja not found. Install Android SDK 'CMake' component (includes Ninja), or add Ninja to PATH. Falling back may select Visual Studio generator and fail." -ForegroundColor Yellow
}
$androidConfigureArgs = @(
'-S', $Source,
'-B', $AndroidBuild,
"-DCMAKE_TOOLCHAIN_FILE=$toolchain",
'-DANDROID_ABI=arm64-v8a',
'-DANDROID_PLATFORM=24',
'-DCMAKE_BUILD_TYPE=Release',
"-DJUCE_ANDROID_MIN_SDK_VERSION=24",
"-DJUCE_ANDROID_TARGET_SDK_VERSION=34"
) + $generatorArgs
Write-Host "Configuring Android build folder '$AndroidBuildDir'" -ForegroundColor DarkGray
# If an existing build dir was configured with a different generator (e.g., Visual Studio), clean it
$androidCache = Join-Path $AndroidBuild 'CMakeCache.txt'
if (Test-Path $androidCache) {
try {
$cacheContent = Get-Content -Raw $androidCache
if ($cacheContent -match 'CMAKE_GENERATOR[^=]*=([^\r\n]+)') {
$prevGen = $Matches[1].Trim()
if ($prevGen -notmatch 'Ninja') {
Write-Host "Detected previous generator '$prevGen' in $AndroidBuild; cleaning directory due to generator change to Ninja" -ForegroundColor Yellow
Remove-Item -Recurse -Force $AndroidBuild
}
}
} catch { }
}
& cmake @androidConfigureArgs
if ($LASTEXITCODE -ne 0) { throw "Android CMake configure failed with exit code $LASTEXITCODE" }
$gradle = Get-ChildItem -Path $AndroidBuild -Recurse -Filter "settings.gradle" -ErrorAction SilentlyContinue | Select-Object -First 1
if ($gradle) {
$proj = Split-Path -Parent $gradle.FullName
Write-Host "`nAndroid Studio project generated at:" -ForegroundColor Green
Write-Host $proj
Write-Host "`nOpen this folder in Android Studio (File > Open)." -ForegroundColor Green
exit 0
} else {
Write-Host "Android build configured. No Gradle project detected. Preferred: export a Gradle project via Projucer so you can open 'Builds/Android' in Android Studio." -ForegroundColor Yellow
$doc = Join-Path $Root 'docs/ANDROID_STUDIO_CMAKE_IMPORT.md'
if (Test-Path $doc) {
Write-Host "See detailed steps: $doc" -ForegroundColor Yellow
}
}
} else {
Write-Host "Android NDK not found in environment variables; that's fine when using Android Studio. It will download/locate the NDK on first sync. Skipping NDK-only configure." -ForegroundColor DarkGray
$doc = Join-Path $Root 'docs/ANDROID_STUDIO_CMAKE_IMPORT.md'
if (Test-Path $doc) {
Write-Host "Tip: Use Projucer export to generate the Gradle project, then open it in Android Studio. Details: $doc" -ForegroundColor DarkGray
}
}
# Final note and exit without error to keep CMake GUI runs clean
Write-Host "[3/3] Done. Use the printed Gradle folder above (e.g. 'Builds/Android') when opening in Android Studio, or see docs/ANDROID_STUDIO_CMAKE_IMPORT.md." -ForegroundColor Cyan
exit 0