-
Notifications
You must be signed in to change notification settings - Fork 0
/
gui_interface.pyw
415 lines (335 loc) · 11.7 KB
/
gui_interface.pyw
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import rpncalc
#import readline
import copy
import pickle
import sys
if (sys.version_info > (3, 0)):
import tkinter as tk
import tkinter.filedialog as tkFileDialog
import tkinter.font as tkFont
else:
import Tkinter as tk
import tkFileDialog
import tkFont
import os
import math
import pkgutil
import importlib
import settings
STACK = 0
GRAPH_XY = 1
GRAPH_X = 2
mode = STACK
loaded_plugins = {}
#load the plugins
def load_all_modules_from_dir_old(dirname):
for importer, package_name, _ in pkgutil.iter_modules([dirname]):
full_package_name = '%s.%s' % (dirname, package_name)
if full_package_name not in sys.modules:
module = importer.find_module(package_name).load_module(full_package_name)
yield module
def load_all_modules_from_dir(dirname):
for name in os.listdir(dirname):
if name.endswith('.py') and not name.startswith('__'):
module_name = '{}.{}'.format(dirname,name[:-3])
if module_name not in sys.modules:
module = importlib.import_module(module_name)
yield module
for module in load_all_modules_from_dir('plugins'):
loaded_plugins.update(module.register())
function_list = rpncalc.ops.copy()
function_list.update(loaded_plugins)
interp = rpncalc.Interpreter(function_list)
class ShutErDownBoys(Exception):
pass
class BadPythonCommand(Exception):
pass
history = []
history_position = 0
historyfile = open('history', 'w+')
history = historyfile.readlines()
'''
def editor_validator(keystroke):
#raise Exception('ERRORRRRR: ' + str(keystroke))
message = str(keystroke)
inputbox.do_command(keystroke)
'''
def import_file(filename):
f = open(filename)
commands = f.read()
f.close()
for command in commands.split('\n'):
if len(command) > 0:
if command[0] == "#":
continue
parse(command)
def parse(input_string):
global mode
if input_string[0] == ':': # interface commands start with a colon
input_string = input_string[1:]
text = input_string.split()
if text[0] == 'step':
interp.step()
elif text[0] == 'run':
interp.resume()
elif text[0] == 'import':
import_file(os.path.join(settings.functions_directory, text[1] + '.rpn'))
elif text[0] == 'export':
f = open(os.path.join(settings.functions_directory, text[1] + '.rpn'), 'w+')
commands = interp.stack[-1].stack
for cmd in commands:
f.write(cmd)
f.write('\n')
f.close()
elif text[0] == 'quit':
raise ShutErDownBoys()
elif text[0] == '!':
try:
command = ''
for character in input_string[1:]:
if character == '?':
command += str(interp.pop()[0].val)
else:
command += character
res = eval(command)
interp.parse(str(res))
except Exception as e:
raise BadPythonCommand('Bad Python Command (' + command + ') ' + e.message)
elif text[0] == 'graph':
if len(text) > 1:
if text[1] == 'x':
mode = GRAPH_X
interp.message("X Graph Mode")
elif text[1] == 'xy':
mode = GRAPH_XY
interp.message("XY Graph Mode")
elif mode == GRAPH_XY:
mode = GRAPH_X
interp.message("X Graph Mode")
else:
mode = GRAPH_XY
interp.message("XY Graph Mode")
elif text[0] == 'stack':
interp.message("Stack Mode")
mode = STACK
else:
interp.parse(input_string, True)
if settings.auto_import_functions:
for dirpath, dirnames, filenames in os.walk(settings.auto_functions_directory):
for filename in filenames:
if len(filename) > 5:
if (filename[-4:] == '.rpn') and (filename[0] != '.'):
import_file(os.path.join(settings.auto_functions_directory, filename))
loop = True
root = tk.Tk()
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master, height=850, width=400)
self.pack(fill=tk.BOTH, expand=1)
self.createWidgets()
self.inputbox.focus_set()
def update_display(self):
self.stackbox.delete(0,tk.END)
stack = interp.get_stack()
if interp.function_stack is not None:
stack += ['['] + interp.function_stack
if interp.paused:
stack += ['@'] + interp.get_broken_commands()
for x in stack[::-1]:
self.stackbox.insert(0, str(x))
self.stackbox.see(tk.END)
for msg in interp.messages:
self.messagebox.insert(0, str(msg))
def step(self):
interp.step()
self.update_display()
def pause(self):
interp.parse('@')
self.update_display()
def resume(self):
interp.resume()
self.update_display()
def EnterKey(self, event):
try:
entry_text = self.inputbox.get()
self.inputbox.delete(0,tk.END)
history.append(entry_text)
history_position = 0
parse(entry_text)
self.update_display()
except ShutErDownBoys:
loop = False
except KeyboardInterrupt:
#input_string = input_string_pre + input_string_post
#if input_string:
#input_string_post = ''
#input_string_pre = ''
#else:
loop = False
except BadPythonCommand as e:
interp.message(e.message)
except:
for x in rpncalc.log:
print(x)
raise
def UpKey(self, event):
global history_position
if history_position < len(history):
history_position += 1
self.inputbox.delete(0,tk.END)
self.inputbox.insert(0,str(history[-history_position][:]))
def DownKey(self, event):
global history_position
if history_position > 1:
history_position -= 1
self.inputbox.delete(0,tk.END)
self.inputbox.insert(0,str(history[-history_position][:]))
elif history_position == 1:
self.inputbox.delete(0,tk.END)
def CtrlC(self, event):
entry_text = self.inputbox.get()
if entry_text:
self.inputbox.delete(0,tk.END)
else:
self.quit()
def command_inserter(self, op):
return lambda: self.inputbox.insert(tk.END, ' %s' % op)
def command_executer(self, ops):
def executer():
for op in ops:
self.inputbox.insert(tk.END, ' %s' % op)
self.EnterKey(None)
return executer
def showoperators(self):
self.operatormenu.delete(0,tk.END)
submenus = {}
submenus['Builtin'] = tk.Menu(self.operatormenu, tearoff=0)
for op in interp.operatorlist:
if '.' in op:
namespace, command = op.split('.')
if namespace not in submenus:
submenus[namespace] = tk.Menu(self.operatormenu, tearoff=0)
submenus[namespace].add_command(label=op, command=self.command_inserter(op))
else:
submenus['Builtin'].add_command(label=op, command=self.command_inserter(op))
for sub in submenus:
self.operatormenu.add_cascade(label=sub, menu=submenus[sub])
def showvars(self):
self.varmenu.delete(0,tk.END)
for op in interp.variables:
self.varmenu.add_command(label=op, command=self.command_inserter(op))
def save(self):
options = {}
options['defaultextension'] = '.rpn'
options['filetypes'] = [('all files', '.*'), ('rpn files', '.rpn')]
options['title'] = 'Save Session'
filename = tkFileDialog.asksaveasfilename(filetypes=[('RPN files', '.rpn'), ('all files', '*')], title='Load Session')
if filename:
interp2 = copy.deepcopy(interp)
interp2.builtin_functions = {}
interp2.operatorlist = []
f = open(filename, 'wb')
pickle.dump(interp2, f, 2)
f.close()
self.messagebox.insert(0, 'Saved as ' + filename)
else:
self.messagebox.insert(0, 'Invalid Filename ' + filename)
def copy_val(self):
root.clipboard_clear()
text = ''
for sel in self.stackbox.curselection():
text += self.stackbox.get(sel) + '\n'
root.clipboard_append(text)
root.update()
def copy_all(self):
try:
root.clipboard_clear()
text = ''
for t in self.stackbox.get(0, tk.END):
text += ''.join(t) + '\n'
root.update()
except:
interp.message('error')
def load(self):
global interp
filename = tkFileDialog.askopenfilename(filetypes=[('RPN files', '.rpn'), ('all files', '*')], title='Load Session')
if filename:
f = open(filename, 'rb')
tmp = pickle.load(f)
f.close()
tmp.builtin_functions = interp.builtin_functions
tmp.operatorlist = interp.operatorlist
interp = tmp
self.update_display()
self.messagebox.insert(0, 'Loaded ' + filename)
else:
self.messagebox.insert(0, 'Invalid Filename ' + filename)
def createWidgets(self):
self.menubar = tk.Menu(self)
self.filemenu = tk.Menu(self.menubar, tearoff=0)
self.filemenu.add_command(label="quit", command=self.quit)
self.filemenu.add_command(label="save", command=self.save)
self.filemenu.add_command(label="load", command=self.load)
self.menubar.add_cascade(label="File", menu=self.filemenu)
self.editmenu = tk.Menu(self.menubar, tearoff=0)
self.editmenu.add_command(label="copy val", command=self.copy_val)
self.editmenu.add_command(label="copy all", command=self.copy_all)
self.menubar.add_cascade(label="Edit", menu=self.editmenu)
self.operatormenu = tk.Menu(self.menubar, tearoff=0, postcommand=self.showoperators)
self.menubar.add_cascade(label="Operators", menu=self.operatormenu)
self.varmenu = tk.Menu(self.menubar, tearoff=0, postcommand=self.showvars)
self.menubar.add_cascade(label="Variables", menu=self.varmenu)
self.controlmenu = tk.Menu(self.menubar, tearoff=0)
self.controlmenu.add_command(label="break", command=self.pause)
self.controlmenu.add_command(label="step", command=self.step)
self.controlmenu.add_command(label="resume", command=self.resume)
self.menubar.add_cascade(label="Control", menu=self.controlmenu)
root.config(menu=self.menubar)
self.left = tk.Frame(self, width=400, height=500)
self.left.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
self.right = tk.Frame(self, width=100, height=500)
self.right.pack(fill=tk.BOTH, expand=1)
self.stackframe = tk.Frame(self.left, width=400, height=500)
self.stackframe.pack(fill=tk.BOTH, expand=1)
self.stackscroll = tk.Scrollbar(self.stackframe, orient=tk.VERTICAL)
#self.font = tkFont.Font(family='Courier',size=18)
self.font = tkFont.Font(family='Consolas',size=18)
self.stackbox = tk.Listbox(self.stackframe, yscrollcommand=self.stackscroll.set, width=30, font=self.font, selectmode=tk.EXTENDED)
self.stackscroll.config(command=self.stackbox.yview)
self.stackscroll.pack(side=tk.RIGHT, fill=tk.Y)
self.stackbox.pack(fill=tk.BOTH, expand=1)
self.inputbox = tk.Entry(self.left, font=self.font)
self.inputbox.pack(fill=tk.X, expand=0)
self.inputbox.bind('<Return>', self.EnterKey)
self.inputbox.bind('<KP_Enter>', self.EnterKey)
self.inputbox.bind('<Up>', self.UpKey)
self.inputbox.bind('<Down>', self.DownKey)
self.inputbox.bind('<Control-c>', self.CtrlC)
self.messageframe = tk.Frame(self.left)
self.messageframe.pack(fill=tk.X, expand=0)
self.messagescrolly = tk.Scrollbar(self.messageframe, orient=tk.VERTICAL)
self.messagebox = tk.Listbox(self.messageframe, yscrollcommand=self.messagescrolly.set, height=3)
self.messagescrolly.config(command=self.messagebox.yview)
self.messagescrolly.pack(side=tk.RIGHT, fill=tk.Y)
self.messagebox.pack(fill=tk.X, expand=0)
self.faveframe = tk.Frame(self.right)
self.faveframe.pack(fill=tk.X, expand=0)
from favorites import favorites
for fave in favorites:
#self.favebox = tk.Listbox(self.faveframe, yscrollcommand=self.favescrolly.set, height=3)
favebtn = tk.Button(self.faveframe, text=fave[0], command=self.command_executer(fave[1]))
favebtn.pack(fill=tk.X, expand=0)
app = Application()
app.master.title('Python RPN Calculator')
app.mainloop()
for v in interp.stack:
print(v)
if settings.history > 0:
historyfile = open('history', 'w')
history_to_log = history
if len(history) > settings.history:
history_to_log = history[-settings.history:]
for historyitem in history_to_log:
historyfile.write(('%s\n' % historyitem.strip()))
historyfile.close()
sys.exit(0)