-
Notifications
You must be signed in to change notification settings - Fork 70
/
a2p_BoM.py
519 lines (453 loc) · 20.5 KB
/
a2p_BoM.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
# ***************************************************************************
# * *
# * Copyright (c) 2018 kbwbe *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * 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 Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library 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 os
import string
from PySide import QtGui, QtCore
import FreeCAD
import FreeCADGui
import Part
import a2plib
import Spreadsheet
# from a2p_fcdocumentreader import FCdocumentReader
from a2p_simpleXMLreader import FCdocumentReader
from a2p_partlistglobals import (
PARTLIST_COLUMN_NAMES,
CLO_PARTLIST_COLUMN_NAMES,
BOM_SHEET_NAME,
BOM_SHEET_LABEL,
CLO_BOM_SHEET_NAME,
CLO_BOM_SHEET_LABEL,
PARTINFORMATION_SHEET_NAME,
BOM_MAX_COLS,
BOM_MAX_LENGTH
)
translate = FreeCAD.Qt.translate
def createCutListOptimizerPartList(
importPath,
parentAssemblyDir,
partListEntries,
recursive=False
):
"""
Extract quantities and descriptions of assembled parts from
document.xml
Is able to analyse subassemblies by recursion
It works with a dict. Structure of an entry is:
filename: [Quantity,[information,information,....] ]
CutListOptimizer (https://cutlistoptimizer.com/) expects the following CSV format:
Length,Width,Qty,Material,Label,Enabled
200,300,3,DEFAULT_MATERIAL,200×300,true
NOTE: The column Material could be skipped, if it is the same for all parts.
"""
fileNameInProject = a2plib.findSourceFileInProject(
importPath,
parentAssemblyDir
)
workingDir, basicFileName = os.path.split(fileNameInProject)
docReader1 = FCdocumentReader()
docReader1.openDocument(fileNameInProject)
for ob in docReader1.getA2pObjects():
# skip converted parts...
if a2plib.to_str(ob.getA2pSource()) == a2plib.to_str('converted'):
continue
if ob.isSubassembly() and recursive:
partListEntries = createPartList(
ob.getA2pSource(),
workingDir,
partListEntries,
recursive
)
# Process information of this a2p object
if not ob.isSubassembly() or not recursive:
# Try to get spreadsheetdata _PARTINFO_ from linked source
linkedSource1 = ob.getA2pSource()
# this returns unicode on py2 systems!
linkedSource = a2plib.findSourceFileInProject(
linkedSource1,
workingDir
)
if linkedSource is None:
print(translate("A2p_BoM", "BOM ERROR: Could not open sourcefile '{}'").format(
linkedSource1))
continue
# Is it already processed minimum one time ?
entry = partListEntries.get(linkedSource, None)
if entry is not None:
# count sourcefile usage
partListEntries.get(linkedSource)[0] += 1
continue # only needed to count imports of this file, information exists yet
# There is no entry in dict, need to read out information from importFile...
docReader2 = FCdocumentReader()
docReader2.openDocument(linkedSource)
# Initialize a default parts information...
partInformation = []
for i in range(0, len(CLO_PARTLIST_COLUMN_NAMES)):
partInformation.append("*")
# if there is a proper spreadsheet, then read it...
for ob in docReader2.getSpreadsheetObjects():
sheetName = PARTINFORMATION_SHEET_NAME
sheetName = a2plib.to_bytes(PARTINFORMATION_SHEET_NAME)
if ob.name == sheetName:
cells = ob.getCells()
for addr in cells.keys():
if addr[:1] == b'B': # column B contains the data, A only the titles
idx = int(addr[1:])-1
if idx < len(CLO_PARTLIST_COLUMN_NAMES): # don't read further!
partInformation[idx] = cells[addr]
# last entry of partinformations is reserved for filename
# without complete path...
partInformation[-1] = os.path.split(linkedSource)[1]
# #########################################################
# add dimensions from the overall bounding box of the file
# in the last 3 fields before the filename
dc = FreeCAD.openDocument(linkedSource)
op = Part.makeCompound([i.Shape for i in dc.findObjects(
"Part::Feature") if i.ViewObject.Visibility and not i.TypeId == "PartDesign::Plane"])
bb = op.BoundBox
partInformation[-2] = str(bb.ZLength)
partInformation[-3] = str(bb.YLength)
partInformation[-4] = str(bb.XLength)
FreeCAD.closeDocument(dc.Name)
# #########################################################
# put information to dict and count usage of sourcefiles..
entry = partListEntries.get(linkedSource, None)
if entry is None:
partListEntries[linkedSource] = [
1,
partInformation
]
else:
# count sourcefile usage
partListEntries.get(linkedSource)[0] += 1
return partListEntries
def createPartList(
importPath,
parentAssemblyDir,
partListEntries,
recursive=False
):
"""
Extract quantities and descriptions of assembled parts from
document.xml
Is able to analyse subassemblies by recursion
It works with a dict. Structure of an entry is:
filename: [Quantity,[information,information,....] ]
"""
fileNameInProject = a2plib.findSourceFileInProject(
importPath,
parentAssemblyDir
)
workingDir, basicFileName = os.path.split(fileNameInProject)
docReader1 = FCdocumentReader()
docReader1.openDocument(fileNameInProject)
for ob in docReader1.getA2pObjects():
# skip converted parts...
if a2plib.to_str(ob.getA2pSource()) == a2plib.to_str('converted'):
continue
if ob.isSubassembly() and recursive:
partListEntries = createPartList(
ob.getA2pSource(),
workingDir,
partListEntries,
recursive
)
# Process information of this a2p object
if not ob.isSubassembly() or not recursive:
# Try to get spreadsheetdata _PARTINFO_ from linked source
linkedSource1 = ob.getA2pSource()
# this returns unicode on py2 systems!
linkedSource = a2plib.findSourceFileInProject(
linkedSource1,
workingDir
)
if linkedSource is None:
print(translate("A2p_BoM", "BOM ERROR: Could not open sourcefile '{}'").format(
linkedSource1))
continue
# Is it already processed minimum one time ?
entry = partListEntries.get(linkedSource, None)
if entry is not None:
# count sourcefile usage
partListEntries.get(linkedSource)[0] += 1
continue # only needed to count imports of this file, information exists yet
# There is no entry in dict, need to read out information from importFile...
docReader2 = FCdocumentReader()
docReader2.openDocument(linkedSource)
# Initialize a default parts information...
partInformation = []
for i in range(0, len(PARTLIST_COLUMN_NAMES)):
partInformation.append("*")
# if there is a proper spreadsheet, then read it...
for ob in docReader2.getSpreadsheetObjects():
sheetName = PARTINFORMATION_SHEET_NAME
sheetName = a2plib.to_bytes(PARTINFORMATION_SHEET_NAME)
if ob.name == sheetName:
cells = ob.getCells()
for addr in cells.keys():
if addr[:1] == b'B': # column B contains the data, A only the titles
idx = int(addr[1:])-1
if idx < len(PARTLIST_COLUMN_NAMES): # don't read further!
partInformation[idx] = cells[addr]
# last entry of partinformations is reserved for filename
# without complete path...
partInformation[-1] = os.path.split(linkedSource)[1]
# put information to dict and count usage of sourcefiles..
entry = partListEntries.get(linkedSource, None)
if entry is None:
partListEntries[linkedSource] = [
1,
partInformation
]
else:
# count sourcefile usage
partListEntries.get(linkedSource)[0] += 1
return partListEntries
class a2p_CreatePartlist():
def clearPartList(self):
alphabet_list = list(string.ascii_uppercase)
doc = FreeCAD.activeDocument()
ss = doc.getObject(BOM_SHEET_NAME)
for i in range(0, BOM_MAX_COLS):
for k in range(0, BOM_MAX_LENGTH):
cellAdress = alphabet_list[i] + str(k + 1)
ss.set(cellAdress, '')
def Activated(self):
doc = FreeCAD.activeDocument()
if doc is None:
QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus", "No active document found!"),
translate("A2plus", "You have to open a FCStd file first.")
)
return
completeFilePath = doc.FileName
p, f = os.path.split(completeFilePath)
flags = QtGui.QMessageBox.StandardButton.Yes | QtGui.QMessageBox.StandardButton.No
msg = translate(
"A2plus", "Please save before generating a parts list! Save now?")
response = QtGui.QMessageBox.information(QtGui.QApplication.activeWindow(
), translate("A2plus", "Save document?"), msg, flags)
if response == QtGui.QMessageBox.No:
QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus", "Parts list generation aborted!"),
translate("A2plus", "You have to save the assembly file first.")
)
return
else:
doc.save()
flags = QtGui.QMessageBox.StandardButton.Yes | QtGui.QMessageBox.StandardButton.No
msg = translate(
"A2plus", "Do you want to iterate recursively over all included subassemblies?")
response = QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(), translate("A2p_BoM", "PARTSLIST"), msg, flags)
if response == QtGui.QMessageBox.Yes:
subAssyRecursion = True
else:
subAssyRecursion = False
partListEntries = createPartList(
doc.FileName,
p,
{},
recursive=subAssyRecursion
)
ss = None
try:
ss = doc.getObject(BOM_SHEET_NAME)
except:
pass
if ss is None:
ss = doc.addObject('Spreadsheet::Sheet', BOM_SHEET_NAME)
ss.Label = BOM_SHEET_LABEL
else:
self.clearPartList()
# Write Column headers to spreadsheet
ss.set('A1', translate("A2p_BoM", "POS"))
ss.set('B1', translate("A2p_BoM", "QTY"))
self.CreateColumnHeadersInSpreadsheet(ss, PARTLIST_COLUMN_NAMES, 'C')
# fill entries for partsList...
idx3 = ord('A')
for idx, k in enumerate(partListEntries.keys()):
ss.set('A' + str(idx + 2), str(idx + 1))
ss.set('B' + str(idx + 2), str(partListEntries[k][0]))
values = partListEntries[k][1]
for j, tx in enumerate(values): # all strings inside values are unicode!
ss.set(chr(idx3 + 2 + j) + str(idx + 2),
tx.replace(''', ''))
# recompute to finish...
doc.recompute()
FreeCAD.Console.PrintMessage(
translate("A2p_BoM", "#PARTSLIST# spreadsheet has been created") + "\n")
def GetResources(self):
return {
'Pixmap': ':/icons/a2p_PartsList.svg',
'MenuText': translate("A2plus", "Create a spreadsheet with a parts list of this file"),
'ToolTip': translate(
"A2plus", "Create a spreadsheet with a " + "\n" +
"parts list of this file." + "\n\n" +
"This function will read out " + "\n" +
"the #PARTINFO# spreadsheet of " + "\n" +
"all involved parts of the " + "\n" +
"assembly and create a new " + "\n" +
"spreadsheet containing the " + "\n" +
"parts list." + "\n\n" +
"This button will open a dialog " + "\n" +
"with the Question:" + "\n" +
"- Iterate recursively over " + "\n" +
" all subassenblies?" + "\n\n" +
"Answer Yes:" + "\n" +
"All parts of all subassemblies are " + "\n" +
"collected to the partlist " + "\n\n" +
"Answer No:" + "\n" +
"Only the parts within the " + "\n" +
"recent assembly are collected.")
}
def CreateColumnHeadersInSpreadsheet(self, ss, columnHeaders, startColumn):
"""
Creates the column headers in the given spreadsheet (`ss`) starting in the column `startColumn`.
The column headers are specified in the array `columnHeaders`.
"""
# Write Column headers to spreadsheet
idx1 = ord(startColumn)
idx2 = idx1 + len(columnHeaders)
i = 0
for c in range(idx1, idx2):
ss.set(chr(c) + "1", columnHeaders[i])
i += 1
# Set the background color of the column headers
ss.setBackground('A1:' + chr(idx2 - 1) + '1',
(0.000000, 1.000000, 0.000000, 1.000000))
# Set the columnwith to proper values
ss.setColumnWidth('A', 40)
i = 0
for c in range(idx1, idx2):
ss.setColumnWidth(chr(c), 150)
i += 1
class a2p_CreateCutListOptimizerPartlist(a2p_CreatePartlist):
def clearPartList(self):
alphabet_list = list(string.ascii_uppercase)
doc = FreeCAD.activeDocument()
ss = doc.getObject(CLO_BOM_SHEET_NAME)
for i in range(0, CLO_BOM_MAX_COLS):
for k in range(0, CLO_BOM_MAX_LENGTH):
cellAdress = alphabet_list[i] + str(k + 1)
ss.set(cellAdress, '')
def Activated(self):
doc = FreeCAD.activeDocument()
if doc is None:
QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus", "No active document found!"),
translate("A2plus", "You have to open a FCStd file first.")
)
return
completeFilePath = doc.FileName
p, f = os.path.split(completeFilePath)
flags = QtGui.QMessageBox.StandardButton.Yes | QtGui.QMessageBox.StandardButton.No
msg = translate(
"A2plus", "Please save before generating a parts list! Save now?")
response = QtGui.QMessageBox.information(QtGui.QApplication.activeWindow(
), translate("A2plus", "Save document?"), msg, flags)
if response == QtGui.QMessageBox.No:
QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus", "Parts list generation aborted!"),
translate("A2plus", "You have to save the assembly file first.")
)
return
else:
doc.save()
flags = QtGui.QMessageBox.StandardButton.Yes | QtGui.QMessageBox.StandardButton.No
msg = translate(
"A2plus", "Do you want to iterate recursively over all included subassemblies?")
response = QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(), translate("A2p_BoM", "PARTSLIST"), msg, flags)
if response == QtGui.QMessageBox.Yes:
subAssyRecursion = True
else:
subAssyRecursion = False
partListEntries = createCutListOptimizerPartList(
doc.FileName,
p,
{},
recursive=subAssyRecursion
)
ss = None
try:
ss = doc.getObject(CLO_BOM_SHEET_NAME)
except:
pass
if ss is None:
ss = doc.addObject('Spreadsheet::Sheet', CLO_BOM_SHEET_NAME)
ss.Label = CLO_BOM_SHEET_LABEL
else:
self.clearPartList()
self.CreateColumnHeadersInSpreadsheet(
ss, CLO_PARTLIST_COLUMN_NAMES, 'A')
self.FillPartsListEntries(ss, partListEntries)
# recompute to finish...
doc.recompute()
FreeCAD.Console.PrintMessage(translate(
"A2p_BoM", "#PARTSLIST_CutListOptimizer# spreadsheet has been created") + "\n")
def GetResources(self):
return {
'Pixmap': ':/icons/a2p_PartsList_CutListOptimizer.svg',
'MenuText': translate("A2plus", "Create a spreadsheet with a parts list for https://cutlistoptimizer.com/ of this file"),
'ToolTip': translate(
"A2plus", "Create a spreadsheet with a " + "\n" +
"parts list https://cutlistoptimizer.com/ of this file." + "\n\n" +
"This function will read out " + "\n" +
"the #PARTINFO# spreadsheet of " + "\n" +
"all involved parts of the " + "\n" +
"assembly and create a new " + "\n" +
"spreadsheet containing the " + "\n" +
"parts list." + "\n\n" +
"This button will open a dialog " + "\n" +
"with the Question:" + "\n" +
"- Iterate recursively over " + "\n" +
" all subassenblies?" + "\n\n" +
"Answer Yes:" + "\n" +
"All parts of all subassemblies are " + "\n" +
"collected to the partlist " + "\n\n" +
"Answer No:" + "\n" +
"Only the parts within the " + "\n" +
"recent assembly are collected.")
}
def FillPartsListEntries(self, ss, partListEntries):
# [2, ['*', '*', '75.0', '45.0', '1050.0', 'LongBeam.FCStd']]
QUANTITY_IDX = 0
LENGTH_IDX = 2
WIDTH_IDX = 3
HEIGHT_IDX = 4
FILENAME_IDX = 5
for idx, k in enumerate(partListEntries.keys()):
quantity = partListEntries[k][QUANTITY_IDX]
values = partListEntries[k][1]
ss.set('A' + str(idx + 2), str(values[LENGTH_IDX]))
ss.set('B' + str(idx + 2), str(values[WIDTH_IDX]))
ss.set('C' + str(idx + 2), str(quantity))
ss.set('D' + str(idx + 2), str(values[HEIGHT_IDX]))
ss.set('E' + str(idx + 2), values[FILENAME_IDX])
ss.set('F' + str(idx + 2), "true")
FreeCADGui.addCommand('a2p_CreatePartlist', a2p_CreatePartlist())
FreeCADGui.addCommand('a2p_CreateCutListOptimizerPartlist',
a2p_CreateCutListOptimizerPartlist())