-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathFlatCAMApp.py
4328 lines (3557 loc) · 161 KB
/
FlatCAMApp.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
import Tkinter
import getopt
import os
import random
import time # Just used for debugging. Double check before removing.
import urllib
import webbrowser
from contextlib import contextmanager
from xml.dom.minidom import parseString as parse_xml_string
########################################
## Imports part of FlatCAM ##
########################################
from ObjectCollection import *
from FlatCAMObj import *
from PlotCanvas import *
from FlatCAMGUI import *
from FlatCAMCommon import LoudDict
from FlatCAMShell import FCShell
from FlatCAMDraw import FlatCAMDraw
from FlatCAMProcess import *
from FlatCAMWorkerStack import WorkerStack
from MeasurementTool import Measurement
from DblSidedTool import DblSidedTool
from multiprocessing import Pool
import gc
import tclCommands
########################################
## App ##
########################################
class App(QtCore.QObject):
"""
The main application class. The constructor starts the GUI.
"""
## Get Cmd Line Options
cmd_line_shellfile = ''
cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
try:
# Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
except getopt.GetoptError:
print cmd_line_help
sys.exit(2)
for opt, arg in cmd_line_options:
if opt == '-h':
print cmd_line_help
sys.exit()
elif opt == '--shellfile':
cmd_line_shellfile = arg
## Logging ##
log = logging.getLogger('base')
log.setLevel(logging.DEBUG)
# log.setLevel(logging.WARNING)
formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
log.addHandler(handler)
## Version
version = 8.4
version_date = "2015/10"
## URL for update checks and statistics
version_url = "http://flatcam.org/version"
## App URL
app_url = "http://flatcam.org"
## Manual URL
manual_url = "http://flatcam.org/manual/index.html"
##################
## Signals ##
##################
# Inform the user
# Handled by:
# * App.info() --> Print on the status bar
inform = QtCore.pyqtSignal(str)
# General purpose background task
worker_task = QtCore.pyqtSignal(dict)
# File opened
# Handled by:
# * register_folder()
# * register_recent()
file_opened = QtCore.pyqtSignal(str, str) # File type and filename
progress = QtCore.pyqtSignal(int) # Percentage of progress
plots_updated = QtCore.pyqtSignal()
# Emitted by new_object() and passes the new object as argument, plot flag.
# on_object_created() adds the object to the collection, plots on appropriate flag
# and emits new_object_available.
object_created = QtCore.pyqtSignal(object, bool)
# Emitted after object has been plotted.
# Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
object_plotted = QtCore.pyqtSignal(object)
# Emitted when a new object has been added to the collection
# and is ready to be used.
new_object_available = QtCore.pyqtSignal(object)
message = QtCore.pyqtSignal(str, str, str)
# Emmited when shell command is finished(one command only)
shell_command_finished = QtCore.pyqtSignal(object)
# Emitted when multiprocess pool has been recreated
pool_recreated = QtCore.pyqtSignal(object)
# Emitted when an unhandled exception happens
# in the worker task.
thread_exception = QtCore.pyqtSignal(object)
def __init__(self, user_defaults=True, post_gui=None):
"""
Starts the application.
:return: app
:rtype: App
"""
App.log.info("FlatCAM Starting...")
###################
### OS-specific ###
###################
if sys.platform == 'win32':
from win32com.shell import shell, shellcon
App.log.debug("Win32!")
self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
'/FlatCAM'
self.os = 'windows'
else: # Linux/Unix/MacOS
self.data_path = os.path.expanduser('~') + \
'/.FlatCAM'
self.os = 'unix'
###############################
### Setup folders and files ###
###############################
if not os.path.exists(self.data_path):
os.makedirs(self.data_path)
App.log.debug('Created data folder: ' + self.data_path)
try:
f = open(self.data_path + '/defaults.json')
f.close()
except IOError:
App.log.debug('Creating empty defaults.json')
f = open(self.data_path + '/defaults.json', 'w')
json.dump({}, f)
f.close()
try:
f = open(self.data_path + '/recent.json')
f.close()
except IOError:
App.log.debug('Creating empty recent.json')
f = open(self.data_path + '/recent.json', 'w')
json.dump([], f)
f.close()
# Application directory. Chdir to it. Otherwise, trying to load
# GUI icons will fail as thir path is relative.
# This will fail under cx_freeze ...
self.app_home = os.path.dirname(os.path.realpath(__file__))
App.log.debug("Application path is " + self.app_home)
App.log.debug("Started in " + os.getcwd())
# cx_freeze workaround
if os.path.isfile(self.app_home):
self.app_home = os.path.dirname(self.app_home)
os.chdir(self.app_home)
# Create multiprocessing pool
self.pool = Pool()
####################
## Initialize GUI ##
####################
QtCore.QObject.__init__(self)
self.ui = FlatCAMGUI(self.version)
self.connect(self.ui,
QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
self.save_geometry)
#### Plot Area ####
# self.plotcanvas = PlotCanvas(self.ui.splitter)
self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
# self.plotcanvas.mpl_connect('button_press_event', self.on_click_over_plot)
# self.plotcanvas.mpl_connect('motion_notify_event', self.on_mouse_move_over_plot)
# self.plotcanvas.mpl_connect('key_press_event', self.on_key_over_plot)
self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
self.plotcanvas.vis_connect('mouse_release', self.on_click_over_plot)
self.plotcanvas.vis_connect('key_press', self.on_key_over_plot)
self.ui.splitter.setStretchFactor(1, 2)
##############
#### Data ####
##############
self.recent = []
self.clipboard = QtGui.QApplication.clipboard()
self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
self.project_filename = None
self.toggle_units_ignore = False
self.defaults_form = GlobalOptionsUI()
self.defaults_form_fields = {
"units": self.defaults_form.units_radio,
"gerber_plot": self.defaults_form.gerber_group.plot_cb,
"gerber_solid": self.defaults_form.gerber_group.solid_cb,
"gerber_multicolored": self.defaults_form.gerber_group.multicolored_cb,
"gerber_isotooldia": self.defaults_form.gerber_group.iso_tool_dia_entry,
"gerber_isopasses": self.defaults_form.gerber_group.iso_width_entry,
"gerber_isooverlap": self.defaults_form.gerber_group.iso_overlap_entry,
"gerber_ncctools": self.defaults_form.gerber_group.ncc_tool_dia_entry,
"gerber_nccoverlap": self.defaults_form.gerber_group.ncc_overlap_entry,
"gerber_nccmargin": self.defaults_form.gerber_group.ncc_margin_entry,
"gerber_combine_passes": self.defaults_form.gerber_group.combine_passes_cb,
"gerber_cutouttooldia": self.defaults_form.gerber_group.cutout_tooldia_entry,
"gerber_cutoutmargin": self.defaults_form.gerber_group.cutout_margin_entry,
"gerber_cutoutgapsize": self.defaults_form.gerber_group.cutout_gap_entry,
"gerber_gaps": self.defaults_form.gerber_group.gaps_radio,
"gerber_noncoppermargin": self.defaults_form.gerber_group.noncopper_margin_entry,
"gerber_noncopperrounded": self.defaults_form.gerber_group.noncopper_rounded_cb,
"gerber_bboxmargin": self.defaults_form.gerber_group.bbmargin_entry,
"gerber_bboxrounded": self.defaults_form.gerber_group.bbrounded_cb,
"excellon_plot": self.defaults_form.excellon_group.plot_cb,
"excellon_solid": self.defaults_form.excellon_group.solid_cb,
"excellon_drillz": self.defaults_form.excellon_group.cutz_entry,
"excellon_travelz": self.defaults_form.excellon_group.travelz_entry,
"excellon_feedrate": self.defaults_form.excellon_group.feedrate_entry,
"excellon_spindlespeed": self.defaults_form.excellon_group.spindlespeed_entry,
"excellon_toolchangez": self.defaults_form.excellon_group.toolchangez_entry,
"excellon_tooldia": self.defaults_form.excellon_group.tooldia_entry,
"geometry_plot": self.defaults_form.geometry_group.plot_cb,
"geometry_cutz": self.defaults_form.geometry_group.cutz_entry,
"geometry_travelz": self.defaults_form.geometry_group.travelz_entry,
"geometry_feedrate": self.defaults_form.geometry_group.cncfeedrate_entry,
"geometry_cnctooldia": self.defaults_form.geometry_group.cnctooldia_entry,
"geometry_painttooldia": self.defaults_form.geometry_group.painttooldia_entry,
"geometry_spindlespeed": self.defaults_form.geometry_group.cncspindlespeed_entry,
"geometry_paintoverlap": self.defaults_form.geometry_group.paintoverlap_entry,
"geometry_paintmargin": self.defaults_form.geometry_group.paintmargin_entry,
"cncjob_plot": self.defaults_form.cncjob_group.plot_cb,
"cncjob_tooldia": self.defaults_form.cncjob_group.tooldia_entry,
"cncjob_prepend": self.defaults_form.cncjob_group.prepend_text,
"cncjob_append": self.defaults_form.cncjob_group.append_text,
"cncjob_dwell": self.defaults_form.cncjob_group.dwell_cb,
"cncjob_dwelltime": self.defaults_form.cncjob_group.dwelltime_cb
}
self.defaults = LoudDict()
self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
self.defaults.update({
"serial": 0,
"stats": {},
"units": "IN",
"gerber_plot": True,
"gerber_solid": True,
"gerber_multicolored": False,
"gerber_isotooldia": 0.016,
"gerber_isopasses": 1,
"gerber_isooverlap": 0.15,
"gerber_ncctools": "1.0, 0.5",
"gerber_nccoverlap": 0.4,
"gerber_nccmargin": 1,
"gerber_cutouttooldia": 0.07,
"gerber_cutoutmargin": 0.1,
"gerber_cutoutgapsize": 0.15,
"gerber_gaps": "4",
"gerber_noncoppermargin": 0.0,
"gerber_noncopperrounded": False,
"gerber_bboxmargin": 0.0,
"gerber_bboxrounded": False,
"excellon_plot": True,
"excellon_solid": False,
"excellon_drillz": -0.1,
"excellon_travelz": 0.1,
"excellon_feedrate": 3.0,
"excellon_spindlespeed": None,
"excellon_toolchangez": 1.0,
"excellon_tooldia": 0.016,
"geometry_plot": True,
"geometry_cutz": -0.002,
"geometry_travelz": 0.1,
"geometry_feedrate": 3.0,
"geometry_cnctooldia": 0.016,
"geometry_spindlespeed": None,
"geometry_painttooldia": 0.07,
"geometry_paintoverlap": 0.15,
"geometry_paintmargin": 0.0,
"cncjob_plot": True,
"cncjob_tooldia": 0.016,
"cncjob_prepend": "",
"cncjob_append": "",
"cncjob_dwell": True,
"cncjob_dwelltime": 1,
"background_timeout": 300000, # Default value is 5 minutes
"verbose_error_level": 0, # Shell verbosity 0 = default
# (python trace only for unknown errors),
# 1 = show trace(show trace allways),
# 2 = (For the future).
# Persistence
"last_folder": None,
# Default window geometry
"def_win_x": 100,
"def_win_y": 100,
"def_win_w": 1024,
"def_win_h": 650,
# Constants...
"defaults_save_period_ms": 20000, # Time between default saves.
"shell_shape": [500, 300], # Shape of the shell in pixels.
"shell_at_startup": False, # Show the shell at startup.
"recent_limit": 10, # Max. items in recent list.
"fit_key": '1',
"zoom_out_key": '2',
"zoom_in_key": '3',
"zoom_ratio": 1.5,
"point_clipboard_format": "(%.4f, %.4f)",
"zdownrate": None,
"excellon_zeros": "L",
"gerber_use_buffer_for_union": True,
"cncjob_coordinate_format": "X%.4fY%.4f"
})
###############################
### Load defaults from file ###
if user_defaults:
self.load_defaults()
chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
if self.defaults['serial'] == 0 or len(str(self.defaults['serial'])) < 10:
self.defaults['serial'] = ''.join([random.choice(chars) for i in range(20)])
self.save_defaults(silent=True)
self.propagate_defaults()
self.restore_main_win_geom()
def auto_save_defaults():
try:
self.save_defaults(silent=True)
finally:
QtCore.QTimer.singleShot(self.defaults["defaults_save_period_ms"], auto_save_defaults)
if user_defaults:
QtCore.QTimer.singleShot(self.defaults["defaults_save_period_ms"], auto_save_defaults)
self.options_form = GlobalOptionsUI()
self.options_form_fields = {
"units": self.options_form.units_radio,
"gerber_plot": self.options_form.gerber_group.plot_cb,
"gerber_solid": self.options_form.gerber_group.solid_cb,
"gerber_multicolored": self.options_form.gerber_group.multicolored_cb,
"gerber_isotooldia": self.options_form.gerber_group.iso_tool_dia_entry,
"gerber_isopasses": self.options_form.gerber_group.iso_width_entry,
"gerber_isooverlap": self.options_form.gerber_group.iso_overlap_entry,
"gerber_ncctools": self.options_form.gerber_group.ncc_tool_dia_entry,
"gerber_nccoverlap": self.options_form.gerber_group.ncc_overlap_entry,
"gerber_nccmargin": self.options_form.gerber_group.ncc_margin_entry,
"gerber_combine_passes": self.options_form.gerber_group.combine_passes_cb,
"gerber_cutouttooldia": self.options_form.gerber_group.cutout_tooldia_entry,
"gerber_cutoutmargin": self.options_form.gerber_group.cutout_margin_entry,
"gerber_cutoutgapsize": self.options_form.gerber_group.cutout_gap_entry,
"gerber_gaps": self.options_form.gerber_group.gaps_radio,
"gerber_noncoppermargin": self.options_form.gerber_group.noncopper_margin_entry,
"gerber_noncopperrounded": self.options_form.gerber_group.noncopper_rounded_cb,
"gerber_bboxmargin": self.options_form.gerber_group.bbmargin_entry,
"gerber_bboxrounded": self.options_form.gerber_group.bbrounded_cb,
"excellon_plot": self.options_form.excellon_group.plot_cb,
"excellon_solid": self.options_form.excellon_group.solid_cb,
"excellon_drillz": self.options_form.excellon_group.cutz_entry,
"excellon_travelz": self.options_form.excellon_group.travelz_entry,
"excellon_feedrate": self.options_form.excellon_group.feedrate_entry,
"excellon_spindlespeed": self.options_form.excellon_group.spindlespeed_entry,
"excellon_toolchangez": self.options_form.excellon_group.toolchangez_entry,
"excellon_tooldia": self.options_form.excellon_group.tooldia_entry,
"geometry_plot": self.options_form.geometry_group.plot_cb,
"geometry_cutz": self.options_form.geometry_group.cutz_entry,
"geometry_travelz": self.options_form.geometry_group.travelz_entry,
"geometry_feedrate": self.options_form.geometry_group.cncfeedrate_entry,
"geometry_spindlespeed": self.options_form.geometry_group.cncspindlespeed_entry,
"geometry_cnctooldia": self.options_form.geometry_group.cnctooldia_entry,
"geometry_painttooldia": self.options_form.geometry_group.painttooldia_entry,
"geometry_paintoverlap": self.options_form.geometry_group.paintoverlap_entry,
"geometry_paintmargin": self.options_form.geometry_group.paintmargin_entry,
"cncjob_plot": self.options_form.cncjob_group.plot_cb,
"cncjob_tooldia": self.options_form.cncjob_group.tooldia_entry,
"cncjob_prepend": self.options_form.cncjob_group.prepend_text,
"cncjob_append": self.options_form.cncjob_group.append_text
}
self.options = LoudDict()
self.options.set_change_callback(self.on_options_dict_change)
self.options.update({
"units": "IN",
"gerber_plot": True,
"gerber_solid": True,
"gerber_multicolored": False,
"gerber_isotooldia": 0.016,
"gerber_isopasses": 1,
"gerber_isooverlap": 0.15,
"gerber_ncctools": "1.0, 0.5",
"gerber_nccoverlap": 0.4,
"gerber_nccmargin": 1,
"gerber_combine_passes": True,
"gerber_cutouttooldia": 0.07,
"gerber_cutoutmargin": 0.1,
"gerber_cutoutgapsize": 0.15,
"gerber_gaps": "4",
"gerber_noncoppermargin": 0.0,
"gerber_noncopperrounded": False,
"gerber_bboxmargin": 0.0,
"gerber_bboxrounded": False,
"excellon_plot": True,
"excellon_solid": False,
"excellon_drillz": -0.1,
"excellon_travelz": 0.1,
"excellon_feedrate": 3.0,
"excellon_spindlespeed": None,
"excellon_toolchangez": 1.0,
"excellon_tooldia": 0.016,
"geometry_plot": True,
"geometry_cutz": -0.002,
"geometry_travelz": 0.1,
"geometry_feedrate": 3.0,
"geometry_spindlespeed": None,
"geometry_cnctooldia": 0.016,
"geometry_painttooldia": 0.07,
"geometry_paintoverlap": 0.15,
"geometry_paintmargin": 0.0,
"cncjob_plot": True,
"cncjob_tooldia": 0.016,
"cncjob_prepend": "",
"cncjob_append": "",
"background_timeout": 300000, #default value is 5 minutes
"verbose_error_level": 0, # shell verbosity 0 = default(python trace only for unknown errors), 1 = show trace(show trace allways), 2 = (For the future).
})
self.options.update(self.defaults) # Copy app defaults to project options
#self.options_write_form()
self.on_options_combo_change(0) # Will show the initial form
self.collection = ObjectCollection()
self.ui.project_tab_layout.addWidget(self.collection.view)
#### End of Data ####
#### Adjust tabs width ####
self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
#### Worker ####
# App.log.info("Starting Worker...")
# self.worker = Worker(self)
# self.thr1 = QtCore.QThread()
# self.worker.moveToThread(self.thr1)
# self.connect(self.thr1, QtCore.SIGNAL("started()"), self.worker.run)
# self.thr1.start()
#### Check for updates ####
# Separate thread (Not worker)
# App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
# self.worker2 = Worker(self, name="worker2")
# self.thr2 = QtCore.QThread()
# self.worker2.moveToThread(self.thr2)
# self.connect(self.thr2, QtCore.SIGNAL("started()"), self.worker2.run)
# self.connect(self.thr2, QtCore.SIGNAL("started()"),
# lambda: self.worker_task.emit({'fcn': self.version_check,
# 'params': [],
# 'worker_name': "worker2"}))
# self.thr2.start()
# Create multiprocess pool
# self.pool = WorkerPool()
# self.worker_task.connect(self.pool.add_task)
self.workers = WorkerStack()
self.worker_task.connect(self.workers.add_task)
### Signal handling ###
## Custom signals
self.inform.connect(self.info)
self.message.connect(self.message_dialog)
self.progress.connect(self.set_progress_bar)
self.object_created.connect(self.on_object_created)
self.object_plotted.connect(self.on_object_plotted)
self.plots_updated.connect(self.on_plots_updated)
self.file_opened.connect(self.register_recent)
self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
## Standard signals
# Menu
self.ui.menufilenew.triggered.connect(self.on_file_new)
self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
self.ui.menufileimportsvg.triggered.connect(self.on_file_importsvg)
self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
self.ui.menueditnew.triggered.connect(lambda: self.new_object('geometry', 'New Geometry', lambda x, y: None))
self.ui.menueditedit.triggered.connect(self.edit_geometry)
self.ui.menueditok.triggered.connect(self.editor2geometry)
self.ui.menueditjoin.triggered.connect(self.on_edit_join)
self.ui.menueditdelete.triggered.connect(self.on_delete)
self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
self.ui.menuviewdisableall.triggered.connect(lambda: self.disable_plots(self.collection.get_list()))
self.ui.menuviewdisableother.triggered.connect(lambda: self.disable_plots(self.collection.get_non_selected()))
self.ui.menuviewenable.triggered.connect(lambda: self.enable_plots(self.collection.get_list()))
self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
self.ui.menuhelp_about.triggered.connect(self.on_about)
self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
self.ui.menuprojectdelete.triggered.connect(self.on_delete)
# Toolbar
self.ui.file_new_btn.triggered.connect(self.on_file_new)
self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
# self.ui.clear_plot_btn.triggered.connect(lambda: self.disable_plots(self.collection.get_non_selected()))
# self.ui.replot_btn.triggered.connect(lambda: self.enable_plots(self.collection.get_list()))
self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
self.ui.replot_btn.triggered.connect(self.plot_all)
self.ui.newgeo_btn.triggered.connect(lambda: self.new_object('geometry', 'New Geometry', lambda x, y: None))
self.ui.editgeo_btn.triggered.connect(self.edit_geometry)
self.ui.updategeo_btn.triggered.connect(self.editor2geometry)
self.ui.delete_btn.triggered.connect(self.on_delete)
self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
# Object list
self.collection.view.activated.connect(self.on_row_activated)
# Options
self.ui.options_combo.activated.connect(self.on_options_combo_change)
self.options_form.units_radio.group_toggle_fn = self.on_toggle_units
####################
### Other setups ###
####################
# Sets up FlatCAMObj, FCProcess and FCProcessContainer.
self.setup_obj_classes()
self.setup_recent_items()
self.setup_component_editor()
#########################
### Tools and Plugins ###
#########################
self.dblsidedtool = DblSidedTool(self)
self.dblsidedtool.install()
self.measeurement_tool = Measurement(self)
self.measeurement_tool.install()
self.draw = FlatCAMDraw(self, disabled=True)
#############
### Shell ###
#############
# TODO: Move this to its own class
self.shell = FCShell(self)
self.shell.setWindowIcon(self.ui.app_icon)
self.shell.setWindowTitle("FlatCAM Shell")
self.shell.resize(*self.defaults["shell_shape"])
self.shell.append_output("FlatCAM %s\n(c) 2014-2015 Juan Pablo Caram\n\n" % self.version)
self.shell.append_output("Type help to get started.\n\n")
self.init_tcl()
self.ui.shell_dock = QtGui.QDockWidget("FlatCAM TCL Shell")
self.ui.shell_dock.setWidget(self.shell)
self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
self.ui.shell_dock.setFeatures(QtGui.QDockWidget.DockWidgetMovable |
QtGui.QDockWidget.DockWidgetFloatable | QtGui.QDockWidget.DockWidgetClosable)
self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
if self.defaults["shell_at_startup"]:
self.ui.shell_dock.show()
else:
self.ui.shell_dock.hide()
if self.cmd_line_shellfile:
try:
with open(self.cmd_line_shellfile, "r") as myfile:
cmd_line_shellfile_text = myfile.read()
self.shell._sysShell.exec_command(cmd_line_shellfile_text)
except Exception as ext:
print "ERROR: ", ext
sys.exit(2)
# Post-GUI initialization: Experimental attempt
# to perform unit tests on the GUI.
if post_gui is not None:
post_gui(self)
App.log.debug("END of constructor. Releasing control.")
def init_tcl(self):
if hasattr(self,'tcl'):
# self.tcl = None
# TODO we need to clean non default variables and procedures here
# new object cannot be used here as it will not remember values created for next passes,
# because tcl was execudted in old instance of TCL
pass
else:
self.tcl = Tkinter.Tcl()
self.setup_shell()
def defaults_read_form(self):
for option in self.defaults_form_fields:
self.defaults[option] = self.defaults_form_fields[option].get_value()
def defaults_write_form(self):
for option in self.defaults:
self.defaults_write_form_field(option)
# try:
# self.defaults_form_fields[option].set_value(self.defaults[option])
# except KeyError:
# #self.log.debug("defaults_write_form(): No field for: %s" % option)
# # TODO: Rethink this?
# pass
def defaults_write_form_field(self, field):
try:
self.defaults_form_fields[field].set_value(self.defaults[field])
except KeyError:
#self.log.debug("defaults_write_form(): No field for: %s" % option)
# TODO: Rethink this?
pass
def disable_plots(self, objects):
# TODO: This method is very similar to replot_all. Try to merge.
"""
Disables plots
:param objects: list
Objects to be disabled
:return:
"""
self.progress.emit(10)
def worker_task(app_obj):
percentage = 0.1
try:
delta = 0.9 / len(objects)
except ZeroDivisionError:
self.progress.emit(0)
return
for obj in objects:
obj.options['plot'] = False
percentage += delta
self.progress.emit(int(percentage*100))
self.progress.emit(0)
self.plots_updated.emit()
self.collection.update_view()
# Send to worker
self.worker_task.emit({'fcn': worker_task, 'params': [self]})
def clear_pool(self):
self.pool.close()
self.pool = Pool()
self.pool_recreated.emit(self.pool)
gc.collect()
def clear_plots(self):
objects = self.collection.get_list()
for obj in objects:
obj.clear(obj == objects[-1])
# Clear pool to free memory
self.clear_pool()
def edit_geometry(self):
"""
Send the current geometry object (if any) into the editor.
:return: None
"""
if not isinstance(self.collection.get_active(), FlatCAMGeometry):
self.info("Select a Geometry Object to edit.")
return
self.ui.updategeo_btn.setEnabled(True)
self.draw.edit_fcgeometry(self.collection.get_active())
def editor2geometry(self):
"""
Transfers the geometry in the editor to the current geometry object.
:return: None
"""
geo = self.collection.get_active()
if not isinstance(geo, FlatCAMGeometry):
self.info("Select a Geometry Object to update.")
return
self.draw.update_fcgeometry(geo)
self.draw.deactivate()
self.ui.updategeo_btn.setEnabled(False)
geo.plot()
def get_last_folder(self):
return self.defaults["last_folder"]
def report_usage(self, resource):
"""
Increments usage counter for the given resource
in self.defaults['stats'].
:param resource: Name of the resource.
:return: None
"""
if resource in self.defaults['stats']:
self.defaults['stats'][resource] += 1
else:
self.defaults['stats'][resource] = 1
# TODO: This shouldn't be here.
class TclErrorException(Exception):
"""
this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
"""
pass
def shell_message(self, msg, show=False, error=False):
"""
Shows a message on the FlatCAM Shell
:param msg: Message to display.
:param show: Opens the shell.
:param error: Shows the message as an error.
:return: None
"""
if show:
self.ui.shell_dock.show()
if error:
self.shell.append_error(msg + "\n")
else:
self.shell.append_output(msg + "\n")
def raise_tcl_unknown_error(self, unknownException):
"""
Raise exception if is different type than TclErrorException
this is here mainly to show unknown errors inside TCL shell console.
:param unknownException:
:return:
"""
if not isinstance(unknownException, self.TclErrorException):
self.raise_tcl_error("Unknown error: %s" % str(unknownException))
else:
raise unknownException
def display_tcl_error(self, error, error_info=None):
"""
escape bracket [ with \ otherwise there is error
"ERROR: missing close-bracket" instead of real error
:param error: it may be text or exception
:return: None
"""
if isinstance(error, Exception):
exc_type, exc_value, exc_traceback = error_info
if not isinstance(error, self.TclErrorException):
show_trace = 1
else:
show_trace = int(self.defaults['verbose_error_level'])
if show_trace > 0:
trc = traceback.format_list(traceback.extract_tb(exc_traceback))
trc_formated = []
for a in reversed(trc):
trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
text = "%s\nPython traceback: %s\n%s" % (exc_value,
exc_type,
"\n".join(trc_formated))
else:
text = "%s" % error
else:
text = error
text = text.replace('[', '\\[').replace('"', '\\"')
self.tcl.eval('return -code error "%s"' % text)
def raise_tcl_error(self, text):
"""
this method pass exception from python into TCL as error, so we get stacktrace and reason
:param text: text of error
:return: raise exception
"""
self.display_tcl_error(text)
raise self.TclErrorException(text)
def exec_command(self, text):
"""
Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
Also handles execution in separated threads
:param text:
:return: output if there was any
"""
self.report_usage('exec_command')
result = self.exec_command_test(text, False)
return result
def exec_command_test(self, text, reraise=True):
"""
Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
:param text: Input command
:param reraise: raise exception and not hide it, used mainly in unittests
:return: output if there was any
"""
text = str(text)
try:
self.shell.open_proccessing()
result = self.tcl.eval(str(text))
if result != 'None':
self.shell.append_output(result + '\n')
except Tkinter.TclError, e:
#this will display more precise answer if something in TCL shell fail
result = self.tcl.eval("set errorInfo")
self.log.error("Exec command Exception: %s" % (result + '\n'))
self.shell.append_error('ERROR: ' + result + '\n')
#show error in console and just return or in test raise exception
if reraise:
raise e
finally:
self.shell.close_proccessing()
pass
return result
"""
Code below is unsused. Saved for later.
"""
parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
parts = [p.replace('\n', '').replace('"', '') for p in parts]
self.log.debug(parts)
try:
if parts[0] not in commands:
self.shell.append_error("Unknown command\n")
return
#import inspect
#inspect.getargspec(someMethod)
if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
(type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
self.shell.append_error(
"Command %s takes %d arguments. %d given.\n" %
(parts[0], commands[parts[0]]["params"], len(parts)-1)
)
return
cmdfcn = commands[parts[0]]["fcn"]
cmdconv = commands[parts[0]]["converters"]
if len(parts) - 1 > 0:
retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
else:
retval = cmdfcn()
retfcn = commands[parts[0]]["retfcn"]
if retval and retfcn(retval):
self.shell.append_output(retfcn(retval) + "\n")
except Exception, e:
#self.shell.append_error(''.join(traceback.format_exc()))
#self.shell.append_error("?\n")
self.shell.append_error(str(e) + "\n")
def info(self, msg):
"""
Informs the user. Normally on the status bar, optionally
also on the shell.
:param msg: Text to write.
:param toshell: Forward the
:return: None
"""
# Type of message in brackets at the begining of the message.
match = re.search("\[([^\]]+)\](.*)", msg)
if match:
level = match.group(1)
msg_ = match.group(2)
self.ui.fcinfo.set_status(QtCore.QString(msg_), level=level)
error = level == "error" or level == "warning"
self.shell_message(msg, error=error, show=True)
else:
self.ui.fcinfo.set_status(QtCore.QString(msg), level="info")
self.shell_message(msg)
def load_defaults(self):
"""
Loads the aplication's default settings from defaults.json into
``self.defaults``.
:return: None
"""
try:
f = open(self.data_path + "/defaults.json")
options = f.read()
f.close()
except IOError:
self.log.error("Could not load defaults file.")
self.inform.emit("ERROR: Could not load defaults file.")
return
try:
defaults = json.loads(options)
except:
e = sys.exc_info()[0]
App.log.error(str(e))
self.inform.emit("ERROR: Failed to parse defaults file.")
return
self.defaults.update(defaults)
def save_geometry(self, x, y, width, height, notebook_width):
self.defaults["def_win_x"] = x
self.defaults["def_win_y"] = y
self.defaults["def_win_w"] = width
self.defaults["def_win_h"] = height
self.defaults["def_notebook_width"] = notebook_width
self.save_defaults()
def message_dialog(self, title, message, kind="info"):
icon = {"info": QtGui.QMessageBox.Information,
"warning": QtGui.QMessageBox.Warning,
"error": QtGui.QMessageBox.Critical}[str(kind)]
dlg = QtGui.QMessageBox(icon, title, message, parent=self.ui)
dlg.setText(message)
dlg.exec_()
def register_recent(self, kind, filename):
self.log.debug("register_recent()")
self.log.debug(" %s" % kind)
self.log.debug(" %s" % filename)
record = {'kind': str(kind), 'filename': str(filename)}
if record in self.recent:
return
self.recent.insert(0, record)
if len(self.recent) > self.defaults['recent_limit']: # Limit reached
self.recent.pop()