-
Notifications
You must be signed in to change notification settings - Fork 993
/
pronterface.py
2581 lines (2347 loc) · 117 KB
/
pronterface.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
# This file is part of the Printrun suite.
#
# Printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Printrun is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import os
import platform
import queue
import sys
import time
import threading
import traceback
import io as StringIO
import subprocess
import glob
import logging
import re
try: import simplejson as json
except ImportError: import json
from . import pronsole
from . import printcore
from printrun.spoolmanager import spoolmanager_gui
from .utils import install_locale, setup_logging, dosify, \
iconfile, configfile, format_time, format_duration, \
hexcolor_to_float, parse_temperature_report, \
prepare_command, check_rgb_color, check_rgba_color, compile_file, \
write_history_to, read_history_from
install_locale('pronterface')
try:
import wx
import wx.adv
if wx.VERSION < (4,):
raise ImportError()
except:
logging.error(_("WX >= 4 is not installed. This program requires WX >= 4 to run."))
raise
from .gui.widgets import SpecialButton, MacroEditor, PronterOptions, ButtonEdit
winsize = (800, 500)
layerindex = 0
if os.name == "nt":
winsize = (800, 530)
pronterface_quitting = False
class PronterfaceQuitException(Exception):
pass
from .gui import MainWindow
from .settings import wxSetting, HiddenSetting, StringSetting, SpinSetting, \
FloatSpinSetting, BooleanSetting, StaticTextSetting, ColorSetting, ComboSetting
from printrun import gcoder
from .pronsole import REPORT_NONE, REPORT_POS, REPORT_TEMP, REPORT_MANUAL
def format_length(mm, fractional=2):
if mm <= 10:
units = mm
suffix = 'mm'
elif mm < 1000:
units = mm / 10
suffix = 'cm'
else:
units = mm / 1000
suffix = 'm'
return '%%.%df' % fractional % units + suffix
class ConsoleOutputHandler:
"""Handle console output. All messages go through the logging submodule. We setup a logging handler to get logged messages and write them to both stdout (unless a log file path is specified, in which case we add another logging handler to write to this file) and the log panel.
We also redirect stdout and stderr to ourself to catch print messages and al."""
def __init__(self, target, log_path):
self.stdout = sys.stdout
self.stderr = sys.stderr
sys.stdout = self
sys.stderr = self
self.print_on_stdout = not log_path
if log_path:
setup_logging(self, log_path, reset_handlers = True)
else:
setup_logging(sys.stdout, reset_handlers = True)
self.target = target
def __del__(self):
sys.stdout = self.stdout
sys.stderr = self.stderr
def write(self, data):
try:
self.target(data)
except:
pass
if self.print_on_stdout:
self.stdout.write(data)
def flush(self):
if self.stdout:
self.stdout.flush()
class PronterWindow(MainWindow, pronsole.pronsole):
_fgcode = None
printer_progress_time = time.time()
def _get_fgcode(self):
return self._fgcode
def _set_fgcode(self, value):
self._fgcode = value
self.excluder = None
self.excluder_e = None
self.excluder_z_abs = None
self.excluder_z_rel = None
fgcode = property(_get_fgcode, _set_fgcode)
def _get_display_graph(self):
return self.settings.tempgraph
display_graph = property(_get_display_graph)
def _get_display_gauges(self):
return self.settings.tempgauges
display_gauges = property(_get_display_gauges)
def __init__(self, app, filename = None, size = winsize):
pronsole.pronsole.__init__(self)
self.app = app
self.window_ready = False
self.ui_ready = False
self._add_settings(size)
self.pauseScript = None #"pause.gcode"
self.endScript = None #"end.gcode"
self.filename = filename
self.capture_skip = {}
self.capture_skip_newline = False
self.fgcode = None
self.excluder = None
self.slicep = None
self.current_pos = [0, 0, 0]
self.paused = False
self.uploading = False
self.sentglines = queue.Queue(0)
self.cpbuttons = {
"motorsoff": SpecialButton(_("Motors off"), ("M84"), (250, 250, 250), _("Switch all motors off")),
"extrude": SpecialButton(_("Extrude"), ("pront_extrude"), (225, 200, 200), _("Advance extruder by set length")),
"reverse": SpecialButton(_("Reverse"), ("pront_reverse"), (225, 200, 200), _("Reverse extruder by set length")),
}
self.custombuttons = []
self.btndict = {}
self.filehistory = None
self.autoconnect = False
self.autoscrolldisable = False
self.parse_cmdline(sys.argv[1:])
for field in dir(self.settings):
if field.startswith("_gcview_color_"):
cleanname = field[1:]
color = hexcolor_to_float(getattr(self.settings, cleanname), 4)
setattr(self, cleanname, list(color))
# FIXME: We need to initialize the main window after loading the
# configs to restore the size, but this might have some unforeseen
# consequences.
# -- Okai, it seems it breaks things like update_gviz_params ><
os.putenv("UBUNTU_MENUPROXY", "0")
size = (self.settings.last_window_width, self.settings.last_window_height)
MainWindow.__init__(self, None, title = _("Pronterface"), size = size)
if self.settings.last_window_maximized:
self.Maximize()
self.SetIcon(wx.Icon(iconfile("pronterface.png"), wx.BITMAP_TYPE_PNG))
self.Bind(wx.EVT_SIZE, self.on_resize)
self.Bind(wx.EVT_MAXIMIZE, self.on_maximize)
self.window_ready = True
self.Bind(wx.EVT_CLOSE, self.closewin)
self.Bind(wx.EVT_CHAR_HOOK, self.on_key)
# set feedrates in printcore for pause/resume
self.p.xy_feedrate = self.settings.xy_feedrate
self.p.z_feedrate = self.settings.z_feedrate
self.panel.SetBackgroundColour(self.bgcolor)
customdict = {}
try:
exec(compile_file(configfile("custombtn.txt")), customdict)
if len(customdict["btns"]):
if not len(self.custombuttons):
try:
self.custombuttons = customdict["btns"]
for n in range(len(self.custombuttons)):
self.cbutton_save(n, self.custombuttons[n])
os.rename("custombtn.txt", "custombtn.old")
rco = open("custombtn.txt", "w")
rco.write(_("# I moved all your custom buttons into .pronsolerc.\n# Please don't add them here any more.\n# Backup of your old buttons is in custombtn.old\n"))
rco.close()
except IOError as x:
logging.error(str(x))
else:
logging.warning(_("Note!!! You have specified custom buttons in both custombtn.txt and .pronsolerc"))
logging.warning(_("Ignoring custombtn.txt. Remove all current buttons to revert to custombtn.txt"))
except:
pass
self.menustrip = wx.MenuBar()
self.reload_ui()
# disable all printer controls until we connect to a printer
self.gui_set_disconnected()
self.statusbar = self.CreateStatusBar()
self.statusbar.SetStatusText(_("Not connected to printer."))
self.t = ConsoleOutputHandler(self.catchprint, self.settings.log_path)
self.stdout = sys.stdout
self.slicing = False
self.loading_gcode = False
self.loading_gcode_message = ""
self.mini = False
self.p.sendcb = self.sentcb
self.p.preprintsendcb = self.preprintsendcb
self.p.printsendcb = self.printsentcb
self.p.startcb = self.startcb
self.p.endcb = self.endcb
self.cur_button = None
self.predisconnect_mainqueue = None
self.predisconnect_queueindex = None
self.predisconnect_layer = None
self.hsetpoint = 0.0
self.bsetpoint = 0.0
if self.autoconnect:
self.connect()
if self.filename is not None:
self.do_load(self.filename)
if self.settings.monitor:
self.update_monitor()
# --------------------------------------------------------------
# Main interface handling
# --------------------------------------------------------------
def reset_ui(self):
MainWindow.reset_ui(self)
self.custombuttons_widgets = []
def reload_ui(self, *args):
if not self.window_ready: return
temp_monitor = self.settings.monitor
self.settings.monitor = False
self.update_monitor()
self.Freeze()
# If UI is being recreated, delete current one
if self.ui_ready:
# Store log console content
logcontent = self.logbox.GetValue()
self.menustrip.SetMenus([])
if len(self.commandbox.history):
#save current command box history
if not os.path.exists(self.history_file):
if not os.path.exists(self.cache_dir):
os.makedirs(self.cache_dir)
write_history_to(self.history_file, self.commandbox.history)
# Create a temporary panel to reparent widgets with state we want
# to retain across UI changes
temppanel = wx.Panel(self)
# TODO: add viz widgets to statefulControls
for control in self.statefulControls:
control.GetContainingSizer().Detach(control)
control.Reparent(temppanel)
self.panel.DestroyChildren()
self.gwindow.Destroy()
self.reset_ui()
# Create UI
self.create_menu()
self.update_recent_files("recentfiles", self.settings.recentfiles)
self.splitterwindow = None
if self.settings.uimode in (_("Tabbed"), _("Tabbed with platers")):
self.createTabbedGui()
else:
self.createGui(self.settings.uimode == _("Compact"),
self.settings.controlsmode == "Mini")
if self.splitterwindow:
self.splitterwindow.SetSashPosition(self.settings.last_sash_position)
def splitter_resize(event):
self.splitterwindow.UpdateSize()
self.splitterwindow.Bind(wx.EVT_SIZE, splitter_resize)
def sash_position_changed(event):
self.set("last_sash_position", self.splitterwindow.GetSashPosition())
self.splitterwindow.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED, sash_position_changed)
# Set gcview parameters here as they don't get set when viewers are
# created
self.update_gcview_params()
# Finalize
if self.p.online:
self.gui_set_connected()
if self.ui_ready:
self.logbox.SetValue(logcontent)
temppanel.Destroy()
self.panel.Layout()
if self.fgcode:
self.start_viz_thread()
self.ui_ready = True
self.settings.monitor = temp_monitor
self.commandbox.history = read_history_from(self.history_file)
self.commandbox.histindex = len(self.commandbox.history)
self.Thaw()
if self.settings.monitor:
self.update_monitor()
def on_resize(self, event):
wx.CallAfter(self.on_resize_real)
event.Skip()
def on_resize_real(self):
maximized = self.IsMaximized()
self.set("last_window_maximized", maximized)
if not maximized and not self.IsIconized():
size = self.GetSize()
self.set("last_window_width", size[0])
self.set("last_window_height", size[1])
def on_maximize(self, event):
self.set("last_window_maximized", self.IsMaximized())
event.Skip()
def on_exit(self, event):
self.Close()
def on_settings_change(self, changed_settings):
if self.gviz:
self.gviz.on_settings_change(changed_settings)
def on_key(self, event):
if not isinstance(event.EventObject, (wx.TextCtrl, wx.ComboBox)) \
or event.HasModifiers():
ch = chr(event.KeyCode)
keys = {'B': self.btemp, 'H': self.htemp, 'J': self.xyb, 'S': self.commandbox,
'V': self.gviz}
widget = keys.get(ch)
#ignore Alt+(S, H), so it can open Settings, Help menu
if widget and (ch not in 'SH' or not event.AltDown()) \
and not (event.ControlDown() and ch == 'V'
and event.EventObject is self.commandbox):
widget.SetFocus()
return
# On MSWindows button mnemonics are processed only if the
# focus is in the parent panel
if event.AltDown() and ch < 'Z':
in_toolbar = self.toolbarsizer.GetItem(event.EventObject)
candidates = (self.connectbtn, self.connectbtn_cb_var), \
(self.pausebtn, self.pause), \
(self.printbtn, self.printfile)
for ctl, cb in candidates:
match = ('&' + ch) in ctl.Label.upper()
handled = in_toolbar and match
if handled:
break
# react to 'P' even for 'Restart', 'Resume'
# print('match', match, 'handled', handled, ctl.Label, ctl.Enabled)
if (match or ch == 'P' and ctl != self.connectbtn) and ctl.Enabled:
# print('call', ch, cb)
cb()
# react to only 1 of 'P' buttons, prefer Resume
return
event.Skip()
def closewin(self, e):
e.StopPropagation()
self.do_exit("force")
def kill(self, e=None):
if len(self.commandbox.history):
#save current command box history
history = (self.history_file)
if not os.path.exists(history):
if not os.path.exists(self.cache_dir):
os.makedirs(self.cache_dir)
write_history_to(history,self.commandbox.history)
if self.p.printing or self.p.paused:
dlg = wx.MessageDialog(self, _("Print in progress ! Are you really sure you want to quit ?"), _("Exit"), wx.YES_NO | wx.ICON_WARNING)
if dlg.ShowModal() == wx.ID_NO:
return
pronsole.pronsole.kill(self)
global pronterface_quitting
pronterface_quitting = True
self.p.recvcb = None
self.p.disconnect()
if hasattr(self, "feedrates_changed"):
self.save_in_rc("set xy_feedrate", "set xy_feedrate %d" % self.settings.xy_feedrate)
self.save_in_rc("set z_feedrate", "set z_feedrate %d" % self.settings.z_feedrate)
self.save_in_rc("set e_feedrate", "set e_feedrate %d" % self.settings.e_feedrate)
if self.settings.last_extrusion != self.settings.default_extrusion:
self.save_in_rc("set last_extrusion", "set last_extrusion %d" % self.settings.last_extrusion)
if self.excluder:
self.excluder.close_window()
wx.CallAfter(self.gwindow.Destroy)
wx.CallAfter(self.Destroy)
@property
def bgcolor(self):
return (wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWFRAME)
if self.settings.bgcolor == 'auto'
else self.settings.bgcolor)
# --------------------------------------------------------------
# Main interface actions
# --------------------------------------------------------------
def do_monitor(self, l = ""):
if l.strip() == "":
self.set("monitor", not self.settings.monitor)
elif l.strip() == "off":
self.set("monitor", False)
else:
try:
self.monitor_interval = float(l)
self.set("monitor", self.monitor_interval > 0)
except:
self.log(_("Invalid period given."))
if self.settings.monitor:
self.log(_("Monitoring printer."))
else:
self.log(_("Done monitoring."))
def do_pront_extrude(self, l = ""):
if self.p.printing and not self.paused:
self.log(_("Please pause or stop print before extruding."))
return
feed = self.settings.e_feedrate
self.do_extrude_final(self.edist.GetValue(), feed)
def do_pront_reverse(self, l = ""):
if self.p.printing and not self.paused:
self.log(_("Please pause or stop print before reversing."))
return
feed = self.settings.e_feedrate
self.do_extrude_final(- self.edist.GetValue(), feed)
def do_settemp(self, l = ""):
try:
if not isinstance(l, str) or not len(l):
l = str(self.htemp.GetValue().split()[0])
l = l.lower().replace(", ", ".")
for i in self.temps.keys():
l = l.replace(i, self.temps[i])
f = float(l)
if f >= 0:
if self.p.online:
self.p.send_now("M104 S" + l)
self.log(_("Setting hotend temperature to %g degrees Celsius.") % f)
self.sethotendgui(f)
else:
self.logError(_("Printer is not online."))
else:
self.logError(_("You cannot set negative temperatures. To turn the hotend off entirely, set its temperature to 0."))
except Exception as x:
self.logError(_("You must enter a temperature. (%s)") % (repr(x),))
def do_bedtemp(self, l = ""):
try:
if not isinstance(l, str) or not len(l):
l = str(self.btemp.GetValue().split()[0])
l = l.lower().replace(", ", ".")
for i in self.bedtemps.keys():
l = l.replace(i, self.bedtemps[i])
f = float(l)
if f >= 0:
if self.p.online:
self.p.send_now("M140 S" + l)
self.log(_("Setting bed temperature to %g degrees Celsius.") % f)
self.setbedgui(f)
else:
self.logError(_("Printer is not online."))
else:
self.logError(_("You cannot set negative temperatures. To turn the bed off entirely, set its temperature to 0."))
except Exception as x:
self.logError(_("You must enter a temperature. (%s)") % (repr(x),))
def do_setspeed(self, l = ""):
try:
if not isinstance(l, str) or not len(l):
l = str(self.speed_slider.GetValue())
else:
l = l.lower()
speed = int(l)
if self.p.online:
self.p.send_now("M220 S" + l)
self.log(_("Setting print speed factor to %d%%.") % speed)
else:
self.logError(_("Printer is not online."))
except Exception as x:
self.logError(_("You must enter a speed. (%s)") % (repr(x),))
def do_setflow(self, l = ""):
try:
if not isinstance(l, str) or not len(l):
l = str(self.flow_slider.GetValue())
else:
l = l.lower()
flow = int(l)
if self.p.online:
self.p.send_now("M221 S" + l)
self.log(_("Setting print flow factor to %d%%.") % flow)
else:
self.logError(_("Printer is not online."))
except Exception as x:
self.logError(_("You must enter a flow. (%s)") % (repr(x),))
def setbedgui(self, f):
self.bsetpoint = f
if self.display_gauges: self.bedtgauge.SetTarget(int(f))
if self.display_graph: wx.CallAfter(self.graph.SetBedTargetTemperature, int(f))
if f > 0:
wx.CallAfter(self.btemp.SetValue, str(f))
self.set("last_bed_temperature", str(f))
wx.CallAfter(self.setboff.SetBackgroundColour, None)
wx.CallAfter(self.setboff.SetForegroundColour, None)
wx.CallAfter(self.setbbtn.SetBackgroundColour, "#FFAA66")
wx.CallAfter(self.setbbtn.SetForegroundColour, "#660000")
wx.CallAfter(self.btemp.SetBackgroundColour, "#FFDABB")
else:
wx.CallAfter(self.setboff.SetBackgroundColour, "#0044CC")
wx.CallAfter(self.setboff.SetForegroundColour, "white")
wx.CallAfter(self.setbbtn.SetBackgroundColour, None)
wx.CallAfter(self.setbbtn.SetForegroundColour, None)
wx.CallAfter(self.btemp.SetBackgroundColour, "white")
wx.CallAfter(self.btemp.Refresh)
def sethotendgui(self, f):
self.hsetpoint = f
if self.display_gauges: self.hottgauge.SetTarget(int(f))
if self.display_graph: wx.CallAfter(self.graph.SetExtruder0TargetTemperature, int(f))
if f > 0:
wx.CallAfter(self.htemp.SetValue, str(f))
self.set("last_temperature", str(f))
wx.CallAfter(self.settoff.SetBackgroundColour, None)
wx.CallAfter(self.settoff.SetForegroundColour, None)
wx.CallAfter(self.settbtn.SetBackgroundColour, "#FFAA66")
wx.CallAfter(self.settbtn.SetForegroundColour, "#660000")
wx.CallAfter(self.htemp.SetBackgroundColour, "#FFDABB")
else:
wx.CallAfter(self.settoff.SetBackgroundColour, "#0044CC")
wx.CallAfter(self.settoff.SetForegroundColour, "white")
wx.CallAfter(self.settbtn.SetBackgroundColour, None)
wx.CallAfter(self.settbtn.SetForegroundColour, None)
wx.CallAfter(self.htemp.SetBackgroundColour, "white")
wx.CallAfter(self.htemp.Refresh)
def rescanports(self, event = None):
scanned = self.scanserial()
portslist = list(scanned)
if self.settings.port != "" and self.settings.port not in portslist:
portslist.append(self.settings.port)
self.serialport.Clear()
self.serialport.AppendItems(portslist)
if os.path.exists(self.settings.port) or self.settings.port in scanned:
self.serialport.SetValue(self.settings.port)
elif portslist:
self.serialport.SetValue(portslist[0])
def appendCommandHistory(self):
cmd = self.commandbox.Value
hist = self.commandbox.history
append = cmd and (not hist or hist[-1] != cmd)
if append:
self.commandbox.history.append(cmd)
return append
def cbkey(self, e):
dir = {wx.WXK_UP: -1, wx.WXK_DOWN: 1}.get(e.KeyCode)
if dir:
if self.commandbox.histindex == len(self.commandbox.history):
if dir == 1:
# do not cycle top => bottom
return
#save unsent command before going back
self.appendCommandHistory()
self.commandbox.histindex = max(0, min(self.commandbox.histindex + dir, len(self.commandbox.history)))
self.commandbox.Value = (self.commandbox.history[self.commandbox.histindex]
if self.commandbox.histindex < len(self.commandbox.history)
else '')
self.commandbox.SetInsertionPointEnd()
else:
e.Skip()
def plate(self, e):
from . import stlplater as plater
self.log(_("Plate function activated"))
plater.StlPlater(size = (800, 580), callback = self.platecb,
parent = self,
build_dimensions = self.build_dimensions_list,
circular_platform = self.settings.circular_bed,
simarrange_path = self.settings.simarrange_path,
antialias_samples = int(self.settings.antialias3dsamples)).Show()
def plate_gcode(self, e):
from . import gcodeplater as plater
self.log(_("G-Code plate function activated"))
plater.GcodePlater(size = (800, 580), callback = self.platecb,
parent = self,
build_dimensions = self.build_dimensions_list,
circular_platform = self.settings.circular_bed,
antialias_samples = int(self.settings.antialias3dsamples)).Show()
def platecb(self, name):
self.log(_("Plated %s") % name)
self.loadfile(None, name)
if self.settings.uimode in (_("Tabbed"), _("Tabbed with platers")):
# Switch to page 1 (Status tab)
self.notebook.SetSelection(1)
def do_editgcode(self, e = None):
if self.filename is not None:
MacroEditor(self.filename, [line.raw for line in self.fgcode], self.doneediting, True)
def doneediting(self, gcode):
open(self.filename, "w").write("\n".join(gcode))
wx.CallAfter(self.loadfile, None, self.filename)
def sdmenu(self, e):
obj = e.GetEventObject()
popupmenu = wx.Menu()
item = popupmenu.Append(-1, _("SD Upload"))
if not self.fgcode:
item.Enable(False)
self.Bind(wx.EVT_MENU, self.upload, id = item.GetId())
item = popupmenu.Append(-1, _("SD Print"))
self.Bind(wx.EVT_MENU, self.sdprintfile, id = item.GetId())
self.panel.PopupMenu(popupmenu, obj.GetPosition())
def htemp_change(self, event):
if self.hsetpoint > 0:
self.do_settemp("")
wx.CallAfter(self.htemp.SetInsertionPoint, 0)
def btemp_change(self, event):
if self.bsetpoint > 0:
self.do_bedtemp("")
wx.CallAfter(self.btemp.SetInsertionPoint, 0)
def tool_change(self, event):
self.do_tool(self.extrudersel.GetValue())
def show_viz_window(self, event):
if self.fgcode:
self.gwindow.Show(True)
self.gwindow.SetToolTip(wx.ToolTip("Mousewheel zooms the display\nShift / Mousewheel scrolls layers"))
self.gwindow.Raise()
def setfeeds(self, e):
self.feedrates_changed = True
try:
if self.efeedc is not None:
self.settings._set("e_feedrate", self.efeedc.GetValue())
except:
pass
try:
self.settings._set("z_feedrate", self.zfeedc.GetValue())
except:
pass
try:
self.settings._set("xy_feedrate", self.xyfeedc.GetValue())
except:
pass
try:
self.settings._set("last_extrusion", self.edist.GetValue())
except:
pass
def homeButtonClicked(self, axis):
# When user clicks on the XY control, the Z control no longer gets spacebar/repeat signals
self.zb.clearRepeat()
if axis == "x":
self.onecmd('home X')
elif axis == "y": # upper-right
self.onecmd('home Y')
elif axis == "z":
self.onecmd('home Z')
elif axis == "all":
self.onecmd('home')
elif axis == "center":
center_x = self.build_dimensions_list[0] / 2 + self.build_dimensions_list[3]
center_y = self.build_dimensions_list[1] / 2 + self.build_dimensions_list[4]
feed = self.settings.xy_feedrate
self.onecmd('G0 X%s Y%s F%s' % (center_x, center_y, feed))
else:
return
self.p.send_now('M114')
def clamped_move_message(self):
self.log(_("Manual move outside of the build volume prevented (see the \"Clamp manual moves\" option)."))
def moveXY(self, x, y):
# When user clicks on the XY control, the Z control no longer gets spacebar/repeat signals
self.zb.clearRepeat()
if x != 0:
if self.settings.clamp_jogging:
new_x = self.current_pos[0] + x
if new_x < self.build_dimensions_list[3] or new_x > self.build_dimensions_list[0] + self.build_dimensions_list[3]:
self.clamped_move_message()
return
self.onecmd('move X %s' % x)
elif y != 0:
if self.settings.clamp_jogging:
new_y = self.current_pos[1] + y
if new_y < self.build_dimensions_list[4] or new_y > self.build_dimensions_list[1] + self.build_dimensions_list[4]:
self.clamped_move_message()
return
self.onecmd('move Y %s' % y)
else:
return
self.p.send_now('M114')
def moveZ(self, z):
if z != 0:
if self.settings.clamp_jogging:
new_z = self.current_pos[2] + z
if new_z < self.build_dimensions_list[5] or new_z > self.build_dimensions_list[2] + self.build_dimensions_list[5]:
self.clamped_move_message()
return
self.onecmd('move Z %s' % z)
self.p.send_now('M114')
# When user clicks on the Z control, the XY control no longer gets spacebar/repeat signals
self.xyb.clearRepeat()
def spacebarAction(self):
self.zb.repeatLast()
self.xyb.repeatLast()
# --------------------------------------------------------------
# Console handling
# --------------------------------------------------------------
def catchprint(self, l):
"""Called by the Tee operator to write to the log box"""
if not self.IsFrozen():
wx.CallAfter(self.addtexttolog, l)
def addtexttolog(self, text):
try:
max_length = 20000
current_length = self.logbox.GetLastPosition()
if current_length > max_length:
self.logbox.Remove(0, current_length / 10)
currentCaretPosition = self.logbox.GetInsertionPoint()
currentLengthOfText = self.logbox.GetLastPosition()
if self.autoscrolldisable:
self.logbox.Freeze()
currentSelectionStart, currentSelectionEnd = self.logbox.GetSelection()
self.logbox.SetInsertionPointEnd()
self.logbox.AppendText(text)
self.logbox.SetInsertionPoint(currentCaretPosition)
self.logbox.SetSelection(currentSelectionStart, currentSelectionEnd)
self.logbox.Thaw()
else:
self.logbox.SetInsertionPointEnd()
self.logbox.AppendText(text)
except:
self.log(_("Attempted to write invalid text to console, which could be due to an invalid baudrate"))
def clear_log(self, e):
self.logbox.Clear()
def set_verbose_communications(self, e):
self.p.loud = e.IsChecked()
def set_autoscrolldisable(self,e):
self.autoscrolldisable = e.IsChecked()
def sendline(self, e):
command = self.commandbox.Value
if not len(command):
return
logging.info(">>> " + command)
line = self.precmd(str(command))
self.onecmd(line)
self.appendCommandHistory()
self.commandbox.histindex = len(self.commandbox.history)
self.commandbox.Value = ''
# --------------------------------------------------------------
# Main menu handling & actions
# --------------------------------------------------------------
def create_menu(self):
"""Create main menu"""
# File menu
m = wx.Menu()
self.Bind(wx.EVT_MENU, self.loadfile, m.Append(-1, _("&Open...\tCtrl+O"), _(" Open file")))
self.savebtn = m.Append(-1, _("&Save..."), _(" Save file"))
self.savebtn.Enable(False)
self.Bind(wx.EVT_MENU, self.savefile, self.savebtn)
self.filehistory = wx.FileHistory(maxFiles = 8, idBase = wx.ID_FILE1)
recent = wx.Menu()
self.filehistory.UseMenu(recent)
self.Bind(wx.EVT_MENU_RANGE, self.load_recent_file,
id = wx.ID_FILE1, id2 = wx.ID_FILE9)
m.Append(wx.ID_ANY, _("&Recent Files"), recent)
self.Bind(wx.EVT_MENU, self.clear_log, m.Append(-1, _("Clear console\tCtrl+L"), _(" Clear output console")))
self.Bind(wx.EVT_MENU, self.on_exit, m.Append(wx.ID_EXIT, _("E&xit"), _(" Closes the Window")))
self.menustrip.Append(m, _("&File"))
# Tools Menu
m = wx.Menu()
self.Bind(wx.EVT_MENU, self.do_editgcode, m.Append(-1, _("&Edit..."), _(" Edit open file")))
self.Bind(wx.EVT_MENU, self.plate, m.Append(-1, _("Plater"), _(" Compose 3D models into a single plate")))
self.Bind(wx.EVT_MENU, self.plate_gcode, m.Append(-1, _("G-Code Plater"), _(" Compose G-Codes into a single plate")))
self.Bind(wx.EVT_MENU, self.exclude, m.Append(-1, _("Excluder"), _(" Exclude parts of the bed from being printed")))
self.Bind(wx.EVT_MENU, self.project, m.Append(-1, _("Projector"), _(" Project slices")))
self.Bind(wx.EVT_MENU,
self.show_spool_manager,
m.Append(-1, _("Spool Manager"),
_(" Manage different spools of filament")))
self.menustrip.Append(m, _("&Tools"))
# Advanced Menu
m = wx.Menu()
self.recoverbtn = m.Append(-1, _("Recover"), _(" Recover previous print after a disconnect (homes X, Y, restores Z and E status)"))
self.recoverbtn.Disable = lambda *a: self.recoverbtn.Enable(False)
self.Bind(wx.EVT_MENU, self.recover, self.recoverbtn)
self.menustrip.Append(m, _("&Advanced"))
if self.settings.slic3rintegration:
m = wx.Menu()
print_menu = wx.Menu()
filament_menu = wx.Menu()
printer_menu = wx.Menu()
m.AppendSubMenu(print_menu, _("Print &settings"))
m.AppendSubMenu(filament_menu, _("&Filament"))
m.AppendSubMenu(printer_menu, _("&Printer"))
menus = {"print": print_menu,
"filament": filament_menu,
"printer": printer_menu}
try:
self.load_slic3r_configs(menus)
self.menustrip.Append(m, _("&Slic3r"))
except IOError:
self.logError(_("Failed to load Slic3r configuration:") +
"\n" + traceback.format_exc())
# Settings menu
m = wx.Menu()
self.macros_menu = wx.Menu()
m.AppendSubMenu(self.macros_menu, _("&Macros"))
self.Bind(wx.EVT_MENU, self.new_macro, self.macros_menu.Append(-1, _("<&New...>")))
self.Bind(wx.EVT_MENU, lambda *e: PronterOptions(self), m.Append(-1, _("&Options"), _(" Options dialog")))
self.Bind(wx.EVT_MENU, lambda x: threading.Thread(target = lambda: self.do_slice("set")).start(), m.Append(-1, _("Slicing settings"), _(" Adjust slicing settings")))
mItem = m.AppendCheckItem(-1, _("Debug communications"),
_("Print all G-code sent to and received from the printer."))
m.Check(mItem.GetId(), self.p.loud)
self.Bind(wx.EVT_MENU, self.set_verbose_communications, mItem)
mItem = m.AppendCheckItem(-1, _("Don't autoscroll"),
_("Disables automatic scrolling of the console when new text is added"))
m.Check(mItem.GetId(), self.autoscrolldisable)
self.Bind(wx.EVT_MENU, self.set_autoscrolldisable, mItem)
self.menustrip.Append(m, _("&Settings"))
self.update_macros_menu()
self.SetMenuBar(self.menustrip)
m = wx.Menu()
self.Bind(wx.EVT_MENU, self.about,
m.Append(-1, _("&About Printrun"), _("Show about dialog")))
self.menustrip.Append(m, _("&Help"))
def project(self, event):
"""Start Projector tool"""
from printrun import projectlayer
projectlayer.SettingsFrame(self, self.p).Show()
def exclude(self, event):
"""Start part excluder tool"""
if not self.fgcode:
wx.CallAfter(self.statusbar.SetStatusText, _("No file loaded. Please use load first."))
return
if not self.excluder:
from .excluder import Excluder
self.excluder = Excluder()
self.excluder.pop_window(self.fgcode, bgcolor = self.bgcolor,
build_dimensions = self.build_dimensions_list)
def show_spool_manager(self, event):
"""Show Spool Manager Window"""
spoolmanager_gui.SpoolManagerMainWindow(self, self.spool_manager).Show()
def about(self, event):
"""Show about dialog"""
info = wx.adv.AboutDialogInfo()
info.SetIcon(wx.Icon(iconfile("pronterface.png"), wx.BITMAP_TYPE_PNG))
info.SetName('Printrun')
info.SetVersion(printcore.__version__)
description = _("Printrun is a pure Python 3D printing"
" (and other types of CNC) host software.")
description += "\n\n" + \
_("%.02fmm of filament have been extruded during prints") \
% self.settings.total_filament_used
info.SetDescription(description)
info.SetCopyright('(C) 2011 - 2020')
info.SetWebSite('https://github.com/kliment/Printrun')
licence = """\
Printrun is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
Printrun is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
Printrun. If not, see <http://www.gnu.org/licenses/>."""
info.SetLicence(licence)
info.AddDeveloper('Kliment Yanev @kliment (code)')
info.AddDeveloper('Guillaume Seguin @iXce (code)')
info.AddDeveloper('@DivingDuck (code)')
info.AddDeveloper('@volconst (code)')
info.AddDeveloper('Rock Storm @rockstorm101 (code, packaging)')
info.AddDeveloper('Miro Hrončok @hroncok (code, packaging)')
info.AddDeveloper('Rob Gilson @D1plo1d (code)')
info.AddDeveloper('Gary Hodgson @garyhodgson (code)')
info.AddDeveloper('Duane Johnson (code,graphics)')
info.AddDeveloper('Alessandro Ranellucci @alranel (code)')
info.AddDeveloper('Travis Howse @tjhowse (code)')
info.AddDeveloper('edef (code)')
info.AddDeveloper('Steven Devijver (code)')
info.AddDeveloper('Christopher Keller (code)')
info.AddDeveloper('Igor Yeremin (code)')
info.AddDeveloper('Jeremy Hammett @jezmy (code)')
info.AddDeveloper('Spencer Bliven (code)')
info.AddDeveloper('Václav \'ax\' Hůla @AxTheB (code)')
info.AddDeveloper('Félix Sipma (code)')
info.AddDeveloper('Maja M. @SparkyCola (code)')
info.AddDeveloper('Francesco Santini @fsantini (code)')
info.AddDeveloper('Cristopher Olah @colah (code)')
info.AddDeveloper('Jeremy Kajikawa (code)')
info.AddDeveloper('Markus Hitter (code)')
info.AddDeveloper('SkateBoss (code)')
info.AddDeveloper('Kaz Walker (code)')
info.AddDeveloper('Brendan Erwin (documentation)')
info.AddDeveloper('Elias (code)')
info.AddDeveloper('Jordan Miller (code)')
info.AddDeveloper('Mikko Sivulainen (code)')
info.AddDeveloper('Clarence Risher (code)')
info.AddDeveloper('Guillaume Revaillot (code)')
info.AddDeveloper('John Tapsell (code)')
info.AddDeveloper('Youness Alaoui (code)')
info.AddDeveloper('@eldir (code)')
info.AddDeveloper('@hg42 (code)')
info.AddDeveloper('@jglauche (code, documentation)')
info.AddDeveloper('Ahmet Cem TURAN @ahmetcemturan (icons, code)')
info.AddDeveloper('Andrew Dalgleish (code)')
info.AddDeveloper('Benny (documentation)')
info.AddDeveloper('Chillance (code)')
info.AddDeveloper('Ilya Novoselov (code)')
info.AddDeveloper('Joeri Hendriks (code)')
info.AddDeveloper('Kevin Cole (code)')
info.AddDeveloper('pinaise (code)')
info.AddDeveloper('Dratone (code)')
info.AddDeveloper('ERoth3 (code)')
info.AddDeveloper('Erik Zalm (code)')
info.AddDeveloper('Felipe Corrêa da Silva Sanches (code)')
info.AddDeveloper('Geordie Bilkey (code)')
info.AddDeveloper('Ken Aaker (code)')
info.AddDeveloper('Lawrence (documentation)')
info.AddDeveloper('Loxgen (code)')
info.AddDeveloper('Matthias Urlichs (code)')
info.AddDeveloper('N Oliver (code)')