-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
BimLibrary.py
1091 lines (971 loc) · 40.7 KB
/
BimLibrary.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
# -*- coding: utf-8 -*-
# ***************************************************************************
# * *
# * Copyright (c) 2018 Yorik van Havre <yorik@uncreated.net> *
# * *
# * 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 *
# * *
# ***************************************************************************
from __future__ import print_function
"""The BIM library tool"""
import os
import FreeCAD
import urllib.request
import urllib.parse
import zipfile
import hashlib
import io
import datetime
import datetime
from BimTranslateUtils import *
FILTERS = [
"*.fcstd",
"*.FCStd",
"*.FCSTD",
"*.stp",
"*.STP",
"*.step",
"*.STEP",
"*.brp",
"*.BRP",
"*.brep",
"*.BREP",
"*.ifc",
"*.IFC",
"*.sat",
"*.SAT",
]
TEMPLIBPATH = os.path.join(FreeCAD.getUserAppDataDir(), "BIM", "OfflineLibrary")
THUMBNAILSPATH = os.path.join(TEMPLIBPATH, "__thumbcache__")
LIBRARYURL = "https://github.com/FreeCAD/FreeCAD-library/tree/master"
RAWURL = LIBRARYURL.replace("/tree", "/raw")
LIBINDEXFILE = "OfflineLibrary.py"
USE_API = True # True to use github API instead of web fetching... Way faster
REFRESH_INTERVAL = (
3600 # Min seconds between allowing a new API calls (3600 = one hour)
)
# TODO as https://github.com/yorikvanhavre/BIM_Workbench/pull/77
# All the print() statements in your code should be replaced by
# FreeCAD.Console.PrintMessage() or FreeCAD.Console.PrintWarning() or
# FreeCAD.Console.PrintError() and the text should be placed in a translate()
# function and "\n" should be added to it.
# Example FreeCAD.Console.PrintError(translate("BIM","Please save the document first")+"\n")
# It would be cool if the preview image would have a max width of the available
# column width, so if the task column is smaller than the image, it gets smaller
# to fit the space. I don't remember exactly how to do that, but it should be
# findable in QDesigner
class BIM_Library:
def GetResources(self):
return {
"Pixmap": os.path.join(
os.path.dirname(__file__), "icons", "BIM_Library.svg"
),
"MenuText": QT_TRANSLATE_NOOP("BIM_Library", "Objects library"),
"ToolTip": QT_TRANSLATE_NOOP("BIM_Library", "Opens the objects library"),
}
def Activated(self):
import FreeCADGui
# trying to locate the parts library
pr = FreeCAD.ParamGet("User parameter:Plugins/parts_library")
libok = False
self.librarypath = pr.GetString("destination", "")
if self.librarypath:
if os.path.exists(self.librarypath):
libok = True
else:
# check if the library is at the standard addon location
addondir = os.path.join(FreeCAD.getUserAppDataDir(), "Mod", "parts_library")
if os.path.exists(addondir):
# save file paths with forward slashes even on windows
pr.SetString("destination", addondir.replace("\\", "/"))
libok = True
FreeCADGui.Control.showDialog(BIM_Library_TaskPanel(offlinemode=libok))
class BIM_Library_TaskPanel:
def __init__(self, offlinemode=False):
from PySide import QtCore, QtGui
import FreeCADGui
self.mainDocName = FreeCAD.Gui.ActiveDocument.Document.Name
self.previewDocName = "Viewer"
self.linked = False
self.librarypath = FreeCAD.ParamGet(
"User parameter:Plugins/parts_library"
).GetString("destination", "")
self.form = FreeCADGui.PySideUic.loadUi(
os.path.join(os.path.dirname(__file__), "dialogLibrary.ui")
)
self.form.setWindowIcon(
QtGui.QIcon(
os.path.join(os.path.dirname(__file__), "icons", "BIM_Library.svg")
)
)
# setting up a flat (no directories) file model for search
self.filemodel = QtGui.QStandardItemModel()
self.filemodel.setColumnCount(1)
# setting up a directory model that shows only fcstd, step and brep
self.dirmodel = LibraryModel()
self.dirmodel.setRootPath(self.librarypath)
self.dirmodel.setNameFilters(self.getFilters())
self.dirmodel.setNameFilterDisables(False)
self.form.tree.setModel(self.dirmodel)
self.form.buttonInsert.clicked.connect(self.insert)
self.form.buttonLink.clicked.connect(self.link)
self.modelmode = 1 # 0 = File search, 1 = Dir mode
# Don't show columns for size, file type, and last modified
self.form.tree.setHeaderHidden(True)
self.form.tree.hideColumn(1)
self.form.tree.hideColumn(2)
self.form.tree.hideColumn(3)
self.form.tree.setRootIndex(self.dirmodel.index(self.librarypath))
self.form.searchBox.textChanged.connect(self.onSearch)
# external search
d = os.path.join(os.path.dirname(__file__), "icons")
sites = {
"BimObject": [
"bimobject.png",
"https://www.bimobject.com/en/product?filetype=8&freetext=",
],
"NBS Library": [
"nbslibrary.png",
"https://www.nationalbimlibrary.com/en/search/?facet=Xo-P0w&searchTerm=",
],
"BIMTool": [
"bimtool.png",
"https://www.bimtool.com/Catalog.aspx?criterio=",
],
"3DFindIt": ["3dfindit.svg", "https://www.3dfindit.com/textsearch?q="],
"GrabCAD": [
"grabcad.svg",
"https://grabcad.com/library?softwares=step-slash-iges&query=",
],
}
for k, v in sites.items():
self.form.comboSearch.addItem(QtGui.QIcon(os.path.join(d, v[0])), k, v[1])
self.form.comboSearch.currentIndexChanged.connect(self.onExternalSearch)
# retrieve preferences
self.p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/BIM")
self.form.checkOnline.toggled.connect(self.onCheckOnline)
self.form.checkOnline.setChecked(
self.p.GetBool("LibraryOnline", not offlinemode)
)
self.form.checkFCStdOnly.toggled.connect(self.onCheckFCStdOnly)
self.form.checkFCStdOnly.setChecked(self.p.GetBool("LibraryFCStdOnly", False))
self.form.checkWebSearch.toggled.connect(self.onCheckWebSearch)
self.form.checkWebSearch.setChecked(self.p.GetBool("LibraryWebSearch", False))
self.form.check3DPreview.toggled.connect(self.onCheck3DPreview)
self.form.check3DPreview.setChecked(self.p.GetBool("3DPreview", False))
# collapsables
if self.p.GetBool("LibraryPreview", False):
self.form.framePreview.show()
self.form.buttonPreview.setText(translate("BIM", "Preview") + " ▼")
else:
self.form.framePreview.hide()
self.form.buttonPreview.setText(translate("BIM", "Preview") + " ▸")
self.form.buttonPreview.clicked.connect(self.onButtonPreview)
self.form.frameOptions.hide()
self.form.buttonOptions.setText(translate("BIM", "Options") + " ▸")
self.form.buttonOptions.clicked.connect(self.onButtonOptions)
# saving functionality, is disabled for now
self.form.buttonSave.hide()
self.form.checkThumbnail.hide()
# self.form.buttonSave.clicked.connect(self.addtolibrary)
# self.form.checkThumbnail.toggled.connect(self.onCheckThumbnail)
# self.form.checkThumbnail.setChecked(self.p.GetBool("SaveThumbnails",False))
# self.fcstdCB = QtGui.QCheckBox('FCStd')
# self.fcstdCB.setCheckState(QtCore.Qt.Checked)
# self.fcstdCB.setEnabled(False)
# self.fcstdCB.hide()
# self.stepCB = QtGui.QCheckBox('STEP')
# self.stepCB.setCheckState(QtCore.Qt.Checked)
# self.stepCB.hide()
# self.stlCB = QtGui.QCheckBox('STL')
# self.stlCB.setCheckState(QtCore.Qt.Checked)
# self.stlCB.hide()
# update the tree
self.onCheckOnline()
def onItemSelected(self, selected, deselected):
"""Generates and displays needed previews"""
from PySide import QtGui
if not selected:
return
index = selected[0].indexes()[0]
if self.modelmode == 1:
path = self.dirmodel.filePath(index)
else:
path = self.filemodel.itemFromIndex(index).toolTip()
if path.startswith(":github"):
path = RAWURL + "/" + path[7:]
thumb = self.getThumbnail(path)
if thumb:
px = QtGui.QPixmap(thumb)
else:
px = QtGui.QPixmap()
self.form.framePreview.setPixmap(px)
if False:
# TO BE REFACTORED
import Part, FreeCADGui
self.previewOn = self.p.GetBool("3DPreview", False)
try:
self.path = self.dirmodel.filePath(index)
except:
self.path = self.previousIndex
print(self.path)
self.isFile = os.path.isfile(self.path)
# if the 3D preview checkbox is on ticked, show the preview
if self.previewOn == True or self.linked == True:
if self.isFile == True:
# close a non linked preview document
if self.linked == False:
try:
FreeCAD.closeDocument(self.previewDocName)
except:
pass
# create different kinds of previews based on file type
if (
self.path.lower().endswith(".stp")
or self.path.lower().endswith(".step")
or self.path.lower().endswith(".brp")
or self.path.lower().endswith(".brep")
):
self.previewDocName = "Viewer"
FreeCAD.newDocument(self.previewDocName)
FreeCAD.setActiveDocument(self.previewDocName)
Part.show(Part.read(self.path))
FreeCADGui.SendMsgToActiveView("ViewFit")
elif self.path.lower().endswith(".fcstd"):
openedDoc = FreeCAD.openDocument(self.path)
FreeCADGui.SendMsgToActiveView("ViewFit")
self.previewDocName = FreeCAD.ActiveDocument.Name
thumbnailSave = self.p.GetBool("SaveThumbnails", False)
if thumbnailSave == True:
FreeCAD.ActiveDocument.save()
if self.linked == False:
self.previousIndex = self.path
# create a 2D image preview
if self.path.lower().endswith(".fcstd"):
zfile = zipfile.ZipFile(self.path)
files = zfile.namelist()
# check for meta-file if it's really a FreeCAD document
if files[0] == "Document.xml":
image = "thumbnails/Thumbnail.png"
if image in files:
image = zfile.read(image)
thumbfile = tempfile.mkstemp(suffix=".png")[1]
thumb = open(thumbfile, "wb")
thumb.write(image)
thumb.close()
im = QtGui.QPixmap(thumbfile)
self.form.framePreview.setPixmap(im)
return self.previewDocName, self.previousIndex, self.linked
self.form.framePreview.clear()
return self.previewDocName, self.previousIndex, self.linked
def link(self, index):
import FreeCADGui
# check if the main document is open
try:
# check if the working document is saved
if FreeCAD.getDocument(self.mainDocName).FileName == "":
print("Please save the working file before linking.")
else:
self.previewOn = self.p.GetBool("3DPreview", False)
self.linked = True
if self.previewOn != True:
BIM_Library_TaskPanel.clicked(self, index, previewDocName="Viewer")
self.librarypath = ""
# save the file prior to linking
BIM_Library_TaskPanel.addtolibrary(self)
# link a document if it has been previously saved
if self.fileDialog[0] != "":
FreeCADGui.Selection.clearSelection()
# link only root objects
for obj in FreeCAD.ActiveDocument.RootObjects:
FreeCADGui.Selection.addSelection(obj)
objects = FreeCADGui.Selection.getSelection()
# tries to create a link for each object in the selection
for obj in objects:
try:
link = (
FreeCAD.getDocument(self.mainDocName)
.addObject("App::Link", "Link")
.setLink(obj)
)
# FreeCAD.getDocument(self.mainDocName).getObject('Link').Label=FreeCAD.ActiveDocument.ActiveObject.Label
FreeCAD.getDocument(self.mainDocName).getObject(
link
).Label = FreeCAD.ActiveDocument.ActiveObject.Label
except:
pass
FreeCAD.setActiveDocument(self.mainDocName)
self.librarypath = FreeCAD.ParamGet(
"User parameter:Plugins/parts_library"
).GetString("destination", "")
self.linked = False
return self.linked
except:
print("It is not possible to link because the main document is closed.")
def addtolibrary(self):
# DISABLED
import Part, Mesh, os
self.fileDialog = QtGui.QFileDialog.getSaveFileName(
None, "Save As", self.librarypath
)
print(self.fileDialog[0])
# check if file saving has been canceled and save .fcstd, .step and .stl copies
if self.fileDialog[0] != "":
# remove the file extension from the file path
fileName = os.path.splitext(self.fileDialog[0])[0]
FCfilename = fileName + ".fcstd"
FreeCAD.ActiveDocument.saveAs(FCfilename)
if self.stepCB.isChecked() or self.stlCB.isChecked():
toexport = []
objs = FreeCAD.ActiveDocument.Objects
for obj in objs:
if obj.ViewObject.Visibility == True:
toexport.append(obj)
if self.stepCB.isChecked() and self.linked == False:
STEPfilename = fileName + ".step"
Part.export(toexport, STEPfilename)
if self.stlCB.isChecked() and self.linked == False:
STLfilename = fileName + ".stl"
Mesh.export(toexport, STLfilename)
return self.fileDialog[0]
def onSearch(self, text):
if text:
self.setSearchModel(text)
else:
self.setFileModel()
def setSearchModel(self, text):
import PartGui
from PySide import QtGui
self.form.tree.setModel(self.filemodel)
self.filemodel.clear()
if self.form.checkOnline.isChecked():
res = self.getOfflineLib(structured=True)
else:
res = os.walk(self.librarypath)
for dp, dn, fn in res:
for f in fn:
if self.isAllowed(f) and (text.lower() in f.lower()):
if not os.path.isdir(os.path.join(dp, f)):
it = QtGui.QStandardItem(f)
it.setToolTip(os.path.join(dp, f))
self.filemodel.appendRow(it)
if f.endswith(".fcstd"):
it.setIcon(QtGui.QIcon(":icons/freecad-doc.png"))
elif f.endswith(".ifc"):
it.setIcon(
QtGui.QIcon(
os.path.join(
os.path.dirname(__file__), "icons", "IFC.svg"
)
)
)
else:
it.setIcon(
QtGui.QIcon(
os.path.join(
os.path.dirname(__file__),
"icons",
"Part_document.svg",
)
)
)
self.modelmode = 0
def getFilters(self):
if self.form.checkFCStdOnly.isChecked():
return FILTERS
else:
return FILTERS[:3]
def isAllowed(self, filename):
e = os.path.splitext(filename)[1]
if e in [f[1:] for f in FILTERS]:
if e in [f[1:] for f in self.getFilters()]:
return True
else:
return False
else:
return True
def setFileModel(self):
# self.form.tree.clear()
self.form.tree.setModel(self.dirmodel)
self.dirmodel.setRootPath(self.librarypath)
self.dirmodel.setNameFilters(self.getFilters())
self.dirmodel.setNameFilterDisables(False)
self.form.tree.setRootIndex(self.dirmodel.index(self.librarypath))
self.modelmode = 1
self.form.tree.setHeaderHidden(True)
self.form.tree.hideColumn(1)
self.form.tree.hideColumn(2)
self.form.tree.hideColumn(3)
self.form.tree.selectionModel().selectionChanged.connect(self.onItemSelected)
def setOnlineModel(self):
from PySide import QtGui
import PartGui
def addItems(root, d, path):
for k, v in d.items():
if self.isAllowed(k):
it = QtGui.QStandardItem(k)
root.appendRow(it)
it.setToolTip(path + "/" + k)
if isinstance(v, dict):
it.setIcon(
QtGui.QIcon.fromTheme(
"folder", QtGui.QIcon(":/icons/Group.svg")
)
)
addItems(it, v, path + "/" + k)
it.setToolTip("")
elif k.lower().endswith(".fcstd"):
it.setIcon(QtGui.QIcon(":icons/freecad-doc.png"))
elif k.lower().endswith(".ifc"):
it.setIcon(
QtGui.QIcon(
os.path.join(
os.path.dirname(__file__), "icons", "IFC.svg"
)
)
)
else:
it.setIcon(
QtGui.QIcon(
os.path.join(
os.path.dirname(__file__),
"icons",
"Part_document.svg",
)
)
)
self.form.tree.setModel(self.filemodel)
self.filemodel.clear()
d = self.getOfflineLib()
addItems(self.filemodel, d, ":github")
self.modelmode = 0
self.form.tree.selectionModel().selectionChanged.connect(self.onItemSelected)
def getOfflineLib(self, structured=False):
def addDir(d, root):
fn = []
dn = []
dp = []
for k, v in d.items():
if isinstance(v, dict):
fn2, dn2, dp2 = addDir(v, root + "/" + k)
fn.extend(fn2)
dn.extend(dn2)
dp.extend(dp2)
else:
fn += k
dn += root
dp += root + "/" + k
return dp, dn, fn
templibfile = os.path.join(TEMPLIBPATH, LIBINDEXFILE)
if not os.path.exists(templibfile):
FreeCAD.Console.PrintError(
translate("BIM", "No structure in cache. Please refresh.") + "\n"
)
return {}
import sys
sys.path.append(TEMPLIBPATH)
import OfflineLibrary
d = OfflineLibrary.library
if structured:
return addDir(d, ":github")
else:
return d
def urlencode(self, text):
import sys
print(text, type(text))
if sys.version_info.major < 3:
import urllib
return urllib.quote_plus(text)
else:
import urllib.parse
return urllib.parse.quote_plus(text)
def openUrl(self, url):
from PySide import QtGui
s = self.p.GetBool("LibraryWebSearch", False)
if s:
import WebGui
WebGui.openBrowser(url)
else:
QtGui.QDesktopServices.openUrl(url)
def needsFullSpace(self):
return True
def getStandardButtons(self):
from PySide import QtGui
return int(QtGui.QDialogButtonBox.Close)
def reject(self):
import FreeCADGui
if hasattr(self, "box") and self.box:
self.box.off()
FreeCADGui.Control.closeDialog()
FreeCAD.ActiveDocument.recompute()
def insert(self, index=None):
import FreeCADGui
# check if the main document is open
try:
FreeCAD.setActiveDocument(self.mainDocName)
except:
FreeCAD.Console.PrintError(
translate(
"BIM",
"It is not possible to insert this object because the document has been closed.",
)
+ "\n"
)
return
if self.previewDocName in FreeCAD.listDocuments().keys():
FreeCAD.closeDocument(self.previewDocName)
if not index:
index = self.form.tree.selectedIndexes()
if not index:
return
index = index[0]
if self.modelmode == 1:
path = self.dirmodel.filePath(index)
else:
path = self.filemodel.itemFromIndex(index).toolTip()
if path.startswith(":github"):
path = self.download(RAWURL + "/" + path[7:])
before = FreeCAD.ActiveDocument.Objects
self.name = os.path.splitext(os.path.basename(path))[0]
ext = os.path.splitext(path.lower())[1]
if ext in [".stp", ".step", ".brp", ".brep"]:
self.place(path)
elif ext == ".fcstd":
FreeCADGui.ActiveDocument.mergeProject(path)
from DraftGui import todo
todo.delay(self.reject, None)
elif ext == ".ifc":
import importIFC
importIFC.ZOOMOUT = False
importIFC.insert(path, FreeCAD.ActiveDocument.Name)
from DraftGui import todo
todo.delay(self.reject, None)
elif ext in [".sat", ".sab"]:
try:
# InventorLoader addon
import importerIL
except ImportError:
try:
# CADExchanger addon
import CadExchangerIO
except ImportError:
FreeCAD.Console.PrintError(
translate(
"BIM",
"Error: Unable to import SAT files - InventorLoader or CadExchanger addon must be installed",
)
+ "\n"
)
else:
path = CadExchangerIO.insert(
path, FreeCAD.ActiveDocument.Name, returnpath=True
)
self.place(path)
else:
path = importerIL.insert(path, FreeCAD.ActiveDocument.Name)
FreeCADGui.Selection.clearSelection()
for o in FreeCAD.ActiveDocument.Objects:
if not o in before:
FreeCADGui.Selection.addSelection(o)
FreeCADGui.SendMsgToActiveView("ViewSelection")
def download(self, url):
filepath = os.path.join(TEMPLIBPATH, url.split("/")[-1])
url = url.replace(" ", "%20")
if not os.path.exists(filepath):
from PySide import QtCore, QtGui
QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
u = urllib.request.urlopen(url)
if not u:
FreeCAD.Console.PrintError(
translate("BIM", "Error: Unable to download") + " " + url + "\n"
)
b = u.read()
f = open(filepath, "wb")
f.write(b)
f.close()
QtGui.QApplication.restoreOverrideCursor()
return filepath
def place(self, path):
import FreeCADGui
import Part
self.shape = Part.read(path)
if hasattr(FreeCADGui, "Snapper"):
try:
import DraftTrackers
except Exception:
import draftguitools.gui_trackers as DraftTrackers
self.box = DraftTrackers.ghostTracker(
self.shape, dotted=True, scolor=(0.0, 0.0, 1.0), swidth=1.0
)
self.delta = self.shape.BoundBox.Center
self.box.move(self.delta)
self.box.on()
if hasattr(FreeCAD, "DraftWorkingPlane"):
FreeCAD.DraftWorkingPlane.setup()
self.origin = self.makeOriginWidget()
FreeCADGui.Snapper.getPoint(
movecallback=self.mouseMove,
callback=self.mouseClick,
extradlg=self.origin,
)
else:
Part.show(self.shape)
def makeOriginWidget(self):
from PySide import QtGui
w = QtGui.QWidget()
w.setWindowTitle(translate("BIM", "Insertion point"))
w.setWindowIcon(
QtGui.QIcon(
os.path.join(os.path.dirname(__file__), "icons", "BIM_Library.svg")
)
)
l = QtGui.QVBoxLayout()
w.setLayout(l)
c = QtGui.QComboBox()
c.ObjectName = "comboOrigin"
w.comboOrigin = c
c.addItems(
[
translate("BIM", "Origin"),
translate("BIM", "Top left"),
translate("BIM", "Top center"),
translate("BIM", "Top right"),
translate("BIM", "Middle left"),
translate("BIM", "Middle center"),
translate("BIM", "Middle right"),
translate("BIM", "Bottom left"),
translate("BIM", "Bottom center"),
translate("BIM", "Bottom right"),
]
)
c.setCurrentIndex(self.p.GetInt("LibraryDefaultInsert", 0))
c.currentIndexChanged.connect(self.storeInsert)
l.addWidget(c)
return w
def storeInsert(self, index):
self.p.SetInt("LibraryDefaultInsert", index)
def mouseMove(self, point, info):
self.box.move(point.add(self.getDelta()))
def mouseClick(self, point, info):
if point:
import Arch
self.box.off()
self.shape.translate(point.add(self.getDelta()))
obj = Arch.makeEquipment()
obj.Shape = self.shape
obj.Label = self.name
self.reject()
def getDelta(self):
d = FreeCAD.Vector(
-self.shape.BoundBox.Center.x, -self.shape.BoundBox.Center.y, 0
)
idx = self.origin.comboOrigin.currentIndex()
if idx <= 0:
return FreeCAD.Vector()
elif idx == 1:
return d.add(
FreeCAD.Vector(
self.shape.BoundBox.XLength / 2, -self.shape.BoundBox.YLength / 2, 0
)
)
elif idx == 2:
return d.add(FreeCAD.Vector(0, -self.shape.BoundBox.YLength / 2, 0))
elif idx == 3:
return d.add(
FreeCAD.Vector(
-self.shape.BoundBox.XLength / 2,
-self.shape.BoundBox.YLength / 2,
0,
)
)
elif idx == 4:
return d.add(FreeCAD.Vector(self.shape.BoundBox.XLength / 2, 0, 0))
elif idx == 5:
return d
elif idx == 6:
return d.add(FreeCAD.Vector(-self.shape.BoundBox.XLength / 2, 0, 0))
elif idx == 7:
return d.add(
FreeCAD.Vector(
self.shape.BoundBox.XLength / 2, self.shape.BoundBox.YLength / 2, 0
)
)
elif idx == 8:
return d.add(FreeCAD.Vector(0, self.shape.BoundBox.YLength / 2, 0))
elif idx == 9:
return d.add(
FreeCAD.Vector(
-self.shape.BoundBox.XLength / 2, self.shape.BoundBox.YLength / 2, 0
)
)
def getOnlineContentsWEB(self, url):
"""Returns a dirs,files pair representing files found from a github url. OBSOLETE"""
# obsolete code - now using getOnlineContentsAPI
result = {}
u = urllib.request.urlopen(url)
if u:
p = u.read()
if sys.version_info.major >= 3:
p = str(p)
dirs = re.findall("<.*?octicon-file-directory.*?href.*?>(.*?)</a>", p)
files = re.findall('<.*?octicon-file".*?href.*?>(.*?)</a>', p)
nfiles = []
for f in files:
for ft in self.getFilters():
if f.endswith(ft[1:]):
nfiles.append(f)
break
files = nfiles
for d in dirs:
# <spans>
if "</span" in d:
d1 = re.findall("<span.*?>(.*?)<", d)
d2 = re.findall("</span>(.*?)$", d)
if d1 and d2:
d = d1[0] + "/" + d2[0]
r = self.getOnlineContentsWEB(url + "/" + d.replace(" ", "%20"))
result[d] = r
for f in files:
result[f] = f
else:
FreeCAD.Console.PrintError(
translate("BIM", "Cannot open URL") + ":" + url + "\n"
)
return result
def getOnlineContentsAPI(self, url):
"""same as getOnlineContents but uses github API (faster)"""
result = {}
import requests
import json
count = 0
r = requests.get(
"https://api.github.com/repos/FreeCAD/FreeCAD-library/git/trees/master?recursive=1"
)
if r.ok:
j = json.loads(r.content)
if j["truncated"]:
print(
"WARNING: The fetched content exceeds maximum Github allowance and is truncated"
)
t = j["tree"]
for f in t:
path = f["path"].split("/")
if f["type"] == "tree":
name = None
else:
name = path[-1]
path = path[:-1]
host = result
for fp in path:
if fp in host:
host = host[fp]
else:
host[fp] = {}
host = host[fp]
if name:
for ft in self.getFilters():
if name.endswith(ft[1:]):
break
else:
continue
host[name] = name
count += 1
else:
FreeCAD.Console.PrintError(
translate("BIM", "Could not fetch library contents") + "\n"
)
# print("result:",result)
if not result:
FreeCAD.Console.PrintError(
translate("BIM", "No results fetched from online library") + "\n"
)
else:
FreeCAD.Console.PrintLog("BIM Library: Reloaded " + str(count) + " files\n")
return result
def onCheckOnline(self, state=None):
"""if the Online checkbox is clicked"""
if state == None:
state = self.form.checkOnline.isChecked()
# save state
self.p.SetBool("LibraryOnline", state)
if state:
# online
if USE_API:
needrefresh = True
timestamp = datetime.datetime.now()
if os.path.exists(os.path.join(TEMPLIBPATH, LIBINDEXFILE)):
stored = self.p.GetUnsigned("LibraryTimeStamp", 0)
if stored:
stored = datetime.datetime.fromtimestamp(stored)
if (timestamp - stored).total_seconds() < REFRESH_INTERVAL:
needrefresh = False
if needrefresh:
self.p.SetUnsigned("LibraryTimeStamp", int(timestamp.timestamp()))
self.onRefresh()
else:
FreeCAD.Console.PrintLog("BIM Library: Using cached library\n")
self.setOnlineModel()
self.form.buttonLink.setEnabled(False)
else:
# offline
self.setFileModel()
self.form.buttonLink.setEnabled(True)
def onRefresh(self):
"""refreshes the tree"""
def writeOfflineLib():
if USE_API:
rootfiles = self.getOnlineContentsAPI(LIBRARYURL)
else:
rootfiles = self.getOnlineContentsWEB(LIBRARYURL)
if rootfiles:
templibfile = os.path.join(TEMPLIBPATH, LIBINDEXFILE)
os.makedirs(TEMPLIBPATH, exist_ok=True)
tf = open(templibfile, "w", encoding="utf8")
tf.write("library=" + str(rootfiles) + "\n")
tf.close()
self.setOnlineModel()
from PySide import QtCore, QtGui
reply = self.p.GetBool("LibraryWarning", False)
if not reply:
reply = QtGui.QMessageBox.information(
None, "", translate("BIM", "Warning, this can take several minutes!")
)
if reply:
self.p.SetBool("LibraryWarning", True)
self.form.setEnabled(False)
QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
self.form.repaint()
QtGui.QApplication.processEvents()
QtCore.QTimer.singleShot(1, writeOfflineLib)
self.form.setEnabled(True)
QtGui.QApplication.restoreOverrideCursor()
else:
self.setOnlineModel()
def onCheckFCStdOnly(self, state):
"""if the FCStd only checkbox is clicked"""
# save state
self.p.SetBool("LibraryFCStdOnly", state)
self.dirmodel.setNameFilters(self.getFilters())
self.onCheckOnline(self.form.checkOnline.isChecked())
def onCheckWebSearch(self, state):
"""if the web search checkbox is clicked"""
# save state
self.p.SetBool("LibraryWebSearch", state)
def onCheck3DPreview(self, state):
"""if the 3D preview checkbox is clicked"""
import FreeCADGui
# save state
self.p.SetBool("3DPreview", state)
self.previewOn = self.p.GetBool("3DPreview", False)
try:
FreeCAD.closeDocument(self.previewDocName)
except:
pass
if self.previewOn == True:
self.previewDocName = "Viewer"
self.doc = FreeCAD.newDocument(self.previewDocName)
FreeCADGui.ActiveDocument.ActiveView.viewIsometric()
return self.previewDocName
def onCheckThumbnail(self, state):
"""if the thumbnail checkbox is clicked"""
# save state
self.p.SetBool("SaveThumbnails", state)
def onButtonOptions(self):
"""hides/shows the options"""
if self.form.frameOptions.isVisible():
self.form.frameOptions.hide()
self.form.buttonOptions.setText(translate("BIM", "Options") + " ▸")
else:
self.form.frameOptions.show()
self.form.buttonOptions.setText(translate("BIM", "Options") + " ▼")