-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathc.py
executable file
·253 lines (199 loc) · 6.74 KB
/
c.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# Copyright (C) 2014 Yu-Jie Lin
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import re
from decimal import Decimal, getcontext
from operator import truediv as div
from operator import add, mul, sub
import urwid
__module__ = 'c'
__description__ = 'Simple calculator in terminal using Urwid'
__copyright__ = 'Copyright 2014, Yu Jie Lin'
__license__ = 'MIT License'
__version__ = '0.2.0'
__website__ = 'http://bitbucket.org/livibetter/c'
__author__ = 'Yu-Jie Lin'
__author_email__ = '[email protected]'
OP_MAP = {'+': add, '-': sub, '*': mul, '/': div}
RE = re.compile('\s+')
LAYOUT = '''
C 7 8 9 +
<-- 4 5 6 -
+/- 1 2 3 *
OFF 0 . = /
'''
LAYOUT = tuple(filter(
None,
(tuple(filter(None, RE.split(line))) for line in LAYOUT.split('\n'))
))
PALETTE = [
(None, 'dark green', 'default'),
('focus', 'light red', 'default'),
('blink', 'white', 'default'),
('output', 'light blue', 'default'),
]
class CBigText(urwid.BigText):
_selectable = True
class CButton(urwid.Button):
def __init__(self, label, on_press=None):
w = CBigText(label, urwid.HalfBlock5x4Font())
self._label = w
w = urwid.AttrMap(w, None, 'focus')
self.__amap = w
w = urwid.Padding(w, align='center', width='clip')
w = urwid.Filler(w, valign='middle', bottom=1)
w = urwid.BoxAdapter(w, height=5)
urwid.WidgetWrap.__init__(self, w)
if on_press:
urwid.connect_signal(self, 'click', on_press)
self.set_label(label)
self.__loop = None
urwid.connect_signal(self, 'click', self.blink_start)
def enable_blink(self, loop):
self.__loop = loop
def blink_start(self, user_data=None):
if not self.__loop:
return
self.__blink_state = 0
self.__loop.set_alarm_in(0, self.__blink)
def __blink(self, loop, user_data=None):
self.__blink_state += 1
self.__amap.set_attr_map({
None: None if self.__blink_state % 2 else 'blink'
})
self.__amap.set_focus_map({
None: 'focus' if self.__blink_state % 2 else 'blink'
})
if self.__blink_state < 5:
self.__loop.set_alarm_in(0.05, self.__blink)
else:
self.__blink_state = 0
class C():
FIGURES = 17 # significant figures
FMT = '%d.%df' % (FIGURES, FIGURES)
def __init__(self):
output = urwid.BigText('', urwid.HalfBlock5x4Font())
self.output = output
top_row = urwid.Padding(output, align='right', width='clip')
top_row = urwid.AttrMap(top_row, 'output')
top_row = urwid.Filler(top_row, top=1)
top_row = urwid.BoxAdapter(top_row, height=5)
_btn = lambda btn: CButton(btn, on_press=self.button_keypress)
_row = lambda btn: _btn(btn) if btn != '---' else urwid.Text('')
rows = [urwid.Columns(map(_row, row)) for row in LAYOUT]
self.buttons = [
btn
for row in rows
for cols in row.contents
for btn in cols
if isinstance(btn, CButton)
]
self.buttons_map = dict(
(btn.get_label(), btn) for btn in self.buttons
)
self.widget = urwid.Filler(urwid.Pile([top_row] + rows))
self.reset(reset_c=True, reset=True, reset_p=True)
self.update_output()
def reset(self, reset_c=False, reset=False, reset_p=False):
if reset_c:
self.c = '0' # current number
if reset:
self.n = None # last number
self.o = None # operator
if reset_p: # order of precedence
self.np = None # number
self.op = None # operator
def update_output(self):
self.output.set_text(self.c)
def handle_input(self, key):
if isinstance(key, tuple) and key[0].startswith('mouse'):
return False
if key == 'backspace':
key = '<--'
elif key == 'esc':
key = 'C'
if key in self.buttons_map:
btn = self.buttons_map[key]
btn.blink_start()
if '0' <= key <= '9':
self.c = key if self.c == '0' else self.c + key
elif key == '.':
if '.' not in self.c:
self.c += key
elif key in ('n', '+/-'):
self.c = self.c[1:] if self.c.startswith('-') else '-' + self.c
elif key in '+-*/':
if self.n is None:
self.n = self.c
self.o = key
else:
if key in ('+', '-'):
if self.op:
self.np = self.do_op(self.op, self.np, self.c)
self.n = self.do_op(self.o, self.n, self.np)
self.o = key
self.reset(reset_p=True)
elif self.o:
self.n = self.do_op(self.o, self.n, self.c)
self.o = key
else:
self.n = self.do_op(key, self.n, self.c)
else:
if self.op:
self.np = self.do_op(self.op, self.np, self.c)
self.op = key
elif self.o in ('+', '-'):
self.np = self.c
self.op = key
else:
self.n = self.do_op(key, self.n, self.c)
self.c = '0'
elif key == '=':
if self.op:
self.c = self.do_op(self.op, self.np, self.c)
self.reset(reset_p=True)
if self.o:
self.c = self.do_op(self.o, self.n, self.c)
self.reset(reset=True)
elif key in ('backspace', '<--'):
self.c = self.c[:-1]
if not self.c:
self.c = '0'
elif key in ('esc', 'C'):
self.reset(reset_c=True, reset=True, reset_p=True)
elif key in ('q', 'Q', 'OFF'):
raise urwid.ExitMainLoop()
self.update_output()
return True
def button_keypress(self, button):
self.handle_input(button.get_label())
@classmethod
def f(cls, n):
return (format(n, cls.FMT)).rstrip('0').rstrip('.')
@classmethod
def do_op(cls, op, a, b):
getcontext().prec = cls.FIGURES
return cls.f(OP_MAP[op](Decimal(a), Decimal(b)))
def main():
c = C()
loop = urwid.MainLoop(c.widget, PALETTE, unhandled_input=c.handle_input)
for btn in c.buttons:
btn.enable_blink(loop)
loop.run()
if __name__ == '__main__':
main()