-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathPostProcessAll.py
More file actions
1412 lines (1241 loc) · 60.8 KB
/
PostProcessAll.py
File metadata and controls
1412 lines (1241 loc) · 60.8 KB
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
#Author-Tim Paterson
#Description-Post process all CAM setups, using the setup name as the output file name.
import adsk.core, adsk.fusion, adsk.cam, traceback, shutil, json, os, os.path, time, re, pathlib, enum, tempfile
# Version number of settings as saved in documents and settings file
# update this whenever settings content changes
version = 11
# Initial default values of settings
defaultSettings = {
"version" : version,
"ncProgram": "",
"output" : "",
"sequence" : True,
"twoDigits" : False,
"delFiles" : False,
"delFolder" : False,
"splitSetup" : False,
"combineTool" : False,
"fastZ" : False,
"toolChange" : "M9 G30",
"numericName" : False,
"endCodes" : "M5 M9 M30",
"onlySelected" : False,
# Groups are expanded or not
"groupPersonal" : True,
"groupPost" : False,
"groupAdvanced" : False,
"groupRename" : False,
# Retry policy
"initialDelay" : 0.2,
"postRetries" : 3
}
# Constants
constCmdName = "Post Process All"
constCmdDefId = "PatersonTech_PostProcessAll"
constCAMWorkspaceId = "CAMEnvironment"
constCAMActionsPanelId = "CAMActionPanel"
constPostProcessControlId = "IronPostProcess"
constCAMProductId = "CAMProductType"
constAttrGroup = constCmdDefId
constAttrName = "settings"
constAttrCompressedName = "CompressedName"
constSettingsFileExt = ".settings"
constPostLoopDelay = 0.1
constBodyTmpFile = "gcodeBody"
constOpTmpFile = "8910" # in case name must be numeric
constRapidZgcode = 'G00 Z{} (Changed from: "{}")\n'
constRapidXYgcode = 'G00 {} (Changed from: "{}")\n'
constFeedZgcode = 'G01 Z{} F{} (Changed from: "{}")\n'
constFeedXYgcode = 'G01 {} F{} (Changed from: "{}")\n'
constFeedXYZgcode = 'G01 {} Z{} F{} (Changed from: "{}")\n'
constAddFeedGcode = " F{} (Feed rate added)\n"
constMotionGcodeSet = {0,1,2,3,33,38,73,76,80,81,82,84,85,86,87,88,89}
constHomeGcodeSet = {28, 30}
constLineNumInc = 5
constNcProgramName = "PostProcessAll NC Program"
# Tool tip text
toolTip = (
"Post process all setups into G-code for your machine.\n\n"
"The name of the setup is used for the name of the output "
"file adding the appropriate extension. A colon (':') in the name indicates "
"the preceding portion is the name of a subfolder. Multiple "
"colons can be used to nest subfolders. Spaces around colons "
"are removed.\n\n"
"Setups within a folder are optionally preceded by a "
"sequence number. This identifies the order in which the "
"setups appear. The sequence numbers for each folder begin "
"with 1."
)
# Global list to keep all event handlers in scope.
# This is only needed with Python.
handlers = []
# Global settingsMgr object
settingsMgr = None
def run(context):
global settingsMgr
ui = None
try:
settingsMgr = SettingsManager()
app = adsk.core.Application.get()
ui = app.userInterface
InitAddIn()
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
def stop(context):
ui = None
try:
app = adsk.core.Application.get()
ui = app.userInterface
# Clean up the UI.
cmdDef = ui.commandDefinitions.itemById(constCmdDefId)
if cmdDef:
cmdDef.deleteMe()
addinsPanel = ui.allToolbarPanels.itemById(constCAMActionsPanelId)
cmdControl = addinsPanel.controls.itemById(constCmdDefId)
if cmdControl:
cmdControl.deleteMe()
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
class SettingsManager:
def __init__(self):
self.default = None
self.path = None
self.fMustSave = False
self.inputs = None
def GetSettings(self, docAttr):
docSettings = None
attr = docAttr.itemByName(constAttrGroup, constAttrName)
if attr:
try:
docSettings = json.loads(attr.value)
if docSettings["version"] == version:
return docSettings
except Exception:
pass
# Document does not have valid settings, get defaults
if not self.default:
# Haven't read the settings file yet
file = None
try:
file = open(self.GetPath())
self.default = json.load(file)
# never allow delFiles or delFolder to default to True
self.default["delFiles"] = False
self.default["delFolder"] = False
if self.default["version"] != version:
self.UpdateSettings(defaultSettings, self.default)
except Exception:
self.default = dict(defaultSettings)
self.fMustSave = True
finally:
if file:
file.close
if not docSettings:
docSettings = dict(self.default)
else:
self.UpdateSettings(self.default, docSettings)
return docSettings
def SaveDefault(self, docSettings):
self.fMustSave = False
self.default = dict(docSettings)
# never allow delFiles or delFolder to default to True
self.default["delFiles"] = False
self.default["delFolder"] = False
try:
strSettings = json.dumps(docSettings)
file = open(self.GetPath(), "w")
file.write(strSettings)
file.close
except Exception:
pass
def SaveSettings(self, docAttr, docSettings):
if self.fMustSave:
self.SaveDefault(docSettings)
docAttr.add(constAttrGroup, constAttrName, json.dumps(docSettings))
def UpdateSettings(self, src, dst):
if "homeEndsOp" in dst:
if dst["homeEndsOp"] and not ("endCodes" in dst):
dst["endCodes"] = "M5 M9 M30 G28 G30"
del dst["homeEndsOp"]
for item in src:
if not (item in dst):
dst[item] = src[item]
dst["version"] = src["version"]
def GetPath(self):
if not self.path:
pos = __file__.rfind(".")
if pos == -1:
pos = len(__file__)
self.path = __file__[0:pos] + constSettingsFileExt
return self.path
def InitAddIn():
ui = None
try:
app = adsk.core.Application.get()
ui = app.userInterface
# Create a button command definition.
cmdDefs = ui.commandDefinitions
cmdDef = cmdDefs.addButtonDefinition(constCmdDefId, constCmdName, toolTip, "resources/Command")
# Connect to the commandCreated event.
commandEventHandler = CommandEventHandler()
cmdDef.commandCreated.add(commandEventHandler)
handlers.append(commandEventHandler)
# Get the Actions panel in the Manufacture workspace.
workSpace = ui.workspaces.itemById(constCAMWorkspaceId)
addInsPanel = workSpace.toolbarPanels.itemById(constCAMActionsPanelId)
# Add the button right after the Post Process command.
cmdControl = addInsPanel.controls.addCommand(cmdDef, constPostProcessControlId, False)
cmdControl.isPromotedByDefault = True
cmdControl.isPromoted = True
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
def CountOutputFolderFiles(folder, limit, fileExt):
cntFiles = 0
cntNcFiles = 0
for path, dirs, files in os.walk(folder):
for file in files:
if file.endswith(fileExt):
cntNcFiles += 1
else:
cntFiles += 1
if cntFiles > limit:
return "many files that are not G-code"
if cntNcFiles > limit * 1.5:
return "many more G-code files than are produced by this design"
return None
def ExpandFileName(file):
return os.path.expanduser(file).replace("\\", "/")
def CompressFileName(file):
# normalize whacks
base = os.path.expanduser("~").replace("\\", "/")
newFile = file.replace("\\", "/").removeprefix(base)
if len(file) != len(newFile) and newFile[0] == "/":
file = "~" + newFile
return file
def AssignOutputFolder(parameters, folder):
parameters.itemByName("nc_program_output_folder").value.value = folder
result = parameters.itemByName("nc_program_output_folder").value.value
if result != folder and folder[0:2] == "\\\\":
parameters.itemByName("nc_program_output_folder").value.value = "\\\\" + folder # double up leading "\"
return None
def GetSetups(cam, settings, setups):
if len(setups) == 0 or not settings["onlySelected"]:
setups = []
# move all setups into a list
for setup in cam.setups:
setups.append(setup)
return setups
def GetNcProgram(cam, settings):
for program in cam.ncPrograms:
if program.name == settings["ncProgram"]:
return program
return cam.ncPrograms.item(0)
def RenameSetups(settings, setups, find, replace, isRegex):
try:
app = adsk.core.Application.get()
ui = app.userInterface
doc = app.activeDocument
cam = adsk.cam.CAM.cast(doc.products.itemByProductType(constCAMProductId))
setups = GetSetups(cam, settings, setups)
for setup in setups:
if isRegex:
newName = re.sub(find, replace, setup.name)
else:
if find == "":
# special case, prepend
newName = replace + setup.name
else:
newName = setup.name.replace(find, replace)
if setup.name != newName:
setup.name = newName
# Save settings in document attributes
settingsMgr.SaveSettings(doc.attributes, settings)
except:
pass
# Event handler for the commandCreated event.
class CommandEventHandler(adsk.core.CommandCreatedEventHandler):
def __init__(self):
super().__init__()
def notify(self, args):
try:
eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
cmd = eventArgs.command
# Get document attributes that will set initial values
app = adsk.core.Application.get()
cam = adsk.cam.CAM.cast(app.activeDocument.products.itemByProductType(constCAMProductId))
docSettings = settingsMgr.GetSettings(app.activeDocument.attributes)
# See if we're doing only selected setups
selectedSetups = []
for setup in cam.setups:
if setup.isSelected:
selectedSetups.append(setup)
# Get the NCProgram
programs = cam.ncPrograms
if programs.count == 0:
ncInput = programs.createInput()
ncInput.displayName = constNcProgramName
program = programs.add(ncInput)
program.postConfiguration = program.postConfiguration
outputFolder = docSettings["output"]
program.attributes.add(constAttrGroup, constAttrCompressedName, outputFolder)
AssignOutputFolder(program.parameters, ExpandFileName(outputFolder))
program.parameters.itemByName("nc_program_createInBrowser").value.value = True
elif programs.count == 1:
program = programs.item(0)
else:
haveProgram = False
for program in programs:
if program.name == docSettings["ncProgram"]:
haveProgram = True
break
if not haveProgram:
program = programs.item(0)
docSettings["ncProgram"] = program.name
# Connect to the execute event.
onExecute = CommandExecuteHandler(docSettings, selectedSetups)
cmd.execute.add(onExecute)
handlers.append(onExecute)
# Add inputs that will appear in a dialog
inputs = cmd.commandInputs
# text box as a label for NC Program
input = inputs.addTextBoxCommandInput("ncProgramLabel",
"",
"NC Program:",
1,
True)
input.isFullWidth = True
label = input
input = inputs.addDropDownCommandInput("ncProgram",
"NC Program",
adsk.core.DropDownStyles.TextListDropDownStyle)
for listItem in programs:
input.listItems.add(listItem.name, listItem.name == program.name)
#input.isFullWidth = True
input.tooltip = "NC Program to Use"
input.tooltipDescription = (
"Post processing will use the settings from the selected NC Program."
)
label.tooltip = input.tooltip
label.tooltipDescription = input.tooltipDescription
# check box to use only selected setups
input = inputs.addBoolValueInput("onlySelected",
"Only selected setups",
True,
"",
docSettings["onlySelected"])
input.tooltip = "Only Process Selected Setups"
input.tooltipDescription = (
"Only setups selected in the browser will be processed. Note "
"that a selected setup will be highlighted, not simply activated. "
"Selecting individual operations within a setup has no effect."
)
input.isEnabled = len(selectedSetups) != 0
# check box to delete existing files
input = inputs.addBoolValueInput("delFiles",
"Delete existing files",
True,
"",
docSettings["delFiles"])
input.tooltip = "Delete Existing Files in Each Folder"
input.tooltipDescription = (
"Delete all files in each output folder before post processing. "
"This will help prevent accumulation of G-code files which are "
"no longer used."
"<p>For example, you could decide to add sequence numbers after "
"already post processing without them. If this option is not "
"checked, you will have two of each file, a newer one with a "
"sequence number and older one without. With this option checked, "
"all previous files will be deleted so only current results will "
"be present.</p>"
"<p>This option will only delete the files in folders in which new "
"G-code files are being written. If you change the name of a "
"folder, for example, it will not be deleted.</p>")
# check box to delete entire output folder
input = inputs.addBoolValueInput("delFolder",
"Delete output folder",
True,
"",
docSettings["delFolder"] and docSettings["delFiles"])
input.isEnabled = docSettings["delFiles"] # enable only if delete existing files
input.tooltip = "Delete Entire Output Folder First"
input.tooltipDescription = (
"Delete the entire output folder before post processing. This "
"deletes all files and subfolders regardless of whether or not "
"new G-code files are written to a particular folder."
"<p><b>WARNING!</b> Be absolutely sure the output folder is set "
"correctly before selecting this option. Run the command once "
"before setting this option and verify the results are in the "
"correct folder. An incorrect setting of the output folder with "
"this option selected could result in unintentionally wiping out "
"a vast number of files.</p>")
# check box to prepend sequence numbers
input = inputs.addBoolValueInput("sequence",
"Prepend sequence number",
True,
"",
docSettings["sequence"])
input.tooltip = "Add Sequence Numbers to Name"
input.tooltipDescription = (
"Begin each file name with a sequence number. The numbering "
"represents the order that the setups appear in the browser tree. "
"Each folder has its own sequence numbers starting with 1.")
# check box to select 2-digit sequence numbers
input = inputs.addBoolValueInput("twoDigits",
"Use 2-digit numbers",
True,
"",
docSettings["twoDigits"])
input.isEnabled = docSettings["sequence"] # enable only if using sequence numbers
input.tooltip = "Use 2-Digit Sequence Numbers"
input.tooltipDescription = (
"Sequence numbers 0 - 9 will have a leading zero added, becoming"
'"01" to "09". This could be useful for formatting or sorting.')
# "Personal Use" version
# check box to split up setup into individual operations
inputGroup = inputs.addGroupCommandInput("groupPersonal", "Personal Use")
input = inputGroup.children.addBoolValueInput("splitSetup",
"Use individual operations",
True,
"",
docSettings["splitSetup"])
input.tooltip = "Split Setup Into Individual Operations"
input.tooltipDescription = (
"Generate output for each operation individually. This is usually "
"REQUIRED when using Fusion for Personal Use, because tool "
"changes are not allowed. The individual operations will be "
"grouped back together into the same file, eliminating this "
"limitation. You will get an error if there is a tool change "
"in a setup and this options is not selected.")
# check box to combine operation that use the same tool
input = inputGroup.children.addBoolValueInput("combineTool",
"Combine operations using same tool",
True,
"",
docSettings["combineTool"])
input.isEnabled = docSettings["splitSetup"] # enable only if using individual operations
input.tooltip = "Combine Consecutive Operations That Use the Same Tool"
input.tooltipDescription = (
"If consecutive operations use the same tool, have Fusion generate "
"their output together. This can optimize G-code for some routers. "
"However, it will cause the logic that restores rapid moves to also "
"treat it as one operation, which can have negative effects if the "
"feed heights for the operations are different.")
# text box as a label for tool change command
input = inputGroup.children.addTextBoxCommandInput("toolLabel",
"",
"G-code for tool change:",
1,
True)
input.isFullWidth = True
label = input
# enter G-code for tool change
input = inputGroup.children.addStringValueInput("toolChange", "", docSettings["toolChange"])
input.isEnabled = docSettings["splitSetup"] # enable only if using individual operations
input.isFullWidth = True
input.tooltip = "G-code to Precede Tool Change"
input.tooltipDescription = (
"Allows inserting a line of code before tool changes. For example, "
"you might want M5 (spindle stop), M9 (coolant stop), and/or G28 or G30 "
"(return to home). The code will be placed on the line before the "
"tool change. You can get mulitple lines by separating them with "
"a colon (:)."
"<p>If you want a line number, just put a dummy line number in front. "
"If you use the colon to get multiple lines, only put the dummy line "
"number on the first line. For example, <b>N10 M9:G30</b> will give "
"you two lines, both with properly sequenced line numbers.</p>"
)
label.tooltip = input.tooltip
label.tooltipDescription = input.tooltipDescription
# text box as a label for operation end commands
input = inputGroup.children.addTextBoxCommandInput("endLabel",
"",
"G-codes that mark ending sequence:",
1,
True)
input.isFullWidth = True
label = input
# enter G-codes for end of operation
input = inputGroup.children.addStringValueInput("endCodes", "", docSettings["endCodes"])
input.isEnabled = docSettings["splitSetup"] # enable only if using individual operations
input.isFullWidth = True
input.tooltip = "G-codes That Mark the Ending Sequence"
input.tooltipDescription = (
"To combine operations generated individually, the ending sequence "
"(which should only appear once) must be found. This entry is the "
"list of G-codes that start this ending sequence. For example, M30 "
"(end program) would normally be here, but it may not be the first "
"G-code of the ending sequence. M5 (spindle stop), M9 (coolant "
"stop) and G28/G30 (move home) are also candidates, but you should "
"look at the code from your post processor to determine what "
"will work in your case. Any one of the G-codes you enter here "
"will mark the start of ending sequence."
)
label.tooltip = input.tooltip
label.tooltipDescription = input.tooltipDescription
# check box to enable restoring rapid moves
input = inputGroup.children.addBoolValueInput("fastZ",
"Restore rapid moves",
True,
"",
docSettings["fastZ"])
input.isEnabled = docSettings["splitSetup"] # enable only if using individual operations
input.tooltip = "Restore Rapid Moves (Experimental)"
input.tooltipDescription = (
"Replace appropriate moves at feed rate with rapid (G0) moves. "
"In Fusion for Personal Use, moves that could be rapid are "
"now limited to the current feed rate. When this option is selected, "
"the G-code will be analyzed to find moves at or above the feed "
"height and replace them with rapid moves."
"<p><b>WARNING!<b> This option should be used with caution. "
"Review the G-code to verify it is correct. Comments have been "
"added to indicate the changes.")
inputGroup.isExpanded = docSettings["groupPersonal"]
# Rename
inputGroup = inputs.addGroupCommandInput("groupRename", "Rename Setups")
# check box to use regular expressions
input = inputGroup.children.addBoolValueInput("regex",
"Use Python regular expressions",
True,
"",
False)
input.tooltip = "Search With Regular Expressions"
input.tooltipDescription = (
"Treat the search string as a Python regular expression (regex). "
"This is extremely flexible but also very technical. Refer to "
"Python documentation for details."
"<p>One example is to put $ in the search box. This special "
"symbol searches for the end of the setup name. Then the replacement "
"string will be appended to the existing name."
)
# text box as a label for search field
input = inputGroup.children.addTextBoxCommandInput("searchLabel",
"",
"Search for this string:",
1,
True)
input.isFullWidth = True
label = input
# Find
input = inputGroup.children.addStringValueInput("findString", "")
input.isFullWidth = True
input.tooltip = "String to find in setup name"
input.tooltipDescription = (
"Replace all occurences of this string with the replacement string. "
"If this is left blank, the replacement string will be prepended to "
"each setup name."
)
label.tooltip = input.tooltip
label.tooltipDescription = input.tooltipDescription
# text box as a label for replace field
input = inputGroup.children.addTextBoxCommandInput("replaceLabel",
"",
"Replace with this string:",
1,
True)
input.isFullWidth = True
label = input
# Replace
input = inputGroup.children.addStringValueInput("replaceString", "")
input.isFullWidth = True
input.tooltip = "String to use as replacement"
input.tooltipDescription = (
"Replace all occurences of the Find string with this string."
)
label.tooltip = input.tooltip
label.tooltipDescription = input.tooltipDescription
# button to execute search & replace
input = inputGroup.children.addBoolValueInput("replace", "Search and replace", False)
input.resourceFolder = "resources/Rename"
input.tooltip = "Execute search and replace"
input.tooltipDescription = (
"Search for all strings matching the Find box and replace them "
"with the string in the Replace box.")
inputGroup.isExpanded = docSettings["groupRename"]
# Advanced -- retry settings
inputGroup = inputs.addGroupCommandInput("groupAdvanced", "Advanced")
# Time delay
input = inputGroup.children.addFloatSpinnerCommandInput("initialDelay",
"Initial time allowance", "s", 0.1, 1.0, 0.1, docSettings["initialDelay"])
input.tooltip = "Initial Time to Post Process an Operation"
input.tooltipDescription = (
"Initial delay to wait for post processor. Doubled for each retry.")
# Retry count
input = inputGroup.children.addIntegerSpinnerCommandInput("postRetries",
"Number of retries", 1, 9, 1, docSettings["postRetries"])
input.tooltip = "Number of Retries"
input.tooltipDescription = (
"Retries if post processing failed. Time delay is doubled each retry.")
inputGroup.isExpanded = docSettings["groupAdvanced"]
# post processor
inputGroup = inputs.addGroupCommandInput("groupPost", "Post Processor")
inputGroup.isExpanded = docSettings["groupPost"]
# Numeric name required?
input = inputGroup.children.addBoolValueInput("numericName",
"Name must be numeric",
True,
"",
docSettings["numericName"])
input.tooltip = "Output File Name Must Be Numeric"
input.tooltipDescription = (
"The name of the setup will not be used in the file name, "
"only sequence numbers. The option to prepend sequence numbers "
"will have no effect.")
# button to save default settings
input = inputs.addBoolValueInput("save", "Save as default", False)
input.resourceFolder = "resources/Save"
input.tooltip = "Save These Settings as System Default"
input.tooltipDescription = (
"Save these settings to use as the default for each new design.")
# text box for error messages
input = inputs.addTextBoxCommandInput("error", "", "", 3, True)
input.isFullWidth = True
input.isVisible = False
# Connect to the inputChanged event.
onInputChanged = CommandInputChangedHandler(docSettings, selectedSetups)
cmd.inputChanged.add(onInputChanged)
handlers.append(onInputChanged)
# Connect to the validateInputs event.
onValidateInputs = CommandValidateInputsHandler()
cmd.validateInputs.add(onValidateInputs)
handlers.append(onValidateInputs)
except:
ui = app.userInterface
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
# Event handler for the inputChanged event.
class CommandInputChangedHandler(adsk.core.InputChangedEventHandler):
def __init__(self, docSettings, selectedSetups):
self.docSettings = docSettings
self.selectedSetups = selectedSetups
super().__init__()
def notify(self, args):
app = adsk.core.Application.get()
ui = app.userInterface
try:
eventArgs = adsk.core.InputChangedEventArgs.cast(args)
cmd = eventArgs.input.parentCommand
inputs = eventArgs.inputs
doc = app.activeDocument
cam = adsk.cam.CAM.cast(doc.products.itemByProductType(constCAMProductId))
# See if button clicked
input = eventArgs.input
if input.id == "save":
settingsMgr.SaveDefault(self.docSettings)
elif input.id == "replace":
cmd.doExecute(False) # do it in execute handler for Undo
return
elif input.id in self.docSettings:
if input.objectType == adsk.core.GroupCommandInput.classType():
self.docSettings[input.id] = input.isExpanded
elif input.objectType == adsk.core.DropDownCommandInput.classType():
self.docSettings[input.id] = input.selectedItem.name
else:
self.docSettings[input.id] = input.value
# Enable twoDigits only if sequence is true
if input.id == "sequence":
inputs.itemById("twoDigits").isEnabled = input.value
# Enable delFolder only if delFiles is true
if input.id == "delFiles":
item = inputs.itemById("delFolder")
item.value = input.value and item.value
item.isEnabled = input.value
# Options for splitSetup
if input.id == "splitSetup":
inputs.itemById("combineTool").isEnabled = input.value
inputs.itemById("toolChange").isEnabled = input.value
inputs.itemById("toolLabel").isEnabled = input.value
inputs.itemById("endCodes").isEnabled = input.value
inputs.itemById("endLabel").isEnabled = input.value
inputs.itemById("fastZ").isEnabled = input.value
except:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
# Event handler for the validateInputs event.
class CommandValidateInputsHandler(adsk.core.ValidateInputsEventHandler):
def __init__(self):
super().__init__()
def notify(self, args):
app = adsk.core.Application.get()
ui = app.userInterface
# No validation currently performed. Skeleton code retained.
try:
eventArgs = adsk.core.ValidateInputsEventArgs.cast(args)
inputs = eventArgs.firingEvent.sender.commandInputs
except:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
# Event handler for the execute event.
class CommandExecuteHandler(adsk.core.CommandEventHandler):
def __init__(self, docSettings, selectedSetups):
self.docSettings = docSettings
self.selectedSetups = selectedSetups
super().__init__()
def notify(self, args):
eventArgs = adsk.core.CommandEventArgs.cast(args)
cmd = eventArgs.command
inputs = cmd.commandInputs
# Code to react to the event.
button = inputs.itemById("replace")
if button.value:
RenameSetups(self.docSettings,
self.selectedSetups,
inputs.itemById("findString").value,
inputs.itemById("replaceString").value,
inputs.itemById("regex").value)
button.value = False
else:
PerformPostProcess(self.docSettings, self.selectedSetups)
def PerformPostProcess(docSettings, setups):
ui = None
progress = None
try:
app = adsk.core.Application.get()
ui = app.userInterface
doc = app.activeDocument
cam = adsk.cam.CAM.cast(doc.products.itemByProductType(constCAMProductId))
cntFiles = 0
cntSkipped = 0
lstSkipped = ""
program = GetNcProgram(cam, docSettings);
parameters = program.parameters
setups = GetSetups(cam, docSettings, setups)
# normalize output folder for this user
# "\" is converted to "/"
outputFolder = parameters.itemByName("nc_program_output_folder").value.value.replace("\\", "/")
# keep leading "\\" for file share
if outputFolder[0:2] == "//":
outputFolder = "\\\\" + outputFolder[2:]
try:
pathlib.Path(outputFolder).mkdir(exist_ok=True)
except Exception as exc:
# see if we can map it to folder with compressed user
compressedName = program.attributes.itemByName(constAttrGroup, constAttrCompressedName).value
if compressedName[0] == "~" and compressedName[1:] == outputFolder[-(len(compressedName) - 1):]:
# yes, it matches
outputFolder = ExpandFileName(compressedName)
compressedName = CompressFileName(outputFolder)
program.attributes.add(constAttrGroup, constAttrCompressedName, compressedName)
docSettings["output"] = compressedName
# Save settings in document attributes
settingsMgr.SaveSettings(doc.attributes, docSettings)
if len(setups) != 0 and cam.allOperations.count != 0:
# make sure we're not going to delete too much
if not docSettings["delFiles"]:
docSettings["delFolder"] = False
if docSettings["delFolder"]:
fileExt = parameters.itemByName("nc_program_nc_extension").value.value
strMsg = CountOutputFolderFiles(outputFolder, len(setups), fileExt)
if strMsg:
docSettings["delFolder"] = False
strMsg = (
"The output folder contains {}. "
"It will not be deleted. You may wish to make sure you selected "
"the correct folder. If you want the folder deleted, you must "
"do it manually."
).format(strMsg)
res = ui.messageBox(strMsg,
constCmdName,
adsk.core.MessageBoxButtonTypes.OKCancelButtonType,
adsk.core.MessageBoxIconTypes.WarningIconType)
if res == adsk.core.DialogResults.DialogCancel:
return # abort!
if docSettings["delFolder"]:
try:
shutil.rmtree(outputFolder, True)
except:
pass #ignore errors
progress = ui.createProgressDialog()
progress.isCancelButtonShown = True
progressMsg = "{} files written to " + outputFolder
progress.show("Post Processing...", "", 0, len(setups))
progress.progressValue = 1 # try to get it to display
progress.progressValue = 0
cntSetups = 0
seqDict = dict()
# We pass through all setups even if only some are selected
# so numbering scheme doesn't change.
for setup in cam.setups:
if progress.wasCancelled:
break
if not setup.isSuppressed and setup.allOperations.count != 0:
nameList = setup.name.split(':') # folder separator
setupFolder = outputFolder
cnt = len(nameList) - 1
i = 0
while i < cnt:
setupFolder += "/" + nameList[i].strip()
i += 1
# keep a separate sequence number for each folder
if setupFolder in seqDict:
seqDict[setupFolder] += 1
# skip if we're not actually including this setup
if setup not in setups:
continue
else:
# first file for this folder
seqDict[setupFolder] = 1
# skip if we're not actually including this setup
if setup not in setups:
continue
if (docSettings["delFiles"]):
# delete all the files in the folder
try:
for entry in os.scandir(setupFolder):
if entry.is_file():
try:
os.remove(entry.path)
except:
pass #ignore errors
except:
pass #ignore errors
# prepend sequence number if enabled
fname = nameList[i].strip()
if docSettings["sequence"] or docSettings["numericName"]:
seq = seqDict[setupFolder]
seqStr = str(seq)
if docSettings["twoDigits"] and seq < 10:
seqStr = "0" + seqStr
if docSettings["numericName"]:
fname = seqStr
else:
fname = seqStr + ' ' + fname
# post the file
status = PostProcessSetup(fname, setup, setupFolder, docSettings, program)
if status == None:
cntFiles += 1
else:
cntSkipped += 1
lstSkipped += "\nFailed on setup " + setup.name + ": " + status
cntSetups += 1
progress.message = progressMsg.format(cntFiles)
progress.progressValue = cntSetups
progress.hide()
# restore program output folder
AssignOutputFolder(parameters, outputFolder)
# done with setups, report results
if cntSkipped != 0:
ui.messageBox("{} files were written. {} Setups were skipped due to error:{}".format(cntFiles, cntSkipped, lstSkipped),
constCmdName,
adsk.core.MessageBoxButtonTypes.OKButtonType,
adsk.core.MessageBoxIconTypes.WarningIconType)
elif cntFiles == 0:
ui.messageBox('No CAM operations posted',
constCmdName,
adsk.core.MessageBoxButtonTypes.OKButtonType,
adsk.core.MessageBoxIconTypes.WarningIconType)
except:
if progress:
progress.hide()
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
def PostProcessSetup(fname, setup, setupFolder, docSettings, program):
ui = None
fileHead = None
fileBody = None
fileOp = None
retVal = "Fusion reported an exception"
try:
app = adsk.core.Application.get()
ui = app.userInterface
doc = app.activeDocument
cam = adsk.cam.CAM.cast(doc.products.itemByProductType(constCAMProductId))
parameters = program.parameters
# Verify file name is valid by creating it now
fileExt = parameters.itemByName("nc_program_nc_extension").value.value
path = setupFolder + "/" + fname + fileExt
try:
pathlib.Path(setupFolder).mkdir(parents=True, exist_ok=True)
fileHead = open(path, "w")
except Exception as exc:
return "Unable to create output file '" + path + "'. Make sure the setup name is valid as a file name."
# Make sure toolpaths are valid
if not cam.checkToolpath(setup):
genStat = cam.generateToolpath(setup)
while not genStat.isGenerationCompleted:
time.sleep(.1)
# set up NCProgram parameters
opName = fname
opFolder = setupFolder
if docSettings["splitSetup"]:
opName = constOpTmpFile
opFolder = tempfile.gettempdir() # e.g., C:\Users\Tim\AppData\Local\Temp
opFolder = opFolder.replace("\\", "/")
parameters.itemByName("nc_program_openInEditor").value.value = False
AssignOutputFolder(parameters, opFolder)
parameters.itemByName("nc_program_filename").value.value = opName
parameters.itemByName("nc_program_name").value.value = fname
# Do it all at once?