-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgui.py
1285 lines (1120 loc) · 45.2 KB
/
gui.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
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Implement the graphical user interface for the Logic Simulator.
Used in the Logic Simulator project to enable the user to run the simulation
or adjust the network properties.
Classes:
--------
MyGLCanvas - handles all canvas drawing operations.
Gui - configures the main window and all the widgets.
"""
from matplotlib.ft2font import VERTICAL
import wx
import wx.lib.agw.gradientbutton as gb
import wx.lib.dialogs as dlgs
import os
import wx.glcanvas as wxcanvas
from OpenGL import GL, GLUT
from names import Names
from devices import Devices
from network import Network
from monitors import Monitors
from scanner import Scanner
from parse import Parser
from gui_utils.gui_utils import Utils
from userint import UserInterface
from guicommandint import GuiCommandInterface
class MyGLCanvas(wxcanvas.GLCanvas):
"""Handle all drawing operations.
This class contains functions for drawing onto the canvas. It
also contains handlers for events relating to the canvas.
Parameters
----------
parent: parent window.
devices: instance of the devices.Devices() class.
monitors: instance of the monitors.Monitors() class.
Public methods
--------------
init_gl(self): Configures the OpenGL context.
render(self, text): Handles all drawing operations.
on_paint(self, event): Handles the paint event.
on_size(self, event): Handles the canvas resize event.
on_mouse(self, event): Handles mouse events.
render_text(self, text, x_pos, y_pos): Handles text drawing
operations.
"""
def __init__(self, parent, size, devices, monitors, names):
"""Initialise canvas properties and useful variables."""
super().__init__(parent, -1, size=size,
attribList=[wxcanvas.WX_GL_RGBA,
wxcanvas.WX_GL_DOUBLEBUFFER,
wxcanvas.WX_GL_DEPTH_SIZE, 16, 0])
GLUT.glutInit()
self.init = False
self.context = wxcanvas.GLContext(self)
# Initialise for signal display
self.monitors = monitors
self.devices = devices
self.names = names
# Initialise variables for panning
self.pan_x = 0
self.pan_y = 0
self.last_mouse_x = 0 # previous mouse x position
self.last_mouse_y = 0 # previous mouse y position
# Initialise variables for zooming
self.zoom = 1
# Bind events to the canvas
self.Bind(wx.EVT_PAINT, self.on_paint)
self.Bind(wx.EVT_SIZE, self.on_size)
self.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse)
def init_gl(self):
"""Configure and initialise the OpenGL context."""
size = self.GetClientSize()
self.SetCurrent(self.context)
GL.glDrawBuffer(GL.GL_BACK)
GL.glClearColor(1.0, 1.0, 1.0, 0.0)
GL.glViewport(0, 0, size.width, size.height)
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glLoadIdentity()
GL.glOrtho(0, size.width, 0, size.height, -1, 1)
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glLoadIdentity()
GL.glTranslated(self.pan_x, self.pan_y, 0.0)
GL.glScaled(self.zoom, self.zoom, self.zoom)
def render(self, text, clearAll=False):
"""Handle all drawing operations."""
self.SetCurrent(self.context)
if not self.init:
# Configure the viewport, modelview and projection matrices
self.init_gl()
self.init = True
# Clear everything
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
# Draw specified text at position (10, 10)
top = 975
self.render_text(text, 10, top)
# Draw signal traces
if not clearAll:
low = 5
high = 25
signalData = self.monitors.display_signals_gui(high=high, low=low)
axis = top-45
for monitor in signalData.keys():
desc, X, Y, device_kind = signalData[monitor]
if len(X) > 0:
margin = len(desc)*10
Y = [axis+y for y in Y]
X = [x+margin+10 for x in X]
rgb = self._trace_colour(device_kind)
self.render_text(desc, X[0]-margin, axis+12)
self._draw_trace(X, Y, axis, rgb)
axis -= 100
# We have been drawing to the back buffer, flush the graphics pipeline
# and swap the back buffer to the front
GL.glFlush()
self.SwapBuffers()
def _draw_trace(self, X, Y, axis, rgb):
"""Draw a signal trace."""
# Draw trace
GL.glShadeModel(GL.GL_FLAT)
GL.glColor3f(rgb[0], rgb[1], rgb[2])
GL.glBegin(GL.GL_LINE_STRIP)
i = 1
while i < len(X):
if Y[i] == axis:
GL.glColor3f(1, 1, 1)
GL.glVertex2f(X[i-1], Y[i-1])
GL.glVertex2f(X[i], Y[i])
GL.glColor3f(rgb[0], rgb[1], rgb[2])
else:
if i > 1 and Y[i-2] == axis:
GL.glColor3f(1, 1, 1)
GL.glVertex2f(X[i-1], Y[i-1])
GL.glColor3f(rgb[0], rgb[1], rgb[2])
GL.glVertex2f(X[i], Y[i])
else:
GL.glVertex2f(X[i-1], Y[i-1])
GL.glVertex2f(X[i], Y[i])
i += 2
GL.glEnd()
# Draw x axis with ticks
GL.glColor3f(0, 0, 0) # x axis is black
GL.glBegin(GL.GL_LINE_STRIP)
for i in range(len(X)):
GL.glVertex2f(X[i], axis)
GL.glVertex2f(X[i], axis-3)
GL.glVertex2f(X[i], axis)
GL.glEnd()
# x axis numbers
t = 0
while t < len(X):
self.render_text(str(int(t/2)), X[t], axis-14)
t += 4
def _trace_colour(self, device_kind):
"""Colour code trace based on device kind."""
gate_strings = ["AND", "NOT", "OR", "NAND", "NOR", "XOR"]
if self.names.get_name_string(device_kind) in gate_strings:
return [0, 0, 1]
if self.names.get_name_string(device_kind) == "CLOCK":
return [0, 1, 0]
if self.names.get_name_string(device_kind) == "SWITCH":
return [1, 0, 1]
if self.names.get_name_string(device_kind) == "DTYPE":
return [1, 0, 0]
else:
return [0, 0, 0]
def on_paint(self, event):
"""Handle the paint event."""
self.SetCurrent(self.context)
if not self.init:
# Configure the viewport, modelview and projection matrices
self.init_gl()
self.init = True
text = _("Welcome to the Logic Simulator! ") + \
_("See User Guide for help.")
self.render(text)
def on_size(self, event):
"""Handle the canvas resize event."""
# Forces reconfiguration of the viewport, modelview and projection
# matrices on the next paint event
self.init = False
def on_mouse(self, event):
"""Handle mouse events."""
text = ""
# Calculate object coordinates of the mouse position
size = self.GetClientSize()
ox = (event.GetX() - self.pan_x) / self.zoom
oy = (size.height - event.GetY() - self.pan_y) / self.zoom
old_zoom = self.zoom
if event.ButtonDown():
self.last_mouse_x = event.GetX()
self.last_mouse_y = event.GetY()
if event.Dragging():
self.pan_x += event.GetX() - self.last_mouse_x
self.pan_y -= event.GetY() - self.last_mouse_y
self.last_mouse_x = event.GetX()
self.last_mouse_y = event.GetY()
self.init = False
if event.GetWheelRotation() < 0:
self.zoom *= (1.0 + (
event.GetWheelRotation() / (20 * event.GetWheelDelta())))
# Adjust pan so as to zoom around the mouse position
self.pan_x -= (self.zoom - old_zoom) * ox
self.pan_y -= (self.zoom - old_zoom) * oy
self.init = False
if event.GetWheelRotation() > 0:
self.zoom /= (1.0 - (
event.GetWheelRotation() / (20 * event.GetWheelDelta())))
# Adjust pan so as to zoom around the mouse position
self.pan_x -= (self.zoom - old_zoom) * ox
self.pan_y -= (self.zoom - old_zoom) * oy
self.init = False
if text:
self.render(text)
else:
self.Refresh() # triggers the paint event
def render_text(
self, text, x_pos, y_pos, font=GLUT.GLUT_BITMAP_HELVETICA_18
):
"""Handle text drawing operations."""
GL.glColor3f(0.0, 0.0, 0.0) # text is black
GL.glRasterPos2f(x_pos, y_pos)
for character in text:
if character == '\n':
y_pos = y_pos - 20
GL.glRasterPos2f(x_pos, y_pos)
else:
GLUT.glutBitmapCharacter(font, ord(character))
class Gui(wx.Frame):
"""Configure the main window and all the widgets.
This class provides a graphical user interface for the Logic Simulator and
enables the user to change the circuit properties and run simulations.
Parameters
----------
title: title of the window.
Public methods
--------------
on_menu(self, event): Event handler for the file menu.
on_browse(self, event): Event handler for browse button.
on_delete_connection(self, event): Event handler for deleting a connection.
on_spin_cycles(self, event): Handle event when user changes cycles.
on_enter_device_button(self, event): Prevents colour change on hover of
device.
on_run_button(self, event): Event handler for when the user clicks the run
button.
on_continue_button(self, event): Event handler for when the user clicks the
continue button.
on_clear_button(self, event): Event handler for when the user clicks the
Clear Canvas button.
on_switch_button(self, event): Event handler for when the user clicks a
switch button.
on_monitor_button(self, event): Event handler for when the user clicks a
monitor button.
on_clear_all_monitors_button(self, event): Event handler for when the user
clears all monitors.
on_monitor_input(self, event): Handle event when user adds a monitor.
on_command_line_input(self, event): Handle user commands.
"""
def __init__(self, title, path, names, devices, network, monitors):
"""Initialise circuit variables."""
self.names = names
self.devices = devices
self.monitors = monitors
self.network = network
self.cycles_completed = 0
self.cycles_to_run = 10
"""Initialise user interface."""
self.path = path
self.userint = UserInterface(names, devices, network, monitors)
"""Initialise utils."""
self.utils = Utils()
self.click = wx.Cursor(wx.Image("gui_utils/smallclick.png"))
self.info_cursor = wx.Cursor(wx.Image('gui_utils/smallinfo.png'))
self.standard_button_size = wx.Size(85, 36)
"""Initialise widgets and layout."""
super().__init__(parent=None, title=title, size=(800, 600))
# Configure the file menu
menuBar = wx.MenuBar()
fileMenu = wx.Menu()
guideMenu = wx.Menu()
fileMenu.Append(wx.ID_OPEN, "&" + _("Open"))
fileMenu.Append(wx.ID_ABOUT, "&" + _("About"))
fileMenu.Append(wx.ID_EXIT, "&" + _("Exit"))
guideMenu.Append(wx.ID_HELP_COMMANDS, "&" + _("Command Line Guide"))
guideMenu.Append(wx.ID_CONTEXT_HELP, "&" + _("Canvas Controls"))
guideMenu.Append(wx.ID_HELP_PROCEDURES, "&" + _("Sidebar Guide"))
menuBar.Append(fileMenu, "&" + _("File"))
menuBar.Append(guideMenu, "&" + _("User Guide"))
self.SetMenuBar(menuBar)
# Set background colour for GUI
self.SetBackgroundColour(self.utils.paleyellow)
# Set fonts
fileFont = wx.Font(wx.FontInfo(18).FaceName("Mono").Bold())
genBtnFont = wx.Font(wx.FontInfo(10).FaceName("Mono").Bold())
helpFont = wx.Font(wx.FontInfo(10).FaceName("Mono"))
self.subHeadingFont = wx.Font(wx.FontInfo(12).FaceName("Mono"))
inputBoxFont = wx.Font(12, wx.SWISS, wx.NORMAL, wx.NORMAL)
go_font = wx.Font(wx.FontInfo(14).FaceName("Rockwell"))
self.delete_font = wx.Font(wx.FontInfo(10).FaceName("Rockwell"))
self.errorBoxFont = wx.Font(wx.FontInfo(10).FaceName("Consolas"))
# Canvas for drawing signals
self.scrollable = wx.ScrolledCanvas(self, wx.ID_ANY)
self.scrollable.SetScrollbars(20, 20, 15, 10)
self.canvas = MyGLCanvas(
self.scrollable, wx.Size(1500, 1000), devices, monitors, names
)
# Configure the widgets
self.file_name = wx.StaticText(
self, wx.ID_ANY, f"", size=wx.Size(350, 30)
)
self.file_name.SetFont(fileFont)
self.browse = wx.Button(self, wx.ID_ANY, _("Browse"))
self.browse.SetFont(genBtnFont)
self.browse.SetCursor(self.click)
self.switches_text = wx.StaticText(self, wx.ID_ANY, "")
self.switches_text.SetFont(self.subHeadingFont)
self.switch_buttons = {}
self.devices_heading = wx.StaticText(self, wx.ID_ANY, _("Devices:"))
self.devices_heading.SetFont(self.subHeadingFont)
self.device_buttons = []
self.monitors_text = wx.StaticText(self, wx.ID_ANY, _("Monitors:"))
self.monitors_text.SetFont(self.subHeadingFont)
self.monitor_input = wx.TextCtrl(
self,
wx.ID_ANY,
"",
style=wx.TE_PROCESS_ENTER,
size=wx.Size(200, 25)
)
self.monitor_input.SetHint(_("Add new monitor"))
self.monitor_input.SetFont(inputBoxFont)
self.monitors_help_text = wx.StaticText(
self, wx.ID_ANY, _("(click to remove)")
)
self.monitors_help_text.SetFont(helpFont)
self.clear_all_monitors = wx.Button(self, wx.ID_ANY, _("Clear All"))
self.clear_all_monitors.SetCursor(self.click)
self.clear_all_monitors.SetFont(genBtnFont)
self.monitor_buttons = {}
self.cycles_text = wx.StaticText(self, wx.ID_ANY, _(" Cycles: "))
self.cycles_text.SetFont(self.subHeadingFont)
self.spin_cycles = wx.SpinCtrl(self, wx.ID_ANY, "10")
self.run_button = gb.GradientButton(self, wx.ID_ANY, label=_("Run"))
self.run_button.SetCursor(self.click)
self.run_button.SetFont(wx.Font(go_font))
self._change_button_colours(
self.run_button,
self.utils.darkgreen,
self.utils.midgreen
)
self.continue_button = gb.GradientButton(
self,
wx.ID_ANY,
label=_("Continue")
)
self.continue_button.SetFont(wx.Font(go_font))
self._change_button_colours(
self.continue_button,
self.utils.darkpurple,
self.utils.lightpurple
)
self.continue_button.SetCursor(self.click)
self.clear_button = gb.GradientButton(
self,
wx.ID_ANY,
label=_("Clear Canvas")
)
self.clear_button.SetCursor(self.click)
self.clear_button.SetFont(wx.Font(go_font))
self.command_line_input = wx.TextCtrl(
self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER, size=(550, 25)
)
self.command_line_input.SetHint(
_("Command line input. See User Guide for help.")
)
self.command_line_input.SetFont(inputBoxFont)
# Bind events to widgets
self.Bind(wx.EVT_MENU, self.on_menu)
self.browse.Bind(wx.EVT_BUTTON, self.on_browse)
self.spin_cycles.Bind(wx.EVT_SPINCTRL, self.on_spin_cycles)
self.run_button.Bind(wx.EVT_BUTTON, self.on_run_button)
self.continue_button.Bind(wx.EVT_BUTTON, self.on_continue_button)
self.clear_button.Bind(wx.EVT_BUTTON, self.on_clear_button)
self.monitor_input.Bind(wx.EVT_TEXT_ENTER, self.on_monitor_input)
self.command_line_input.Bind(
wx.EVT_TEXT_ENTER,
self.on_command_line_input
)
self.clear_all_monitors.Bind(
wx.EVT_BUTTON, self.on_clear_all_monitors_button
)
# Configure sizers for overall layout
main_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.side_sizer = wx.BoxSizer(wx.VERTICAL)
# Sizers and windows to be contained within side sizer
self.file_name_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.manual_settings_sizer = wx.BoxSizer(wx.VERTICAL)
self.devices_sizer = wx.FlexGridSizer(4)
self.devices_window = wx.ScrolledWindow(
self,
wx.ID_ANY,
wx.DefaultPosition,
wx.Size(420, 60),
wx.SUNKEN_BORDER | wx.HSCROLL | wx.VSCROLL,
name="devices"
)
self.devices_window.SetSizer(self.devices_sizer)
self.devices_window.SetScrollRate(10, 10)
self.devices_window.SetAutoLayout(True)
self.switch_buttons_sizer = wx.FlexGridSizer(4)
self.switches_window = wx.ScrolledWindow(
self,
wx.ID_ANY,
wx.DefaultPosition,
wx.Size(420, 60),
wx.SUNKEN_BORDER | wx.HSCROLL | wx.VSCROLL,
name="switches"
)
self.switches_window.SetSizer(self.switch_buttons_sizer)
self.switches_window.SetScrollRate(10, 10)
self.switches_window.SetAutoLayout(True)
self.monitor_buttons_sizer = wx.FlexGridSizer(4)
self.monitors_window = wx.ScrolledWindow(
self,
wx.ID_ANY,
wx.DefaultPosition,
wx.Size(420, 60),
wx.SUNKEN_BORDER | wx.HSCROLL | wx.VSCROLL,
name="monitors"
)
self.monitors_window.SetSizer(self.monitor_buttons_sizer)
self.monitors_window.SetScrollRate(10, 10)
self.monitors_window.SetAutoLayout(True)
self.devices_heading_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.monitors_help_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.cycles_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.command_line_sizer = wx.BoxSizer(wx.HORIZONTAL)
# Add side sizer and canvas to main sizer
main_sizer.Add(self.side_sizer, 5, wx.EXPAND | wx.ALL, 5)
main_sizer.Add(self.scrollable, 10, wx.EXPAND | wx.ALL, 5)
# Add sizers to side_sizer
self.side_sizer.Add(self.file_name_sizer, 0, wx.ALL, 5)
self.side_sizer.Add(self.manual_settings_sizer, 1, wx.ALL, 5)
self.side_sizer.Add(self.cycles_sizer, 0, wx.ALL, 5)
self.side_sizer.Add(self.command_line_sizer, 0, wx.ALL, 5)
# add widgets to smaller sizers
self.file_name_sizer.Add(self.file_name, 0, wx.ALIGN_CENTER, 5)
self.file_name_sizer.AddStretchSpacer()
self.file_name_sizer.AddStretchSpacer()
self.file_name_sizer.Add(self.browse, 0, wx.ALIGN_CENTER, 10)
self.devices_heading_sizer.Add(
self.devices_heading,
0,
wx.ALIGN_CENTER,
5
)
self.devices_heading_sizer.AddStretchSpacer()
self.monitors_help_sizer.Add(self.monitors_text, 0, wx.ALIGN_CENTER, 5)
self.monitors_help_sizer.Add(self.monitor_input, 0, wx.ALL, 5)
self.monitors_help_sizer.Add(
self.clear_all_monitors,
1,
wx.ALIGN_CENTER,
5
)
self.monitors_help_sizer.Add(
self.monitors_help_text, 0, wx.ALIGN_CENTER, 5
)
self.cycles_sizer.Add(self.cycles_text, 0, wx.ALIGN_CENTER, 5)
self.cycles_sizer.Add(self.spin_cycles, 0, wx.ALIGN_CENTER, 5)
self.cycles_sizer.AddStretchSpacer()
self.cycles_sizer.Add(self.run_button, 0, wx.ALL, 5)
self.cycles_sizer.Add(self.continue_button, 0, wx.ALL, 5)
self.cycles_sizer.Add(self.clear_button, 0, wx.ALL, 5)
self.command_line_sizer.Add(self.command_line_input, 1, wx.ALL, 5)
self.manual_settings_sizer.Add(
self.devices_heading_sizer,
0,
wx.ALL,
5
)
self.manual_settings_sizer.Add(
self.devices_window,
1,
wx.EXPAND | wx.ALL,
5
)
self.manual_settings_sizer.Add(self.switches_text, 0, wx.ALL, 5)
self.manual_settings_sizer.Add(
self.switches_window,
1,
wx.EXPAND | wx.ALL,
5
)
self.manual_settings_sizer.Add(self.monitors_help_sizer, 0, wx.ALL, 5)
self.manual_settings_sizer.Add(
self.monitors_window,
1,
wx.EXPAND | wx.ALL,
5
)
self.SetSizeHints(600, 600)
self.SetSizer(main_sizer)
self.Layout()
self.path = path
# If path is None, prompt user to choose a valid file
if self.path is None:
self._choose_file(first=True)
success = True
# Parse file given from command line
else:
scanner = Scanner(path, names)
parser = Parser(names, devices, network, monitors, scanner)
success = parser.parse_network()
if success:
self._update_new_circuit(first=True)
if not success:
# Display errors from file given from command line
self._display_errors(parser.error_message_list, first=True)
self._choose_file(first=True)
success = True
def _choose_file(self, first=False):
"""Allow user to find circuit definition file."""
openFileDialog = wx.FileDialog(
self, _("Open"), "", "",
wildcard="TXT files (*.txt)|*.txt",
style=wx.FD_OPEN+wx.FD_FILE_MUST_EXIST
)
if openFileDialog.ShowModal() == wx.ID_CANCEL:
if not first:
return
else:
# if this is the first time, exit GUI
wx.MessageBox(
_("No file selected. Exiting GUI."),
_("Exiting GUI"),
wx.ICON_INFORMATION | wx.OK
)
self.Close(True)
self.path = openFileDialog.GetPath()
names = Names()
devices = Devices(names)
network = Network(names, devices)
monitors = Monitors(names, devices, network)
scanner = Scanner(self.path, names)
parser = Parser(names, devices, network, monitors, scanner)
success = parser.parse_network()
if success:
self.names = names
self.devices = devices
self.network = network
self.monitors = monitors
self._update_new_circuit(first)
else:
self._display_errors(parser.error_message_list, first)
if first:
self._choose_file(first)
self.Layout()
def _display_errors(self, error_message_list, first=False):
"""Display errors in dialog box."""
errors = ""
for error in error_message_list:
errors += f"\n{error}"
if first:
message = f"{errors} \n \n{self.utils.first_parse_error_string}"
else:
message = f"{errors} \n \n{self.utils.parse_error_string}"
errorBox = dlgs.ScrolledMessageDialog(
self,
message,
error_message_list[-1],
style=wx.DEFAULT_DIALOG_STYLE+wx.RESIZE_BORDER,
size=wx.Size(750, 500)
)
text = errorBox.GetChildren()[0]
text.SetFont(self.errorBoxFont)
errorBox.ShowModal()
def _update_new_circuit(self, first=False):
"""Configure widgets for new circuit and bind events."""
self._set_file_title(self.path)
self.cycles_completed = 0
self._update_current_connections(first)
# find new switches
switches = self.devices.find_devices(self.names.query("SWITCH"))
if len(switches) > 0:
self.switches_text.SetLabel(_("Switches (toggle on/off):"))
else:
self.switches_text.SetLabel(_("No switches in this circuit."))
if not first:
# destroy current switch buttons
for switch in [pair[0] for pair in self.switch_buttons.values()]:
switch.Destroy()
# destroy current device list in sidebars
for button in self.device_buttons:
button.Destroy()
# destroy current monitor buttons
for monitor in self.monitor_buttons.values():
monitor.Destroy()
# add new switches
self.switch_buttons = {}
for s in switches:
name = self.names.get_name_string(s)
state = self.devices.get_device(s).switch_state
shortName = self._shorten(name)
button = gb.GradientButton(
self.switches_window,
s,
label=shortName,
size=self.standard_button_size
)
button.SetToolTip(name)
button.SetCursor(self.click)
if state == 0:
self._change_button_colours(
button,
self.utils.darkred,
self.utils.red
)
else:
self._change_button_colours(
button,
self.utils.blue,
self.utils.lightblue
)
self.switch_buttons[name] = [button, state]
# bind switch buttons to event
for switch in [pair[0] for pair in self.switch_buttons.values()]:
switch.Bind(wx.EVT_BUTTON, self.on_switch_button)
# add switches to sizer
for switch in [pair[0] for pair in self.switch_buttons.values()]:
self.switch_buttons_sizer.Add(
switch, 1, wx.ALL, 9
)
# find new devices
self.device_descs = []
for gate_type in self.devices.gate_types:
gates = self.devices.find_devices(gate_type)
for gateId in gates:
gate = self.devices.get_device(gateId)
label = self._shorten(
self.names.get_name_string(gate.device_id)
)
extra = f": {str(len(gate.inputs.keys()))} " + _("inputs")
self.device_descs.append([gateId, label, extra])
for dev_type in self.devices.device_types:
other_devices = self.devices.find_devices(dev_type)
for id in other_devices:
d = self.devices.get_device(id)
label = self._shorten(self.names.get_name_string(d.device_id))
kind = self.names.get_name_string(d.device_kind)
extra = ""
if kind == "CLOCK":
extra = ": " + _("half-period") + f" {d.clock_half_period}"
self.device_descs.append([id, label, extra])
# add new devices to displayed list
self.device_buttons = []
for d in self.device_descs:
[id, label, extra] = d
device_button = gb.GradientButton(
self.devices_window,
id,
label=self._shorten(f"{label}{extra}"),
size=self.standard_button_size
)
device_button.SetCursor(self.info_cursor)
kindId = self.devices.get_device(id).device_kind
kindLabel = self.names.get_name_string(kindId)
fullName = self.names.get_name_string(id)
device_button.SetToolTip(f"{fullName}, {kindLabel}{extra}")
device_button.SetTopStartColour(self._get_device_colour(kindId)[0])
device_button.SetBottomEndColour(
self._get_device_colour(kindId)[0]
)
device_button.Bind(
wx.EVT_ENTER_WINDOW,
self.on_enter_device_button
)
self.device_buttons.append(device_button)
# add new device list to sizer
for device in self.device_buttons:
self.devices_sizer.Add(device, 1, wx.ALL, 9)
# add new monitor buttons
self.monitor_buttons = {}
self.current_monitors = self.monitors.get_signal_names()[0]
for curr in self.current_monitors:
currId = self.names.lookup([curr])[0]
button = gb.GradientButton(
self.monitors_window,
currId,
label=curr,
size=self.standard_button_size
)
self._change_button_colours(
button,
self.utils.blue,
self.utils.lightblue
)
button.SetCursor(self.click)
self.monitor_buttons[curr] = button
# bind monitor buttons to event
for name in self.monitor_buttons.keys():
self.monitor_buttons[name].Bind(
wx.EVT_BUTTON, self.on_monitor_button
)
# add new monitor buttons to sizer
for mon in self.monitor_buttons.values():
self.monitor_buttons_sizer.Add(mon, 1, wx.ALL, 9)
text = _("New circuit loaded.")
self.canvas.monitors = self.monitors
self.canvas.devices = self.devices
self.canvas.names = self.names
if not first:
self.canvas.render(text)
self.Layout()
def _update_current_connections(self, first=False):
"""Update current connections after user changes."""
# If this is not the first time a circuit is loaded,
# must destroy the existing widgets for connections
if not first:
self.connections_spinner.Destroy()
self.delete_connection.Destroy()
self.connections = {}
for device in self.devices.devices_list:
device_id = device.device_id
for input in device.inputs.keys():
self.connections[(device_id, input)] = device.inputs[input]
self.connections_info = []
for input, output in self.connections.items():
inputName = self.devices.get_signal_name(input[0], input[1])
outputName = self.devices.get_signal_name(output[0], output[1])
self.connections_info.append([
_("from") + f" {outputName} " + _("to") + f" {inputName}",
input,
output
])
self.connections_spinner = wx.Choice(
self,
wx.ID_ANY,
choices=[cnxn[0] for cnxn in self.connections_info],
name=_("Current Connections")
)
self.connections_spinner.SetSelection(0)
self.delete_connection = gb.GradientButton(
self,
wx.ID_ANY,
label=_("Replace Connection")
)
self.delete_connection.SetCursor(self.click)
self.delete_connection.SetFont(wx.Font(self.delete_font))
self.devices_heading_sizer.Add(
self.connections_spinner, 0, wx.ALL, 5
)
self.devices_heading_sizer.Add(
self.delete_connection,
1,
wx.ALIGN_CENTER,
5
)
self.delete_connection.Bind(wx.EVT_BUTTON, self.on_delete_connection)
self.Layout()
def _set_file_title(self, path):
"""Display name of open file at top of screen."""
label = os.path.basename(os.path.splitext(path)[0])
if len(label) > 20:
label = f"\"{label[0:17]}...\""
self.file_name.SetLabel(label)
self.Layout()
def on_menu(self, event):
"""Handle the event when the user selects a menu item."""
Id = event.GetId()
if Id == wx.ID_EXIT:
self.Close(True)
if Id == wx.ID_ABOUT:
wx.MessageBox(
_("Logic Simulator") + "\n" + _("Created by")
+ " Priyanka Patel (霹雳阳科), Tommy Rochussen "
"(托米), Jessye Tu (涂净兮)\n2022",
_("About Logsim"),
wx.ICON_INFORMATION | wx.OK
)
if Id == wx.ID_OPEN:
self._choose_file()
if Id == wx.ID_HELP_COMMANDS:
wx.MessageBox(
self.utils.help_string,
_("Command Line Guide"),
wx.ICON_INFORMATION | wx.OK
)
if Id == wx.ID_CONTEXT_HELP:
wx.MessageBox(
self.utils.canvas_controls_string,
_("Canvas Controls"),
wx.ICON_INFORMATION | wx.OK
)
if Id == wx.ID_HELP_PROCEDURES:
wx.MessageBox(
self.utils.sidebar_guide_string,
_("Sidebar Guide"),
wx.ICON_INFORMATION | wx.OK
)
def on_browse(self, event):
"""Handle event when user clicks browse button."""
self._choose_file()
def on_delete_connection(self, event):
"""Handle event when user presses delete connection."""
connectionIndex = self.connections_spinner.GetSelection()
[inputIds, outputIds] = self.connections_info[connectionIndex][1:3]
input_device_id = inputIds[0]
input_port_id = inputIds[1]
int = GuiCommandInterface(
"",
self.names,
self.devices,
self.network,
self.monitors
)
int.delete_connection(
input_device_id,
input_port_id,
)
allOutputNames = []
allOutputIds = []
for i in [(d.device_id, d.outputs) for d in self.devices.devices_list]:
for output in i[1]:
allOutputIds.append((i[0], output))
allOutputNames.append(
self.devices.get_signal_name(i[0], output)
)
newConnection = wx.SingleChoiceDialog(
self,
_("Choose a new output to connect input ") +
f"{self.devices.get_signal_name(input_device_id, input_port_id)}",
_("Replace Connection"),
allOutputNames,
style=wx.CHOICEDLG_STYLE
)
newConnection.SetBackgroundColour(self.utils.paleyellow)
while newConnection.ShowModal() == wx.ID_CANCEL:
wx.MessageBox(
_("You must select a new connection for this input."),
_("Error - Connection Needed"),
wx.ICON_ERROR
)
choice = newConnection.GetSelection()
(dev, port) = allOutputIds[choice]
int = GuiCommandInterface(
"",
self.names,
self.devices,
self.network,
self.monitors
)
text, success = int.make_connection(
input_device_id,
input_port_id,
dev,
port
)
self.canvas.render(text)
if success:
newConnection.Destroy()
self._update_current_connections()
def on_spin_cycles(self, event):
"""Handle the event when the user changes the number of cycles."""
self.cycles_to_run = self.spin_cycles.GetValue()
text = "".join([_("Number of cycles: "), str(self.cycles_to_run)])