Merge: Document the doc/ directory
[nit.git] / examples / calculator / src / calculator_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 # Android calculator application
18 module calculator_android is
19 app_name "app.nit Calc."
20 app_version(0, 1, git_revision)
21 java_package "org.nitlanguage.calculator"
22
23 # Use a translucent background and lock in portrait mode
24 android_manifest_activity """
25 android:theme="@android:style/Theme.Holo.Wallpaper"
26 android:screenOrientation="portrait""""
27 end
28
29 import android
30 import android::ui
31
32 import calculator_logic
33
34 redef class App
35 private var context = new CalculatorContext
36
37 # The main display, at the top of the screen
38 private var display: EditText
39
40 # Maps operators as `String` to their `Button`
41 private var op2but = new HashMap[String, Button]
42
43 # Has this window been initialized?
44 private var inited = false
45
46 redef fun init_window
47 do
48 super
49
50 if inited then return
51 inited = true
52
53 # Setup UI
54 var context = native_activity
55 var layout = new NativeLinearLayout(context)
56 layout.set_vertical
57
58 # Display screen
59 var display = new EditText
60 layout.add_view_with_weight(display.native, 1.0)
61 display.text_size = 36.0
62 self.display = display
63
64 # Buttons; numbers and operators
65 var ops = [["7", "8", "9", "+"],
66 ["4", "5", "6", "-"],
67 ["1", "2", "3", "*"],
68 ["0", ".", "C", "/"],
69 ["="]]
70
71 for line in ops do
72 var buts_layout = new NativeLinearLayout(context)
73 buts_layout.set_horizontal
74 layout.add_view_with_weight(buts_layout, 1.0)
75
76 for op in line do
77 var but = new Button
78 but.text = op
79 but.text_size = 40
80 buts_layout.add_view_with_weight(but.native, 1.0)
81 op2but[op] = but
82 end
83 end
84
85 context.content_view = layout
86 end
87
88 redef fun catch_event(event)
89 do
90 if event isa ClickEvent then
91 var sender = event.sender
92 var op = sender.text
93
94 if op == "." then
95 sender.enabled = false
96 context.switch_to_decimals
97 else if op.is_numeric then
98 var n = op.to_i
99 context.push_digit n
100 else
101 op2but["."].enabled = true
102 context.push_op op.chars.first
103 end
104
105 display.text = context.display_text
106 end
107 end
108 end