bd2bd11be99976f561c87237ae0bdb0bc61f83bc
[nit.git] / examples / calculator / src / calculator_gtk.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2013-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 # GTK calculator
18 module calculator_gtk
19
20 import calculator_logic
21
22 import gtk
23
24 class CalculatorGui
25 super GtkCallable
26
27 var win : GtkWindow is noinit
28 var container : GtkGrid is noinit
29
30 var lbl_disp : GtkLabel is noinit
31 var but_eq : GtkButton is noinit
32 var but_dot : GtkButton is noinit
33
34 var context = new CalculatorContext
35
36 redef fun signal(sender, op)
37 do
38 if op isa Char then # is an operation
39 if op == '.' then
40 but_dot.sensitive = false
41 context.switch_to_decimals
42 else
43 but_dot.sensitive = true
44 context.push_op op
45 end
46 else if op isa Int then # is a number
47 context.push_digit op
48 end
49
50 lbl_disp.text = context.display_text
51 end
52
53 init
54 do
55 init_gtk
56
57 win = new GtkWindow( 0 )
58
59 container = new GtkGrid(5,5,true)
60 win.add( container )
61
62 lbl_disp = new GtkLabel( "_" )
63 container.attach( lbl_disp, 0, 0, 5, 1 )
64
65 # digits
66 for n in [0..9] do
67 var but = new GtkButton.with_label( n.to_s )
68 but.request_size( 64, 64 )
69 but.signal_connect( "clicked", self, n )
70 if n == 0 then
71 container.attach( but, 0, 4, 1, 1 )
72 else container.attach( but, (n-1)%3, 3-(n-1)/3, 1, 1 )
73 end
74
75 # operators
76 var r = 1
77 for op in ['+', '-', '*', '/' ] do
78 var but = new GtkButton.with_label( op.to_s )
79 but.request_size( 64, 64 )
80 but.signal_connect( "clicked", self, op )
81 container.attach( but, 3, r, 1, 1 )
82 r+=1
83 end
84
85 # =
86 but_eq = new GtkButton.with_label( "=" )
87 but_eq.request_size( 64, 64 )
88 but_eq.signal_connect( "clicked", self, '=' )
89 container.attach( but_eq, 4, 3, 1, 2 )
90
91 # .
92 but_dot = new GtkButton.with_label( "." )
93 but_dot.request_size( 64, 64 )
94 but_dot.signal_connect( "clicked", self, '.' )
95 container.attach( but_dot, 1, 4, 1, 1 )
96
97 #C
98 var but_c = new GtkButton.with_label( "C" )
99 but_c.request_size( 64, 64 )
100 but_c.signal_connect("clicked", self, 'C')
101 container.attach( but_c, 2, 4, 1, 1 )
102
103 win.show_all
104 end
105 end
106
107 # graphical application
108 if "NIT_TESTING".environ == "true" then exit 0
109
110 var app = new CalculatorGui
111 run_gtk