6ed8be7c61a0ef37b2d5f12c30d96c7c768b50de
[nit.git] / examples / calculator / src / calculator.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 # Portable calculator UI
16 module calculator is
17 app_name "app.nit Calc."
18 app_version(0, 1, git_revision)
19 app_namespace "org.nitlanguage.calculator"
20
21 # Lock in portrait mode
22 android_manifest_activity """android:screenOrientation="portrait""""
23 android_api_target 15
24 end
25
26 import app::ui
27 import app::data_store
28 import android::aware
29
30 import calculator_logic
31
32 redef class App
33 redef fun on_create
34 do
35 # Create the main window
36 window = new CalculatorWindow
37 super
38 end
39 end
40
41 # The main (and only) window of this calculator
42 class CalculatorWindow
43 super Window
44
45 # Calculator context, our business logic
46 private var context = new CalculatorContext
47
48 # Main window layout
49 private var layout = new VerticalLayout(parent=self)
50
51 # Main display, at the top of the screen
52 private var display = new TextInput(parent=layout)
53
54 # Maps operators as `String` to their `Button`
55 private var buttons = new HashMap[String, Button]
56
57 init
58 do
59 # All the button labels, row by row
60 var rows = [["7", "8", "9", "+"],
61 ["4", "5", "6", "-"],
62 ["1", "2", "3", "*"],
63 ["0", ".", "C", "/"],
64 ["="]]
65
66 for row in rows do
67 var row_layout = new HorizontalLayout(parent=layout)
68
69 for op in row do
70 var but = new Button(parent=row_layout, text=op)
71 but.observers.add self
72 buttons[op] = but
73 end
74 end
75 end
76
77 redef fun on_event(event)
78 do
79 if event isa ButtonPressEvent then
80
81 var op = event.sender.text
82 if op == "." then
83 event.sender.enabled = false
84 context.switch_to_decimals
85 else if op.is_numeric then
86 var n = op.to_i
87 context.push_digit n
88 else
89 buttons["."].enabled = true
90 context.push_op op.chars.first
91 end
92
93 display.text = context.display_text
94 end
95 end
96
97 redef fun on_save_state
98 do
99 app.data_store["context"] = context
100 super
101 end
102
103 redef fun on_restore_state
104 do
105 super
106
107 var context = app.data_store["context"]
108 if not context isa CalculatorContext then return
109
110 self.context = context
111 display.text = context.display_text
112 end
113 end