Merge: app.nit: Intro the `app_files` annotation, and use it in calculator
[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 name do return "android"
38
39 redef fun supports_libgc do return false
40
41 redef fun supports_libunwind do return false
42
43 redef fun supports_linker_script do return false
44
45 redef fun toolchain(toolcontext, compiler) do return new AndroidToolchain(toolcontext, compiler)
46 end
47
48 class AndroidToolchain
49 super MakefileToolchain
50
51 var android_project_root: nullable String = null
52
53 redef fun compile_dir
54 do
55 var android_project_root = "{root_compile_dir}/android/"
56 self.android_project_root = android_project_root
57 return "{android_project_root}/jni/nit_compile/"
58 end
59
60 redef fun default_outname do return "{super}.apk"
61
62 redef fun write_files(compile_dir, cfiles)
63 do
64 var android_project_root = android_project_root.as(not null)
65 var project = new AndroidProject(toolcontext.modelbuilder, compiler.mainmodule)
66 var release = toolcontext.opt_release.value
67
68 var app_name = project.name
69 if not release then app_name += " Debug"
70
71 var short_project_name = project.short_name
72
73 var app_package = project.namespace
74 if not release then app_package += "_debug"
75
76 var app_version = project.version
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 # Insert an importation of the generated R class to all Java files from the FFI
108 for mod in compiler.mainmodule.in_importation.greaters do
109 var java_ffi_file = mod.java_file
110 if java_ffi_file != null then java_ffi_file.add "import {app_package}.R;"
111 end
112
113 # compile normal C files
114 super
115
116 # Gather extra C files generated elsewhere than in super
117 for f in compiler.extern_bodies do
118 if f isa ExternCFile then cfiles.add(f.filename.basename)
119 end
120
121 var project_root = "."
122 var mpackage = compiler.mainmodule.first_real_mmodule.mpackage
123 if mpackage != null then
124 var root = mpackage.root
125 if root != null then
126 var filepath = root.filepath
127 if filepath != null then
128 project_root = filepath
129 end
130 end
131 end
132
133 # Set the default pretty application name
134 """<?xml version="1.0" encoding="utf-8"?>
135 <resources>
136 <string name="app_name">{{{app_name}}}</string>
137 </resources>""".write_to_file "{android_project_root}/res/values/strings.xml"
138
139 # Copy assets, resources and libs where expected by the SDK
140
141 ## Collect path to all possible folder where we can find the `android` folder
142 var app_files = [project_root]
143 app_files.add_all project.files
144
145 for path in app_files do
146 # Copy the assets folder
147 var assets_dir = path / "assets"
148 if assets_dir.file_exists then
149 assets_dir = assets_dir.realpath
150 toolcontext.exec_and_check(["cp", "-r", assets_dir, android_project_root], "Android project error")
151 end
152
153 # Copy the whole `android` folder
154 var android_dir = path / "android"
155 if android_dir.file_exists then
156 android_dir = android_dir.realpath
157 toolcontext.exec_and_check(["cp", "-r", android_dir, root_compile_dir], "Android project error")
158 end
159 end
160
161 # Is there an icon?
162 var resolutions = ["ldpi", "mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"]
163 var icon_available = false
164 for res in resolutions do
165 var path = project_root / "android/res/drawable-{res}/icon.png"
166 if path.file_exists then
167 icon_available = true
168 break
169 end
170 end
171
172 var icon_declaration
173 if icon_available then
174 icon_declaration = "android:icon=\"@drawable/icon\""
175 else icon_declaration = ""
176
177 # Also copy over the java files
178 dir = "{android_project_root}/src/"
179 for mmodule in compiler.mainmodule.in_importation.greaters do
180 var extra_java_files = mmodule.extra_java_files
181 if extra_java_files != null then for file in extra_java_files do
182 var path = file.filename
183 path.file_copy_to(dir/path.basename)
184 end
185 end
186
187 ## Generate Application.mk
188 dir = "{android_project_root}/jni/"
189 """
190 APP_ABI := armeabi armeabi-v7a x86
191 APP_PLATFORM := android-{{{app_target_api}}}
192 """.write_to_file "{dir}/Application.mk"
193
194 ## Generate delegating makefile
195 """
196 include $(call all-subdir-makefiles)
197 """.write_to_file "{dir}/Android.mk"
198
199 # Gather ldflags for Android
200 var ldflags = new Array[String]
201 var platform_name = "android"
202 for mmodule in compiler.mainmodule.in_importation.greaters do
203 if mmodule.ldflags.keys.has(platform_name) then
204 ldflags.add_all mmodule.ldflags[platform_name]
205 end
206 end
207
208 ### generate makefile into "{compile_dir}/Android.mk"
209 dir = compile_dir
210 """
211 LOCAL_PATH := $(call my-dir)
212 include $(CLEAR_VARS)
213
214 LOCAL_CFLAGS := -D ANDROID -D WITH_LIBGC
215 LOCAL_MODULE := main
216 LOCAL_SRC_FILES := \\
217 {{{cfiles.join(" \\\n")}}}
218 LOCAL_LDLIBS := {{{ldflags.join(" ")}}} $(TARGET_ARCH)/libgc.a
219 LOCAL_STATIC_LIBRARIES := android_native_app_glue
220
221 include $(BUILD_SHARED_LIBRARY)
222
223 $(call import-module,android/native_app_glue)
224 """.write_to_file("{dir}/Android.mk")
225
226 ### generate AndroidManifest.xml
227 dir = android_project_root
228 var manifest_file = new FileWriter.open("{dir}/AndroidManifest.xml")
229 manifest_file.write """
230 <?xml version="1.0" encoding="utf-8"?>
231 <!-- BEGIN_INCLUDE(manifest) -->
232 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
233 package="{{{app_package}}}"
234 android:versionCode="{{{project.version_code}}}"
235 android:versionName="{{{app_version}}}">
236
237 <uses-sdk
238 android:minSdkVersion="{{{app_min_api}}}"
239 android:targetSdkVersion="{{{app_target_api}}}"
240 {{{app_max_api}}} />
241
242 <application
243 android:label="@string/app_name"
244 android:hasCode="true"
245 android:debuggable="{{{not release}}}"
246 {{{icon_declaration}}}>
247 """
248
249 for activity in project.activities do
250 manifest_file.write """
251 <activity android:name="{{{activity}}}"
252 android:label="@string/app_name"
253 {{{project.manifest_activity_attributes.join("\n")}}}
254 {{{icon_declaration}}}>
255 <intent-filter>
256 <action android:name="android.intent.action.MAIN" />
257 <category android:name="android.intent.category.LAUNCHER" />
258 </intent-filter>
259 </activity>
260 """
261 end
262
263 manifest_file.write """
264 {{{project.manifest_application_lines.join("\n")}}}
265
266 </application>
267
268 {{{project.manifest_lines.join("\n")}}}
269
270 </manifest>
271 <!-- END_INCLUDE(manifest) -->
272 """
273 manifest_file.close
274
275 ### Link to png sources
276 # libpng is not available on Android NDK
277 # FIXME make optional when we have alternatives to mnit
278 var nit_dir = toolcontext.nit_dir
279 var share_dir = nit_dir/"share/"
280 if not share_dir.file_exists then
281 print "Android project error: Nit share directory not found, please use the environment variable NIT_DIR"
282 exit 1
283 end
284 share_dir = share_dir.realpath
285
286 # Ensure that android-setup-libgc.sh has been executed
287 if not "{share_dir}/libgc/arm/lib".file_exists then
288 toolcontext.exec_and_check(["{share_dir}/libgc/android-setup-libgc.sh"], "Android project error")
289 end
290
291 # Copy GC files
292 for arch in ["arm", "x86", "mips"] do
293 dir = android_project_root/arch
294 dir.mkdir
295 toolcontext.exec_and_check(["cp", "{share_dir}/libgc/{arch}/lib/libgc.a",
296 dir/"libgc.a"], "Android project error")
297 end
298
299 toolcontext.exec_and_check(["ln", "-s", "{share_dir}/libgc/arm/include/gc/",
300 "{compile_dir}/gc"], "Android project error")
301 end
302
303 redef fun write_makefile(compile_dir, cfiles)
304 do
305 # Do nothing, already done in `write_files`
306 end
307
308 redef fun compile_c_code(compile_dir)
309 do
310 var android_project_root = android_project_root.as(not null)
311 var short_project_name = compiler.mainmodule.name.replace("-", "_")
312 var release = toolcontext.opt_release.value
313
314 # Compile C code (and thus Nit)
315 toolcontext.exec_and_check(["ndk-build", "-s", "-j", "-C", android_project_root], "Android project error")
316
317 # Generate the apk
318 var args = ["ant", "-f", android_project_root+"/build.xml"]
319 if release then
320 args.add "release"
321 else args.add "debug"
322 toolcontext.exec_and_check(args, "Android project error")
323
324 # Move the apk to the target
325 var outname = outfile(compiler.mainmodule)
326
327 if release then
328 var apk_path = "{android_project_root}/bin/{short_project_name}-release-unsigned.apk"
329
330 # Sign APK
331 var keystore_path= "KEYSTORE".environ
332 var key_alias= "KEY_ALIAS".environ
333 var tsa_server= "TSA_SERVER".environ
334
335 if key_alias.is_empty then
336 toolcontext.warning(null, "key-alias",
337 "Warning: the environment variable `KEY_ALIAS` is not set, the APK file will not be signed.")
338
339 # Just move the unsigned APK to outname
340 args = ["mv", apk_path, outname]
341 toolcontext.exec_and_check(args, "Android project error")
342 return
343 end
344
345 # We have a key_alias, try to sign the APK
346 args = ["jarsigner", "-sigalg", "MD5withRSA", "-digestalg", "SHA1", apk_path, key_alias]
347
348 ## Use a custom keystore
349 if not keystore_path.is_empty then args.add_all(["-keystore", keystore_path])
350
351 ## Use a TSA server
352 if not tsa_server.is_empty then args.add_all(["-tsa", tsa_server])
353
354 toolcontext.exec_and_check(args, "Android project error")
355
356 # Clean output file
357 if outname.to_path.exists then outname.to_path.delete
358
359 # Align APK
360 args = ["zipalign", "4", apk_path, outname]
361 toolcontext.exec_and_check(args, "Android project error")
362 else
363 # Move to the expected output path
364 args = ["mv", "{android_project_root}/bin/{short_project_name}-debug.apk", outname]
365 toolcontext.exec_and_check(args, "Android project error")
366 end
367 end
368 end
369
370 redef class JavaClassTemplate
371 redef fun write_to_files(compdir)
372 do
373 var jni_path = "jni/nit_compile/"
374 if compdir.has_suffix(jni_path) then
375 var path = "{compdir.substring(0, compdir.length-jni_path.length)}/src/"
376 return super(path)
377 else return super
378 end
379 end