forked from 1548976092/-Youth-without-regrets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
axis
executable file
·3551 lines (3115 loc) · 126 KB
/
axis
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
#!/usr/bin/python
# This is a component of AXIS, a front-end for LinuxCNC
# Copyright 2004, 2005, 2006, 2007, 2008, 2009
# Jeff Epler <[email protected]> and Chris Radek <[email protected]>
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import pdb
import sys, os
import string
print sys.argv[0]
print os.path.dirname(sys.argv[0])
print os.path.join(os.path.dirname(sys.argv[0]), "..")
print os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
BASE = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
sys.path.insert(0, os.path.join(BASE, "lib", "python"))
# otherwise, on hardy the user is shown spurious "[application] closed
# unexpectedly" messages but denied the ability to actually "report [the]
# problem"
sys.excepthook = sys.__excepthook__
import gettext;
gettext.install("linuxcnc", localedir=os.path.join(BASE, "share", "locale"), unicode=True)
import array, time, atexit, tempfile, shutil, errno, thread, select, re, getopt
import traceback
# Print Tk errors to stdout. python.org/sf/639266
import Tkinter
OldTk = Tkinter.Tk
class Tk(OldTk):
def __init__(self, *args, **kw):
OldTk.__init__(self, *args, **kw)
self.tk.createcommand('tkerror', self.tkerror)
def tkerror(self, arg):
print "TCL error in asynchronous code:"
print self.tk.call("set", "errorInfo")
Tkinter.Tk = Tk
from Tkinter import *
from minigl import *
RTLD_NOW, RTLD_GLOBAL = 0x1, 0x100 # XXX portable?
old_flags = sys.getdlopenflags()
sys.setdlopenflags(RTLD_NOW | RTLD_GLOBAL);
import gcode
sys.setdlopenflags(old_flags)
from rs274.OpenGLTk import *
from rs274.interpret import StatMixin
from rs274.glcanon import GLCanon, GlCanonDraw
from hershey import Hershey
from propertywindow import properties
import rs274.options
import nf
import locale
import bwidget
from math import hypot, atan2, sin, cos, pi, sqrt
import linuxcnc
from glnav import *
if os.environ.has_key("AXIS_NO_HAL"):
hal_present = 0;
else:
hal_present = 1;
if hal_present == 1 :
import hal
import ConfigParser
cp = ConfigParser.ConfigParser
class AxisPreferences(cp):
types = {
bool: cp.getboolean,
float: cp.getfloat,
int: cp.getint,
str: cp.get,
repr: lambda self,section,option: eval(cp.get(self,section,option)),
}
def __init__(self):
cp.__init__(self)
self.fn = os.path.expanduser("~/.axis_preferences")
self.read(self.fn)
def getpref(self, option, default=False, type=bool):
m = self.types.get(type)
try:
o = m(self, "DEFAULT", option)
except Exception, detail:
print detail
self.set("DEFAULT", option, default)
self.write(open(self.fn, "w"))
o = default
return o
def putpref(self, option, value, type=bool):
self.set("DEFAULT", option, type(value))
self.write(open(self.fn, "w"))
if sys.argv[1] != "-ini":
raise SystemExit, "-ini must be first argument"
inifile = linuxcnc.ini(sys.argv[2])
ap = AxisPreferences()
os.system("xhost -SI:localuser:gdm -SI:localuser:root > /dev/null 2>&1")
root_window = Tkinter.Tk(className="Axis")
root_window.iconify()
nf.start(root_window)
nf.makecommand(root_window, "_", _)
rs274.options.install(root_window)
root_window.tk.call("set", "version", linuxcnc.version)
try:
nf.source_lib_tcl(root_window,"axis.tcl")
except TclError:
print root_window.tk.call("set", "errorInfo")
raise
def General_Halt():
text = _("Do you really want to close linuxcnc?")
if not root_window.tk.call("nf_dialog", ".error", _("Confirm Close"), text, "warning", 1, _("Yes"), _("No")):
root_window.destroy()
root_window.protocol("WM_DELETE_WINDOW", General_Halt)
program_start_line = 0
program_start_line_last = -1
lathe = 0
mdi_history_max_entries = 1000
mdi_history_save_filename =\
inifile.find('DISPLAY', 'MDI_HISTORY_FILE') or "~/.axis_mdi_history"
feedrate_blackout = 0
rapidrate_blackout = 0
spindlerate_blackout = 0
maxvel_blackout = 0
jogincr_index_last = 1
mdi_history_index= -1
resume_inhibit = 0
help1 = [
("F1", _("Emergency stop")),
("F2", _("Turn machine on")),
("", ""),
("X, `", _("Activate first axis")),
("Y, 1", _("Activate second axis")),
("Z, 2", _("Activate third axis")),
("A, 3", _("Activate fourth axis")),
("4..8", _("Activate fifth through ninth axis")),
("`, 1..9, 0", _("Set Feed Override from 0% to 100%")),
(_(", and ."), _("Select jog speed")),
(_("< and >"), _("Select angular jog speed")),
(_("I, Shift-I"), _("Select jog increment")),
("C", _("Continuous jog")),
(_("Home"), _("Send active axis home")),
(_("Ctrl-Home"), _("Home all axes")),
(_("Shift-Home"), _("Zero G54 offset for active axis")),
(_("End"), _("Set G54 offset for active axis")),
(_("Ctrl-End"), _("Set tool offset for loaded tool")),
("-, =", _("Jog active axis")),
(";, '", _("Select Max velocity")),
("", ""),
(_("Left, Right"), _("Jog first axis")),
(_("Up, Down"), _("Jog second axis")),
(_("Pg Up, Pg Dn"), _("Jog third axis")),
(_("Shift+above jogs"), _("Jog at traverse speed")),
("[, ]", _("Jog fourth axis")),
("", ""),
("D", _("Toggle between Drag and Rotate mode")),
(_("Left Button"), _("Pan, rotate or select line")),
(_("Shift+Left Button"), _("Rotate or pan")),
(_("Right Button"), _("Zoom view")),
(_("Wheel Button"), _("Rotate view")),
(_("Rotate Wheel"), _("Zoom view")),
(_("Control+Left Button"), _("Zoom view")),
]
help2 = [
("F3", _("Manual control")),
("F5", _("Code entry (MDI)")),
(_("Control-M"), _("Clear MDI history")),
(_("Control-H"), _("Copy selected MDI history elements")),
("", _("to clipboard")),
(_("Control-Shift-H"), _("Paste clipboard to MDI history")),
("L", _("Override Limits")),
("", ""),
("O", _("Open program")),
(_("Control-R"), _("Reload program")),
(_("Control-S"), _("Save g-code as")),
("R", _("Run program")),
("T", _("Step program")),
("P", _("Pause program")),
("S", _("Resume program")),
("ESC", _("Stop running program, or")),
("", _("stop loading program preview")),
("", ""),
("F7", _("Toggle mist")),
("F8", _("Toggle flood")),
("B", _("Spindle brake off")),
(_("Shift-B"), _("Spindle brake on")),
("F9", _("Turn spindle clockwise")),
("F10", _("Turn spindle counterclockwise")),
("F11", _("Turn spindle more slowly")),
("F12", _("Turn spindle more quickly")),
(_("Control-K"), _("Clear live plot")),
("V", _("Cycle among preset views")),
("F4", _("Cycle among preview, DRO, and user tabs")),
("@", _("toggle Actual/Commanded")),
("#", _("toggle Relative/Machine")),
(_("Ctrl-Space"), _("Clear notifications")),
(_("Alt-F, M, V"), _("Open a Menu")),
]
def install_help(app):
keys = nf.makewidget(app, Frame, '.keys.text')
fixed = app.tk.call("linuxcnc::standard_fixed_font")
for i in range(len(help1)):
a, b = help1[i]
Label(keys, text=a, font=fixed, padx=4, pady=0, highlightthickness=0).grid(row=i, column=0, sticky="w")
Label(keys, text=b, padx=4, pady=0, highlightthickness=0).grid(row=i, column=1, sticky="w")
for i in range(len(help2)):
a, b = help2[i]
Label(keys, text=a, font=fixed, padx=4, pady=0, highlightthickness=0).grid(row=i, column=3, sticky="w")
Label(keys, text=b, padx=4, pady=0, highlightthickness=0).grid(row=i, column=4, sticky="w")
Label(keys, text=" ").grid(row=0, column=2)
def joints_mode():
return s.motion_mode == linuxcnc.TRAJ_MODE_FREE and s.kinematics_type != linuxcnc.KINEMATICS_IDENTITY
def parse_color(c):
if c == "": return (1,0,0)
return tuple([i/65535. for i in root_window.winfo_rgb(c)])
def to_internal_units(pos, unit=None):
if unit is None:
unit = s.linear_units
lu = (unit or 1) * 25.4
lus = [lu, lu, lu, 1, 1, 1, lu, lu, lu]
return [a/b for a, b in zip(pos, lus)]
def to_internal_linear_unit(v, unit=None):
if unit is None:
unit = s.linear_units
lu = (unit or 1) * 25.4
return v/lu
def from_internal_units(pos, unit=None):
if unit is None:
unit = s.linear_units
lu = (unit or 1) * 25.4
lus = [lu, lu, lu, 1, 1, 1, lu, lu, lu]
return [a*b for a, b in zip(pos, lus)]
def from_internal_linear_unit(v, unit=None):
if unit is None:
unit = s.linear_units
lu = (unit or 1) * 25.4
return v*lu
class Notification(Tkinter.Frame):
def __init__(self, master):
self.widgets = []
self.cache = []
Tkinter.Frame.__init__(self, master)
def clear(self,iconname=None):
if iconname:
cpy = self.widgets[:]
for i, item in enumerate(cpy):
frame,icon,text,button,iname = item
if iname == "icon_std_" + iconname:
self.remove(cpy[i])
else:
while self.widgets:
self.remove(self.widgets[0])
def clear_one(self):
if self.widgets:
self.remove(self.widgets[0])
def add(self, iconname, message):
self.place(relx=1, rely=1, y=-20, anchor="se")
iconname = self.tk.call("load_image", "std_" + iconname)
close = self.tk.call("load_image", "close", "notification-close")
if len(self.widgets) > 10:
self.remove(self.widgets[0])
if self.cache:
frame, icon, text, button, discard = self.cache.pop()
icon.configure(image=iconname)
text.configure(text=message)
widgets = frame, icon, text, button, iconname
else:
frame = Tkinter.Frame(self)
icon = Tkinter.Label(frame, image=iconname)
text = Tkinter.Label(frame, text=message, wraplength=300, justify="left")
button = Tkinter.Button(frame, image=close)
widgets = frame, icon, text, button, iconname
text.pack(side="left")
icon.pack(side="left")
button.pack(side="left")
button.configure(command=lambda: self.remove(widgets))
frame.pack(side="top", anchor="e")
self.widgets.append(widgets)
def remove(self, widgets):
self.widgets.remove(widgets)
if len(self.cache) < 10:
widgets[0].pack_forget()
self.cache.append(widgets)
else:
widgets[0].destroy()
if len(self.widgets) == 0:
self.place_forget()
def soft_limits():
def fudge(x):
if abs(x) > 1e30: return 0
return x
ax = s.axis
return (
to_internal_units([fudge(ax[i]['min_position_limit']) for i in range(3)]),
to_internal_units([fudge(ax[i]['max_position_limit']) for i in range(3)]))
class MyOpengl(GlCanonDraw, Opengl):
def __init__(self, *args, **kw):
self.after_id = None
self.motion_after = None
self.perspective = False
Opengl.__init__(self, *args, **kw)
GlCanonDraw.__init__(self, s, None)
self.bind('<Button-1>', self.select_prime, add=True)
self.bind('<ButtonRelease-1>', self.select_fire, add=True)
self.bind('<Button1-Motion>', self.select_cancel, add=True)
self.highlight_line = None
self.select_event = None
self.select_buffer_size = 100
self.select_primed = None
self.last_position = None
self.last_homed = None
self.last_origin = None
self.last_rotation_xy = None
self.last_tool = None
self.last_limits = None
self.set_eyepoint(5.)
self.get_resources()
self.realize()
def getRotateMode(self):
return vars.rotate_mode.get()
def get_font_info(self):
return coordinate_charwidth, coordinate_linespace, fontbase
def get_resources(self):
self.colors = dict(GlCanonDraw.colors)
for c in self.colors.keys():
if isinstance(c, tuple):
c, d = c
elif c.endswith("_alpha"):
d = "Alpha"
else:
d = "Foreground"
option_value = self.option_get(c, d)
if option_value:
if d == "Alpha":
self.colors[c] = float(option_value)
else:
self.colors[c] = parse_color(option_value)
x = float(self.option_get("tool_light_x", "Float"))
y = float(self.option_get("tool_light_y", "Float"))
z = float(self.option_get("tool_light_z", "Float"))
dist = (x**2 + y**2 + z**2) ** .5
self.light_position = (x/dist, y/dist, z/dist, 0)
def select_prime(self, event):
self.select_primed = event
def select_cancel(self, event):
if self.select_primed and (event.x != self.select_primed.x or event.y != self.select_primed.y):
self.select_primed = None
def select_fire(self, event):
if self.select_primed: self.queue_select(event)
def queue_select(self, event):
self.select_event = event
self.tkRedraw()
def deselect(self, event):
self.set_highlight_line(None)
def select(self, event):
GlCanonDraw.select(self, event.x, event.y)
def get_joints_mode(self): return joints_mode()
def get_current_tool(self): return current_tool
def is_lathe(self): return lathe
def get_show_commanded(self): return vars.display_type.get()
def get_show_rapids(self): return vars.show_rapids.get()
def get_geometry(self): return geometry
def is_foam(self): return foam
def get_num_joints(self): return num_joints
def get_program_alpha(self): return vars.program_alpha.get()
def get_a_axis_wrapped(self): return a_axis_wrapped
def get_b_axis_wrapped(self): return b_axis_wrapped
def get_c_axis_wrapped(self): return c_axis_wrapped
def set_current_line(self, line):
if line == vars.running_line.get(): return
t.tag_remove("executing", "0.0", "end")
if line is not None and line > 0:
vupdate(vars.running_line, line)
if vars.highlight_line.get() <= 0:
t.see("%d.0" % (line+2))
t.see("%d.0" % line)
t.tag_add("executing", "%d.0" % line, "%d.end" % line)
else:
vupdate(vars.running_line, 0)
def get_highlight_line(self):
return vars.highlight_line.get()
def set_highlight_line(self, line):
if line == self.get_highlight_line(): return
GlCanonDraw.set_highlight_line(self, line)
t.tag_remove("sel", "0.0", "end")
if line is not None and line > 0:
t.see("%d.0" % (line+2))
t.see("%d.0" % line)
t.tag_add("sel", "%d.0" % line, "%d.end" % line)
vupdate(vars.highlight_line, line)
else:
vupdate(vars.highlight_line, -1)
def tkRedraw(self, *dummy):
if self.after_id:
# May need to upgrade to an instant redraw
self.after_cancel(self.after_id)
self.after_id = self.after_idle(self.actual_tkRedraw)
def redraw_soon(self, *dummy):
if self.after_id: return
self.after_id = self.after(50, self.actual_tkRedraw)
def tkRedraw_perspective(self, *dummy):
"""Cause the opengl widget to redraw itself."""
self.redraw_perspective()
def tkRedraw_ortho(self, *dummy):
"""Cause the opengl widget to redraw itself."""
self.redraw_ortho()
def startRotate(self, event):
if lathe: return
return Opengl.startRotate(self, event)
def tkAutoSpin(self, event):
if lathe: return
return Opengl.tkAutoSpin(self, event)
def tkRotate(self, event):
if lathe: return
Opengl.tkRotate(self, event)
self.perspective = True
widgets.view_z.configure(relief="link")
widgets.view_z2.configure(relief="link")
widgets.view_x.configure(relief="link")
widgets.view_y.configure(relief="link")
widgets.view_p.configure(relief="link")
vars.view_type.set(0)
def tkTranslateOrRotate(self, event):
if self.getRotateMode():
self.tkRotate(event)
else:
self.tkTranslate(event)
def tkRotateOrTranslate(self, event):
if self.getRotateMode():
self.tkTranslate(event)
else:
self.tkRotate(event)
def actual_tkRedraw(self, *dummy):
self.after_id = None
if self.perspective:
self.tkRedraw_perspective()
else:
self.tkRedraw_ortho()
def get_show_program(self): return vars.show_program.get()
def get_show_offsets(self): return vars.show_offsets.get()
def get_show_extents(self): return vars.show_extents.get()
def get_grid_size(self): return vars.grid_size.get()
def get_show_metric(self): return vars.metric.get()
def get_show_live_plot(self): return vars.show_live_plot.get()
def get_show_machine_speed(self): return vars.show_machine_speed.get()
def get_show_distance_to_go(self): return vars.show_distance_to_go.get()
def get_view(self):
x,y,z,p = 0,1,2,3
if str(widgets.view_x['relief']) == "sunken":
view = x
elif str(widgets.view_y['relief']) == "sunken":
view = y
elif (str(widgets.view_z['relief']) == "sunken" or
str(widgets.view_z2['relief']) == "sunken"):
view = z
else:
view = p
return view
def get_show_relative(self): return vars.coord_type.get()
def get_show_limits(self): return vars.show_machine_limits.get()
def get_show_tool(self): return vars.show_tool.get()
def redraw(self):
if not self.winfo_viewable():
return self.redraw_dro()
if self.select_event:
self.select(self.select_event)
self.select_event = None
GlCanonDraw.redraw(self)
def redraw_dro(self):
self.stat.poll()
limit, homed, posstrs, droposstrs = self.posstrs()
text = widgets.numbers_text
font = "Courier 10 pitch"
if not hasattr(self, 'font_width'):
self.font_width = text.tk.call(
"font", "measure", (font, -100, "bold"), "0")
self.font_vertspace = text.tk.call(
"font", "metrics", (font, -100, "bold"), "-linespace") - 100
self.last_font = None
font_width = self.font_width
font_vertspace = self.font_vertspace
text.delete("0.0", "end")
t = droposstrs[:]
i = 0
for ts in t:
if i < len(homed) and homed[i]:
t[i] += "*"
else:
t[i] += " "
if i < len(homed) and limit[i]:
t[i] += "!" # !!!1!
else:
t[i] += " "
i+=1
text.insert("end", "\n".join(t))
window_height = text.winfo_height()
window_width = text.winfo_width()
dro_lines = len(droposstrs)
dro_width = len(droposstrs[0]) + 3
# pixels of height required, for "100 pixel" font
req_height = dro_lines * 100 + (dro_lines + 1) * font_vertspace
# pixels of width required, for "100 pixel" font
req_width = dro_width * font_width
height_ratio = float(window_height) / req_height
width_ratio = float(window_width) / req_width
ratio = min(height_ratio, width_ratio)
new_font = -int(100*ratio)
if new_font != self.last_font:
text.configure(font=(font, new_font, "bold"))
self.last_font = new_font
def init():
glDrawBuffer(GL_BACK)
glDisable(GL_CULL_FACE)
glLineStipple(2, 0x5555)
glDisable(GL_LIGHTING)
glClearColor(0,0,0,0)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
def toggle_perspective(e):
o.perspective = not o.perspective
o.tkRedraw()
def select_line(event):
i = t.index("@%d,%d" % (event.x, event.y))
i = int(i.split('.')[0])
o.set_highlight_line(i)
o.tkRedraw()
return "break"
def select_prev(event):
if o.highlight_line is None:
i = o.last_line
else:
i = max(1, o.highlight_line - 1)
o.set_highlight_line(i)
o.tkRedraw()
def select_next(event):
if o.highlight_line is None:
i = 1
else:
i = min(o.last_line, o.highlight_line + 1)
o.set_highlight_line(i)
o.tkRedraw()
def scroll_up(event):
t.yview_scroll(-2, "units")
def scroll_down(event):
t.yview_scroll(2, "units")
current_tool = None
def vupdate(var, val):
try:
if var.get() == val: return
except ValueError:
pass
var.set(val)
class LivePlotter:
def __init__(self, window):
self.win = window
window.live_plot_size = 0
self.after = None
self.error_after = None
self.running = BooleanVar(window)
self.running.set(False)
self.lastpts = -1
self.last_speed = -1
self.last_limit = None
self.last_motion_mode = None
self.last_joint_position = None
self.notifications_clear = False
self.notifications_clear_info = False
self.notifications_clear_error = False
def start(self):
if self.running.get(): return
if not os.path.exists(linuxcnc.nmlfile):
return False
try:
self.stat = linuxcnc.stat()
except linuxcnc.error:
return False
self.current_task_mode = self.stat.task_mode
def C(s):
a = o.colors[s + "_alpha"]
s = o.colors[s]
return [int(x * 255) for x in s + (a,)]
self.logger = linuxcnc.positionlogger(linuxcnc.stat(),
C('backplotjog'),
C('backplottraverse'),
C('backplotfeed'),
C('backplotarc'),
C('backplottoolchange'),
C('backplotprobing'),
geometry, foam
)
o.after_idle(lambda: thread.start_new_thread(self.logger.start, (.01,)))
global feedrate_blackout, rapidrate_blackout, spindlerate_blackout, maxvel_blackout
feedrate_blackout=rapidrate_blackout=spindlerate_blackout=maxvel_blackout=time.time()+1
self.running.set(True)
def stop(self):
if not self.running.get(): return
if hasattr(self, 'stat'): del self.stat
if self.after is not None:
self.win.after_cancel(self.after)
self.after = None
if self.error_after is not None:
self.win.after_cancel(self.error_after)
self.error_after = None
self.logger.stop()
self.running.set(True)
def error_task(self):
error = e.poll()
while error:
kind, text = error
if kind in (linuxcnc.NML_ERROR, linuxcnc.OPERATOR_ERROR):
icon = "error"
else:
icon = "info"
notifications.add(icon, text)
error = e.poll()
self.error_after = self.win.after(200, self.error_task)
def update(self):
if not self.running.get():
return
try:
self.stat.poll()
except linuxcnc.error, detail:
print "error", detail
del self.stat
return
if (self.stat.task_mode != self.current_task_mode):
self.current_task_mode = self.stat.task_mode
if (self.current_task_mode == linuxcnc.MODE_MANUAL):
root_window.tk.eval(pane_top + ".tabs raise manual")
if (self.current_task_mode == linuxcnc.MODE_MDI):
root_window.tk.eval(pane_top + ".tabs raise mdi")
if (self.current_task_mode == linuxcnc.MODE_AUTO):
# not sure if anything needs to be done for this
pass
self.after = self.win.after(update_ms, self.update)
self.win.set_current_line(self.stat.id or self.stat.motion_line)
speed = self.stat.current_vel
limits = soft_limits()
if (self.logger.npts != self.lastpts
or limits != o.last_limits
or self.stat.actual_position != o.last_position
or self.stat.joint_actual_position != o.last_joint_position
or self.stat.homed != o.last_homed
or self.stat.g5x_offset != o.last_g5x_offset
or self.stat.g92_offset != o.last_g92_offset
or self.stat.g5x_index != o.last_g5x_index
or self.stat.rotation_xy != o.last_rotation_xy
or self.stat.limit != o.last_limit
or self.stat.tool_table[0] != o.last_tool
or self.stat.motion_mode != o.last_motion_mode
or abs(speed - self.last_speed) > .01):
o.redraw_soon()
o.last_limits = limits
o.last_limit = self.stat.limit
o.last_homed = self.stat.homed
o.last_position = self.stat.actual_position
o.last_g5x_offset = self.stat.g5x_offset
o.last_g92_offset = self.stat.g92_offset
o.last_g5x_index = self.stat.g5x_index
o.last_rotation_xy = self.stat.rotation_xy
o.last_motion_mode = self.stat.motion_mode
o.last_tool = self.stat.tool_table[0]
o.last_joint_position = self.stat.joint_actual_position
self.last_speed = speed
self.lastpts = self.logger.npts
root_window.update_idletasks()
vupdate(vars.exec_state, self.stat.exec_state)
vupdate(vars.interp_state, self.stat.interp_state)
vupdate(vars.queued_mdi_commands, self.stat.queued_mdi_commands)
if hal_present == 1 :
notifications_clear = comp["notifications-clear"]
if self.notifications_clear != notifications_clear:
self.notifications_clear = notifications_clear
if self.notifications_clear:
notifications.clear()
notifications_clear_info = comp["notifications-clear-info"]
if self.notifications_clear_info != notifications_clear_info:
self.notifications_clear_info = notifications_clear_info
if self.notifications_clear_info:
notifications.clear("info")
notifications_clear_error = comp["notifications-clear-error"]
if self.notifications_clear_error != notifications_clear_error:
self.notifications_clear_error = notifications_clear_error
if self.notifications_clear_error:
notifications.clear("error")
now_resume_inhibit = comp["resume-inhibit"]
global resume_inhibit
if resume_inhibit != now_resume_inhibit:
resume_inhibit = now_resume_inhibit
if resume_inhibit:
root_window.tk.call("pause_image_override")
else:
root_window.tk.call("pause_image_normal")
vupdate(vars.task_mode, self.stat.task_mode)
vupdate(vars.task_state, self.stat.task_state)
vupdate(vars.task_paused, self.stat.task_paused)
vupdate(vars.taskfile, self.stat.file)
vupdate(vars.interp_pause, self.stat.paused)
vupdate(vars.mist, self.stat.mist)
vupdate(vars.flood, self.stat.flood)
vupdate(vars.brake, self.stat.spindle_brake)
vupdate(vars.spindledir, self.stat.spindle_direction)
vupdate(vars.motion_mode, self.stat.motion_mode)
vupdate(vars.optional_stop, self.stat.optional_stop)
vupdate(vars.block_delete, self.stat.block_delete)
if time.time() > spindlerate_blackout:
vupdate(vars.spindlerate, int(100 * self.stat.spindlerate + .5))
if time.time() > feedrate_blackout:
vupdate(vars.feedrate, int(100 * self.stat.feedrate + .5))
if time.time() > rapidrate_blackout:
vupdate(vars.rapidrate, int(100 * self.stat.rapidrate + .5))
if time.time() > maxvel_blackout:
m = to_internal_linear_unit(self.stat.max_velocity)
if vars.metric.get(): m = m * 25.4
vupdate(vars.maxvel_speed, float(int(600 * m)/10.0))
root_window.tk.call("update_maxvel_slider")
vupdate(vars.override_limits, self.stat.axis[0]['override_limits'])
on_any_limit = 0
for i, l in enumerate(self.stat.limit):
if self.stat.axis_mask & (1<<i) and l:
on_any_limit = True
vupdate(vars.on_any_limit, on_any_limit)
global current_tool
current_tool = self.stat.tool_table[0]
if current_tool:
tool_data = {'tool': current_tool[0], 'zo': current_tool[3], 'xo': current_tool[1], 'dia': current_tool[10]}
if current_tool is None:
vupdate(vars.tool, _("Unknown tool %d") % self.stat.tool_in_spindle)
elif tool_data['tool'] == 0 or tool_data['tool'] == -1:
vupdate(vars.tool, _("No tool"))
elif current_tool.xoffset == 0 and not lathe:
vupdate(vars.tool, _("Tool %(tool)d, offset %(zo)g, diameter %(dia)g") % tool_data)
else:
vupdate(vars.tool, _("Tool %(tool)d, zo %(zo)g, xo %(xo)g, dia %(dia)g") % tool_data)
active_codes = []
for i in self.stat.gcodes[1:]:
if i == -1: continue
if i % 10 == 0:
active_codes.append("G%d" % (i/10))
else:
active_codes.append("G%(ones)d.%(tenths)d" % {'ones': i/10, 'tenths': i%10})
for i in self.stat.mcodes[1:]:
if i == -1: continue
active_codes.append("M%d" % i)
feed_str = "F%.1f" % self.stat.settings[1]
if feed_str.endswith(".0"): feed_str = feed_str[:-2]
active_codes.append(feed_str)
active_codes.append("S%.0f" % self.stat.settings[2])
codes = " ".join(active_codes)
widgets.code_text.configure(state="normal")
widgets.code_text.delete("0.0", "end")
widgets.code_text.insert("end", codes)
widgets.code_text.configure(state="disabled")
user_live_update()
def clear(self):
self.logger.clear()
o.redraw_soon()
def running(do_poll=True):
if do_poll: s.poll()
return s.task_mode == linuxcnc.MODE_AUTO and s.interp_state != linuxcnc.INTERP_IDLE
def manual_tab_visible():
page = root_window.tk.call(widgets.tabs, "raise")
return page == "manual"
def manual_ok(do_poll=True):
"""warning: deceptive function name.
This function returns TRUE when not running a program, i.e., when a user-
initiated action (whether an MDI command or a jog) is acceptable.
This means this function returns True when the mdi tab is visible."""
if do_poll: s.poll()
if s.task_state != linuxcnc.STATE_ON: return False
return s.interp_state == linuxcnc.INTERP_IDLE or (s.task_mode == linuxcnc.MODE_MDI and s.queued_mdi_commands < vars.max_queued_mdi_commands.get())
# If LinuxCNC is not already in one of the modes given, switch it to the
# first mode
def ensure_mode(m, *p):
s.poll()
if s.task_mode == m or s.task_mode in p: return True
if running(do_poll=False): return False
c.mode(m)
c.wait_complete()
return True
class DummyProgress:
def update(self, count): pass
def nextphase(self, count): pass
def done(self): pass
class Progress:
def __init__(self, phases, total):
self.num_phases = phases
self.phase = 0
self.total = total or 1
self.lastcount = 0
self.text = None
self.old_focus = root_window.tk.call("focus", "-lastfor", ".")
root_window.tk.call("canvas", ".info.progress",
"-width", 1, "-height", 1,
"-highlightthickness", 0,
"-borderwidth", 2, "-relief", "sunken",
"-cursor", "watch")
root_window.configure(cursor="watch")
root_window.tk.call(".menu", "configure", "-cursor", "watch")
t.configure(cursor="watch")
root_window.tk.call("bind", ".info.progress", "<Key>", "break")
root_window.tk.call("pack", ".info.progress", "-side", "left",
"-fill", "both", "-expand", "1")
root_window.tk.call(".info.progress", "create", "rectangle",
(-10, -10, -10, -10),
"-fill", "blue", "-outline", "blue")
root_window.update_idletasks()
root_window.tk.call("focus", "-force", ".info.progress")
root_window.tk.call("patient_grab", ".info.progress")
def update(self, count, force=0):
if force or count - self.lastcount > 400:
fraction = (self.phase + count * 1. / self.total) / self.num_phases
self.lastcount = count
try:
width = int(t.tk.call("winfo", "width", ".info.progress"))
except Tkinter.TclError, detail:
print detail
return
height = int(t.tk.call("winfo", "height", ".info.progress"))
t.tk.call(".info.progress", "coords", "1",
(0, 0, int(fraction * width), height))
t.tk.call("update", "idletasks")
def nextphase(self, total):
self.phase += 1
self.total = total or 1
self.lastcount = -100
self.update(0, True)
def done(self):
root_window.tk.call("destroy", ".info.progress")
root_window.tk.call("grab", "release", ".info.progress")
root_window.tk.call("focus", self.old_focus)
root_window.configure(cursor="")
root_window.tk.call(".menu", "configure", "-cursor", "")
t.configure(cursor="xterm")
def __del__(self):
if root_window.tk.call("winfo", "exists", ".info.progress"):
self.done()
def set_text(self, text):
if self.text is None:
self.text = root_window.tk.call(".info.progress", "create", "text",
(1, 1), "-text", text, "-anchor", "nw")
else:
root_window.tk.call(".info.progress", "itemconfigure", text,
"-text", text)
class AxisCanon(GLCanon, StatMixin):
def __init__(self, widget, text, linecount, progress, arcdivision):
GLCanon.__init__(self, widget.colors, geometry, foam)
StatMixin.__init__(self, s, random_toolchanger)
self.text = text
self.linecount = linecount
self.progress = progress
self.aborted = False
self.arcdivision = arcdivision
def change_tool(self, pocket):
GLCanon.change_tool(self, pocket)
StatMixin.change_tool(self, pocket)
def is_lathe(self): return lathe
def do_cancel(self, event):
self.aborted = True
def check_abort(self):