lib/android: implement `TextAsset`
[nit.git] / lib / android / assets.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Implementation of `app::assets`
16 #
17 # This module is a client of `assets_and_resources` as the latter
18 # covers the services of Android.
19 module assets
20
21 intrude import assets_and_resources
22
23 redef class TextAsset
24 redef fun load
25 do
26 jni_env.push_local_frame 8
27
28 var manager = app.asset_manager
29 var stream = manager.open(path)
30 if stream.is_java_null then
31 self.error = new Error("Failed to open asset at '{path}'")
32 jni_env.pop_local_frame
33 self.to_s = ""
34 return ""
35 end
36
37 var text = stream.read_all
38 stream.close
39 if text.is_java_null then
40 self.error = new Error("Failed to read content of asset file at '{path}'")
41 jni_env.pop_local_frame
42 self.to_s = ""
43 return ""
44 end
45
46 var content = text.to_s
47 jni_env.pop_local_frame
48 self.to_s = content
49 return content
50 end
51 end
52
53 redef class NativeInputStream
54
55 # Read and return all the content of this stream
56 private fun read_all: JavaString in "Java" `{
57 // `available` returns the n of bytes currently available, not the total.
58 // This may cause problems in the future with large asset files.
59 try {
60 int size = self.available();
61 byte[] bytes = new byte[size];
62 self.read(bytes, 0, size);
63
64 return new String(bytes);
65 } catch (java.lang.Exception exception) {
66 exception.printStackTrace();
67 return null;
68 }
69 `}
70 end