Merge: Android support improvements
[nit.git] / src / platform / android.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Compile program for the Android platform
18 module android
19
20 import platform
21 import compiler::abstract_compiler
22 import ffi
23 intrude import ffi::extra_java_files
24 import android_annotations
25
26 redef class ToolContext
27 redef fun platform_from_name(name)
28 do
29 if name == "android" then return new AndroidPlatform
30 return super
31 end
32 end
33
34 class AndroidPlatform
35 super Platform
36
37 redef fun supports_libgc do return true
38
39 redef fun supports_libunwind do return false
40
41 redef fun supports_linker_script do return false
42
43 redef fun toolchain(toolcontext) do return new AndroidToolchain(toolcontext)
44 end
45
46 class AndroidToolchain
47 super MakefileToolchain
48
49 var android_project_root: nullable String = null
50
51 redef fun compile_dir
52 do
53 var android_project_root = "{super}/android/"
54 self.android_project_root = android_project_root
55 return "{android_project_root}/jni/nit_compile/"
56 end
57
58 redef fun default_outname(mainmodule) do return "{mainmodule.name}.apk"
59
60 redef fun write_files(compiler, compile_dir, cfiles)
61 do
62 var android_project_root = android_project_root.as(not null)
63 var project = toolcontext.modelbuilder.android_project_for(compiler.mainmodule)
64 var short_project_name = compiler.mainmodule.name.replace("-", "_")
65 var release = toolcontext.opt_release.value
66
67 var app_name = project.name
68 if app_name == null then app_name = compiler.mainmodule.name
69 if not release then app_name += " Debug"
70
71 var app_package = project.java_package
72 if app_package == null then app_package = "org.nitlanguage.{short_project_name}"
73 if not release then app_package += "_debug"
74
75 var app_version = project.version
76 if app_version == null then app_version = "1.0"
77
78 var app_min_api = project.min_api
79 if app_min_api == null then app_min_api = 10
80
81 var app_target_api = project.target_api
82 if app_target_api == null then app_target_api = app_min_api
83
84 var app_max_api = ""
85 if project.max_api != null then app_max_api = "android:maxSdkVersion=\"{project.max_api.as(not null)}\""
86
87 # Clear the previous android project, so there is no "existing project warning"
88 # or conflict between Java files of different projects
89 if android_project_root.file_exists then android_project_root.rmdir
90
91 var args = ["android", "-s",
92 "create", "project",
93 "--name", short_project_name,
94 "--target", "android-{app_target_api}",
95 "--path", android_project_root,
96 "--package", app_package,
97 "--activity", short_project_name]
98 toolcontext.exec_and_check(args, "Android project error")
99
100 # create compile_dir
101 var dir = "{android_project_root}/jni/"
102 if not dir.file_exists then dir.mkdir
103
104 dir = compile_dir
105 if not dir.file_exists then dir.mkdir
106
107 # compile normal C files
108 super(compiler, compile_dir, cfiles)
109
110 # Gather extra C files generated elsewhere than in super
111 for f in compiler.extern_bodies do
112 if f isa ExternCFile then cfiles.add(f.filename.basename(""))
113 end
114
115 # Is there an icon?
116 var resolutions = ["ldpi", "mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"]
117 var icon_available = false
118 for res in resolutions do
119 var path = "res/drawable-{res}/icon.png"
120 if path.file_exists then
121 icon_available = true
122 break
123 end
124 end
125
126 var icon_declaration
127 if icon_available then
128 icon_declaration = "android:icon=\"@drawable/icon\""
129 else icon_declaration = ""
130
131 # Also copy over the java files
132 dir = "{android_project_root}/src/"
133 for mmodule in compiler.mainmodule.in_importation.greaters do
134 var extra_java_files = mmodule.extra_java_files
135 if extra_java_files != null then for file in extra_java_files do
136 var path = file.filename
137 path.file_copy_to(dir/path.basename(""))
138 end
139 end
140
141 ## Generate delagating makefile
142 dir = "{android_project_root}/jni/"
143 """
144 include $(call all-subdir-makefiles)
145 """.write_to_file("{dir}/Android.mk")
146
147 ### generate makefile into "{compile_dir}/Android.mk"
148 dir = compile_dir
149 """
150 LOCAL_PATH := $(call my-dir)
151 include $(CLEAR_VARS)
152
153 LOCAL_CFLAGS := -D ANDROID -D WITH_LIBGC
154 LOCAL_MODULE := main
155 LOCAL_SRC_FILES := \\
156 {{{cfiles.join(" \\\n")}}}
157 LOCAL_LDLIBS := -llog -landroid -lEGL -lGLESv1_CM -lz libgc.a
158 LOCAL_STATIC_LIBRARIES := android_native_app_glue png
159
160 include $(BUILD_SHARED_LIBRARY)
161
162 $(call import-module,android/native_app_glue)
163 """.write_to_file("{dir}/Android.mk")
164
165 ### generate AndroidManifest.xml
166 dir = android_project_root
167 """<?xml version="1.0" encoding="utf-8"?>
168 <!-- BEGIN_INCLUDE(manifest) -->
169 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
170 package="{{{app_package}}}"
171 android:versionCode="{{{project.version_code}}}"
172 android:versionName="{{{app_version}}}">
173
174 <!-- This is the platform API where NativeActivity was introduced. -->
175 <uses-sdk
176 android:minSdkVersion="{{{app_min_api}}}"
177 android:targetSdkVersion="{{{app_target_api}}}"
178 {{{app_max_api}}} />
179
180 <application
181 android:label="@string/app_name"
182 android:hasCode="true"
183 android:debuggable="{{{not release}}}"
184 {{{icon_declaration}}}
185 android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|screenLayout|fontScale|uiMode|orientation">
186
187 <!-- Our activity is the built-in NativeActivity framework class.
188 This will take care of integrating with our NDK code. -->
189 <activity android:name="android.app.NativeActivity"
190 android:label="@string/app_name"
191 {{{project.manifest_activity_attributes.join("\n")}}}
192 {{{icon_declaration}}}>
193 <!-- Tell NativeActivity the name of our .so -->
194 <meta-data android:name=\"android.app.lib_name\"
195 android:value=\"main\" />
196 <intent-filter>
197 <action android:name="android.intent.action.MAIN" />
198 <category android:name="android.intent.category.LAUNCHER" />
199 </intent-filter>
200 </activity>
201
202 {{{project.manifest_application_lines.join("\n")}}}
203
204 </application>
205
206 {{{project.manifest_lines.join("\n")}}}
207
208 </manifest>
209 <!-- END_INCLUDE(manifest) -->
210 """.write_to_file("{dir}/AndroidManifest.xml")
211
212 ### Link to png sources
213 # libpng is not available on Android NDK
214 # FIXME make obtionnal when we have alternatives to mnit
215 var nit_dir = toolcontext.nit_dir
216 var share_dir = nit_dir/"share/"
217 if not share_dir.file_exists then
218 print "Android project error: Nit share directory not found, please use the environment variable NIT_DIR"
219 exit 1
220 end
221 share_dir = share_dir.realpath
222 var target_png_dir = "{android_project_root}/jni/png"
223 if not target_png_dir.file_exists then
224 toolcontext.exec_and_check(["ln", "-s", "{share_dir}/png/", target_png_dir], "Android project error")
225 end
226
227 # Ensure that android-setup-libgc.sh has been executed
228 if not "{share_dir}/libgc/lib".file_exists then
229 toolcontext.exec_and_check(["{share_dir}/libgc/android-setup-libgc.sh"], "Android project error")
230 end
231
232 # Copy GC files
233 toolcontext.exec_and_check(["cp", "{share_dir}/libgc/lib/libgc.a", "{android_project_root}/libgc.a"], "Android project error")
234 toolcontext.exec_and_check(["ln", "-s", "{share_dir}/libgc/include/gc/", "{android_project_root}/jni/nit_compile/gc"], "Android project error")
235
236 ### Link to assets (for mnit and others)
237 # This will be accessed from `android_project_root`
238 var assets_dir
239 if compiler.mainmodule.location.file != null then
240 # it is a real file, use "{file}/../assets"
241 assets_dir = "{compiler.mainmodule.location.file.filename.dirname}/../assets"
242 else
243 # probably used -m, use "."
244 assets_dir = "assets"
245 end
246 if assets_dir.file_exists then
247 assets_dir = assets_dir.realpath
248 var target_assets_dir = "{android_project_root}/assets"
249 if not target_assets_dir.file_exists then
250 toolcontext.exec_and_check(["ln", "-s", assets_dir, target_assets_dir], "Android project error")
251 end
252 end
253
254 ### Copy resources and libs where expected by the SDK
255 var project_root
256 if compiler.mainmodule.location.file != null then
257 # it is a real file, use "{file}/../res"
258 project_root = "{compiler.mainmodule.location.file.filename.dirname}/.."
259 else
260 # probably used -m, use "."
261 project_root = "."
262 end
263
264 # Android resources folder
265 var res_dir = project_root / "res"
266 if res_dir.file_exists then
267 # copy the res folder to .nit_compile
268 res_dir = res_dir.realpath
269 toolcontext.exec_and_check(["cp", "-R", res_dir, android_project_root], "Android project error")
270 end
271
272 if not res_dir.file_exists or not "{res_dir}/values/strings.xml".file_exists then
273 # Create our own custom `res/values/string.xml` with the App name
274 """<?xml version="1.0" encoding="utf-8"?>
275 <resources>
276 <string name="app_name">{{{app_name}}}</string>
277 </resources>""".write_to_file "{dir}/res/values/strings.xml"
278 end
279
280 # Android libs folder
281 var libs_dir = project_root / "libs"
282 if libs_dir.file_exists then
283 toolcontext.exec_and_check(["cp", "-r", libs_dir, android_project_root], "Android project error")
284 end
285 end
286
287 redef fun write_makefile(compiler, compile_dir, cfiles)
288 do
289 # Do nothing, already done in `write_files`
290 end
291
292 redef fun compile_c_code(compiler, compile_dir)
293 do
294 var android_project_root = android_project_root.as(not null)
295 var short_project_name = compiler.mainmodule.name.replace("-", "_")
296 var release = toolcontext.opt_release.value
297
298 # Compile C code (and thus Nit)
299 toolcontext.exec_and_check(["ndk-build", "-s", "-j", "-C", android_project_root], "Android project error")
300
301 # Generate the apk
302 var args = ["ant", "-q", "-f", android_project_root+"/build.xml"]
303 if release then
304 args.add "release"
305 else args.add "debug"
306 toolcontext.exec_and_check(args, "Android project error")
307
308 # Move the apk to the target
309 var outname = outfile(compiler.mainmodule)
310
311 if release then
312 var apk_path = "{android_project_root}/bin/{short_project_name}-release-unsigned.apk"
313
314 # Sign APK
315 var keystore_path= "KEYSTORE".environ
316 var key_alias= "KEY_ALIAS".environ
317 var tsa_server= "TSA_SERVER".environ
318
319 if key_alias.is_empty then
320 toolcontext.fatal_error(null,
321 "Fatal Error: the environment variable `KEY_ALIAS` must be set to use the `--release` option on Android projects.")
322 end
323
324 args = ["jarsigner", "-sigalg", "MD5withRSA", "-digestalg", "SHA1", apk_path, key_alias]
325
326 ## Use a custom keystore
327 if not keystore_path.is_empty then args.add_all(["-keystore", keystore_path])
328
329 ## Use a TSA server
330 if not tsa_server.is_empty then args.add_all(["-tsa", tsa_server])
331
332 toolcontext.exec_and_check(args, "Android project error")
333
334 # Clean output file
335 if outname.to_path.exists then outname.to_path.delete
336
337 # Align APK
338 args = ["zipalign", "4", apk_path, outname]
339 toolcontext.exec_and_check(args, "Android project error")
340 else
341 # Move to the expected output path
342 args = ["mv", "{android_project_root}/bin/{short_project_name}-debug.apk", outname]
343 toolcontext.exec_and_check(args, "Android project error")
344 end
345 end
346 end
347
348 redef class JavaClassTemplate
349 redef fun write_to_files(compdir)
350 do
351 var jni_path = "jni/nit_compile/"
352 if compdir.has_suffix(jni_path) then
353 var path = "{compdir.substring(0, compdir.length-jni_path.length)}/src/"
354 return super(path)
355 else return super
356 end
357 end