-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathCacheFunctions.py
More file actions
900 lines (809 loc) · 33.6 KB
/
Copy pathCacheFunctions.py
File metadata and controls
900 lines (809 loc) · 33.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
# *************************************************************************
# * *
# * Copyright (c) 2019-2024 Paul Ebbers *
# * *
# * 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 3 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 FreeCAD as App
import FreeCADGui as Gui
import os
from PySide.QtGui import QIcon, QPixmap, QAction, QGuiApplication
from PySide.QtWidgets import (
QListWidgetItem,
QTableWidgetItem,
QListWidget,
QTableWidget,
QToolBar,
QToolButton,
QComboBox,
QPushButton,
QMenu,
QWidget,
QLineEdit,
QSizePolicy,
QRadioButton,
QLabel,
QProgressBar,
)
from PySide.QtCore import Qt, SIGNAL, Signal, QObject, QThread, QSize, QEvent
import sys
import json
from datetime import datetime
import shutil
import Standard_Functions_Ribbon as StandardFunctions
from Standard_Functions_Ribbon import CommandInfoCorrections
import Standard_Functions_Ribbon as StandardFunctions
from Standard_Functions_Ribbon import CommandInfoCorrections
import Parameters_Ribbon
from Parameters_Ribbon import Parameters
import Serialize_Ribbon
import webbrowser
import StyleMapping_Ribbon
import requests
# Get the resources
ConfigDirectory = Parameters.CONFIG_DIR
pathIcons = Parameters.ICON_LOCATION
pathStylSheets = Parameters.STYLESHEET_LOCATION
pathUI = Parameters.UI_LOCATION
pathScripts = os.path.join(ConfigDirectory, "Scripts")
pathPackages = os.path.join(os.path.dirname(__file__), "Resources", "packages")
pathBackup = Parameters.BACKUP_LOCATION
sys.path.append(ConfigDirectory)
sys.path.append(pathIcons)
sys.path.append(pathStylSheets)
sys.path.append(pathUI)
sys.path.append(pathPackages)
sys.path.append(pathBackup)
# Define the translation
translate = App.Qt.translate
ReproAdress: str = ""
IsChanged = False
# Set the data file version. Triggeres an question if an update is needed
DataFileVersion = "1.5"
# Define list of the workbenches, toolbars and commands on class level
List_Workbenches = []
StringList_Toolbars = []
List_WorkBenchToolBarItems = []
List_Commands = []
# Create lists for the several list in the json file.
List_IgnoredToolbars = []
List_IconOnly_Toolbars = []
List_QuickAccessCommands = []
List_IgnoredWorkbenches = []
Dict_RibbonCommandPanel = {}
Dict_CustomToolbars = {}
Dict_DropDownButtons = {}
Dict_NewPanels = {}
List_IgnoredToolbars_internal = []
# Create the lists for the deserialized icons
List_CommandIcons = []
List_WorkBenchIcons = []
# Create a tomporary list for newly added dropdown buttons
newDDBList = []
def CreateCache(RestartFreeCAD=False):
# Create a progressbar
progressBar = QProgressBar(minimum=0, value=0)
progressBar.setWindowFlags(
Qt.WindowType.Dialog | Qt.WindowType.WindowStaysOnTopHint
)
progressBar.setWindowFlag(Qt.WindowType.CustomizeWindowHint, True)
progressBar.setWindowFlag(Qt.WindowType.WindowMinMaxButtonsHint, False)
progressBar.setWindowFlag(Qt.WindowType.WindowMinimizeButtonHint, True)
progressBar.setWindowFlag(Qt.WindowType.WindowCloseButtonHint, False)
progressBar.setMinimumSize(400, 20)
# Get the stylesheet from the main window and use it for this form
(
progressBar.setStyleSheet(
"background-color: "
+ "none"
+ ";color: "
+ "none"
+ ";"
)
)
progressBar.setMaximum(5)
progressBar.setValue(0)
# Load the workbenches
loadAllWorkbenches(
AutoHide=False,
FinishMessage=translate(
"FreeCAD Ribbon", "Ribbon UI: Data file is created."
),
progressBar=progressBar,
maximum=progressBar.maximum(),
)
# clear the lists first
StringList_Toolbars.clear()
List_Commands.clear()
# get the system language
FreeCAD_preferences = App.ParamGet("User parameter:BaseApp/Preferences/General")
FCLanguage = FreeCAD_preferences.GetString("Language")
# --- Workbenches ----------------------------------------------------------------------------------------------
#
# Create a list of all workbenches with their icon
progressBar.setFormat(translate("FreeCAD Ribbon", "Create workbench list"))
progressBar.setValue(progressBar.value() + 1)
#
List_Workbenches.clear()
for WorkBenchName in Gui.listWorkbenches().keys():
try:
if str(WorkBenchName) != "" or WorkBenchName is not None:
if str(WorkBenchName) != "NoneWorkbench":
# Gui.activateWorkbench(WorkBenchName)
WorkBench = Gui.getWorkbench(WorkBenchName)
# Get the toolbar items
ToolbarItems: dict = WorkBench.getToolbarItems()
# Update the toolbar items with corrections
ToolbarItems: dict = StandardFunctions.CorrectGetToolbarItems(
ToolbarItems
)
IconName = ""
IconName = str(Gui.getWorkbench(WorkBenchName).Icon)
WorkbenchTitle = Gui.getWorkbench(WorkBenchName).MenuText
WorkbenchTitleTranslated = StandardFunctions.TranslationsMapping(
WorkBenchName, WorkbenchTitle
)
List_Workbenches.append(
[
str(WorkBenchName),
IconName,
WorkbenchTitle,
ToolbarItems,
WorkbenchTitleTranslated,
]
)
except Exception:
pass
# --- Toolbars ----------------------------------------------------------------------------------------------
#
# Go through the list of workbenches
progressBar.setFormat(translate("FreeCAD Ribbon", "Create toolbar list"))
progressBar.setValue(progressBar.value() + 1)
#
i = 0
for WorkBench in List_Workbenches:
wbToolbars = []
if (
WorkBench[0] != "General"
and WorkBench[0] != ""
and WorkBench[0] is not None
):
# Gui.activateWorkbench(WorkBench[0])
wbToolbars = Gui.getWorkbench(WorkBench[0]).listToolbars()
# Go through the toolbars
for Toolbar in wbToolbars:
ToolBarTtranslated = StandardFunctions.TranslationsMapping(
WorkBench[0], Toolbar
)
StringList_Toolbars.append(
[Toolbar, WorkBench[2], WorkBench[0], ToolBarTtranslated]
)
# Add the custom toolbars
CustomToolbars = List_ReturnCustomToolbars()
for Customtoolbar in CustomToolbars:
StringList_Toolbars.append(Customtoolbar)
CustomToolbars = List_ReturnCustomToolbars_Global()
for Customtoolbar in CustomToolbars:
StringList_Toolbars.append(Customtoolbar)
# --- Commands ----------------------------------------------------------------------------------------------
#
# Create a list of all commands with their icon
progressBar.setFormat(translate("FreeCAD Ribbon", "Create command list"))
progressBar.setValue(progressBar.value() + 1)
#
List_Commands.clear()
# Create a list of command names
CommandNames = []
for i in range(len(List_Workbenches)):
# Gui.activateWorkbench(List_Workbenches[i][0])
WorkBench = Gui.getWorkbench(List_Workbenches[i][0])
WorkBenchName = List_Workbenches[i][0]
# Get the toolbar items
ToolbarItems: dict = WorkBench.getToolbarItems()
# Update the toolbar items with corrections
ToolbarItems: dict = StandardFunctions.CorrectGetToolbarItems(ToolbarItems)
for key, value in list(ToolbarItems.items()):
for j in range(len(value)):
if value[j] != "Std_Workbench":
CommandName = GetCommand(value[j])
if CommandName.startswith("Std_"):
Item = [CommandName, "Standard"]
else:
Item = [CommandName, WorkBenchName]
IsInList = False
for CommandNamesItem in CommandNames:
if CommandNamesItem == Item:
IsInList = True
break
if IsInList is False:
CommandNames.append(Item)
# Add commands that are not in any toolbars
for commandNamesItem in Gui.listCommands():
CommandName_2 = GetCommand(commandNamesItem)
if CommandName_2.lower().startswith("std_"):
inList = False
for CommandName in CommandNames:
if CommandName[0] == CommandName_2:
inList = True
# Skip "Std_Workbench".
if commandNamesItem == "Std_Workbench":
continue
if inList is False:
CommandNames.append([CommandName_2, "Standard"])
else:
inList = False
for CommandName in CommandNames:
if CommandName[0] == commandNamesItem:
inList = True
if inList is False:
WorkBench = ""
for WorkBenchName in List_Workbenches:
if CommandName_2.startswith(WorkBenchName[0]) or WorkBenchName[0].startswith(CommandName_2.split("_")[0]):
WorkBench = WorkBenchName[0]
break
Icon = StandardFunctions.returnQiCons_Commands(CommandName_2)
if Icon is not None or Icon.isNull() is False:
CommandNames.append([CommandName_2, WorkBench])
# Go through the list
shadowList = []
for CommandName in CommandNames:
# get the command with this name
command = Gui.Command.get(CommandName[0])
ChildCommands = returnDropDownCommands(CommandName[0])
WorkBenchName = CommandName[1]
if command is not None and WorkBenchName != "":
# get the icon for this command
if CommandInfoCorrections(CommandName[0])["pixmap"] != "":
IconName = CommandInfoCorrections(CommandName[0])["pixmap"]
else:
IconName = ""
MenuName = CommandInfoCorrections(CommandName[0])["menuText"].replace(
"&", ""
)
MenuNameTranslated = CommandInfoCorrections(CommandName[0])[
"ActionText"
].replace("&", "")
# Remove numbers from dropdown child commands
if MenuName.split(" ")[0].isdigit() is True:
MenuName = MenuName.split(" ")[1]
if MenuNameTranslated.split(" ")[0].isdigit() is True:
MenuNameTranslated = MenuNameTranslated.split(" ")[1]
if len(ChildCommands) > 0:
if not MenuName.endswith("..."):
MenuName = MenuName + "..."
if not MenuNameTranslated.endswith("..."):
MenuNameTranslated = MenuNameTranslated + "..."
if CommandName[0] not in shadowList:
List_Commands.append(
[
CommandName[0],
IconName,
MenuName,
WorkBenchName,
MenuNameTranslated,
]
)
shadowList.append(CommandName[0])
# Add children of the commands if there are any
if len(ChildCommands) > 0:
for childCommand in ChildCommands:
if childCommand[0] not in shadowList:
List_Commands.append(
[
childCommand[0],
childCommand[1],
childCommand[2],
WorkBenchName,
childCommand[3],
]
)
shadowList.append(childCommand[0])
# add also custom commands
Toolbars = List_ReturnCustomToolbars()
for Toolbar in Toolbars:
WorkbenchTitle = Toolbar[1]
for WorkBench in List_Workbenches:
if WorkbenchTitle == WorkBench[2]:
WorkBenchName = WorkBench[0]
for CustomCommand in Toolbar[2]:
if CustomCommand not in shadowList:
command = Gui.Command.get(CustomCommand)
if CommandInfoCorrections(CustomCommand)["pixmap"] != "":
IconName = CommandInfoCorrections(CustomCommand)["pixmap"]
else:
IconName = ""
MenuName = CommandInfoCorrections(CustomCommand)[
"menuText"
].replace("&", "")
MenuNameTranslated = CommandInfoCorrections(CustomCommand)[
"ActionText"
].replace("&", "")
List_Commands.append(
[
CustomCommand,
IconName,
MenuName,
WorkBenchName,
MenuNameTranslated,
]
)
shadowList.append(CustomCommand)
Toolbars = List_ReturnCustomToolbars_Global()
for Toolbar in Toolbars:
for CustomCommand in Toolbar[2]:
if CustomCommand not in shadowList:
command = Gui.Command.get(CustomCommand)
if CommandInfoCorrections(CustomCommand)["pixmap"] != "":
IconName = CommandInfoCorrections(CustomCommand)["pixmap"]
else:
IconName = None
MenuName = CommandInfoCorrections(CustomCommand)["menuText"].replace(
"&", ""
)
MenuNameTranslated = CommandInfoCorrections(CustomCommand)[
"ActionText"
].replace("&", "")
List_Commands.append(
[CustomCommand, IconName, MenuName, Toolbar[1], MenuNameTranslated]
)
shadowList.append(CustomCommand)
# Add general commands
if int(App.Version()[0]) > 0:
ListCommands = [
"Std_Measure",
"Std_ViewZoomOut",
"Std_ViewZoomIn",
"Std_ViewBoxZoom",
"Part_SelectFilter",
"Std_UnitsCalculator",
"Std_Properties",
"Std_BoxElementSelection",
"Std_BoxSelection",
]
for CommandName in ListCommands:
if CommandName not in shadowList:
command = Gui.Command.get(CommandName)
if CommandInfoCorrections(CommandName)["pixmap"] != "":
IconName = CommandInfoCorrections(CommandName)["pixmap"]
else:
IconName = ""
MenuName = CommandInfoCorrections(CommandName)["menuText"].replace(
"&", ""
)
MenuNameTranslated = CommandInfoCorrections(CommandName)[
"ActionText"
].replace("&", "")
List_Commands.append(
[CommandName, IconName, MenuName, "Standard", MenuNameTranslated]
)
shadowList.append(CommandName)
# # re-activate the workbench that was stored.
# Gui.activateWorkbench(ActiveWB)
# --- Serialize Icons ------------------------------------------------------------------------------------------
#
progressBar.setFormat(translate("FreeCAD Ribbon", "Serialize icons"))
progressBar.setValue(progressBar.value() + 1)
#
WorkbenchIcon = []
for WorkBenchItem in List_Workbenches:
WorkBenchName = WorkBenchItem[0]
Icon = Gui.getIcon(WorkBenchItem[1])
if Icon is not None and Icon.isNull() is False:
try:
SerializedIcon = Serialize_Ribbon.serializeIcon(Icon)
WorkbenchIcon.append([WorkBenchName, SerializedIcon])
# add the icons also to the deserialized list
List_WorkBenchIcons.append([WorkBenchName, Icon])
except Exception as e:
if Parameters.DEBUG_MODE is True:
StandardFunctions.Print(
f"{e.with_traceback(e.__traceback__)}", "Warning"
)
CommandIcons = []
for CommandItem in List_Commands:
CommandName = CommandItem[0]
Icon = StandardFunctions.returnQiCons_Commands(CommandName, CommandItem[1])
if Icon is not None and Icon.isNull() is False:
try:
SerializedIcon = Serialize_Ribbon.serializeIcon(Icon)
CommandIcons.append([CommandName, SerializedIcon])
# add the icons also to the deserialized list
List_CommandIcons.append([CommandName, Icon])
except Exception as e:
if Parameters.DEBUG_MODE is True:
StandardFunctions.Print(
f"{e.with_traceback(e.__traceback__)}", "Warning"
)
# Write the lists to a data file
progressBar.setFormat(translate("FreeCAD Ribbon", "Write data files"))
progressBar.setValue(progressBar.value() + 1)
#
# clear the data file. If not exists, create it
DataFile = os.path.join(ConfigDirectory, "RibbonDataFile.dat")
open(DataFile, "w").close()
# Open de data file, load it as json and then close it again
Data = {}
# Update the data
Data["dataVersion"] = DataFileVersion
Data["Language"] = FCLanguage
Data["List_Workbenches"] = List_Workbenches
Data["StringList_Toolbars"] = StringList_Toolbars
Data["List_Commands"] = List_Commands
Data["WorkBench_Icons"] = WorkbenchIcon
Data["Command_Icons"] = CommandIcons
# Write to the data file
DataFile = os.path.join(ConfigDirectory, "RibbonDataFile.dat")
with open(DataFile, "w") as outfile:
json.dump(Data, outfile, indent=4)
outfile.close()
# Write a second data file with the list of commands, Language and data version only
Data2 = {}
Data2["dataVersion"] = DataFileVersion
Data2["Language"] = FCLanguage
Data2["List_Commands"] = List_Commands
# Write to the data file
DataFile2 = os.path.join(ConfigDirectory, "RibbonDataFile2.dat")
with open(DataFile2, "w") as outfile:
json.dump(Data2, outfile, indent=4)
outfile.close()
# Write a time stamp to preferences
TimeStamp = datetime.now().strftime("%B %d, %Y, %H:%M:%S")
Parameters_Ribbon.Settings.SetStringSetting("ReloadTimeStamp", TimeStamp)
if RestartFreeCAD is True:
result = StandardFunctions.RestartDialog(includeIcons=True)
if result == "yes":
StandardFunctions.restart_freecad()
# show the dialog
progressBar.close()
return True
# region - helper functions
def GetCommand(CommandName):
if len(CommandName.split(", ")) > 1:
# Split the commandname
CommandName_1 = CommandName.split(", ")[0]
ActionNumber = int(CommandName.split(", ")[1])
# Get the parent command
ParentCommand = Gui.Command.get(CommandName_1)
# If parent is not none, get the action based on the number
if ParentCommand is not None:
action = ParentCommand.getAction()[ActionNumber]
if action.objectName() != "":
CommandName = action.objectName()
return CommandName
else:
return CommandName
return CommandName
return CommandName
def List_ReturnCustomToolbars():
"""
Returns custom toolbars as a list.
each item is a list with:
[
Name,
Workbench Title,
List of commands
]
"""
# Get the main window of FreeCAD
mw = Gui.getMainWindow()
Toolbars = []
List_Workbenches = Gui.listWorkbenches().copy()
for WorkBenchName in List_Workbenches:
WorkbenchTitle = Gui.getWorkbench(WorkBenchName).MenuText
if str(WorkBenchName) != "" or WorkBenchName is not None:
if str(WorkBenchName) != "NoneWorkbench":
# Get the custom toolbars for this workbench
CustomToolbars: list = App.ParamGet(
"User parameter:BaseApp/Workbench/" + WorkBenchName + "/Toolbar"
).GetGroups()
for Group in CustomToolbars:
Parameter = App.ParamGet(
"User parameter:BaseApp/Workbench/"
+ WorkBenchName
+ "/Toolbar/"
+ Group
)
Name = Parameter.GetString("Name")
ListCommands = []
try:
# get list of all buttons in toolbar
TB = mw.findChildren(QToolBar, Name)
allButtons: list = TB[0].findChildren(QToolButton)
for button in allButtons:
if button.text() == "":
continue
action = button.defaultAction()
if action is not None:
Command = action.objectName()
ListCommands.append(Command)
Toolbars.append([Name, WorkbenchTitle, ListCommands, Name])
except Exception:
continue
return Toolbars
def List_ReturnCustomToolbars_Global():
"""
Returns custom toolbars as a list.
each item is a list with:
[
Name,
Workbench Title,
List of commands
]
"""
# Get the main window of FreeCAD
mw = Gui.getMainWindow()
Toolbars = []
# Get the custom toolbars for this workbench
CustomToolbars: list = App.ParamGet(
"User parameter:BaseApp/Workbench/Global/Toolbar"
).GetGroups()
for Group in CustomToolbars:
Parameter = App.ParamGet(
"User parameter:BaseApp/Workbench/Global/Toolbar/" + Group
)
Name = Parameter.GetString("Name")
ListCommands = []
# get list of all buttons in toolbar
try:
TB = mw.findChildren(QToolBar, Name)
allButtons: list = TB[0].findChildren(QToolButton)
for button in allButtons:
if button.text() == "":
continue
action = button.defaultAction()
if action is not None:
Command = action.objectName()
ListCommands.append(Command)
Toolbars.append([Name, "Global", ListCommands, Name])
except Exception:
continue
return Toolbars
def Dict_ReturnCustomToolbars(WorkBenchName):
"""_summary_
Args:
WorkBenchName (string): the internal name of the workbench
Returns:
dict: a dict with the toolbar name as key and a list of commandnames as value
"""
# Get the main window of FreeCAD
mw = Gui.getMainWindow()
Toolbars = {}
if str(WorkBenchName) != "" or WorkBenchName is not None:
if str(WorkBenchName) != "NoneWorkbench":
# Get the custom toolbars for this workbench
CustomToolbars: list = App.ParamGet(
"User parameter:BaseApp/Workbench/" + WorkBenchName + "/Toolbar"
).GetGroups()
for Group in CustomToolbars:
Parameter = App.ParamGet(
"User parameter:BaseApp/Workbench/"
+ WorkBenchName
+ "/Toolbar/"
+ Group
)
Name = Parameter.GetString("Name")
if Name != "":
ListCommands = []
# get list of all buttons in toolbar
try:
TB = mw.findChildren(QToolBar, Name)
allButtons: list = TB[0].findChildren(QToolButton)
for button in allButtons:
if button.text() == "":
continue
action = button.defaultAction()
Command = action.objectName()
ListCommands.append(Command)
Toolbars[Name] = ListCommands
except Exception:
continue
return Toolbars
def Dict_ReturnCustomToolbars_Global():
"""_summary_
Returns:
dict: a dict with the toolbar name as key and a list of commandnames as value
"""
# Get the main window of FreeCAD
mw = Gui.getMainWindow()
Toolbars = {}
# Get the custom toolbars for this workbench
CustomToolbars: list = App.ParamGet(
"User parameter:BaseApp/Workbench/Global/Toolbar"
).GetGroups()
for Group in CustomToolbars:
Parameter = App.ParamGet(
"User parameter:BaseApp/Workbench/Global/Toolbar/" + Group
)
Name = Parameter.GetString("Name")
IsIgnored = False
for ToolBar in List_IgnoredToolbars:
if ToolBar == Name:
IsIgnored = True
if Name != "" and IsIgnored is False:
ListCommands = []
# get list of all buttons in toolbar
TB = mw.findChildren(QToolBar, Name)
allButtons: list = TB[0].findChildren(QToolButton)
for button in allButtons:
if button.text() == "":
continue
action = button.defaultAction()
Command = action.objectName()
ListCommands.append(Command)
Toolbars[Name] = ListCommands
return Toolbars
def returnWorkBenchToolbars(WorkBenchName):
wbToolbars = []
try:
for ToolbarItem in StringList_Toolbars:
if ToolbarItem[2] == WorkBenchName:
wbToolbars.append(ToolbarItem[0])
except Exception:
Gui.activateWorkbench(WorkBenchName)
wbToolbars: list = Gui.getWorkbench(WorkBenchName).listToolbars()
return wbToolbars
def returnToolbarCommands(WorkBenchName):
try:
for item in List_Workbenches:
if item[0] == WorkBenchName:
return item[3]
except Exception:
Gui.activateWorkbench(WorkBenchName)
Toolbars = Gui.getWorkbench(WorkBenchName).getToolbarItems()
return Toolbars
def returnDropDownCommands(commandName):
Commands = []
if commandName is not None:
command = Gui.Command.get(commandName)
if command is not None:
if len(command.getAction()) > 1:
for i in range(len(command.getAction()) - 1):
action = command.getAction()[i]
if action is not None and (
action.icon() is not None and not action.icon().isNull()
):
IconName = StandardFunctions.CommandInfoCorrections(action.objectName())["pixmap"]
Commands.append(
[
action.objectName(),
IconName,
action.text(),
action.text(),
]
)
return Commands
def loadAllWorkbenches(AutoHide=True, HideOnly=False, FinishMessage="", progressBar: QProgressBar = None, maximum = 0):
if HideOnly is False:
activeWorkbench = Gui.activeWorkbench().name()
progressBar.show()
lst = Gui.listWorkbenches()
progressBar.setMaximum(len(lst) - 1 + maximum)
for i, wb in enumerate(lst):
try:
msg = (
translate("FreeCAD Ribbon", "Loading workbench ")
+ wb
+ " ("
+ str(i + 1)
+ "/"
+ str(len(lst))
+ ")"
)
print(msg)
progressBar.setFormat(msg)
progressBar.setValue(i)
Gui.updateGui() # Probably slower with this, because it redraws the entire GUI with all tool buttons changed etc. but allows the label to actually be updated, and it looks nice and gives a quick overview of all the workbenches…
Gui.activateWorkbench(wb)
List_Workbenches.append(wb)
except Exception:
pass
if FinishMessage != "":
print(FinishMessage)
Gui.activateWorkbench(activeWorkbench)
return
# endregion---------------------------------------------------------------------------------------
def DownLoadIcons():
PathList = []
url = 'https://raw.githubusercontent.com/FreeCAD/FreeCAD/main/src/Gui/Icons/3dx_pivot.png'
response = requests.get(url)
response.raise_for_status() # proper handle HTTP errors
file_content = response.text
print(f"HTTP status: {response.status_code}")
with open("setup.py", "w") as file:
file.write(file_content)
def CheckDataFileVersion():
DataFileIsUpToDate = False
# Check if there is a datafile. if not, ask the user to create one.
DataFile = os.path.join(ConfigDirectory, "RibbonDataFile.dat")
if os.path.exists(DataFile) is False:
Question = translate(
"FreeCAD Ribbon",
"The first time, a data file must be generated!\n"
"This can take a while! Do you want to proceed?",
)
Answer = StandardFunctions.Mbox(Question, "FreeCAD Ribbon", 1, "Question")
if Answer == "yes":
CreateCache()
else:
return
# region - Load data------------------------------------------------------------------
#
Data = {}
# read ribbon structure from JSON file
with open(DataFile, "r") as file:
Data.update(json.load(file))
file.close()
DataUpdateNeeded = False
try:
FileVersion = Data["dataVersion"]
if FileVersion != DataFileVersion:
DataUpdateNeeded = True
except Exception:
DataUpdateNeeded = True
if DataUpdateNeeded is True:
Question = translate(
"FreeCAD Ribbon",
"The current data file is based on an older format!\n"
"It is important to update the data!\n"
"Do you want to proceed?\n"
"This can take a while!",
)
Answer = StandardFunctions.Mbox(Question, "FreeCAD Ribbon", 1, "Question")
if Answer == "yes":
CreateCache()
# get the system language
FreeCAD_preferences = App.ParamGet("User parameter:BaseApp/Preferences/General")
try:
FCLanguage = FreeCAD_preferences.GetString("Language")
# Check if the language in the data file machtes the system language
IsSystemLanguage = True
if FCLanguage != Data["Language"]:
IsSystemLanguage = False
# If the languguage doesn't match, ask the user to update the data
if IsSystemLanguage is False:
Question = translate(
"FreeCAD Ribbon",
"The data was generated for a differernt language!\n"
"Do you want to update the data?\n"
"This can take a while!",
)
Answer = StandardFunctions.Mbox(
Question, "FreeCAD Ribbon", 1, "Question"
)
if Answer == "yes":
CreateCache()
except Exception:
pass
# test if List_Commands is correct
i = 5
if len(List_Commands) > 0:
for item in List_Commands:
if len(item) < 5:
i = len(item)
break
if i < 5:
Question = translate(
"FreeCAD Ribbon",
"It seems that the data file is not up-to-date.\n"
"Do you want to update the data?\n"
"This can take a while!",
)
Answer = StandardFunctions.Mbox(Question, "FreeCAD Ribbon", 1, "Question")
if Answer == "yes":
DataFileIsUpToDate = CreateCache()
return DataFileIsUpToDate