forked from FernV/NativeCAM
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ncam.py
executable file
·5159 lines (4340 loc) · 203 KB
/
ncam.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
#!/usr/bin/env python
# coding: utf-8
# ------------------------------------------------------------------
# -- NO USER SETTINGS IN THIS FILE -- EDIT PREFERENCES INSTEAD ---
# ------------------------------------------------------------------
APP_COPYRIGHT = '''Copyright © 2017 Fernand Veilleux : [email protected]
Copyright © 2012 Nick Drobchenko aka Nick from cnc-club.ru'''
APP_AUTHORS = ['Fernand Veilleux, maintainer', 'Nick Drobchenko, initiator',
'Meison Kim', 'Alexander Wigen', 'Konstantin Navrockiy', 'Mit Zot',
'Dewey Garrett', 'Karl Jacobs', 'Philip Mullen']
APP_VERSION = "(non deb)"
import gtk
import sys
import pygtk
pygtk.require('2.0')
from gtk import gdk
import pango
from lxml import etree
import gobject
import ConfigParser
import re, os
import getopt
import shutil
import hashlib
import subprocess
import webbrowser
import io
from cStringIO import StringIO
import gettext
import time
import locale
import platform
import pref_edit
import Tkinter
import math
SYS_DIR = os.path.dirname(os.path.realpath(__file__))
locale.setlocale(locale.LC_ALL, '')
decimal_point = locale.localeconv()["decimal_point"]
# if False, NO_ICON_FILE will be used
DEFAULT_USE_NO_ICON = True
NO_ICON_FILE = 'no-icon.png'
# info at http://www.pygtk.org/pygtk2reference/pango-markup-language.html
# when grayed, uses these format
gray_header_fmt_str = '<span foreground="gray" style="oblique">%s...</span>'
gray_sub_header_fmt_str = '<span foreground="gray" style="oblique">%s...</span>'
gray_sub_header_fmt_str2 = '<span foreground="gray" style="oblique" weight="bold">%s</span>'
gray_feature_fmt_str = '<span foreground="gray" weight="bold">%s</span>'
gray_items_fmt_str = '<span foreground="gray" style="oblique" weight="bold">%s</span>'
gray_val = '<span foreground="gray">%s</span>'
# when NOT grayed
header_fmt_str = '<i>%s...</i>'
sub_header_fmt_str = '<i>%s...</i>'
sub_header_fmt_str2 = '<b><i>%s</i></b>'
feature_fmt_str = '<b>%s</b>'
items_fmt_str = '<span foreground="blue" style="oblique"><b>%s</b></span>'
UNDO_MAX_LEN = 200
gmoccapy_time_out = 0.0
# use or test translation file
APP_NAME = 'nativecam'
nativecam_locale = os.getenv('NATIVECAM_LOCALE')
if nativecam_locale is not None :
translate_test = True
else :
translate_test = False
nativecam_locale = '/usr/share/locale'
gettext.bindtextdomain(APP_NAME, nativecam_locale)
gettext.textdomain(APP_NAME)
try :
lang = gettext.translation(APP_NAME, nativecam_locale, fallback = True)
lang.install()
_ = lang.ugettext
except :
gettext.install(APP_NAME, None, str = True)
APP_TITLE = _("NativeCAM for LinuxCNC")
APP_COMMENTS = _('A GUI to help create LinuxCNC NGC files.')
APP_LICENCE = _('''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.\n
It is recommended you use the deb package
''')
VALID_CATALOGS = ['mill', 'plasma', 'lathe']
DEFAULT_CATALOG = "mill"
# directories
CFG_DIR = 'cfg'
PROJECTS_DIR = 'projects'
LIB_DIR = 'lib'
NGC_DIR = 'scripts'
EXAMPLES_DIR = 'examples'
CATALOGS_DIR = 'catalogs'
GRAPHICS_DIR = 'graphics'
DEFAULTS_DIR = 'defaults'
CUSTOM_DIR = 'my-stuff'
# files
DEFAULT_TEMPLATE = 'default_template.xml'
USER_DEFAULT_FILE = 'custom_defaults.conf'
EXCL_MSG_FILE = 'excluded_msg.conf'
CURRENT_WORK = "current_work.xml"
PREFERENCES_FILE = "default.conf"
CONFIG_FILE = 'ncam.conf'
TOOLBAR_FNAME = "toolbar.conf"
TOOLBAR_CUSTOM_FNAME = "toolbar-custom.conf"
GENERATED_FILE = "ncam.ngc"
CURRENT_PROJECT = ''
DEFAULT_EDITOR = 'gedit'
SUPPORTED_DATA_TYPES = ['sub-header', 'header', 'bool', 'boolean', 'int', 'gc-lines',
'tool', 'gcode', 'text', 'list', 'float', 'string', 'engrave',
'combo', 'combo-user', 'items', 'filename', 'prjname']
NUMBER_TYPES = ['float', 'int']
NO_ICON_TYPES = ['sub-header', 'header']
GROUP_HEADER_TYPES = ['items', 'sub-header', 'header']
XML_TAG = "lcnc-ncam"
HOME_PAGE = 'https://github.com/FernV/NativeCAM'
class tv_select : # 'enum' items
none, feature, items, header, param = list(range(5))
class search_warning :
none, print_only, dialog = list(range(3))
#global variables
INCLUDE = []
DEFINITIONS = []
PIXBUF_DICT = {}
USER_VALUES = {}
USER_SUBROUTINES = []
TB_CATALOG = {}
EXCL_MESSAGES = {}
GLOBAL_PREF = None
UNIQUE_ID = 9
UI_INFO = '''
<ui>
<toolbar name='dummy'>
<toolitem action='SingleView' />
<toolitem action='DualView'/>
<toolitem action='TopBottom'/>
<toolitem action='SideSide'/>
<toolitem action='HideCol'/>
<toolitem action='SubHdrs'/>
</toolbar>
<toolbar name='ToolBar'>
<toolitem action='Build' />
<separator />
<toolitem action='Add' />
<toolitem action='Duplicate' />
<toolitem action='Delete' />
<separator />
<toolitem action='Undo' />
<toolitem action='Redo' />
<separator />
<toolitem action='MoveUp' />
<toolitem action='MoveDown' />
<separator />
<toolitem action='AppendItm' />
<toolitem action='RemoveItm' />
<separator />
<toolitem action='Collapse' />
</toolbar>
<popup name='PopupMenu'>
<menuitem action='Rename' />
<menu action='SetDigits'>
<menuitem action='Digit1'/>
<menuitem action='Digit2'/>
<menuitem action='Digit3'/>
<menuitem action='Digit4'/>
<menuitem action='Digit5'/>
<menuitem action='Digit6'/>
</menu>
<menuitem action='DataType' />
<menuitem action='RevertType' />
<separator />
<menuitem action='Undo' />
<menuitem action='Redo' />
<separator />
<menuitem action='HideField' />
<menuitem action='ShowFields' />
<menuitem action='ChngGrp' />
<separator />
<menuitem action='Add' />
<menuitem action='Duplicate' />
<menuitem action='Delete' />
<separator />
<menuitem action='Cut' />
<menuitem action='Copy' />
<menuitem action='Paste' />
<separator />
<menuitem action='MoveUp' />
<menuitem action='MoveDown' />
<separator />
<menuitem action='AppendItm' />
<menuitem action='RemoveItm' />
<separator />
<menuitem action='SaveUser' />
<menuitem action='DeleteUser' />
</popup>
<popup name='PopupMenu2'>
<menu action='SetDigits'>
<menuitem action='Digit1'/>
<menuitem action='Digit2'/>
<menuitem action='Digit3'/>
<menuitem action='Digit4'/>
<menuitem action='Digit5'/>
<menuitem action='Digit6'/>
</menu>
<menuitem action='DataType' />
<menuitem action='RevertType' />
<separator />
<menuitem action='Undo' />
<menuitem action='Redo' />
<separator />
<menuitem action='HideField' />
<menuitem action='ShowFields' />
<menuitem action='ChngGrp' />
<separator />
<menuitem action='SaveUser' />
<menuitem action='DeleteUser' />
</popup>
</ui>
'''
def get_int(s10) :
index = s10.find('.')
if index > -1 :
s10 = s10[:index]
try :
return int(s10)
except :
return 0
def get_float(s10) :
try :
return float(s10)
except :
try :
return locale.atof(s10)
except :
return 0.0
def get_string(float_val, digits, localized = True):
fmt = '%' + '0.%sf' % digits
if localized :
return (locale.format(fmt, float_val))
else :
return (fmt % float_val)
def search_path(warn, f, *argsl) :
if f == "" :
return None
if os.path.isfile(f) :
return f
src = NCAM_DIR
i = 0
j = argsl.__len__()
while i < j :
src = os.path.join(src, argsl[i])
i += 1
src = os.path.abspath(os.path.join(src, f))
if os.path.isfile(src) :
return src
for pa in [GRAPHICS_DIR, CFG_DIR, CATALOGS_DIR, LIB_DIR, PROJECTS_DIR] :
src = os.path.join(pa, f)
if os.path.isfile(src) :
return src
src = os.path.join(os.getcwd(), f)
if os.path.isfile(src) :
return src
if warn > search_warning.none:
print(_("Can not find file %(filename)s") % {"filename":f})
if warn == search_warning.dialog :
mess_dlg(_("Can not find file %(filename)s") % {"filename":f})
return None
def get_pixbuf(icon, size) :
if size < 16 :
size = 16
if ((icon is None) or (icon.strip() == "")) :
if DEFAULT_USE_NO_ICON:
return None
else :
icon = NO_ICON_FILE
icon_id = icon + str(size)
if (icon_id) in PIXBUF_DICT :
return PIXBUF_DICT[icon_id]
icon_fname = search_path(search_warning.none, icon, GRAPHICS_DIR)
if icon_fname is not None :
try :
pix_buf = gdk.pixbuf_new_from_file_at_size(icon_fname, size, size)
PIXBUF_DICT[icon_id] = pix_buf
return pix_buf
except gdk.PixbufError as err :
print(err)
PIXBUF_DICT[icon_id] = None
return None
def translate(fstring):
# translate the glade file when testing translation
txt2 = fstring.split('\n')
fstring = ''
for line in txt2 :
inx = line.find('translatable="yes">')
if inx > -1 :
inx2 = line.find('</')
txt = line[inx + 19:inx2]
line = re.sub(r'%s' % txt, '%s' % _(txt), line)
fstring += (line + '\n')
return fstring
def mess_dlg(mess, title = "NativeCAM"):
dlg = gtk.MessageDialog(parent = None,
flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
type = gtk.MESSAGE_WARNING,
buttons = gtk.BUTTONS_OK, message_format = '%s' % mess)
dlg.set_title(title)
dlg.set_keep_above(True)
dlg.run()
dlg.destroy()
def mess_yesno(mess, title = ""):
return mess_with_buttons(mess, (gtk.STOCK_YES, gtk.RESPONSE_YES, \
gtk.STOCK_NO, gtk.RESPONSE_NO), title) == gtk.RESPONSE_YES
def mess_with_buttons(mess, buttons, title = ""):
mwb = gtk.Dialog(parent = None,
buttons = buttons,
flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
)
mwb.set_title(title)
finbox = mwb.get_content_area()
l = gtk.Label(mess)
finbox.pack_start(l)
mwb.set_keep_above(True)
mwb.show_all()
response = mwb.run()
mwb.hide()
mwb.destroy()
return response
class copymode: # 'enum' items
one_at_a_time, yes_to_all, no_to_all = list(range(3))
def copy_dir_recursive(fromdir, todir,
update_ct = 0,
mode = copymode.one_at_a_time,
overwrite = False,
verbose = False) :
if not os.path.isdir(todir) :
os.makedirs(todir, 0o755)
for p in os.listdir(fromdir) :
frompath = os.path.join(fromdir, p)
topath = os.path.join(todir, p)
if os.path.isdir(frompath) :
mode, update_ct = copy_dir_recursive(frompath, topath,
update_ct = update_ct,
mode = mode,
overwrite = overwrite,
verbose = verbose)
continue
# copy files
if not os.path.isfile(topath) or overwrite :
shutil.copy(frompath, topath)
update_ct += 1
continue
else : # local file exists and not overwrite
if (hashlib.md5(open(frompath, 'rb').read()).digest()
== hashlib.md5(open(topath, 'rb').read()).digest()) :
# files are same
if verbose :
print("NOT copying %s to %s" % (p, todir))
else : # files are different
if (os.path.getctime(frompath) < os.path.getctime(topath)) :
# different and local file most recent
if verbose :
print(_('Keeping modified local file %(filename)s') % {"filename":p})
pass
else : # different and system file is most recent
if mode == copymode.yes_to_all :
if verbose :
print("copying %s to %s" % (p, todir))
shutil.copy(frompath, topath)
update_ct += 1
continue
if mode == copymode.no_to_all :
os.utime(topath, None) # touch it
continue
buttons = (gtk.STOCK_YES, gtk.RESPONSE_YES,
gtk.STOCK_NO, gtk.RESPONSE_NO,
gtk.STOCK_REFRESH, gtk.RESPONSE_ACCEPT,
gtk.STOCK_CANCEL, gtk.RESPONSE_NONE)
msg = (_('\nAn updated system file is available:\n\n%(frompath)s\n\n'
'YES -> Use new system file\n'
'NO -> Keep local file\n'
'Refresh -> Accept all new system files (don\'t ask again)\n'
'Cancel -> Keep all local files (don\'t ask again)\n') \
% {'frompath':frompath})
ans = mess_with_buttons(msg, buttons,
title = _("NEW file version available"))
# set copymode
if ans == gtk.RESPONSE_YES :
pass
elif ans == gtk.RESPONSE_ACCEPT :
mode = copymode.yes_to_all
elif ans == gtk.RESPONSE_NONE :
mode = copymode.no_to_all
elif ans == gtk.RESPONSE_NO :
pass
else :
ans = gtk.RESPONSE_NO # anything else (window close etc)
# copy or touch
if ans == gtk.RESPONSE_YES or mode == copymode.yes_to_all :
if verbose:
print("copying %s to %s" % (p, todir))
shutil.copy(frompath, topath)
update_ct += 1
if ans == gtk.RESPONSE_NO or mode == copymode.no_to_all :
os.utime(topath, None) # touch it (update timestamp)
return mode, update_ct
def err_exit(errtxt):
print(errtxt)
mess_dlg(errtxt)
sys.exit(1)
if platform.system() != 'Windows' :
try :
import linuxcnc
except ImportError as detail :
err_exit(detail)
def require_ini_items(fname, ini_instance):
global NCAM_DIR, NGC_DIR
val = ini_instance.find('DISPLAY', 'NCAM_DIR')
if val is None :
err_exit(_('Ini file <%(inifilename)s>\n'
'must have entry for [DISPLAY]NCAM_DIR')
% {'inifilename':fname})
val = os.path.expanduser(val)
if os.path.isabs(val) :
NCAM_DIR = val
else :
NCAM_DIR = (os.path.realpath(os.path.dirname(fname) + '/' + val))
val = ini_instance.find('DISPLAY', 'PROGRAM_PREFIX')
if val is None :
msg = _("There is no PROGRAM_PREFIX in ini file\n"
"Edit to add in DISPLAY section\n\n"
"PROGRAM_PREFIX = abs or relative path to scripts directory\n"
"i.e. PROGRAM_PREFIX = ./scripts or ~/ncam/scripts")
err_exit(msg)
else :
if ':' in val :
val = val.split(':')[0]
val = os.path.expanduser(val)
if os.path.isabs(val) :
NGC_DIR = val
else :
NGC_DIR = (os.path.realpath(os.path.dirname(fname) + '/' + val))
def require_ncam_lib(fname, ini_instance):
# presumes already checked:[DISPLAY]NCAM_DIR
# ini file must specify a [RS274NGC]SUBROUTINE_PATH that
# includes NCAM_DIR + LIB_DIR (typ: [DISPLAY]NCAM_DIR/lib)
require_lib = os.path.join(NCAM_DIR, LIB_DIR)
found_lib_dir = False
try :
subroutine_path = ini_instance.find('RS274NGC', 'SUBROUTINE_PATH')
if subroutine_path is None :
err_exit(_('Required lib missing:\n\n'
'[RS274NGC]SUBROUTINE_PATH'))
print("[RS274NGC]SUBROUTINE_PATH = %s\n Real paths:" % subroutine_path)
for i, d in enumerate(subroutine_path.split(":")):
d = os.path.expanduser(d)
if os.path.isabs(d) :
thedir = d
else :
thedir = os.path.join(os.path.realpath(os.path.dirname(fname)), d)
if os.path.isdir(thedir) :
print(" %s" % (os.path.realpath(thedir)))
if not found_lib_dir :
found_lib_dir = thedir.find(require_lib) == 0
print("")
if not found_lib_dir :
err_exit (_('\nThe required NativeCAM lib directory :\n<%(lib)s>\n\n'
'is not in [RS274NGC]SUBROUTINE_PATH:\n'
'<%(path)s>\n\nEdit ini and correct\n'
% {'lib':require_lib, 'path':subroutine_path}))
except Exception as detail :
err_exit(_('Required NativeCAM lib\n%(err_details)s') % {'err_details':detail})
def get_short_id():
global UNIQUE_ID
UNIQUE_ID += 1
return str(UNIQUE_ID)
def create_M_file() :
p = os.path.join(NCAM_DIR, NGC_DIR, 'M123')
with open(p, 'wb') as f :
f.write('#!/usr/bin/env python\n# coding: utf-8\n')
f.write("import gtk\nimport os\nimport pygtk\npygtk.require('2.0')\nfrom gtk import gdk\n\n")
f.write("fname = '%s'\n" % os.path.join(NCAM_DIR, CATALOGS_DIR, 'no_skip_dlg.conf'))
f.write('if os.path.isfile(fname) :\n exit(0)\n\n')
f.write("msg = '%s'\n" % _('Stop LinuxCNC program, toggle the shown button, then restart'))
f.write("msg1 = '%s'\n" % _('Skip block not active'))
f.write("icon_fname = '%s'\n\n" % os.path.join(NCAM_DIR, GRAPHICS_DIR, 'skip_block.png'))
f.write('dlg = gtk.MessageDialog(parent = None, flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, type = gtk.MESSAGE_WARNING, buttons = gtk.BUTTONS_NONE, message_format = msg1)\n\n')
f.write("dlg.set_title('NativeCAM')\ndlg.format_secondary_markup(msg)\n\n")
f.write('dlg.set_image(gtk.Image())\n')
f.write('dlg.get_image().set_from_pixbuf(gdk.pixbuf_new_from_file_at_size(icon_fname, 80, 80))\n\n')
f.write('cb = gtk.CheckButton(label = "%s")\n' % _("Do not show again"))
f.write('dlg.get_content_area().pack_start(cb, True, True, 0)\n')
f.write('dlg.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK).grab_focus()\n\n')
f.write('dlg.set_keep_above(True)\ndlg.show_all()\n\ndlg.run()\n')
f.write("if cb.get_active() :\n open(fname, 'w').close()\n")
f.write('exit(0)\n')
os.chmod(p, 0o755)
mess_dlg(_('LinuxCNC needs to be restarted now'))
class Tools(object):
def __init__(self):
self.table_fname = None
self.list = ''
self.orientation = 0
def set_file(self, tool_table_file):
fn = search_path(search_warning.dialog, tool_table_file)
if fn is not None :
self.table_fname = fn
self.load_table()
def load_table(self, *arg):
self.table = None
self.table = []
if self.table_fname is not None :
tbl = open(self.table_fname).read().split("\n")
for s in tbl :
s = s.strip()
if ";" in s:
tnumber = '0'
torient = '0'
s = s.split(";")
tdesc = s[1][0:]
s = s[0][0:]
s1 = s.split(" ")
for s2 in s1 :
if (len(s2) > 1) :
if (s2[0] == 'T') :
tnumber = s2[1:]
elif (s2[0] == 'Q') :
torient = s2[1:]
if tnumber != '0' :
if tdesc == '' :
tdesc = _('no description')
self.table.append([int(tnumber), tnumber, tdesc, torient])
self.table.append ([0, '0', _('None')])
self.table.sort()
self.list = ''
for tool in self.table :
self.list += tool[1] + ' - ' + tool[2] + '=' + tool[1] + ':'
self.list = self.list.rstrip(':')
def get_text(self, tn):
for tool in self.table :
if tool[1] == tn :
return tool[1] + ' - ' + tool[2]
return '0 - ' + _('None')
def save_tool_orient(self, tn):
if tn == 0 :
self.orientation = 0
else :
for tool in self.table :
if tool[0] == tn :
self.orientation = get_int(tool[3])
def get_tool_orient(self):
return self.orientation
class VKB(object):
def __init__(self, toplevel, tooltip, min_value, max_value, data_type, convertible) :
self.dlg = gtk.Dialog(parent = toplevel)
self.dlg.set_decorated(False)
self.dlg.set_transient_for(None)
self.dlg.set_border_width(3)
self.dlg.set_property("skip-taskbar-hint", True)
lbl = gtk.Label('')
lbl.set_line_wrap(True)
self.dlg.vbox.pack_start(lbl, expand = False)
lbl.set_markup(tooltip)
self.entry = gtk.Label('')
self.entry.modify_font(pango.FontDescription('sans 14'))
self.entry.set_alignment(1.0, 0.5)
self.entry.set_property('ellipsize', pango.ELLIPSIZE_START)
self.min_value = min_value
self.max_value = max_value
self.data_type = data_type
self.convertible_units = convertible
box = gtk.EventBox()
box.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color('#FFFFFF'))
box.add(self.entry)
frame = gtk.Frame()
frame.add(box)
tbl = gtk.Table(rows = 6, columns = 5, homogeneous = True)
tbl.attach(frame, 0, 5, 0, 1,
xoptions = gtk.EXPAND | gtk.FILL,
yoptions = gtk.EXPAND | gtk.FILL)
self.dlg.vbox.pack_start(tbl)
btn = gtk.Button(_('BS'))
btn.connect("clicked", self.input, 'BS')
btn.set_can_focus(False)
tbl.attach(btn, 4, 5, 2, 3)
i = 0
for lbl in ['F2', 'Pi', '()', '=', 'C'] :
btn = gtk.Button(lbl)
btn.connect("clicked", self.input, lbl)
btn.set_can_focus(False)
tbl.attach(btn, i, i + 1, 1, 2)
i = i + 1
i = 2
for lbl in ['/', '*', '-', '+'] :
btn = gtk.Button(lbl)
btn.connect("clicked", self.input, lbl)
btn.set_can_focus(False)
tbl.attach(btn, 3, 4, i, i + 1)
i = i + 1
k = 10
for i in range(2, 5) :
k = k - 3
for j in range(0, 3):
lbl = str(k + j)
btn = gtk.Button(lbl)
btn.connect("clicked", self.input, lbl)
btn.set_can_focus(False)
tbl.attach(btn, j, j + 1, i, i + 1)
if (self.min_value < 0.0) :
btn = gtk.Button('+/-')
btn.connect("clicked", self.input, '+/-')
btn.set_can_focus(False)
tbl.attach(btn, 2, 3, 5, 6)
last_col = 2
else :
last_col = 3
if self.data_type == 'float' : # and get_int(self.digits) > 0 :
btn = gtk.Button(decimal_point)
btn.connect("clicked", self.input, decimal_point)
btn.set_can_focus(False)
tbl.attach(btn, last_col - 1, last_col, 5, 6)
last_col = last_col - 1
btn = gtk.Button('0')
btn.connect("clicked", self.input, '0')
btn.set_can_focus(False)
tbl.attach(btn, 0, last_col, 5, 6)
btn = gtk.Button()
img = gtk.Image()
img.set_from_stock('gtk-cancel', menu_icon_size)
btn.set_image(img)
btn.connect("clicked", self.cancel)
btn.set_can_focus(False)
tbl.attach(btn, 4, 5, 3, 4)
if self.convertible_units :
btn = gtk.Button()
img = gtk.Image()
img.set_from_pixbuf(get_pixbuf('mm2in.png', treeview_icon_size))
btn.set_image(img)
btn.connect("clicked", self.input, 'CV')
btn.set_can_focus(False)
tbl.attach(btn, 4, 5, 4, 5)
self.OKbtn = gtk.Button()
img = gtk.Image()
img.set_from_stock('gtk-ok', menu_icon_size)
self.OKbtn.set_image(img)
self.OKbtn.connect("clicked", self.ok)
self.OKbtn.set_can_focus(False)
if self.convertible_units :
tbl.attach(self.OKbtn, 4, 5, 5, 6)
else :
tbl.attach(self.OKbtn, 4, 5, 4, 6)
self.dlg.connect('key-press-event', self.key_press_event)
self.dlg.connect('focus-out-event', self.focus_out)
self.dlg.set_keep_above(True)
def __enter__(self):
self.not_allowed_msg = _("Not allowed - F2 edit")
self.err_msg = _("Error - F2 edit")
return self
def initvalue(self, value, saved, initialize):
self.entry.set_markup('<b>%s</b>' % value)
self.save_edit = saved
self.initialize = initialize
def run(self, not_allowed):
def show_error(errm) :
self.entry.set_markup('<b>%s</b>' % errm)
self.initialize = True
self.opened_paren = 0
while True :
self.convert_units = False
self.OKbtn.grab_focus()
response = self.dlg.run()
if response == gtk.RESPONSE_OK:
if self.entry.get_text() in ['', self.not_allowed_msg, self.err_msg] :
self.entry.set_markup('<b>0</b>')
is_good, rval = self.compute(self.entry.get_text())
if not is_good :
show_error(self.err_msg)
elif self.data_type == 'int' :
val = int(rval)
a_min = int(self.min_value)
a_max = int(self.max_value)
if val > a_max :
val = a_max
elif val < a_min :
val = a_min
if not_allowed is not None :
for na in not_allowed.split(':') :
if get_int(na) == val :
is_good = False
show_error(self.not_allowed_msg)
break
if is_good :
return response, str(val)
else:
if self.convert_units :
if default_metric :
rval = rval * 25.4
else :
rval = rval / 25.4
if rval > self.max_value :
rval = self.max_value
elif rval < self.min_value :
rval = self.min_value
if not_allowed is not None :
for na in not_allowed.split(':') :
if get_float(na) == rval :
is_good = False
show_error(self.not_allowed_msg)
break
if is_good :
return response, str(rval)
else :
return response, None
def input(self, btn, data):
if self.initialize :
lbl = '0'
self.initialize = False
self.opened_paren = 0
else :
lbl = self.entry.get_text()
if lbl in ['0.0', '0.00', '0.000', '0.0000', '0.00000', '0.000000'] :
lbl = '0'
if data == 'C' :
self.entry.set_markup('<b>0</b>')
self.opened_paren = 0
elif data == '=' :
is_good, rval = self.compute(self.entry.get_text())
if not is_good :
self.show_error(_("Error - F2 to edit"))
elif self.data_type == 'int' :
self.entry.set_markup('<b>%d</b>' % int(rval))
else :
self.entry.set_markup('<b>%s</b>' % locale.format('%0.6f', rval))
elif data == 'F2' :
self.entry.set_markup('<b>%s</b>' % self.save_edit)
elif data == 'BS' :
if (len(lbl) == 1) or lbl == 'Pi':
self.input(None, 'C')
return
elif lbl[-1] == 'i' :
self.entry.set_markup('<b>%s</b>' % lbl[0:-2])
elif lbl[-1] == ')' :
self.opened_paren += self.opened_paren
self.entry.set_markup('<b>%s</b>' % lbl[0:-1])
elif lbl[-1] == '(' :
self.entry.set_markup('<b>%s</b>' % lbl[0:-1])
self.opened_paren -= 1
else :
self.entry.set_markup('<b>%s</b>' % lbl[0:-1])
elif data == 'CV' :
self.convert_units = True
self.dlg.response(gtk.RESPONSE_OK)
elif data == '+/-' :
if lbl == '0' :
self.entry.set_markup('<b>-</b>')
elif lbl.find('-') == 0 :
self.entry.set_markup('<b>%s</b>' % lbl[1:])
else :
self.entry.set_markup('<b>-%s</b>' % lbl)
elif data == 'Pi' :
if lbl == '0' :
self.entry.set_markup('<b>%s</b>' % data)
elif lbl[-1] in ['+', '-', '*', '/', '('] :
self.entry.set_markup('<b>%s%s</b>' % (lbl, data))
elif data in ['*', '/', '+'] :
if lbl != '0' and not lbl[-1] in ['+', '-', '*', '/', '('] :
self.entry.set_markup('<b>%s%s</b>' % (lbl, data))
elif data == '()' :
if lbl == '0' :
self.entry.set_markup('<b>(</b>')
self.opened_paren = 1
elif lbl[-1] in ['+', '-', '*', '/', '('] :
self.entry.set_markup('<b>%s(</b>' % lbl)
self.opened_paren += 1
elif lbl[-1] not in ['+', '-', '*', '/', '('] :
if self.opened_paren > 0 :
self.entry.set_markup('<b>%s)</b>' % lbl)
self.opened_paren -= 1
elif data == decimal_point :
if lbl == '0' :
self.entry.set_markup('<b>0%s</b>' % data)
elif lbl[-1] in ['+', '-', '*', '/', '('] :
self.entry.set_markup('<b>%s0%s</b>' % (lbl, data))
elif lbl[-1] >= '0' and lbl[-1] <= '9' :
j = len(lbl)
i = 0
while (i < j) :
car = lbl[-i]
i += 1
if car == decimal_point :
return
if car in ['+', '-', '*', '/', '('] :
self.entry.set_markup('<b>%s%s</b>' % (lbl, data))
return
self.entry.set_markup('<b>%s%s</b>' % (lbl, data))
else :
if lbl == '0' : # numbers and minus sign
self.entry.set_markup('<b>%s</b>' % data)
elif lbl[-1] not in [')', 'i'] :
self.entry.set_markup('<b>%s%s</b>' % (lbl, data))
def key_press_event(self, win, event):
if event.type == gdk.KEY_PRESS:
k_name = gdk.keyval_name(event.keyval)
# print(k_name)
if ((k_name >= 'KP_0' and k_name <= 'KP_9') or \
(k_name >= '0' and k_name <= '9')) :
self.input(None, k_name[-1])
elif k_name in ['KP_Decimal', 'period', 'comma', 'KP_Separator'] :
if (self.data_type == 'float'):
self.input(None, decimal_point)
elif k_name in ['KP_Divide', 'slash'] :
self.input(None, '/')
elif k_name in ['KP_Multiply', 'asterisk'] :
self.input(None, '*')
elif k_name in ['parenleft', 'parenright'] :
self.input(None, '()')
elif k_name == 'F2' :
self.input(None, 'F2')
elif k_name in ['C', 'c'] :
self.input(None, 'C')
elif k_name == 'equal' :
self.input(None, '=')
elif k_name in ['KP_Subtract', 'minus'] :
self.input(None, '-')
elif k_name in ['KP_Add', 'plus'] :
self.input(None, '+')
elif k_name == 'BackSpace' :
self.input(None, 'BS')
elif k_name in ['KP_Enter', 'Return', 'space']:
self.dlg.response(gtk.RESPONSE_OK)
def ok(self, btn):
self.convert_units = False
self.dlg.response(gtk.RESPONSE_OK)
def cancel(self, btn):
self.dlg.response(gtk.RESPONSE_CANCEL)
def focus_out(self, widget, event):
if vkb_cancel_on_out:
self.dlg.response(gtk.RESPONSE_CANCEL)
else :
self.dlg.response(gtk.RESPONSE_OK)
def compute(self, input_string):
while input_string.count('(') > input_string.count(')') :
input_string = input_string + ')'
self.opened_paren = 0
self.save_edit = input_string
for i in('-', '+', '/', '*', '(', ')'):
input_string = input_string.replace(i, " %s " % i)
input_string = input_string.replace('Pi', str(math.pi))
qualified = ''
for i in input_string.split():
try:
i = str(locale.atof(i))
qualified = qualified + str(float(i))
except:
qualified = qualified + i
try :
return True, eval(qualified)
except :
return False, 0.0
def __exit__(self, type, value, traceback):
self.dlg.hide()
self.dlg.destroy()
self.dlg = None
class CellRendererMx(gtk.CellRendererText):
def __init__(self, treeview) :
gtk.CellRendererText.__init__(self)