-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy patha2p_importpart.py
2151 lines (1796 loc) · 82.1 KB
/
a2p_importpart.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
#***************************************************************************
#* *
#* Copyright (c) 2018 kbwbe *
#* *
#* Portions of code based on hamish's assembly 2 *
#* *
#* 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 sys
import FreeCAD, FreeCADGui
from PySide import QtGui, QtCore
import copy
import platform
from a2p_translateUtils import *
import a2plib
from a2p_MuxAssembly import muxAssemblyWithTopoNames
import a2p_solversystem
from a2plib import getRelativePathesEnabled
import a2p_importedPart_class
import a2p_convertPart
from a2p_topomapper import TopoMapper
import a2p_lcs_support
from a2p_importedPart_class import Proxy_importPart, ImportedPartViewProviderProxy
import a2p_constraintServices
#PYVERSION = sys.version_info[0]
#==============================================================================
class DataContainer():
def __init__(self):
self.tx = None
#==============================================================================
class ObjectCache:
"""
An assembly could use multiple instances of then same importPart.
Cache them here so fileImports have to be executed only one time...
"""
def __init__(self):
self.objects = {} # dict, key=fileName, val=object
def cleanUp(self,doc):
for key in self.objects.keys():
try:
doc.removeObject(self.objects[key].Name) #remove temporaryParts from doc
except:
pass
self.objects = {} # dict, key=fileName
def add(self,fileName,obj): # pi_obj = PartInformation-Object
self.objects[fileName] = obj
def get(self,fileName):
obj = self.objects.get(fileName,None)
if obj:
return obj
else:
return None
def isCached(self,fileName):
if fileName in self.objects.keys():
return True
else:
return False
def len(self):
return len(self.objects.keys())
objectCache = ObjectCache()
#==============================================================================
class a2p_multiShapeExtractDialog(QtGui.QDialog):
"""
Select a label from shape which has to be imported from a file.
"""
Deleted = QtCore.Signal()
Accepted = QtCore.Signal()
def __init__(self, parent, labelList = [], iconList = [], data = None):
super(a2p_multiShapeExtractDialog,self).__init__(parent=parent)
self.labelList = labelList
self.iconList = iconList
self.data = data
self.initUI()
def initUI(self):
self.setWindowTitle(translate("A2plus", "Import Objects"))
self.mainLayout = QtGui.QGridLayout() # a VBoxLayout for the whole form
lzip = sorted(zip(self.labelList, self.iconList))
self.labelList = [li[0] for li in lzip]
self.iconList = [li[1] for li in lzip]
l = self.labelList
self.label = QtGui.QLabel(self)
self.label.setText(translate("A2plus", "Select objects to import"))
self.listView = QtGui.QListWidget()
for i, item in enumerate(l):
icon = self.iconList[i]
item = QtGui.QListWidgetItem(item)
item.setIcon(icon)
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setCheckState(QtCore.Qt.Unchecked)
self.listView.addItem(item)
self.buttons = QtGui.QDialogButtonBox(self)
self.buttons.setOrientation(QtCore.Qt.Horizontal)
self.buttons.addButton(translate("A2plus", "Cancel"), QtGui.QDialogButtonBox.RejectRole)
self.buttons.addButton(translate("A2plus", "Import"), QtGui.QDialogButtonBox.AcceptRole)
self.connect(self.buttons, QtCore.SIGNAL("accepted()"), self, QtCore.SLOT("accept()"))
self.connect(self.buttons, QtCore.SIGNAL("rejected()"), self, QtCore.SLOT("reject()"))
self.mainLayout.addWidget(self.label)
self.mainLayout.addWidget(self.listView)
self.mainLayout.addWidget(self.buttons)
self.setLayout(self.mainLayout)
def accept(self):
if self.data is not None:
checked_items = []
for index in range(self.listView.count()):
if self.listView.item(index).checkState() == QtCore.Qt.Checked:
checked_items.append(self.listView.item(index).text())
if checked_items:
for i in checked_items:
print(translate("A2plus", "Importing"), i)
self.data.tx = checked_items
self.deleteLater()
def reject(self):
self.deleteLater()
#==============================================================================
class a2p_shapeExtractDialog(QtGui.QDialog):
"""
Select a label from shape which has to be imported from a file.
"""
Deleted = QtCore.Signal()
Accepted = QtCore.Signal()
def __init__(self,parent,labelList = [], data = None):
super(a2p_shapeExtractDialog,self).__init__(parent=parent)
#super(a2p_shapeExtractDialog,self).__init__()
self.labelList = labelList
self.data = data
self.initUI()
def initUI(self):
self.resize(400,100)
self.setWindowTitle(translate("A2plus", "Select a shape to be imported"))
self.mainLayout = QtGui.QGridLayout() # a VBoxLayout for the whole form
self.shapeCombo = QtGui.QComboBox(self)
l = sorted(self.labelList)
self.shapeCombo.addItems(l)
self.buttons = QtGui.QDialogButtonBox(self)
self.buttons.setOrientation(QtCore.Qt.Horizontal)
self.buttons.addButton(translate("A2plus", "Cancel"), QtGui.QDialogButtonBox.RejectRole)
self.buttons.addButton(translate("A2plus", "Choose"), QtGui.QDialogButtonBox.AcceptRole)
self.connect(self.buttons, QtCore.SIGNAL("accepted()"), self, QtCore.SLOT("accept()"))
self.connect(self.buttons, QtCore.SIGNAL("rejected()"), self, QtCore.SLOT("reject()"))
self.mainLayout.addWidget(self.shapeCombo,0,0,1,1)
self.mainLayout.addWidget(self.buttons,1,0,1,1)
self.setLayout(self.mainLayout)
def accept(self):
if self.data is not None:
self.data.tx = self.shapeCombo.currentText()
self.deleteLater()
def reject(self):
self.deleteLater()
#==============================================================================
def importPartFromFile(
_doc,
filename,
extractSingleShape = False, # load only a single user defined shape from file
desiredShapeLabel = None,
importToCache = False,
cacheKey = ""
):
doc = _doc
#-------------------------------------------
# Get the importDocument
#-------------------------------------------
# look only for filenames, not paths, as there are problems on WIN10 (Address-translation??)
importDoc = None
importDocIsOpen = False
requestedFile = os.path.split(filename)[1]
for d in FreeCAD.listDocuments().values():
recentFile = os.path.split(d.FileName)[1]
if requestedFile == recentFile:
importDoc = d # file is already open...
importDocIsOpen = True
break
if not importDocIsOpen:
if filename.lower().endswith('.fcstd'):
importDoc = FreeCAD.openDocument(filename)
elif filename.lower().endswith('.stp') or filename.lower().endswith('.step'):
import ImportGui
fname = os.path.splitext(os.path.basename(filename))[0]
FreeCAD.newDocument(fname)
newname = FreeCAD.ActiveDocument.Name
FreeCAD.setActiveDocument(newname)
ImportGui.insert(filename,newname)
importDoc = FreeCAD.ActiveDocument
else:
msg = translate("A2plus", "A part can only be imported from a FreeCAD '*.FCStd' file")
QtGui.QMessageBox.information( QtGui.QApplication.activeWindow(), translate("A2plus", "Value Error"), msg )
return
#-------------------------------------------
# recalculate imported part if requested by preferences
# This can be useful if the imported part depends on an
# external master-spreadsheet
#-------------------------------------------
if a2plib.getRecalculateImportedParts():
for ob in importDoc.Objects:
ob.recompute()
importDoc.save() # useless without saving...
#-------------------------------------------
# Initialize the new TopoMapper
#-------------------------------------------
topoMapper = TopoMapper(importDoc)
#-------------------------------------------
# Get a list of the importable Objects
#-------------------------------------------
importableObjects = topoMapper.getTopLevelObjects(allowSketches=True)
if len(importableObjects) == 0:
msg = translate("A2plus", "No visible Part to import found. Aborting operation")
QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus", "Import Error"),
msg
)
return
#-------------------------------------------
# if only one single shape of the importdoc is wanted..
#-------------------------------------------
labelList = []
dc = DataContainer()
if extractSingleShape:
if desiredShapeLabel is None: # ask for a shape label
for io in importableObjects:
labelList.append(io.Label)
dialog = a2p_shapeExtractDialog(
QtGui.QApplication.activeWindow(),
labelList,
dc)
dialog.exec_()
if dc.tx is None:
msg = translate("A2plus", "Import of a shape reference aborted by user")
QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus", "Import Error"),
msg
)
return
else: # use existent shape label
dc.tx = desiredShapeLabel
#-------------------------------------------
# Discover whether we are importing a subassembly or a single part
#-------------------------------------------
subAssemblyImport = False
if all([ 'importPart' in obj.Content for obj in importableObjects]) == 1:
subAssemblyImport = True
#-------------------------------------------
# create new object
#-------------------------------------------
if importToCache:
partName = 'CachedObject_'+str(objectCache.len())
newObj = doc.addObject("Part::FeaturePython",partName)
newObj.Label = partName
else:
partName = a2plib.findUnusedObjectName( importDoc.Label, document=doc )
if extractSingleShape == False:
partLabel = a2plib.findUnusedObjectLabel( importDoc.Label, document=doc )
else:
partLabel = a2plib.findUnusedObjectLabel(
importDoc.Label,
document=doc,
extension=dc.tx
)
newObj = doc.addObject( "Part::FeaturePython", str(partName.encode('utf-8')) ) # works on Python 3.6.5
newObj.Label = partLabel
Proxy_importPart(newObj)
if FreeCAD.GuiUp:
ImportedPartViewProviderProxy(newObj.ViewObject)
newObj.a2p_Version = a2plib.getA2pVersion()
assemblyPath = os.path.normpath(os.path.split(doc.FileName)[0])
absPath = os.path.normpath(filename)
if getRelativePathesEnabled():
if platform.system() == "Windows":
prefix = '.\\'
else:
prefix = './'
relativePath = prefix+os.path.relpath(absPath, assemblyPath)
newObj.sourceFile = relativePath
else:
newObj.sourceFile = absPath
if dc.tx is not None:
newObj.sourcePart = dc.tx
newObj.setEditorMode("timeLastImport",1)
newObj.timeLastImport = os.path.getmtime( filename )
if a2plib.getForceFixedPosition():
newObj.fixedPosition = True
else:
newObj.fixedPosition = not any([i.fixedPosition for i in doc.Objects if hasattr(i, 'fixedPosition') ])
newObj.subassemblyImport = subAssemblyImport
newObj.setEditorMode("subassemblyImport",1)
if subAssemblyImport:
if extractSingleShape:
newObj.muxInfo, newObj.Shape, newObj.ViewObject.DiffuseColor, newObj.ViewObject.Transparency = \
muxAssemblyWithTopoNames(importDoc,desiredShapeLabel = dc.tx)
else:
newObj.muxInfo, newObj.Shape, newObj.ViewObject.DiffuseColor, newObj.ViewObject.Transparency = \
muxAssemblyWithTopoNames(importDoc)
else:
# TopoMapper manages import of non A2p-Files. It generates the shapes and appropriate topo names...
if extractSingleShape:
newObj.muxInfo, newObj.Shape, newObj.ViewObject.DiffuseColor, newObj.ViewObject.Transparency = \
topoMapper.createTopoNames(desiredShapeLabel = dc.tx)
else:
newObj.muxInfo, newObj.Shape, newObj.ViewObject.DiffuseColor, newObj.ViewObject.Transparency = \
topoMapper.createTopoNames()
newObj.objectType = 'a2pPart'
if extractSingleShape == True:
if a2plib.isA2pSketch(newObj):
newObj.objectType = 'a2pSketch'
newObj.setEditorMode("objectType",1)
doc.recompute()
if importToCache: # this import is used to update already imported parts
objectCache.add(cacheKey, newObj)
else: # this is a first time import of a part
if not a2plib.getPerFaceTransparency():
# turn of perFaceTransparency by accessing ViewObject.Transparency and set to zero (non transparent)
newObj.ViewObject.Transparency = 1
newObj.ViewObject.Transparency = 0 # import assembly first time as non transparent.
lcsList = a2p_lcs_support.getListOfLCS(doc,importDoc)
if not importDocIsOpen:
FreeCAD.closeDocument(importDoc.Name)
if len(lcsList) > 0:
#=========================================
# create a group containing imported LCS's
lcsGroupObjectName = 'LCS_Collection'
lcsGroupLabel = translate("A2plus", "LCS_Collection")
lcsGroup = doc.addObject( "Part::FeaturePython", str(lcsGroupObjectName.encode('utf-8')) ) # works on Python 3.6.5
lcsGroup.Label = lcsGroupLabel
a2p_lcs_support.LCS_Group(lcsGroup)
a2p_lcs_support.VP_LCS_Group(lcsGroup.ViewObject)
for lcs in lcsList:
lcsGroup.addObject(lcs)
lcsGroup.Owner = newObj.Name
newObj.addProperty("App::PropertyLinkList","lcsLink","importPart").lcsLink = lcsGroup
newObj.Label = newObj.Label # this is needed to trigger an update
lcsGroup.Label = lcsGroup.Label
#=========================================
return newObj
#==============================================================================
toolTip = \
translate("A2plus",
'''
Add shapes from an external file
to the assembly
'''
)
class a2p_ImportShapeReferenceCommand():
def GetResources(self):
return {'Pixmap' : a2plib.get_module_path()+'/icons/a2p_ShapeReference.svg',
'Accel' : "Ctrl+Shift+A", # a default shortcut (optional)
'MenuText': translate("A2plus", "Add shapes from an external file"),
'ToolTip' : toolTip
}
def Activated(self):
if FreeCAD.ActiveDocument is None:
QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus", "No active document found!"),
translate("A2plus", "First create an empty file and save it under desired name")
)
return
#
if FreeCAD.ActiveDocument.FileName == '':
QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus", "Unnamed document"),
translate("A2plus", "Before inserting first part, please save the empty assembly to give it a name")
)
FreeCADGui.SendMsgToActiveView("Save")
return
doc = FreeCAD.activeDocument()
guidoc = FreeCADGui.activeDocument()
view = guidoc.activeView()
dialog = QtGui.QFileDialog(
QtGui.QApplication.activeWindow(),
translate("A2plus", "Select FreeCAD document to import part from")
)
# set option "DontUseNativeDialog"=True, as native Filedialog shows
# misbehavior on Unbuntu 18.04 LTS. It works case sensitively, what is not wanted...
if a2plib.getNativeFileManagerUsage():
dialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, False)
else:
dialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, True)
dialog.setNameFilter(translate("A2plus", "Supported Formats (*.FCStd *.fcstd *.stp *.step);;All files (*.*)"))
if dialog.exec_():
filename = str(dialog.selectedFiles()[0])
else:
return
if not a2plib.checkFileIsInProjectFolder(filename):
msg = translate("A2plus", "The part you try to import is outside of your project-folder! Check your settings of A2plus preferences.")
QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus", "Import Error"),
msg
)
return
#==========================================================================================
# for multiple part import: first open the importDoc, if possible
#==========================================================================================
# look only for filenames, not paths, as there are problems on WIN10 (Address-translation??)
#==========================================================================================
importDoc = None
importDocIsOpen = False
requestedFile = os.path.split(filename)[1]
for d in FreeCAD.listDocuments().values():
recentFile = os.path.split(d.FileName)[1]
if requestedFile == recentFile:
importDoc = d # file is already open...
importDocIsOpen = True
break
if not importDocIsOpen:
if filename.lower().endswith('.fcstd'):
importDoc = FreeCAD.openDocument(filename)
elif filename.lower().endswith('.stp') or filename.lower().endswith('.step'):
import ImportGui
fname = os.path.splitext(os.path.basename(filename))[0]
FreeCAD.newDocument(fname)
newname = FreeCAD.ActiveDocument.Name
FreeCAD.setActiveDocument(newname)
ImportGui.insert(filename,newname)
importDoc = FreeCAD.ActiveDocument
else:
msg = translate("A2plus", "A part can only be imported from a FreeCAD '*.FCStd' file")
QtGui.QMessageBox.information( QtGui.QApplication.activeWindow(), translate("A2plus", "Value Error"), msg )
return
#==========================================================================================
# file seems to be open....
# detect the importable objects...
#==========================================================================================
topoMapper = TopoMapper(importDoc)
importableObjects = topoMapper.getTopLevelObjects(allowSketches=True)
if len(importableObjects) == 0:
msg = translate("A2plus", "No visible Part to import found. Aborting operation")
QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus", "Import Error"),
msg
)
return
#==========================================================================================
# creates a dialog for selecting the parts
#==========================================================================================
labelList = []
iconList = []
dc = DataContainer()
for io in importableObjects:
labelList.append(io.Label)
iconList.append(io.ViewObject.Icon)
dialog = a2p_multiShapeExtractDialog(
QtGui.QApplication.activeWindow(),
labelList, iconList,
dc
)
dialog.exec_()
if dialog.rejected:
FreeCAD.closeDocument(importDoc.Name)
if dc.tx is None or len(dc.tx)==0:
return
selectedObjects = dc.tx
importedObjectsList = []
for so in selectedObjects:
importedObject = importPartFromFile(doc, filename, extractSingleShape=True, desiredShapeLabel = so)
if not importedObject:
a2plib.Msg(translate("A2plus", "Imported Object is empty/none") + "\n")
continue
importedObjectsList.append(importedObject)
try:
FreeCAD.closeDocument(importDoc.Name) #avoid errormessage if doc already closed...
except:
pass
mw = FreeCADGui.getMainWindow()
mdi = mw.findChild(QtGui.QMdiArea)
sub = mdi.activeSubWindow()
if sub is not None:
sub.showMaximized()
self.timer = QtCore.QTimer()
QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.GuiViewFit)
self.timer.start( 200 ) #0.2 seconds
for io in importedObjectsList:
if io and a2plib.isA2pSketch(io):
if not any([i.fixedPosition for i in doc.Objects if hasattr(i, 'fixedPosition') ]):
io.fixedPosition = True
# At first, make all imported Objects invisible,
for io in importedObjectsList:
io.ViewObject.Visibility = False
for io in importedObjectsList:
io.ViewObject.Visibility = True # make imported objects visible step by step,
# in order to see, which one is recently being placed..
if io and not a2plib.isA2pSketch(io) and not io.fixedPosition:
pm = PartMover( view, io, deleteOnEscape = True )
while pm.isActive:
FreeCADGui.updateGui() # keeping the UI responsible
del pm
return
# def IsActive(self):
# doc = FreeCAD.activeDocument()
# if doc is None: return False
# return True
def GuiViewFit(self):
FreeCADGui.SendMsgToActiveView("ViewFit")
self.timer.stop()
FreeCADGui.addCommand('a2p_ImportShapeReferenceCommand',a2p_ImportShapeReferenceCommand())
#==============================================================================
toolTip = \
translate("A2plus",
'''
Restore transparency to
active document objects
'''
)
class a2p_Restore_Transparency_Command():
def GetResources(self):
return {'Pixmap' : a2plib.get_module_path()+'/icons/a2p_Restore_Transparency.svg',
'Accel' : "Shift+T", # a default shortcut (optional)
'MenuText': translate("A2plus", "Restore transparency to active document objects"),
'ToolTip' : toolTip
}
def Activated(self):
doc = FreeCAD.ActiveDocument
if doc is None:
FreeCAD.Console.Print(translate("A2plus", "No active document found!"))
return
else:
for obj in doc.Objects:
if hasattr (obj, 'ViewObject'):
if hasattr (obj.ViewObject, 'Transparency'):
if obj.ViewObject.Transparency < 100:
transparency = obj.ViewObject.Transparency
obj.ViewObject.Transparency = transparency + 1
obj.ViewObject.Transparency = transparency
return
def IsActive(self):
doc = FreeCAD.activeDocument()
if doc is None: return False
return True
FreeCADGui.addCommand('a2p_Restore_Transparency',a2p_Restore_Transparency_Command())
#==============================================================================
toolTip = \
translate("A2plus",
'''
Add a part from an external file
to the assembly
'''
)
class a2p_ImportPartCommand():
def GetResources(self):
return {'Pixmap' : a2plib.get_module_path()+'/icons/a2p_ImportPart.svg',
'Accel' : "Shift+A", # a default shortcut (optional)
'MenuText': translate("A2plus", "Add a part from an external file"),
'ToolTip' : toolTip
}
def Activated(self):
if FreeCAD.ActiveDocument is None:
QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus", "No active document found!"),
translate("A2plus", "First create an empty file and save it under desired name")
)
return
#
if FreeCAD.ActiveDocument.FileName == '':
QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus", "Unnamed document"),
translate("A2plus", "Before inserting first part, please save the empty assembly to give it a name")
)
FreeCADGui.SendMsgToActiveView("Save")
return
doc = FreeCAD.activeDocument()
guidoc = FreeCADGui.activeDocument()
view = guidoc.activeView()
dialog = QtGui.QFileDialog(
QtGui.QApplication.activeWindow(),
translate("A2plus", "Select FreeCAD document to import part from")
)
# set option "DontUseNativeDialog"=True, as native Filedialog shows
# misbehavior on Unbuntu 18.04 LTS. It works case sensitively, what is not wanted...
if a2plib.getNativeFileManagerUsage():
dialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, False)
else:
dialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, True)
dialog.setNameFilter(translate("A2plus", "Supported Formats (*.FCStd *.fcstd *.stp *.step);;All files (*.*)"))
if dialog.exec_():
filename = str(dialog.selectedFiles()[0])
else:
return
if not a2plib.checkFileIsInProjectFolder(filename):
msg = translate("A2plus", "The part you try to import is outside of your project-folder! Check your settings of A2plus preferences.")
QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus","Import Error"),
msg
)
return
#TODO: change for multi separate part import
importedObject = importPartFromFile(doc, filename)
if not importedObject:
a2plib.Msg(translate("A2plus", "Imported Object is empty/none\n"))
return
mw = FreeCADGui.getMainWindow()
mdi = mw.findChild(QtGui.QMdiArea)
sub = mdi.activeSubWindow()
if sub is not None:
sub.showMaximized()
# WF: how will this work for multiple imported objects?
# only A2p AI's will have property "fixedPosition"
if importedObject and not importedObject.fixedPosition:
PartMover( view, importedObject, deleteOnEscape = True )
else:
self.timer = QtCore.QTimer()
QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.GuiViewFit)
self.timer.start( 200 ) #0.2 seconds
return
# def IsActive(self):
# doc = FreeCAD.activeDocument()
# if doc is None: return False
# return True
def GuiViewFit(self):
FreeCADGui.SendMsgToActiveView("ViewFit")
self.timer.stop()
FreeCADGui.addCommand('a2p_ImportPart',a2p_ImportPartCommand())
#==============================================================================
def updateImportedParts(doc, partial=False):
doc.openTransaction("updateImportParts")
objectCache.cleanUp(doc)
selectedObjects=[]
selection = [s for s in FreeCADGui.Selection.getSelection()
if s.Document == FreeCAD.ActiveDocument and
(a2plib.isA2pPart(s) or a2plib.isA2pSketch(s))
]
if selection and len(selection)>0:
if partial==True:
response = QtGui.QMessageBox.Yes
else:
flags = QtGui.QMessageBox.StandardButton.Yes | QtGui.QMessageBox.StandardButton.No
response = QtGui.QMessageBox.information(
QtGui.QApplication.activeWindow(),
translate("A2plus", "ASSEMBLY UPDATE"),
translate("A2plus", "Do you want to update only the selected parts?"),
flags
)
if response == QtGui.QMessageBox.Yes:
for s in selection:
selectedObjects.append(s)
if len(selectedObjects) >0:
workingSet = selectedObjects
else:
workingSet = doc.Objects
for obj in workingSet:
if hasattr(obj, 'sourceFile') and a2plib.to_str(obj.sourceFile) == a2plib.to_str('converted'):
if hasattr(obj,'localSourceObject') and obj.localSourceObject is not None and obj.localSourceObject != "":
a2p_convertPart.updateConvertedPart(doc, obj)
continue
if hasattr(obj, 'sourceFile') and a2plib.to_str(obj.sourceFile) != a2plib.to_str('converted'):
#repair data structures (perhaps an old Assembly2 import was found)
if hasattr(obj,"Content") and 'importPart' in obj.Content: # be sure to have an assembly object
if obj.Proxy is None:
#print (u"Repair Proxy of: {}, Proxy: {}".format(obj.Label, obj.Proxy))
Proxy_importPart(obj)
ImportedPartViewProviderProxy(obj.ViewObject)
assemblyPath = os.path.normpath(os.path.split(doc.FileName)[0])
absPath = a2plib.findSourceFileInProject(obj.sourceFile, assemblyPath)
if absPath is None:
QtGui.QMessageBox.critical( QtGui.QApplication.activeWindow(),
translate("A2plus", "Source file not found"),
translate("A2plus", "Unable to find '{}'").format(
obj.sourceFile
)
)
if absPath is not None and os.path.exists( absPath ):
newPartCreationTime = os.path.getmtime( absPath )
if (
newPartCreationTime > obj.timeLastImport or
obj.a2p_Version != a2plib.getA2pVersion() or
a2plib.getRecalculateImportedParts() # open always all parts as they could depend on spreadsheets
):
cacheKeyExtension = obj.sourcePart
if cacheKeyExtension is None:
cacheKeyExtension = "AllShapes"
elif cacheKeyExtension == "":
cacheKeyExtension = "AllShapes"
cacheKeyExtension = '-' + cacheKeyExtension
cacheKey = absPath+cacheKeyExtension
if not objectCache.isCached(cacheKey): # Load every changed object one time to cache
if obj.sourcePart is not None and obj.sourcePart != '':
importPartFromFile(
doc,
absPath,
importToCache=True,
cacheKey = cacheKey,
extractSingleShape = True,
desiredShapeLabel = obj.sourcePart
) # the version is now in the cache
else:
importPartFromFile(
doc,
absPath,
importToCache=True,
cacheKey = cacheKey
) # the version is now in the cache
newObject = objectCache.get(cacheKey)
obj.timeLastImport = newPartCreationTime
if hasattr(newObject, 'a2p_Version'):
obj.a2p_Version = a2plib.getA2pVersion()
importUpdateConstraintSubobjects( doc, obj, newObject ) # do this before changing shape and mux
if hasattr(newObject, 'muxInfo'):
obj.muxInfo = newObject.muxInfo
# save Placement because following newObject.Shape.copy() isn't resetting it to zeroes...
savedPlacement = obj.Placement
obj.Shape = newObject.Shape.copy()
if a2plib.isA2pSketch(obj):
pass
else:
obj.Placement = savedPlacement # restore the old placement
a2plib.copyObjectColors(obj,newObject)
#repair constraint directions if for e.g. face-normals flipped around during updating of parts.
a2p_constraintServices.reAdjustConstraintDirections(doc)
mw = FreeCADGui.getMainWindow()
mdi = mw.findChild(QtGui.QMdiArea)
sub = mdi.activeSubWindow()
if sub is not None:
sub.showMaximized()
objectCache.cleanUp(doc)
a2p_solversystem.autoSolveConstraints(
doc,
useTransaction = False,
callingFuncName = "updateImportedParts"
) #transaction is already open...
doc.recompute()
doc.commitTransaction()
toolTip = \
translate("A2plus",
'''
Update parts, which have been
imported to the assembly.
(If you modify a part in an
external file, the new shape
is taken to the assembly by
this function.)
'''
)
class a2p_UpdateImportedPartsCommand:
def Activated(self):
doc = FreeCAD.ActiveDocument
updateImportedParts(doc)
def GetResources(self):
return {
'Pixmap' : a2plib.path_a2p + '/icons/a2p_ImportPart_Update.svg',
'MenuText': translate("A2plus", "Update parts imported into the assembly"),
'ToolTip' : toolTip
}
def IsActive(self):
doc = FreeCAD.activeDocument()
if doc is None: return False
return True
FreeCADGui.addCommand('a2p_updateImportedParts', a2p_UpdateImportedPartsCommand())
def duplicateImportedPart( part ):
doc = FreeCAD.ActiveDocument
nameBase = part.Label
partName = a2plib.findUnusedObjectName(nameBase,document=doc)
partLabel = a2plib.findUnusedObjectLabel(nameBase,document=doc)
newObj = doc.addObject("Part::FeaturePython", str(partName.encode("utf-8")) )
newObj.Label = partLabel
Proxy_importPart(newObj)
ImportedPartViewProviderProxy(newObj.ViewObject)
newObj.a2p_Version = part.a2p_Version
newObj.sourceFile = part.sourceFile
newObj.sourcePart = part.sourcePart
newObj.localSourceObject = part.localSourceObject
newObj.timeLastImport = part.timeLastImport
newObj.setEditorMode("timeLastImport",1)
newObj.fixedPosition = False
newObj.updateColors = getattr(part,'updateColors',True)
newObj.muxInfo = part.muxInfo
newObj.subassemblyImport = part.subassemblyImport
newObj.Shape = part.Shape.copy()
for p in part.ViewObject.PropertiesList: #assuming that the user may change the appearance of parts differently depending on their role in the assembly.
if hasattr(part.ViewObject, p) and p not in ['DiffuseColor','Proxy','MappedColors']:
setattr(newObj.ViewObject, p, getattr( part.ViewObject, p))
newObj.ViewObject.DiffuseColor = copy.copy( part.ViewObject.DiffuseColor )
newObj.ViewObject.Transparency = part.ViewObject.Transparency
newObj.Placement.Base = part.Placement.Base
newObj.Placement.Rotation = part.Placement.Rotation
return newObj
toolTip = \
translate("A2plus",
'''
Make a duplicate of a
part, which is already
imported to the assembly.
Select a imported part and hit
this button. A duplicate
will be created and can be
placed somewhere by mouse.
Hold "Shift" for doing this
multiple times.
'''
)
class a2p_DuplicatePartCommand:
def __init__(self):
self.partMover = None
def Activated(self):
doc = FreeCAD.activeDocument()
selection = [s for s in FreeCADGui.Selection.getSelectionEx() if s.Document == doc ]
self.partMover = PartMover(
FreeCADGui.activeDocument().activeView(),
duplicateImportedPart(selection[0].Object),
deleteOnEscape = True
)
self.timer = QtCore.QTimer()
QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.onTimer)
self.timer.start( 100 )
def onTimer(self):
if self.partMover is not None:
if self.partMover.objectToDelete is not None:
FreeCAD.activeDocument().removeObject(self.partMover.objectToDelete.Name)
self.partMover.objectToDelete = None
self.timer.start(100)
def IsActive(self):
doc = FreeCAD.activeDocument()
if doc is None: return False
#
selection = [s for s in FreeCADGui.Selection.getSelectionEx() if s.Document == doc ]
if len(selection) != 1: return False