├── .vscode
└── settings.json
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── .gitattributes
├── README.md
├── settings.gradle.kts
├── jdk-transform
├── build.gradle.kts
└── src
│ └── main
│ └── java
│ └── com
│ └── itsaky
│ └── androidide
│ └── jdktransform
│ └── Main.java
├── gradlew.bat
└── gradlew
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "java.configuration.updateBuildConfiguration": "automatic"
3 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidIDEOfficial/androidide-jdk-transform/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Ignore Gradle project-specific cache directory
2 | .gradle
3 |
4 | # Ignore Gradle build output directory
5 | build
6 | jdk-transform/bin
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | #
2 | # https://help.github.com/articles/dealing-with-line-endings/
3 | #
4 | # These are explicitly windows files and should use crlf
5 | *.bat text eol=crlf
6 |
7 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # androidide-jdk-transform
2 | Transform android.jar files to a custom JDK image which can be used in AndroidIDE to provide java completions and actions.
3 |
4 | ***Not used anymore in AndroidIDE***.
5 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | /*
2 | * This file was generated by the Gradle 'init' task.
3 | *
4 | * The settings file is used to specify which projects to include in your build.
5 | *
6 | * Detailed information about configuring a multi-project build in Gradle can be found
7 | * in the user manual at https://docs.gradle.org/7.3/userguide/multi_project_builds.html
8 | */
9 |
10 | rootProject.name = "AndroidIDEJDKTransform"
11 | include("jdk-transform")
12 |
--------------------------------------------------------------------------------
/jdk-transform/build.gradle.kts:
--------------------------------------------------------------------------------
1 | /*
2 | * This file was generated by the Gradle 'init' task.
3 | *
4 | * This generated file contains a sample Java application project to get you started.
5 | * For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle
6 | * User Manual available at https://docs.gradle.org/7.3/userguide/building_java_projects.html
7 | */
8 |
9 | import org.gradle.jvm.tasks.Jar
10 |
11 | val fatJar = task("fatJar", type = Jar::class) {
12 | baseName = "${project.name}-fat"
13 | manifest {
14 | attributes["Implementation-Title"] = "AndroidIDE JDK Transform"
15 | attributes["Implementation-Version"] = "1.0.0"
16 | attributes["Main-Class"] = "com.itsaky.androidide.jdktransform.Main"
17 | }
18 |
19 | with(tasks["jar"] as CopySpec)
20 | }
21 |
22 | tasks {
23 | "build" {
24 | dependsOn(fatJar)
25 | }
26 | }
27 |
28 | plugins {
29 | // Apply the application plugin to add support for building a CLI application in Java.
30 | application
31 | }
32 |
33 | application {
34 | // Define the main class for the application.
35 | mainClass.set("com.itsaky.androidide.jdktransform.Main")
36 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Use "xargs" to parse quoted args.
209 | #
210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
211 | #
212 | # In Bash we could simply go:
213 | #
214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
215 | # set -- "${ARGS[@]}" "$@"
216 | #
217 | # but POSIX shell has neither arrays nor command substitution, so instead we
218 | # post-process each arg (as a line of input to sed) to backslash-escape any
219 | # character that might be a shell metacharacter, then use eval to reverse
220 | # that process (while maintaining the separation between arguments), and wrap
221 | # the whole thing up as a single "set" statement.
222 | #
223 | # This will of course break if any of these variables contains a newline or
224 | # an unmatched quote.
225 | #
226 |
227 | eval "set -- $(
228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
229 | xargs -n1 |
230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
231 | tr '\n' ' '
232 | )" '"$@"'
233 |
234 | exec "$JAVACMD" "$@"
235 |
--------------------------------------------------------------------------------
/jdk-transform/src/main/java/com/itsaky/androidide/jdktransform/Main.java:
--------------------------------------------------------------------------------
1 | package com.itsaky.androidide.jdktransform;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.File;
5 | import java.io.FileInputStream;
6 | import java.io.FileNotFoundException;
7 | import java.io.FileOutputStream;
8 | import java.io.IOException;
9 | import java.io.InputStream;
10 | import java.io.InputStreamReader;
11 | import java.nio.file.Files;
12 | import java.util.Objects;
13 | import java.util.TreeSet;
14 | import java.util.zip.ZipEntry;
15 | import java.util.zip.ZipFile;
16 | import java.util.zip.ZipInputStream;
17 | import java.util.zip.ZipOutputStream;
18 |
19 | /**
20 | * Generates a JDK image using the jlink tool with
21 | * a single java.base module which contains classes
22 | * from the Android SDK.
23 | *
24 | * CompilerModuleGenerator
25 | */
26 | public class Main {
27 |
28 | private final Arguments arg;
29 | private final Exec exec;
30 | private final String jlinkVersion;
31 |
32 | public Main(Arguments arg, Exec exec, String jlinkVersion) {
33 | this.arg = arg;
34 | this.exec = exec;
35 | this.jlinkVersion = jlinkVersion;
36 | }
37 |
38 | private File generate() throws FileNotFoundException, IOException, InterruptedException {
39 | System.out.println("Generating java.base module descriptor...");
40 |
41 | final var sb = new StringBuilder();
42 | final var packages = new TreeSet();
43 | sb.append("module java.base {");
44 |
45 | try (final var zip = new ZipFile(arg.androidJar);) {
46 | final var iterator = zip.entries();
47 | while (iterator.hasMoreElements()) {
48 | final var entry = iterator.nextElement();
49 | if (!entry.getName().endsWith(".class")) {
50 | continue;
51 | }
52 |
53 | var name = entry.getName();
54 | if (!name.contains("/")) {
55 | continue;
56 | }
57 |
58 | name = name.substring(0, name.lastIndexOf('/'));
59 | name = name.replace('/', '.');
60 | packages.add(name);
61 | }
62 | }
63 |
64 | System.out.println("Found " + packages.size() + " packages in android.jar");
65 | for (var name : packages) {
66 | sb.append("\n exports ");
67 | sb.append(name);
68 | sb.append(';');
69 | }
70 |
71 | sb.append("\n}");
72 |
73 | final var out = new File("./temp/module-info.java");
74 | out.getParentFile().delete();
75 | out.getParentFile().mkdirs();
76 |
77 | try (var outStream = new FileOutputStream(out)) {
78 | outStream.write(sb.toString().getBytes());
79 | outStream.flush();
80 | }
81 |
82 | if (!out.exists()) {
83 | throw new RuntimeException("Unable to generate module-info.java");
84 | }
85 |
86 | System.out.println("module-info.java has been written to " + out.getPath());
87 | return compileModuleDescriptor(out);
88 | }
89 |
90 | private File compileModuleDescriptor(File moduleInfoJava) throws IOException, InterruptedException {
91 | System.out.println("Compiling module descriptor...");
92 | final var builder = new ProcessBuilder(
93 | exec.javac.getAbsolutePath(),
94 | "--system=none",
95 | "--patch-module=java.base=" + arg.androidJar.getAbsolutePath(),
96 | "-d", moduleInfoJava.getParentFile().getAbsolutePath(), moduleInfoJava.getAbsolutePath());
97 | builder.redirectErrorStream(true);
98 | final var process = builder.start();
99 |
100 | new Thread(new InReader(process.getInputStream())).start();
101 |
102 | final var exit = process.waitFor();
103 | final var classFile = new File(moduleInfoJava.getParentFile(), "module-info.class");
104 |
105 | if (exit != 0 || !classFile.exists()) {
106 | throw new RuntimeException("Unable to compile module-info.java");
107 | }
108 |
109 | System.out.println("Successfully compiled module-info.java to " + classFile);
110 | return createModuleJar(classFile);
111 | }
112 |
113 | private File createModuleJar(File classFile) throws FileNotFoundException, IOException, InterruptedException {
114 | System.out.println("Creating modular jar file...");
115 | final var moduleJar = new File(classFile.getParentFile(), "java.base-module.jar");
116 | try (var out = new ZipOutputStream(new FileOutputStream(moduleJar));
117 | var zip = new ZipInputStream(new FileInputStream(arg.androidJar));) {
118 |
119 | // Write the module-info.class entry
120 | final var entry = new ZipEntry(classFile.getName());
121 | out.putNextEntry(entry);
122 | Files.copy(classFile.toPath(), out);
123 | out.closeEntry();
124 |
125 | // Write all the classes present in android.jar
126 | ZipEntry systemJarEntry;
127 | while ((systemJarEntry = zip.getNextEntry()) != null) {
128 | if (!systemJarEntry.getName().endsWith(".class")) {
129 | continue;
130 | }
131 |
132 | final var newJarEntry = new ZipEntry(systemJarEntry.getName());
133 | final byte[] data = new byte[1024];
134 | int read = -1;
135 |
136 | out.putNextEntry(newJarEntry);
137 | while ((read = zip.read(data)) != -1) {
138 | out.write(data, 0, read);
139 | }
140 |
141 | out.closeEntry();
142 | }
143 | }
144 |
145 | System.err.println("Module JAR has been succesfully created" + moduleJar);
146 |
147 | return createJmod(moduleJar);
148 | }
149 |
150 | private File createJmod(File moduleJar) throws IOException, InterruptedException {
151 | System.out.println("Generating Jmod file...");
152 | final var jmodOut = new File(moduleJar.getParentFile(), "java.base.jmod");
153 | final var builder = new ProcessBuilder(exec.jmod.getAbsolutePath(),
154 | "create",
155 | "--module-version", jlinkVersion,
156 | "--target-platform", "android",
157 | "--class-path", moduleJar.getAbsolutePath(),
158 | jmodOut.getAbsolutePath());
159 | builder.redirectErrorStream(true);
160 |
161 | final var process = builder.start();
162 |
163 | new Thread(new InReader(process.getInputStream())).start();
164 |
165 | final var exit = process.waitFor();
166 |
167 | if (exit != 0 || !jmodOut.exists()) {
168 | throw new RuntimeException("Unable to generate Jmod file for modular jar " + moduleJar);
169 | }
170 |
171 | System.out.println("Jmod file has successfully been generated to " + jmodOut);
172 |
173 | return createJdkImage(jmodOut);
174 | }
175 |
176 | private File createJdkImage(File jmodOut) throws IOException, InterruptedException {
177 | System.out.println("Creating JDK image...");
178 |
179 | final var builder = new ProcessBuilder(exec.jlink.getAbsolutePath(),
180 | "--module-path", jmodOut.getAbsolutePath(),
181 | "--add-modules", "java.base",
182 | "--output", arg.outputDir.getAbsolutePath(),
183 | "--disable-plugin", "system-modules");
184 | builder.redirectErrorStream(true);
185 |
186 | final var process = builder.start();
187 |
188 | new Thread(new InReader(process.getInputStream())).start();
189 |
190 | final var exit = process.waitFor();
191 |
192 | final var modulesFile = new File(arg.outputDir, "lib/modules");
193 | if (exit != 0 || !modulesFile.exists()) {
194 | throw new RuntimeException("Unable to generate JDK image. Process failed.");
195 | }
196 |
197 | System.out.println("JDK image has been successfully generated to output directory: " + arg.outputDir.getPath());
198 |
199 | return modulesFile;
200 | }
201 |
202 | public static void main(String[] args) throws Exception {
203 | try {
204 | final var arg = Arguments.parse(args);
205 | final var javaHome = findJavaHome();
206 | final var exec = Exec.instance(javaHome);
207 | final var jlinkVersion = findJlinkVersion(exec);
208 |
209 | System.out.println("Generating compiler module...");
210 | System.out.println("arg=" + arg + ", jlinkVersion=" + jlinkVersion);
211 |
212 | new Main(arg, exec, jlinkVersion).generate();
213 | } catch (Throwable th) {
214 | System.err.println();
215 | System.err.println(th.getMessage());
216 | System.err.println();
217 | System.err.println();
218 | printUsage();
219 | System.exit(1);
220 | }
221 | }
222 |
223 | private static void printUsage() {
224 | System.err.println("AndroidIDE JDK Transform");
225 | System.err.println(
226 | "This tool is used to generate the 'compiler module' (a custom JDK image) used in AndroidIDE.");
227 | System.err.println("The generated JDK image is used for code completions and actions in the IDE.");
228 | System.err.println();
229 | System.err.println("Usage - ");
230 | System.err.println(
231 | " -a, --android-jar Specify the android.jar file which will be used to generate the compiler module. Classes from this android.jar file will be included in the java.base module of the generated JDK image. REQUIRED.");
232 | System.err.println(
233 | " -o, --output-dir Specify the directory in which JDK image will be generated. Please note that this directory will be DELETED. This is an optional argument. By default, it is set to ''./compiler_module'.");
234 | }
235 |
236 | private static File findJavaHome() {
237 | final var prop = System.getProperty("java.home", null);
238 | if (prop != null) {
239 | return assertExistsAndGet(prop);
240 | }
241 |
242 | final var env = System.getenv("JAVA_HOME");
243 | if (env != null) {
244 | return assertExistsAndGet(env);
245 | }
246 |
247 | throw new RuntimeException("Cannot find JAVA_HOME");
248 | }
249 |
250 | private static File assertExistsAndGet(String prop) {
251 | final var file = new File(prop);
252 | if (!file.exists()) {
253 | throw new RuntimeException("JAVA_HOME is set to a directory which does not exist!");
254 | }
255 | return file;
256 | }
257 |
258 | private static String findJlinkVersion(Exec exec) throws IOException {
259 | final var builder = new ProcessBuilder(exec.jlink.getAbsolutePath(), "--version");
260 | final var process = builder.start();
261 | final var in = process.getInputStream();
262 | final var reader = new BufferedReader(new InputStreamReader(in));
263 | final var sb = new StringBuilder();
264 |
265 | int data = -1;
266 | while ((data = reader.read()) != -1) {
267 | sb.append((char) data);
268 | }
269 |
270 | assertNotBlank(sb.toString());
271 |
272 | return sb.toString().trim();
273 | }
274 |
275 | private static void assertNotBlank(String value) {
276 | if (value == null || value.trim().length() == 0) {
277 | throw new IllegalArgumentException(String.format("Invalid value: '%s'", value));
278 | }
279 | }
280 |
281 | private static void assertHasValue(final int last, int i, final String current) {
282 | if (i == last) {
283 | throw new IllegalArgumentException("No value specified for ".concat(current));
284 | }
285 | }
286 |
287 | static class Exec {
288 |
289 | final File javaHome;
290 | final File javac;
291 | final File jlink;
292 | final File jmod;
293 |
294 | public Exec(File javaHome) {
295 | this.javaHome = javaHome;
296 |
297 | final var bin = new File(javaHome, "bin");
298 | this.javac = new File(bin, "javac");
299 | this.jlink = new File(bin, "jlink");
300 | this.jmod = new File(bin, "jmod");
301 | }
302 |
303 | static Exec instance(File javaHome) {
304 | return new Exec(javaHome);
305 | }
306 |
307 | @Override
308 | public String toString() {
309 | return "Exec [javaHome=" + javaHome + ", jlink=" + jlink + ", jmod=" + jmod + "]";
310 | }
311 | }
312 |
313 | static class Arguments {
314 | File androidJar;
315 | File outputDir;
316 |
317 | static Arguments parse(String... args) {
318 | Objects.requireNonNull(args);
319 |
320 | final var arg = new Arguments();
321 |
322 | final var size = args.length;
323 | final var last = size - 1;
324 | for (int i = 0; i < args.length; i++) {
325 | final var current = args[i];
326 | String value = parseValue(args, current, last, i);
327 | if (Opts.optAndroidJar.equals(current) || Opts.optAndroidJar_short.equals(current)) {
328 | arg.androidJar = new File(value);
329 | i++;
330 | } else if (Opts.optOutDir.equals(current) || Opts.optOutDir_short.equals(current)) {
331 | arg.outputDir = new File(value);
332 | i++;
333 | }
334 | }
335 |
336 | if (arg.androidJar == null) {
337 | throw new IllegalArgumentException("android.jar file must be specified!");
338 | }
339 |
340 | if (arg.outputDir == null) {
341 | arg.outputDir = new File("./compiler_module");
342 | }
343 |
344 | if (arg.outputDir.exists()) {
345 | arg.outputDir.delete();
346 | }
347 |
348 | return arg;
349 | }
350 |
351 | private static String parseValue(String[] args, String current, int last, int i) {
352 | assertHasValue(last, i, current);
353 | final var value = args[++i];
354 | assertNotBlank(value);
355 | return value;
356 | }
357 |
358 | @Override
359 | public String toString() {
360 | return "Arguments [androidJar=" + androidJar + ", outputDir=" + outputDir + "]";
361 | }
362 | }
363 |
364 | static class Opts {
365 | static final String optAndroidJar = "--android-jar";
366 | static final String optAndroidJar_short = "-a";
367 |
368 | static final String optOutDir = "--output-dir";
369 | static final String optOutDir_short = "-o";
370 | }
371 |
372 | static class InReader implements Runnable {
373 |
374 | private final InputStream in;
375 |
376 | public InReader(InputStream in) {
377 | this.in = in;
378 | }
379 |
380 | @Override
381 | public void run() {
382 | try (var reader = new BufferedReader(new InputStreamReader(in))) {
383 | String line;
384 |
385 | while ((line = reader.readLine()) != null) {
386 | System.err.println(line);
387 | }
388 | } catch (IOException e) {
389 | e.printStackTrace();
390 | }
391 | }
392 | }
393 | }
--------------------------------------------------------------------------------