-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCreate-Discipline-Document.py
340 lines (273 loc) · 11.2 KB
/
Create-Discipline-Document.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
# Author-schneik.
# Description-This is add-in to take the active design document tab and insert into a new document as a child. the new document is named based on a user selection to help capture intent.
# from pydoc import doc
import adsk.core
import adsk.fusion
import traceback
import os
import os.path
import json
app = adsk.core.Application.get()
ui = app.userInterface
dropDownCommandInput = adsk.core.DropDownCommandInput.cast(None)
boolvalueInput = adsk.core.BoolValueCommandInput.cast(None)
stringDocname = adsk.core.StringValueCommandInput.cast(None)
my_hub = app.data.activeHub
# create doc name values
docSeed = ""
docTitle = ""
docSeed = ""
myDocsDict = ()
globalCommand = " Create Related Document"
panelId = "SolidCreatePanel"
commandIdOnPanel = globalCommand
# local_handlers
local_handlers = []
# Load project and folder from json
def loadProject(__file__):
global app, data, myDocsDict
my_addin_path = os.path.dirname(os.path.realpath(__file__))
my_projectfolder_json_path = os.path.join(my_addin_path, "data.json")
my_docs_json_path = os.path.join(my_addin_path, "docs.json")
# check if the documents json has been created
docsExist = os.path.isfile(my_docs_json_path)
if docsExist == False:
with open(my_projectfolder_json_path) as json_file:
data = json.load(json_file)
app = adsk.core.Application.get()
# ui = app.userInterface
my_hub = app.data.activeHub
my_project = my_hub.dataProjects.itemById(data["PROJECT_ID"])
if my_project is None:
ui.messageBox(
f"Project with id:{data['PROJECT_ID']} not found, review the readme file for instructions on how to set up the add-in."
)
return data
my_folder = my_project.rootFolder.dataFolders.itemById(data["FOLDER_ID"])
if my_folder is None:
ui.messageBox(
f"Folder with id:{data['FOLDER_ID']} not found, review the readme file for instructions on how to set up the add-in."
)
return data
myDocsDictUnsorted = {}
for data_file in my_folder.dataFiles:
if data_file.fileExtension == "f3d":
dname = data_file.name + "dict"
myDocsDictUnsorted.update(
{
dname: {
"name": data_file.name,
"urn": data_file.id,
}
}
)
myDocsDict = dict(sorted(myDocsDictUnsorted.items()))
...
myDocsJson = json.dumps(myDocsDict)
with open(my_docs_json_path, "w") as f:
f.write(myDocsJson)
else:
with open(my_docs_json_path) as json_file:
myDocsDict = json.load(json_file)
return
data = loadProject(__file__)
def commandDefinitionById(id):
app = adsk.core.Application.get()
ui = app.userInterface
if not id:
ui.messageBox("commandDefinition id is not specified")
return None
commandDefinitions_ = ui.commandDefinitions
commandDefinition_ = commandDefinitions_.itemById(id)
return commandDefinition_
def commandControlByIdForPanel(id):
app = adsk.core.Application.get()
ui = app.userInterface
if not id:
ui.messageBox("commandControl id is not specified")
return None
workspaces_ = ui.workspaces
modelingWorkspace_ = workspaces_.itemById("FusionSolidEnvironment")
toolbarPanels_ = modelingWorkspace_.toolbarPanels
toolbarPanel_ = toolbarPanels_.itemById(panelId)
toolbarControls_ = toolbarPanel_.controls
toolbarControl_ = toolbarControls_.itemById(id)
return toolbarControl_
def destroyObject(uiObj, tobeDeleteObj):
if uiObj and tobeDeleteObj:
if tobeDeleteObj.isValid:
tobeDeleteObj.deleteMe()
else:
uiObj.messageBox(tobeDeleteObj + " is not a valid object")
class CommandExecuteHandler(adsk.core.CommandEventHandler):
def __init__(self):
super().__init__()
def notify(self, args: adsk.core.CommandEventArgs):
global doc_urn, docSeed, docTitle
try:
docActiveUrn = app.data.findFileById(doc_urn)
docActive = app.activeDocument
docTitleinput: adsk.core.StringValueCommandInput = (
args.command.commandInputs.itemById("stringValueInput_")
)
docTitle = docTitleinput.value
docNew = app.documents.open(docActiveUrn)
docNew.saveAs(
docTitle,
docActive.dataFile.parentFolder,
"Auto created by related data add-in",
"",
)
transform = adsk.core.Matrix3D.create()
seedDoc = adsk.fusion.Design.cast(
docNew.products.itemByProductType("DesignProductType")
)
seedDoc.rootComponent.occurrences.addByInsert(
docActive.dataFile, transform, True
)
docNew.save(
"Auto saved by related data add-in"
) # Save new doc and add boiler plate comment
except:
if ui:
ui.messageBox(
"command executed failed: {}".format(traceback.format_exc())
)
class CommandCreatedEventHandlerPanel(adsk.core.CommandCreatedEventHandler):
def __init__(self):
super().__init__()
def notify(self, args):
global docSeed, doc_urn
returnValue = 1
if app.activeDocument.isSaved == False:
returnValue = ui.messageBox(
"Related Documents can only be created from saved Documents.\nPlease save this document and try again",
"Document Not Saved",
0,
3,
)
if returnValue == 0:
return
try:
cmd = args.command
cmd.helpFile = "help.html"
onExecute = CommandExecuteHandler()
cmd.execute.add(onExecute)
onInputChanged = InputChangedHandler()
cmd.inputChanged.add(onInputChanged)
# keep the handler referenced beyond this function
local_handlers.append(onExecute)
local_handlers.append(onInputChanged)
commandInputs_ = cmd.commandInputs
dropDownCommandInput = commandInputs_.addDropDownCommandInput(
"dropDownCommandInput",
"Type",
adsk.core.DropDownStyles.LabeledIconDropDownStyle,
)
dropDownItems_ = dropDownCommandInput.listItems
for key, val in myDocsDict.items():
if isinstance(val, dict):
dropDownItems_.add(val.get("name"), True),
docActive = app.activeDocument
doc_with_ver = docActive.name
docSeed = doc_with_ver.rsplit(" ", 1)[0] # trim version
docTitle = docSeed + " - - " + (val.get("name"))
doc_urn = val.get("urn")
boolCommandInput = commandInputs_.addBoolValueInput(
"boolvalueInput_", "Auto-Name", True
)
boolCommandInput.value = True
stringDocName = commandInputs_.addStringValueInput(
"stringValueInput_", "Name", docTitle
)
stringDocName.isEnabled = False
except:
if ui:
ui.messageBox(
_("Panel command created failed: {}").format(traceback.format_exc())
)
class InputChangedHandler(adsk.core.InputChangedEventHandler):
def __init__(self):
super().__init__()
def notify(self, args):
try:
cmdInput = args.input
global doc_urn, docTitle, docSeed
stringDocname = args.inputs.itemById("stringValueInput_")
# handle the combobox change event
if cmdInput.id == "dropDownCommandInput":
searchDict = cmdInput.selectedItem.name
# find the right dictionary based on the combo box value
listOfKeys = ""
for i in myDocsDict.keys():
for j in myDocsDict[i].values():
if searchDict in j:
if i not in listOfKeys:
listOfKeys = i
doc_urn = (myDocsDict).get(listOfKeys).get("urn") # set the urn
doctempname = (myDocsDict).get(listOfKeys).get("name")
docTitle = docSeed + " - - " + doctempname
stringDocname.value = docTitle
# Auto name or user name input
if cmdInput.id == "boolvalueInput_":
if cmdInput.value == True:
stringDocname.isEnabled = False
else:
stringDocname.isEnabled = True
except:
if ui:
ui.messageBox(
"Input changed event failed: {}".format(traceback.format_exc())
)
def run(context):
ui = None
try:
app = adsk.core.Application.get()
ui = app.userInterface
commandName = globalCommand
commandDescription = globalCommand
commandResources = "./resources"
# iconResources = "./resources"
commandDefinitions_ = ui.commandDefinitions
# add a command on create panel in modeling workspace
workspaces_ = ui.workspaces
modelingWorkspace_ = workspaces_.itemById("FusionSolidEnvironment")
toolbarPanels_ = modelingWorkspace_.toolbarPanels
# add the new command under the CREATE panel
toolbarPanel_ = toolbarPanels_.itemById(panelId)
toolbarControlsPanel_ = toolbarPanel_.controls
toolbarControlPanel_ = toolbarControlsPanel_.itemById(commandIdOnPanel)
if not toolbarControlPanel_:
commandDefinitionPanel_ = commandDefinitions_.itemById(commandIdOnPanel)
if not commandDefinitionPanel_:
commandDefinitionPanel_ = commandDefinitions_.addButtonDefinition(
commandIdOnPanel, commandName, commandDescription, commandResources
)
onCommandCreated = CommandCreatedEventHandlerPanel()
commandDefinitionPanel_.commandCreated.add(onCommandCreated)
# keep the handler referenced beyond this function
local_handlers.append(onCommandCreated)
toolbarControlPanel_ = toolbarControlsPanel_.addCommand(
commandDefinitionPanel_
)
toolbarControlPanel_.isVisible = True
except:
if ui:
ui.messageBox("Failed to start Add-In: {}".format(traceback.format_exc()))
def stop(context):
ui = None
try:
app = adsk.core.Application.get()
ui = app.userInterface
objArrayPanel = []
commandControlPanel_ = commandControlByIdForPanel(commandIdOnPanel)
if commandControlPanel_:
objArrayPanel.append(commandControlPanel_)
commandDefinitionPanel_ = commandDefinitionById(commandIdOnPanel)
if commandDefinitionPanel_:
objArrayPanel.append(commandDefinitionPanel_)
for obj in objArrayPanel:
destroyObject(ui, obj)
except:
if ui:
ui.messageBox("Failed to stop Add-In: {}").format(traceback.format_exc())