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