Android: add Android Studio support, completely redone java part (#9066)
[oweals/minetest.git] / src / porting_android.cpp
1 /*
2 Minetest
3 Copyright (C) 2014 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #ifndef __ANDROID__
21 #error This file may only be compiled for android!
22 #endif
23
24 #include "util/numeric.h"
25 #include "porting.h"
26 #include "porting_android.h"
27 #include "threading/thread.h"
28 #include "config.h"
29 #include "filesys.h"
30 #include "log.h"
31
32 #include <sstream>
33 #include <exception>
34 #include <cstdlib>
35
36 #ifdef GPROF
37 #include "prof.h"
38 #endif
39
40 extern int main(int argc, char *argv[]);
41
42 void android_main(android_app *app)
43 {
44         int retval = 0;
45         porting::app_global = app;
46
47         Thread::setName("Main");
48
49         try {
50                 app_dummy();
51                 char *argv[] = {strdup(PROJECT_NAME), NULL};
52                 main(ARRLEN(argv) - 1, argv);
53                 free(argv[0]);
54         } catch (std::exception &e) {
55                 errorstream << "Uncaught exception in main thread: " << e.what() << std::endl;
56                 retval = -1;
57         } catch (...) {
58                 errorstream << "Uncaught exception in main thread!" << std::endl;
59                 retval = -1;
60         }
61
62         porting::cleanupAndroid();
63         infostream << "Shutting down." << std::endl;
64         exit(retval);
65 }
66
67 /* handler for finished message box input */
68 /* Intentionally NOT in namespace porting */
69 /* TODO this doesn't work as expected, no idea why but there's a workaround   */
70 /* for it right now */
71 extern "C" {
72         JNIEXPORT void JNICALL Java_net_minetest_minetest_GameActivity_putMessageBoxResult(
73                         JNIEnv * env, jclass thiz, jstring text)
74         {
75                 errorstream << "Java_net_minetest_minetest_GameActivity_putMessageBoxResult got: "
76                                 << std::string((const char*)env->GetStringChars(text,0))
77                                 << std::endl;
78         }
79 }
80
81 namespace porting {
82
83 std::string path_storage = DIR_DELIM "sdcard" DIR_DELIM;
84
85 android_app* app_global;
86 JNIEnv*      jnienv;
87 jclass       nativeActivity;
88
89 jclass findClass(std::string classname)
90 {
91         if (jnienv == 0) {
92                 return 0;
93         }
94
95         jclass nativeactivity = jnienv->FindClass("android/app/NativeActivity");
96         jmethodID getClassLoader =
97                         jnienv->GetMethodID(nativeactivity,"getClassLoader",
98                                         "()Ljava/lang/ClassLoader;");
99         jobject cls =
100                         jnienv->CallObjectMethod(app_global->activity->clazz, getClassLoader);
101         jclass classLoader = jnienv->FindClass("java/lang/ClassLoader");
102         jmethodID findClass =
103                         jnienv->GetMethodID(classLoader, "loadClass",
104                                         "(Ljava/lang/String;)Ljava/lang/Class;");
105         jstring strClassName =
106                         jnienv->NewStringUTF(classname.c_str());
107         return (jclass) jnienv->CallObjectMethod(cls, findClass, strClassName);
108 }
109
110 void initAndroid()
111 {
112         porting::jnienv = NULL;
113         JavaVM *jvm = app_global->activity->vm;
114         JavaVMAttachArgs lJavaVMAttachArgs;
115         lJavaVMAttachArgs.version = JNI_VERSION_1_6;
116         lJavaVMAttachArgs.name = PROJECT_NAME_C "NativeThread";
117         lJavaVMAttachArgs.group = NULL;
118 #ifdef NDEBUG
119         // This is a ugly hack as arm v7a non debuggable builds crash without this
120         // printf ... if someone finds out why please fix it!
121         infostream << "Attaching native thread. " << std::endl;
122 #endif
123         if ( jvm->AttachCurrentThread(&porting::jnienv, &lJavaVMAttachArgs) == JNI_ERR) {
124                 errorstream << "Failed to attach native thread to jvm" << std::endl;
125                 exit(-1);
126         }
127
128         nativeActivity = findClass("net/minetest/minetest/GameActivity");
129         if (nativeActivity == 0) {
130                 errorstream <<
131                         "porting::initAndroid unable to find java native activity class" <<
132                         std::endl;
133         }
134
135 #ifdef GPROF
136         /* in the start-up code */
137         __android_log_print(ANDROID_LOG_ERROR, PROJECT_NAME_C,
138                         "Initializing GPROF profiler");
139         monstartup("libminetest.so");
140 #endif
141 }
142
143 void cleanupAndroid()
144 {
145
146 #ifdef GPROF
147         errorstream << "Shutting down GPROF profiler" << std::endl;
148         setenv("CPUPROFILE", (path_user + DIR_DELIM + "gmon.out").c_str(), 1);
149         moncleanup();
150 #endif
151
152         JavaVM *jvm = app_global->activity->vm;
153         jvm->DetachCurrentThread();
154 }
155
156 static std::string javaStringToUTF8(jstring js)
157 {
158         std::string str;
159         // Get string as a UTF-8 c-string
160         const char *c_str = jnienv->GetStringUTFChars(js, NULL);
161         // Save it
162         str = c_str;
163         // And free the c-string
164         jnienv->ReleaseStringUTFChars(js, c_str);
165         return str;
166 }
167
168 // Calls static method if obj is NULL
169 static std::string getAndroidPath(jclass cls, jobject obj, jclass cls_File,
170                 jmethodID mt_getAbsPath, const char *getter)
171 {
172         // Get getter method
173         jmethodID mt_getter;
174         if (obj)
175                 mt_getter = jnienv->GetMethodID(cls, getter,
176                                 "()Ljava/io/File;");
177         else
178                 mt_getter = jnienv->GetStaticMethodID(cls, getter,
179                                 "()Ljava/io/File;");
180
181         // Call getter
182         jobject ob_file;
183         if (obj)
184                 ob_file = jnienv->CallObjectMethod(obj, mt_getter);
185         else
186                 ob_file = jnienv->CallStaticObjectMethod(cls, mt_getter);
187
188         // Call getAbsolutePath
189         jstring js_path = (jstring) jnienv->CallObjectMethod(ob_file,
190                         mt_getAbsPath);
191
192         return javaStringToUTF8(js_path);
193 }
194
195 void initializePathsAndroid()
196 {
197         // Get Environment class
198         jclass cls_Env = jnienv->FindClass("android/os/Environment");
199         // Get File class
200         jclass cls_File = jnienv->FindClass("java/io/File");
201         // Get getAbsolutePath method
202         jmethodID mt_getAbsPath = jnienv->GetMethodID(cls_File,
203                                 "getAbsolutePath", "()Ljava/lang/String;");
204
205         path_cache   = getAndroidPath(nativeActivity, app_global->activity->clazz,
206                         cls_File, mt_getAbsPath, "getCacheDir");
207         path_storage = getAndroidPath(cls_Env, NULL, cls_File, mt_getAbsPath,
208                         "getExternalStorageDirectory");
209         path_user    = path_storage + DIR_DELIM + PROJECT_NAME_C;
210         path_share   = path_storage + DIR_DELIM + PROJECT_NAME_C;
211
212         migrateCachePath();
213 }
214
215 void showInputDialog(const std::string& acceptButton, const  std::string& hint,
216                 const std::string& current, int editType)
217 {
218         jmethodID showdialog = jnienv->GetMethodID(nativeActivity,"showDialog",
219                 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V");
220
221         if (showdialog == 0) {
222                 assert("porting::showInputDialog unable to find java show dialog method" == 0);
223         }
224
225         jstring jacceptButton = jnienv->NewStringUTF(acceptButton.c_str());
226         jstring jhint         = jnienv->NewStringUTF(hint.c_str());
227         jstring jcurrent      = jnienv->NewStringUTF(current.c_str());
228         jint    jeditType     = editType;
229
230         jnienv->CallVoidMethod(app_global->activity->clazz, showdialog,
231                         jacceptButton, jhint, jcurrent, jeditType);
232 }
233
234 int getInputDialogState()
235 {
236         jmethodID dialogstate = jnienv->GetMethodID(nativeActivity,
237                         "getDialogState", "()I");
238
239         if (dialogstate == 0) {
240                 assert("porting::getInputDialogState unable to find java dialog state method" == 0);
241         }
242
243         return jnienv->CallIntMethod(app_global->activity->clazz, dialogstate);
244 }
245
246 std::string getInputDialogValue()
247 {
248         jmethodID dialogvalue = jnienv->GetMethodID(nativeActivity,
249                         "getDialogValue", "()Ljava/lang/String;");
250
251         if (dialogvalue == 0) {
252                 assert("porting::getInputDialogValue unable to find java dialog value method" == 0);
253         }
254
255         jobject result = jnienv->CallObjectMethod(app_global->activity->clazz,
256                         dialogvalue);
257
258         const char* javachars = jnienv->GetStringUTFChars((jstring) result,0);
259         std::string text(javachars);
260         jnienv->ReleaseStringUTFChars((jstring) result, javachars);
261
262         return text;
263 }
264
265 #ifndef SERVER
266 float getDisplayDensity()
267 {
268         static bool firstrun = true;
269         static float value = 0;
270
271         if (firstrun) {
272                 jmethodID getDensity = jnienv->GetMethodID(nativeActivity, "getDensity",
273                                         "()F");
274
275                 if (getDensity == 0) {
276                         assert("porting::getDisplayDensity unable to find java getDensity method" == 0);
277                 }
278
279                 value = jnienv->CallFloatMethod(app_global->activity->clazz, getDensity);
280                 firstrun = false;
281         }
282         return value;
283 }
284
285 v2u32 getDisplaySize()
286 {
287         static bool firstrun = true;
288         static v2u32 retval;
289
290         if (firstrun) {
291                 jmethodID getDisplayWidth = jnienv->GetMethodID(nativeActivity,
292                                 "getDisplayWidth", "()I");
293
294                 if (getDisplayWidth == 0) {
295                         assert("porting::getDisplayWidth unable to find java getDisplayWidth method" == 0);
296                 }
297
298                 retval.X = jnienv->CallIntMethod(app_global->activity->clazz,
299                                 getDisplayWidth);
300
301                 jmethodID getDisplayHeight = jnienv->GetMethodID(nativeActivity,
302                                 "getDisplayHeight", "()I");
303
304                 if (getDisplayHeight == 0) {
305                         assert("porting::getDisplayHeight unable to find java getDisplayHeight method" == 0);
306                 }
307
308                 retval.Y = jnienv->CallIntMethod(app_global->activity->clazz,
309                                 getDisplayHeight);
310
311                 firstrun = false;
312         }
313         return retval;
314 }
315 #endif // ndef SERVER
316 }