-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathLoadAddCommands.py
More file actions
2761 lines (2395 loc) · 123 KB
/
Copy pathLoadAddCommands.py
File metadata and controls
2761 lines (2395 loc) · 123 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
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) 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.QtCore import Qt, SIGNAL, Signal, QObject, QThread, QSize, QEvent, QEventLoop
from PySide.QtWidgets import (
QTabWidget,
QSlider,
QSpinBox,
QCheckBox,
QComboBox,
QLabel,
QDialogButtonBox,
QApplication,
QPushButton,
QDialog,
QListWidget,
QListWidgetItem,
QLineEdit,
QToolBar,
QToolButton,
QDockWidget,
QSizePolicy,
QGridLayout,
QHBoxLayout,
)
from PySide.QtGui import QIcon, QPixmap, QDragEnterEvent, QDragLeaveEvent, QDropEvent
import sys
import json
from datetime import datetime, timedelta
import Standard_Functions_Ribbon as StandardFunctions
from Standard_Functions_Ribbon import CommandInfoCorrections
import Parameters_Ribbon
from Parameters_Ribbon import Parameters
import Serialize_Ribbon
import CacheFunctions
import FCBinding
from CustomWidgets import QuickAccessToolButton, CustomControls
import StyleMapping_Ribbon
import webbrowser
import pyqtribbon_local as pyqtribbon
from pyqtribbon_local.ribbonbar import RibbonMenu, RibbonTitleWidget, RibbonApplicationButton
from pyqtribbon_local.panel import RibbonPanel, RibbonPanelItemWidget, RibbonPanelTitle
from pyqtribbon_local.toolbutton import RibbonToolButton, RibbonButtonStyle
from pyqtribbon_local.separator import RibbonSeparator
from pyqtribbon_local.category import RibbonCategory, RibbonCategoryLayoutButton, RibbonNormalCategory, RibbonContextCategory
# 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)
# import graphical created Ui. (With QtDesigner or QtCreator)
import AddCommands_ui as AddCommands_ui
# Define the translation
translate = App.Qt.translate
# Get the main window from FreeCAD
mw = Gui.getMainWindow()
class LoadDialog(AddCommands_ui.Ui_Form):
ReproAdress: str = ""
# Create a list for the commands
List_Commands = []
# Create a dict for the dropdownbuttons and newPanels
Dict_DropDownButtons = {}
Dict_NewPanels = {}
# Create the lists for the deserialized icons
List_CommandIcons = []
List_WorkBenchIcons = []
# 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 = {}
# Create a variable to state if the dialog is closed or not
DialogClosed = False
# Create a dict for the workbench
workBenchDict = {}
# Create varables for the current workbench title and name
CurrentWorkBenchTitle = None
CurrentWorkBenchName = None
# Create a tomporary list for newly added dropdown buttons
newDDBList = []
# Create a list for all listwidget items. Used to switch filters to "All"
listWidgetItems_NP = []
listWidgetItems_DDB = []
def __init__(self, parent):
super(LoadDialog, self).__init__()
RibbonBar: FCBinding.ModernMenu = mw.findChild(FCBinding.ModernMenu, "Ribbon")
self.List_CommandIcons = RibbonBar.List_CommandIcons
self.List_IgnoredWorkbenches = RibbonBar.ribbonStructure["ignoredWorkbenches"]
# Set the wait cursor
QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor)
QApplication.processEvents(QEventLoop.ProcessEventsFlag.AllEvents)
# # this will create a Qt widget from our ui file
self.form = Gui.PySideUic.loadUi(os.path.join(pathUI, "AddCommands.ui"))
# Set its title
self.form.setWindowTitle(translate("FreeCAD Ribbon", "Add or remove buttons"))
self.form.setAcceptDrops(True)
# Install an event filter to catch events from the main window and act on it.
self.form.installEventFilter(EventInspector(self.form))
# set all widgets on the form to not accepting drops
self.form.CommandsAvailable_NP.setAcceptDrops(False)
self.form.SearchBar_NP.setAcceptDrops(False)
# Get the address of the repository address
PackageXML = os.path.join(os.path.dirname(__file__), "package.xml")
self.ReproAdress = StandardFunctions.ReturnXML_Value(
PackageXML, "url", "type", "repository"
)
# load the RibbonStructure.json
self.ReadJson()
# Make sure that the dialog stays on top
self.form.raise_()
self.form.setWindowFlags(Qt.WindowType.WindowStaysOnTopHint)
self.form.setFocus(Qt.FocusReason.PopupFocusReason)
# Get the style from the main window and use it for this form
palette = mw.palette()
self.form.setPalette(palette)
Style = mw.style()
self.form.setStyle(Style)
# Position the dialog in front of FreeCAD
centerPoint = mw.geometry().center()
Rectangle = self.form.frameGeometry()
Rectangle.moveCenter(centerPoint)
self.form.move(Rectangle.topLeft())
# 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":
CacheFunctions.CreateCache()
else:
# Restore the cursor
QApplication.restoreOverrideCursor()
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 != CacheFunctions.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":
CacheFunctions.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":
CacheFunctions.CreateCache(resetTexts=True)
except Exception:
pass
# Load the standard lists for Workbenches, toolbars and commands
self.List_Workbenches = Data["List_Workbenches"]
self.StringList_Toolbars = Data["StringList_Toolbars"]
self.List_Commands = Data["List_Commands"]
# test if List_Commands is correct
i = 5
if len(self.List_Commands) > 0:
for item in self.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":
CacheFunctions.CreateCache()
# Load icons for all workbenches
try:
for IconItem in Data["WorkBench_Icons"]:
Icon: QIcon = Serialize_Ribbon.deserializeIcon(IconItem[1])
item = [IconItem[0], Icon]
if item not in self.List_CommandIcons:
self.List_WorkBenchIcons.append(item)
except Exception as e:
StandardFunctions.Print(f"{e.with_traceback(e.__traceback__)}", "Warning")
pass
# Load icons for all commands
try:
for CommandItem in self.List_Commands:
isInList = False
for IconItem in self.List_CommandIcons:
if CommandItem[0] == IconItem[0]:
isInList = True
if Parameters.DEBUG_MODE:
print(f"{CommandItem[0]} already present in the list")
break
if isInList is False:
# Check first if the icon can be loaded quickly
Icon = QIcon()
FreeCAD_Icons = os.path.abspath(os.path.join(os.path.dirname(__file__), "Resources", "FreeCAD Icons"))
for root, dirs, files in os.walk(FreeCAD_Icons):
for fileName in files:
if CommandItem[0] == fileName.split(".")[0]:
Icon = QIcon()
Icon.addPixmap(QPixmap(os.path.join(root, fileName)))
# Print a message when debug mode is enabled
if Parameters.DEBUG_MODE:
print(f"{fileName} created from resources")
if Icon is None or (Icon is not None and Icon.isNull()):
IconName = StandardFunctions.CommandInfoCorrections(CommandItem[0])["pixmap"]
Icon = StandardFunctions.returnQiCons_Commands(CommandItem[0], IconName)
# Print a message when debug mode is enabled
if Parameters.DEBUG_MODE:
print(f"Icon for {CommandItem[0]} retrieved from FreeCAD")
# If the Icon is still none or empty, get it from the datafile
if Icon is None or (Icon is not None and Icon.isNull()):
for IconItem in Data["Command_Icons"]:
if IconItem[0] == CommandItem[0] and IconItem[0] != "" and CommandItem[0] != "":
Icon: QIcon = Serialize_Ribbon.deserializeIcon(IconItem[1])
# Print a message when debug mode is enabled
if Parameters.DEBUG_MODE:
print(f"Icon for {CommandItem[0]} retrieved from data file")
# Add the icon to the icon list
item = [CommandItem[0], Icon]
self.List_CommandIcons.append(item)
except Exception as e:
StandardFunctions.Print(f"{e.with_traceback(e.__traceback__)}", "Warning")
pass
# check if the list with workbenches is up-to-date
missingWB = []
for WorkBenchName in Gui.listWorkbenches():
for j in range(len(self.List_Workbenches)):
if (
WorkBenchName == self.List_Workbenches[j][0]
or WorkBenchName == "NoneWorkbench"
):
break
if j == len(self.List_Workbenches) - 1:
missingWB.append(WorkBenchName)
if len(missingWB) > 0:
ListWB = " "
for WB in missingWB:
ListWB = ListWB + WB + "\n" + " "
Question = translate(
"FreeCAD Ribbon",
"The following workbenches were installed after the last data update: \n"
"{}\n\n"
"Do you want to update the data?\n"
"This can take a while!",
).format(ListWB)
Answer = StandardFunctions.Mbox(Question, "FreeCAD Ribbon", 1, "Question")
if Answer == "yes":
CacheFunctions.CreateCache()
# Add dropdownbuttons to the list of commands
try:
for DropDownCommand, Commands in RibbonBar.workBenchDict["dropdownButtons"].items():
if isinstance(Commands, list):
CommandName = Commands[0][0]
IconName = ""
for CommandItem in self.List_Commands:
if CommandItem[0] == CommandName:
IconName = StandardFunctions.CommandInfoCorrections(CommandItem[1])["pixmap"]
self.List_Commands.append(
[
DropDownCommand,
IconName,
DropDownCommand.split("_")[0],
"General",
DropDownCommand.split("_")[0],
]
)
else:
del RibbonBar.workBenchDict["dropdownButtons"]
StandardFunctions.Print(
"dropdownbuttons have wrong format. Please create them again!",
"Warning",
)
except Exception as e:
if Parameters.DEBUG_MODE is True:
StandardFunctions.Print(
f"{e.with_traceback(e.__traceback__)}", "Warning"
)
pass
# endregion
# Add the workbenches
self.addWorkbenches()
# Load the commands
self.LoadCommands()
# Add all toolbar to the listboxes for the panels
self.LoadPanels()
# Connect the filter for the quick commands on the quickcommands tab
def FilterWorkbench_NP():
self.on_ListCategory_NP_TextChanged()
#
# --- AddCOmmandsTab ------------------
#
# Connect the filter for the quick commands on the quickcommands tab
self.form.ListCategory_NP.currentTextChanged.connect(FilterWorkbench_NP)
# Connect the searchbar for the quick commands on the quick commands tab
self.form.SearchBar_NP.textChanged.connect(
self.on_SearchBar_NP_TextChanged
)
# Connect the "CreateNewPanel" button
self.form.CreateNewPanel.clicked.connect(self.on_CreateNewPanel_clicked)
#
# --- CombinePanelsTab ------------------
#
# Connect move and events to the buttons on the Custom Panels Tab
self.form.MoveUpPanelCommand_CP.connect(
self.form.MoveUpPanelCommand_CP,
SIGNAL("clicked()"),
self.on_MoveUpPanelCommand_CP_clicked,
)
self.form.MoveDownPanelCommand_CP.connect(
self.form.MoveDownPanelCommand_CP,
SIGNAL("clicked()"),
self.on_MoveDownPanelCommand_CP_clicked,
)
# Connect Add events to the buttons on the Custom Panels Tab for adding commands to the panel
self.form.AddPanel_CP.connect(
self.form.AddPanel_CP, SIGNAL("clicked()"), self.on_AddPanel_CP_clicked
)
self.form.AddCustomPanel_CP.connect(
self.form.AddCustomPanel_CP,
SIGNAL("clicked()"),
self.on_AddCustomPanel_CP_clicked,
)
# Connect custom toolbar selector on the Custom Panels Tab
def CommandList_CP():
self.on_CustomToolbarSelector_CP_activated()
self.form.CustomToolbarSelector_CP.activated.connect(CommandList_CP)
self.form.RemovePanel_CP.connect(
self.form.RemovePanel_CP,
SIGNAL("clicked()"),
self.on_RemovePanel_CP_clicked,
)
self.form.WorkbenchList_CP.setHidden(True)
self.form.label_7.setHidden(True)
#
# --- CreateDropDownButtonTab ----------------
#
# Connect the Create dropdown button
self.form.CreateControl_DDB.connect(
self.form.CreateControl_DDB,
SIGNAL("clicked()"),
self.on_CreateControl_DDB_clicked,
)
# Connect dropdownselector on the create dropdown button Tab
def CommandList_DDB():
self.on_CommandList_DDB_activated()
self.form.CommandList_DDB.activated.connect(CommandList_DDB)
# Connect the remove dropdown button
self.form.RemoveControl_DDB.connect(
self.form.RemoveControl_DDB,
SIGNAL("clicked()"),
self.on_RemoveControl_DDB_clicked,
)
# Connect Add/Remove and move events to the buttons on the QuickAccess Tab
self.form.AddCommand_DDB.connect(
self.form.AddCommand_DDB,
SIGNAL("clicked()"),
self.on_AddCommand_DDB_clicked,
)
self.form.RemoveCommand_DDB.connect(
self.form.RemoveCommand_DDB,
SIGNAL("clicked()"),
self.on_RemoveCommand_DDB_clicked,
)
self.form.MoveUpCommand_DDB.connect(
self.form.MoveUpCommand_DDB,
SIGNAL("clicked()"),
self.on_MoveUpCommand_DDB_clicked,
)
self.form.MoveDownCommand_DDB.connect(
self.form.MoveDownCommand_DDB,
SIGNAL("clicked()"),
self.on_MoveDownCommand_DDB_clicked,
)
# Connect the filter for the quick commands on the quickcommands tab
def FilterWorkbench_DDB():
self.on_ListCategory_DDB_TextChanged()
# Connect the filter for the quick commands on the quickcommands tab
self.form.ListCategory_DDB.currentTextChanged.connect(FilterWorkbench_DDB)
# Connect the searchbar for the quick commands on the quick commands tab
self.form.SearchBar_DDB.textChanged.connect(
self.on_SearchBar_DDB_TextChanged
)
# --- Form controls ------------------
#
# Connect the reload button
self.form.LoadWB.connect(
self.form.LoadWB, SIGNAL("clicked()"), self.on_ReloadWB_clicked
)
# Set the icon and size for the refresh button
self.form.LoadWB.heightForWidth(1)
self.form.LoadWB.setIcon(Gui.getIcon("view-refresh"))
self.form.LoadWB.setIconSize(QSize(20, 20))
# Create the a message to indicate when the last time the data was (re)created.
TimeStamp = Parameters_Ribbon.Settings.GetStringSetting("ReloadTimeStamp")
if TimeStamp != "":
date_format = "%B %d, %Y, %H:%M:%S"
lastDate = datetime.strptime(TimeStamp, date_format)
deltaDate: timedelta = datetime.now()-lastDate
deltaDict = StandardFunctions.TimeDeltaToDict(deltaDate)
# Get the separate values
delta_days = deltaDict['days']
delta_hours = deltaDict['hours']
delta_minutes= deltaDict['minutes']
# Set the message
self.form.TimeStamp_Reloaded.setText(translate("FreeCAD Ribbon", f"Last reloaded on: {TimeStamp}. This is {delta_days} days, {delta_hours} hour(s) and {delta_minutes} minutes ago."))
else:
TimeStamp = "-"
self.form.TimeStamp_Reloaded.setText(translate("FreeCAD Ribbon", f"Last reloaded on: {TimeStamp}."))
# Connect the OK and Cancel buttons
self.form.cancelButton.clicked.connect(self.on_Cancel_Clicked)
self.form.okButton.clicked.connect(self.on_Ok_Clicked)
self.form.applyButton.clicked.connect(self.on_Apply_Clicked)
self.form.cancelButton_2.clicked.connect(self.on_Cancel_Clicked)
self.form.okButton_2.clicked.connect(self.on_Ok_Clicked)
self.form.applyButton_2.clicked.connect(self.on_Apply_Clicked)
# Connect the helpbutton
self.form.HelpButton.setIcon(Gui.getIcon("help-browser"))
self.form.HelpButton.clicked.connect(self.on_Helpbutton_clicked)
# Set the correct workbench active and connect it with the tab change
RibbonBar: FCBinding.ModernMenu = mw.findChild(FCBinding.ModernMenu, "Ribbon")
RibbonBar.TabChanged.connect(self.setWB)
self.setWB()
# Hide the correct ok and cancel button when the form is docked or not
if Parameters.DOCKED_DIALOGS is True:
self.form.okButton.setHidden(True)
self.form.cancelButton.setHidden(True)
self.form.applyButton.setHidden(True)
else:
self.form.DockedButtonFrame.setHidden(True)
# Set the first tab active
self.form.tabWidget.setCurrentIndex(0)
# Enable drag for the listWidget.
#
# Qt6
try:
self.form.ListCategory_NP.setSupportedDragActions(Qt.DropAction.CopyAction|Qt.DropAction.MoveAction)
except Exception:
pass
# Qt5
try:
from PySide2 import QtWidgets
self.form.ListCategory_NP.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
self.form.ListCategory_NP.setAcceptDrops(True)
self.form.ListCategory_NP.setDragEnabled(True)
except Exception:
pass
# Restore the cursor
QApplication.restoreOverrideCursor()
return
def addWorkbenches(self):
ShadowList = [] # List to add the commands and prevent duplicates
# Fill the Workbenches available, selected and workbench list
self.form.ListCategory_NP.clear()
self.form.ListCategory_DDB.clear()
# Add "All" to the categoryListWidgets
All_KeyWord = translate("FreeCAD Ribbon", "All")
self.form.ListCategory_NP.addItem(All_KeyWord, "All", [All_KeyWord, "All", "All"])
self.form.ListCategory_DDB.addItem(All_KeyWord, "All", [All_KeyWord, "All", "All"])
# Add "Standard" to the list for the panels
Standard_KeyWord = translate("FreeCAD Ribbon", "Standard")
self.form.ListCategory_NP.addItem(Gui.getIcon("freecad"), Standard_KeyWord, [Standard_KeyWord, "Standard", "Standard"])
self.form.ListCategory_DDB.addItem(Gui.getIcon("freecad"), Standard_KeyWord, [Standard_KeyWord, "Standard", "Standard"])
# # Add "Global" to the list for the panels
# Standard_KeyWord = translate("FreeCAD Ribbon", "Global")
# self.form.ListCategory_NP.addItem(Gui.getIcon("freecad"), Standard_KeyWord, [Standard_KeyWord, "Global", "Global"])
# self.form.ListCategory_DDB.addItem(Gui.getIcon("freecad"), Standard_KeyWord, [Standard_KeyWord, "Global", "Global"])
# Sort the workbenches according the order of tabs
def sortWorkbenches(item):
WorkbenchOrderedList: list = Parameters.TAB_ORDER.split(",")
position = None
try:
position = WorkbenchOrderedList.index(item[0])
except ValueError as e:
position = 999999
return position
self.List_Workbenches.sort(key=sortWorkbenches)
WorkbenchName =""
for workbench in self.List_Workbenches:
WorkbenchName = workbench[0]
WorkbenchTitle = workbench[2]
if WorkbenchTitle in self.List_IgnoredWorkbenches:
continue
if WorkbenchName in self.List_IgnoredWorkbenches:
continue
if [WorkbenchName, WorkbenchTitle] not in ShadowList:
# Get the translate worbench title
if len(workbench) == 5:
WorkbenchTitle = workbench[4]
else:
WorkbenchTitle = workbench[2]
# Define a new ListWidgetItem.
Icon: QIcon = self.ReturnWorkbenchIcon(WorkbenchName)
# Add the ListWidgetItem also to the categoryListWidgets
self.form.ListCategory_NP.addItem(
Icon,
WorkbenchTitle,
workbench,
)
self.form.ListCategory_DDB.addItem(
Icon,
WorkbenchTitle,
workbench,
)
ShadowList.append([WorkbenchName, WorkbenchTitle])
self.form.ListCategory_NP.setCurrentText(All_KeyWord)
self.form.ListCategory_DDB.setCurrentText(All_KeyWord)
return
def LoadCommands(self):
RibbonBar: FCBinding.ModernMenu = mw.findChild(FCBinding.ModernMenu, "Ribbon")
"""Fill the Quick Commands Available and Selected"""
self.form.CommandsAvailable_NP.clear()
self.form.CommandList_DDB.clear()
self.form.CommandsAvailable_DDB.clear()
self.form.NewControl_DDB.clear()
# Set the stylesheet for the listwidgets
stylesheet = """ QToolTip {
background-color: #FFFFE1;
color: black;
border: black solid 1px;
border-radius: 2px;
}"""
self.form.CommandsAvailable_NP.setStyleSheet(stylesheet)
self.form.CommandList_DDB.setStyleSheet(stylesheet)
self.form.CommandsAvailable_DDB.setStyleSheet(stylesheet)
self.form.NewControl_DDB.setStyleSheet(stylesheet)
ShadowList = [] # List to add the commands and prevent duplicates
for CommandItem in self.List_Commands:
CommandName = CommandItem[0]
MenuNameTranslated = CommandItem[2].replace("&", "") # Not translated
if len(CommandItem) == 5:
MenuNameTranslated = CommandItem[4].replace("&", "") # Translated
# Remove numbers from dropdown child commands
if MenuNameTranslated.split(" ")[0].isdigit() is True:
MenuNameTranslated = MenuNameTranslated.split(" ")[1]
# Remove any suffix frp, the menuname
if CommandName.endswith("_ddb"):
MenuNameTranslated = CommandName.replace("_ddb", "")
# If the command is from an ignored workbench, skip it
WorkBenchName = CommandItem[3]
WorkbenchTitle = ""
try:
WorkbenchTitle = Gui.getWorkbench(WorkBenchName).MenuText
except Exception:
pass
if WorkBenchName in self.List_IgnoredWorkbenches or WorkbenchTitle in self.List_IgnoredWorkbenches:
continue
if MenuNameTranslated != "":
if CommandName not in ShadowList:
Icon = QIcon()
Icon = self.ReturnCommandIcon(CommandName=CommandName)
Text = MenuNameTranslated
ListWidgetItem = QListWidgetItem()
ListWidgetItem.setText(Text)
ListWidgetItem.setData(Qt.ItemDataRole.UserRole, CommandName)
if Icon is not None and Icon.isNull() is False:
# Check if there is an Icon. if not add a replacement
if Icon.pixmap(64,64).toImage().bytesPerLine() < 256:
# Icon = Gui.getIcon("preferences-workbenches")
# ListWidgetItem.setIcon(Icon)
continue
ListWidgetItem.setIcon(Icon)
ListWidgetItem.setToolTip(
CommandName
) # Use the tooltip to store the actual command.
# Add the ListWidgetItem to the correct ListWidget
self.form.CommandsAvailable_NP.addItem(ListWidgetItem)
# Append a clone of the item to the listwidget item list
self.listWidgetItems_NP.append(ListWidgetItem.clone())
command = Gui.Command.get(CommandName)
if command is not None and len(command.getAction()) == 1:
# Add clones of the listWidgetItem to the other listwidgets
self.form.CommandsAvailable_DDB.addItem(ListWidgetItem.clone())
# Append a clone of the item to the listwidget item list
self.listWidgetItems_DDB.append(ListWidgetItem.clone())
# If there are any dropdown buttons in the json file, add them to the dropdown list
if (str(CommandName).endswith("_ddb") and "dropdownButtons" in RibbonBar.workBenchDict):
self.form.CommandList_DDB.addItem(CommandName.replace("_ddb", ""))
ShadowList.append(CommandName)
# Add a "new" item to the dropdown list
self.form.CommandList_DDB.addItem(translate("FreeCAD Ribbon", "New"), "new")
self.form.CommandList_DDB.setCurrentText(translate("FreeCAD Ribbon", "New"))
return
# region - Add commands
def on_ListCategory_NP_TextChanged(self):
self.FilterCommands_ListCategory(
self.form.CommandsAvailable_NP,
self.form.ListCategory_NP,
self.form.SearchBar_NP,
False,
)
return
def on_SearchBar_NP_TextChanged(self):
self.FilterCommands_SearchBar(
self.form.CommandsAvailable_NP,
self.form.SearchBar_NP,
self.form.ListCategory_NP,
)
return
def on_CreateNewPanel_clicked(self):
if self.form.PanelTitle.text() != "":
RibbonBar: FCBinding.ModernMenu = mw.findChild(FCBinding.ModernMenu, "Ribbon")
RibbonBar.CreateNewPanel(self.form.PanelTitle.text())
return
# endregion---------------------------------------------------------------------------------------
# region - Combine panels tab
def setWB(self):
# Get the ribbon, the current wb title and name
RibbonBar: FCBinding.ModernMenu = mw.findChild(FCBinding.ModernMenu, "Ribbon")
self.CurrentWorkBenchTitle = RibbonBar.currentCategory().title()
self.CurrentWorkBenchName = RibbonBar.currentCategory().objectName()
# Activate the correct workbench in this dialog (ComboBox is hidden)
self.on_WorkbenchList_CP__activated()
return
def on_WorkbenchList_CP__activated(
self, setCustomToolbarSelector_CP: bool = False, CurrentText=""
):
RibbonBar: FCBinding.ModernMenu = mw.findChild(FCBinding.ModernMenu, "Ribbon")
# Set the workbench name.
WorkBenchName = self.CurrentWorkBenchName
WorkBenchTitle = self.CurrentWorkBenchTitle
# If there is no workbench, return
if WorkBenchName == "":
return
# Get the toolbars of the workbench
wbToolbars = self.returnWorkBenchToolbars(WorkBenchName)
# Get all the custom toolbars from the toolbar layout
CustomToolbars = self.List_ReturnCustomToolbars()
for CustomToolbar in CustomToolbars:
if CustomToolbar[1] == WorkBenchTitle:
wbToolbars.append(CustomToolbar[0])
# Get the global custom toolbars
CustomToolbars = self.Dict_ReturnCustomToolbars_Global()
for CustomToolbar in CustomToolbars:
wbToolbars.append(CustomToolbar)
# Get the custom panels
if "customToolbars" in RibbonBar.workBenchDict:
CustomPanel = self.List_ReturnCustomPanel(
RibbonBar.workBenchDict["customToolbars"], WorkBenchName=WorkBenchName
)
for CustomToolbar in CustomPanel:
if CustomToolbar[1] == WorkBenchTitle or CustomToolbar[1] == "Global":
wbToolbars.append(CustomToolbar[0])
# Get the new panels per workbench
if "newPanels" in RibbonBar.workBenchDict:
NewPanels = self.List_ReturnNewPanel(
RibbonBar.workBenchDict["newPanels"], WorkBenchName=WorkBenchName, PanelDict="newPanels"
)
for Newpanel in NewPanels:
if Newpanel[1] == WorkBenchTitle:
wbToolbars.append(Newpanel[0])
# Get the new panels globally
NewPanels = self.List_ReturnNewPanel(
RibbonBar.workBenchDict["newPanels"], WorkBenchName="Global", PanelDict="newPanels"
)
for Newpanel in NewPanels:
if Newpanel[1] == "Global":
wbToolbars.append(Newpanel[0])
# Clear the listwidget before filling it
self.form.PanelAvailable_CP.clear()
# Sort the toolbar list
wbToolbars = self.SortedPanelList(wbToolbars, WorkBenchName)
# Go through the toolbars and check if they must be ignored.
shadowList = []
for Toolbar in wbToolbars:
if Toolbar in shadowList:
continue
IsIgnored = False
if "ignoredToolbars" in RibbonBar.workBenchDict:
for IgnoredToolbar in RibbonBar.workBenchDict["ignoredToolbars"]:
if Toolbar.lower() == IgnoredToolbar.lower():
IsIgnored = True
# If the are not to be ignored, add them to the listwidget
if IsIgnored is False and Toolbar != "":
ToolbarTransLated = Toolbar
# Get the translated toolbar name
for ToolBarItem in self.StringList_Toolbars:
if ToolBarItem[0] == Toolbar:
if len(ToolBarItem) == 4:
ToolbarTransLated = ToolBarItem[3]
else:
ToolbarTransLated = ToolBarItem[0]
# If it is a custom toolbar, remove the suffix
ToolbarTransLated = ToolbarTransLated.replace("_custom", "").replace(
"_newPanel", ""
)
# Remove possible workbench names from the titles
title = ToolbarTransLated
if (
"_custom" not in title
and "_global" not in title
and "_newPanel" not in title
):
List = [
WorkBenchName,
WorkBenchTitle,
WorkBenchTitle.replace(" ", ""),
]
for Name in List:
ListDelimiters = [" - ", "-", "_"]
for delimiter in ListDelimiters:
if f"{delimiter}{Name}" in title:
title = title.replace(f"{delimiter}{Name}", "")
elif f"{Name}{delimiter}" in title:
title = title.replace(f"{Name}{delimiter}", "")
if Name in title and Name != title:
title = title.replace(Name, "")
if title[:1] == " ":
title = title[1:]
# remove any suffix from the panel title
if title.endswith("_custom"):
title = title.replace("_custom", "")
if title.endswith("_global"):
title = title.replace("_global", "")
if title.endswith("_newPanel"):
title = title.replace("_newPanel", "")
ListWidgetItem = QListWidgetItem()
ListWidgetItem.setText(title.replace("&", ""))
ListWidgetItem.setData(Qt.ItemDataRole.UserRole, Toolbar)
self.form.PanelAvailable_CP.addItem(ListWidgetItem)
# Add the toolbar to the shadow list to prevent from being added more than once.
shadowList.append(Toolbar)
if setCustomToolbarSelector_CP is True:
self.form.CustomToolbarSelector_CP.setCurrentText(
translate("FreeCAD Ribbon", "New")
)
self.form.CustomToolbarSelector_CP.setItemData(
0, "new", Qt.ItemDataRole.UserRole
)
# Get the ribbonbar
RibbonBar: FCBinding.ModernMenu = mw.findChild(FCBinding.ModernMenu, "Ribbon")
# Activate all buttons
RibbonBar.activateButtons()
self.form.PanelSelected_CP.clear()
return
def on_MoveUpPanelCommand_CP_clicked(self):
self.MoveItem(ListWidget=self.form.PanelSelected_CP, Up=True)
# # Enable the apply button
# if self.CheckChanges() is True:
# self.form.UpdateJson.setEnabled(True)
return
def on_MoveDownPanelCommand_CP_clicked(self):
self.MoveItem(ListWidget=self.form.PanelSelected_CP, Up=False)
# # Enable the apply button
# if self.CheckChanges() is True:
# self.form.UpdateJson.setEnabled(True)
return
def on_AddPanel_CP_clicked(self):
RibbonBar: FCBinding.ModernMenu = mw.findChild(FCBinding.ModernMenu, "Ribbon")
SelectedToolbars = self.form.PanelAvailable_CP.selectedItems()
# Set the workbench name.
WorkbenchName = self.CurrentWorkBenchName
# Get the dict with the toolbars of this workbench
ToolbarItems = self.returnToolbarCommands(WorkbenchName)
# Get the custom toolbars from each installed workbench
CustomCommands = self.Dict_ReturnCustomToolbars(WorkbenchName)
ToolbarItems.update(CustomCommands)
# Get the global custom toolbars
CustomCommands = self.Dict_ReturnCustomToolbars_Global()
ToolbarItems.update(CustomCommands)
# Get the new panels from each installed workbench
NewPanelCommands = self.Dict_ReturnNewPanel(RibbonBar.workBenchDict, WorkbenchName)
ToolbarItems.update(NewPanelCommands)
# Get the global new panels
NewPanelCommands = self.Dict_ReturnNewPanel(RibbonBar.workBenchDict)
ToolbarItems.update(NewPanelCommands)
for key, value in list(ToolbarItems.items()):
# Go through the selected items, if they mach continue
for i in range(len(SelectedToolbars)):
toolbar = SelectedToolbars[i].data(Qt.ItemDataRole.UserRole)
if key == toolbar:
for j in range(len(value)):
CommandName = value[j]
for ToolbarCommand in self.List_Commands:
if ToolbarCommand[0] == CommandName or ToolbarCommand[2] == CommandName:
# Get the command
MenuName = ToolbarCommand[4].replace("&", "")
# get the icon for this command if there isn't one, leave it None
Icon = QIcon()
Icon = self.ReturnCommandIcon(CommandName=CommandName)
# Define a new ListWidgetItem.
ListWidgetItem = QListWidgetItem()
ListWidgetItem.setText(
StandardFunctions.TranslationsMapping(
WorkbenchName, MenuName
)
)
if Icon is not None:
ListWidgetItem.setIcon(Icon)
ListWidgetItem.setData(
Qt.ItemDataRole.UserRole, [key, CommandName]
) # add here the toolbar name as hidden data
IsInList = False
for k in range(self.form.PanelSelected_CP.count()):
if (
self.form.PanelSelected_CP.item(k).text()