-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathFCBinding.py
2502 lines (2212 loc) · 113 KB
/
FCBinding.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# *************************************************************************
# * *
# * Copyright (c) 2019-2024 Hakan Seven, Geolta, 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
from pathlib import Path
from PySide.QtGui import (
QIcon,
QAction,
QPixmap,
QScrollEvent,
QKeyEvent,
QActionGroup,
QRegion,
QFont,
QColor,
QStyleHints,
QFontMetrics,
QTextOption,
QTextItem,
QPainter,
QKeySequence,
QShortcut,
)
from PySide.QtWidgets import (
QToolButton,
QToolBar,
QSizePolicy,
QDockWidget,
QWidget,
QMenuBar,
QMenu,
QMainWindow,
QLayout,
QSpacerItem,
QLayoutItem,
QGridLayout,
QScrollArea,
QTabBar,
QWidgetAction,
QStylePainter,
QStyle,
QStyleOptionButton,
QPushButton,
QHBoxLayout,
QLabel,
QVBoxLayout,
QToolTip,
QWidgetItem,
)
from PySide.QtCore import (
Qt,
QTimer,
Signal,
QObject,
QMetaMethod,
SIGNAL,
QEvent,
QMetaObject,
QCoreApplication,
QSize,
Slot,
QRect,
)
from CustomWidgets import CustomControls
import json
import os
import sys
import webbrowser
import LoadDesign_Ribbon
import Parameters_Ribbon
import LoadSettings_Ribbon
import LoadLicenseForm_Ribbon
import Standard_Functions_RIbbon as StandardFunctions
from Standard_Functions_RIbbon import CommandInfoCorrections
import Serialize_Ribbon
import StyleMapping
import platform
import math
# Get the resources
pathIcons = Parameters_Ribbon.ICON_LOCATION
pathStylSheets = Parameters_Ribbon.STYLESHEET_LOCATION
pathUI = Parameters_Ribbon.UI_LOCATION
pathScripts = os.path.join(os.path.dirname(__file__), "Scripts")
pathPackages = os.path.join(os.path.dirname(__file__), "Resources", "packages")
sys.path.append(pathIcons)
sys.path.append(pathStylSheets)
sys.path.append(pathUI)
sys.path.append(pathPackages)
translate = App.Qt.translate
import pyqtribbon_local as pyqtribbon
from pyqtribbon_local.ribbonbar import RibbonMenu, RibbonBar
from pyqtribbon_local.panel import RibbonPanel
from pyqtribbon_local.toolbutton import RibbonToolButton
from pyqtribbon_local.separator import RibbonSeparator
from pyqtribbon_local.category import RibbonCategoryLayoutButton
# import pyqtribbon_local as pyqtribbon
# from pyqtribbon.ribbonbar import RibbonMenu, RibbonBar
# from pyqtribbon.panel import RibbonPanel, RibbonPanelTitle
# from pyqtribbon.toolbutton import RibbonToolButton
# from pyqtribbon.separator import RibbonSeparator
# from pyqtribbon.category import RibbonCategoryLayoutButton
# Get the main window of FreeCAD
mw = Gui.getMainWindow()
# Define a timer
timer = QTimer()
class ModernMenu(RibbonBar):
"""
Create ModernMenu QWidget.
"""
# Define a placeholder for the repro adress
ReproAdress: str = ""
# Placeholders for building the ribbonbar
ribbonStructure = {}
wbNameMapping = {}
isWbLoaded = {}
MainWindowLoaded = False
LeaveEventEnabled = True
# use icon size from FreeCAD preferences
iconSize = Parameters_Ribbon.ICON_SIZE_SMALL
ApplicationButtonSize = Parameters_Ribbon.APP_ICON_SIZE
QuickAccessButtonSize = Parameters_Ribbon.QUICK_ICON_SIZE
# RightToolBarButtonSize = Parameters_Ribbon.RIGHT_ICON_SIZE # Is overruled
# TabBar_Size = Parameters_Ribbon.TABBAR_SIZE # Is overruled
LargeButtonSize = Parameters_Ribbon.ICON_SIZE_LARGE
# Define a placeholder for the ribbon height
RibbonHeight = 0
# Set a size factor for the buttons
sizeFactor = 1.3
# Create an offset for the panelheight
PanelHeightOffset = 36
# Create an offset for the whole ribbon height
RibbonOffset = 46 + QuickAccessButtonSize # Set to zero to hide the panel titles
# Set the minimum height for the ribbon
RibbonMinimalHeight = QuickAccessButtonSize + 10
# From v1.6.x, the size of tab bar and right toolbar are controlled by the size of the quickaccess toolbar
TabBar_Size = QuickAccessButtonSize
RightToolBarButtonSize = QuickAccessButtonSize
# Declare the right padding for dropdown menus
PaddingRight = 10
# Create the list for the commands
List_Commands = []
# Create the lists for the deserialized icons
List_CommandIcons = []
List_WorkBenchIcons = []
# Declare the custom overlay function states
OverlayToggled = False
TransparancyToggled = False
RibbonMenu = QMenu()
HelpMenu = QMenu()
OverlayMenu = None
def __init__(self):
"""
Constructor
"""
super().__init__(title="", iconSize=self.iconSize)
self.setObjectName("Ribbon")
self.setWindowFlags(self.windowFlags() | Qt.Dialog)
# connect the signals
self.connectSignals()
# read ribbon structure from JSON file
with open(Parameters_Ribbon.RIBBON_STRUCTURE_JSON, "r") as file:
self.ribbonStructure.update(json.load(file))
file.close()
DataFile2 = os.path.join(os.path.dirname(__file__), "RibbonDataFile2.dat")
if os.path.exists(DataFile2) is True:
Data = {}
# read ribbon structure from JSON file
with open(DataFile2, "r") as file:
Data.update(json.load(file))
file.close()
try:
# Load the list of commands
self.List_Commands = Data["List_Commands"]
except Exception:
pass
# if FreeCAD is version 0.21 create a custom toolbar "Individual Views"
if int(App.Version()[0]) == 0 and int(App.Version()[1]) <= 21:
StandardFunctions.CreateToolbar(
Name="Individual views",
WorkBenchName="Global",
ButtonList=[
"Std_ViewIsometric",
"Std_ViewRight",
"Std_ViewLeft",
"Std_ViewFront",
"Std_ViewRear",
"Std_ViewTop",
"Std_ViewBottom",
],
)
if int(App.Version()[0]) == 1 and int(App.Version()[1]) >= 0:
StandardFunctions.RemoveWorkBenchToolbars(
Name="Individual views",
WorkBenchName="Global",
)
# Check there is a custom toolbar "views - ribbon". If so, remove it
if Parameters_Ribbon.Settings.GetBoolSetting("RibbonViewRemoved") is False:
StandardFunctions.RemoveWorkBenchToolbars(
Name="Views - Ribbon",
WorkBenchName="Global",
)
Parameters_Ribbon.Settings.SetBoolSetting("RibbonViewRemoved", True)
# Check there is a custom toolbar "Tools". If so, remove it
if Parameters_Ribbon.Settings.GetBoolSetting("ToolsRemoved") is False:
StandardFunctions.RemoveWorkBenchToolbars(
Name="Tools",
WorkBenchName="Global",
)
Parameters_Ribbon.Settings.SetBoolSetting("ToolsRemoved", True)
# Add a toolbar "Views - Ribbon"
#
PreferredToolbar = Parameters_Ribbon.Settings.GetIntSetting("Preferred_view")
# Create a key if not present
if PreferredToolbar == 2:
StandardFunctions.add_keys_nested_dict(
self.ribbonStructure,
["newPanels", "Global", "Views - Ribbon_newPanel"],
)
self.ribbonStructure["newPanels"]["Global"]["Views - Ribbon_newPanel"] = [
["Std_ViewGroup", "AssemblyWorkbench"],
["Std_ViewFitAll", "AssemblyWorkbench"],
["Std_ViewFitSelection", "AssemblyWorkbench"],
["Std_ViewZoomOut", "Global"],
["Std_ViewZoomIn", "Global"],
["Std_ViewBoxZoom", "Global"],
["Std_AlignToSelection", "AssemblyWorkbench"],
["Part_SelectFilter", "Global"],
]
else:
try:
if "Views - Ribbon_newPanel" in self.ribbonStructure["newPanels"]["Global"]:
del self.ribbonStructure["newPanels"]["Global"]["Views - Ribbon_newPanel"]
except Exception:
pass
# # Add a toolbar "tools"
#
UseToolsPanel = Parameters_Ribbon.Settings.GetBoolSetting("UseToolsPanel")
# Create a key if not present
try:
if "Tools_newPanel" not in self.ribbonStructure["newPanels"]["Global"] and UseToolsPanel is True:
StandardFunctions.add_keys_nested_dict(
self.ribbonStructure,
["newPanels", "Global", "Tools_newPanel"],
)
self.ribbonStructure["newPanels"]["Global"]["Tools_newPanel"] = [
["Std_Measure", "Global"],
["Std_UnitsCalculator", "Global"],
["Std_Properties", "Global"],
["Std_BoxElementSelection", "Global"],
["Std_BoxSelection", "Global"],
["Std_WhatsThis", "AssemblyWorkbench"],
]
except Exception:
pass
# Set the preferred toolbars
PreferredToolbar = Parameters_Ribbon.Settings.GetIntSetting("Preferred_view")
ListIgnoredToolbars: list = self.ribbonStructure["ignoredToolbars"]
# check if the toolbar is already ignored
View_Inlist = False
ViewsRibbon_Inlist = False
IndividualViews_Inlist = False
for ToolBar in ListIgnoredToolbars:
if ToolBar == "View":
View_Inlist = True
if ToolBar == "Views - Ribbon":
ViewsRibbon_Inlist = True
if ToolBar == "Individual views":
IndividualViews_Inlist = True
if PreferredToolbar == 0:
if View_Inlist is False:
ListIgnoredToolbars.append("View")
if ViewsRibbon_Inlist is False:
ListIgnoredToolbars.append("Views - Ribbon")
if "Individual views" in ListIgnoredToolbars:
ListIgnoredToolbars.remove("Individual views")
if PreferredToolbar == 1:
if IndividualViews_Inlist is False:
ListIgnoredToolbars.append("Individual views")
if ViewsRibbon_Inlist is False:
ListIgnoredToolbars.append("Views - Ribbon")
if "View" in ListIgnoredToolbars:
ListIgnoredToolbars.remove("View")
if PreferredToolbar == 2:
if IndividualViews_Inlist is False:
ListIgnoredToolbars.append("Individual views")
if View_Inlist is False:
ListIgnoredToolbars.append("View")
if "Views - Ribbon" in ListIgnoredToolbars:
ListIgnoredToolbars.remove("Views - Ribbon")
if PreferredToolbar == 3:
if IndividualViews_Inlist is False:
ListIgnoredToolbars.append("Individual views")
if View_Inlist is False:
ListIgnoredToolbars.append("View")
if ViewsRibbon_Inlist is False:
ListIgnoredToolbars.append("Views - Ribbon")
self.ribbonStructure["ignoredToolbars"] = ListIgnoredToolbars
# write the change to the json file
# Writing to sample.json
with open(Parameters_Ribbon.RIBBON_STRUCTURE_JSON, "w") as outfile:
json.dump(self.ribbonStructure, outfile, indent=4)
outfile.close()
# 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")
if self.ReproAdress != "" or self.ReproAdress is not None:
print(translate("FreeCAD Ribbon", "FreeCAD Ribbon: ") + self.ReproAdress)
# Set the icon size if parameters has none
Parameters_Ribbon.Settings.WriteSettings()
# Activate the workbenches used in the new panels otherwise the panel stays empty
try:
if "newPanels" in self.ribbonStructure:
for WorkBenchName in self.ribbonStructure["newPanels"]:
for NewPanel in self.ribbonStructure["newPanels"][WorkBenchName]:
# Get the commands from the custom panel
Commands = self.ribbonStructure["newPanels"][WorkBenchName][NewPanel]
# Get the command and its original toolbar
for CommandItem in Commands:
if CommandItem[1] != "General" and CommandItem[1] != "Global":
# Activate the workbench if not loaded
Gui.activateWorkbench(CommandItem[1])
except Exception as e:
if Parameters_Ribbon.DEBUG_MODE is True:
StandardFunctions.Print(
f"new panels have wrong format. Please create them again!\n{e}",
"Error",
)
pass
# Activate the workbenches used in the dropdown buttons otherwise the button stays empty
try:
if "dropdownButtons" in self.ribbonStructure:
for DropDownCommand, Commands in self.ribbonStructure["dropdownButtons"].items():
for CommandItem in Commands:
if CommandItem[1] != "General" and CommandItem[1] != "Global":
# Activate the workbench if not loaded
Gui.activateWorkbench(CommandItem[1])
except Exception as e:
if Parameters_Ribbon.DEBUG_MODE is True:
StandardFunctions.Print(
f"dropdownbuttons have wrong format. Please create them again!\n{e}",
"Warning",
)
pass
# Create the ribbon
self.CreateMenus() # Create the menus
self.createModernMenu() # Create the ribbon
self.onUserChangedWorkbench(False) # Set the dockwidget and ribbonheight as done after changing from workbench
# Set the custom stylesheet
StyleSheet = Path(Parameters_Ribbon.STYLESHEET).read_text()
# modify the stylesheet to set the border and background for a toolbar and menu
hexColor = StyleMapping.ReturnStyleItem("Background_Color")
hexColorTab = StyleMapping.ReturnStyleItem("Background_Color", True, True)
if hexColor is not None and hexColor != "" and Parameters_Ribbon.BUTTON_BACKGROUND_ENABLED is True:
# Set the quickaccess toolbar background color. This fixes a transparant toolbar.
self.quickAccessToolBar().setStyleSheet("QToolBar {background: " + hexColor + ";}")
self.tabBar().setStyleSheet("background: " + hexColorTab + ";")
# Set the background color. This fixes transparant backgrounds when FreeCAD has no stylesheet
StyleSheet_Addition = "\n\nQToolButton {background: solid " + hexColor + ";}"
StyleSheet_Addition_2 = (
"\n\nRibbonBar {border: none;background: solid " + hexColor + ";color: " + hexColor + ";}"
)
StyleSheet = StyleSheet_Addition_2 + StyleSheet + StyleSheet_Addition
self.setStyleSheet(StyleSheet)
# If the text for the tabs is set to be disabled, update the stylesheet
if Parameters_Ribbon.TABBAR_STYLE == 1:
StyleSheet_Addition_3 = (
"""QTabBar::tab {
background: """
+ StyleMapping.ReturnStyleItem("Background_Color_Hover", True, True)
+ """;color: """
+ StyleMapping.ReturnStyleItem("Background_Color_Hover", True, True)
+ """;min-width: """
+ str(self.TabBar_Size)
+ """px;
max-width: """
+ str(self.TabBar_Size)
+ """px;
padding-left: 6px;
padding-right: 0px;
margin: 3px
}"""
)
StyleSheet = StyleSheet_Addition_3 + StyleSheet
self.setStyleSheet(StyleSheet)
# Add an addition for selected tabs
StyleSheet_Addition_4 = (
"""QTabBar::tab:selected, QTabBar::tab:hover {
background: """
+ StyleMapping.ReturnStyleItem("Background_Color_Hover")
+ """;}"""
)
# If the tabs are set to icon only, set the text to the hover background color also
if Parameters_Ribbon.TABBAR_STYLE == 1:
StyleSheet_Addition_4 = (
"""QTabBar::tab:selected, QTabBar::tab:hover {
background: """
+ StyleMapping.ReturnStyleItem("Background_Color_Hover")
+ """;color: """
+ StyleMapping.ReturnStyleItem("Background_Color_Hover")
+ """;}"""
)
StyleSheet = StyleSheet_Addition_4 + StyleSheet
self.setStyleSheet(StyleSheet)
# Add an addition for Font sizes
StyleSheet_Addition_5 = """
QWidgetItem,
QMenu, QMenu::item,
QAction,
RibbonApplicationButton,
RibbonMenu,
RibbonMenu::item,
RibbonPanelTitle,
RibbonToolButton::item,
QToolButton, QToolButton::menu,
QLabel,
QTextEdit,
SearchBoxLight
{ font-size:11px;}
QTabBar {font-size:14px;}"""
StyleSheet = StyleSheet_Addition_5 + StyleSheet
self.setStyleSheet(StyleSheet)
# get the state of the mainwindow
self.MainWindowLoaded = True
# Set these settings and connections at init
# Set the autohide behavior of the ribbon
preferences = App.ParamGet("User parameter:BaseApp/Preferences/DockWindows")
if preferences.GetBool("ActivateOverlay") is True:
Parameters_Ribbon.AUTOHIDE_RIBBON = False
self.setAutoHideRibbon(Parameters_Ribbon.AUTOHIDE_RIBBON)
# Remove the collapseble button
RightToolbar = self.rightToolBar()
RightToolbar.removeAction(RightToolbar.actions()[0])
# make sure that the ribbon cannot "disappear"
self.setMinimumHeight(self.RibbonMinimalHeight)
self.setSizeIncrement(1, 1)
# Set the menuBar hidden as standard
mw.menuBar().hide()
if self.isEnabled() is False:
mw.menuBar().show()
# connect a tabbar click event to the tarbar click funtion
# this used to replaced the native functions
self.tabBar().tabBarClicked.connect(self.onTabBarClicked)
# override the default scroll behavior with a custom function
self.tabBar().wheelEvent = lambda event_tabBar: self.wheelEvent_TabBar(event_tabBar)
self.wheelEvent = lambda event_CC: self.wheelEvent_CC(event_CC)
self.tabBar().setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.currentCategory().setFocusPolicy(Qt.FocusPolicy.StrongFocus)
# Customize the tabBar. Has only to be done once
# The scrollbuttons for the ribbon are set per ribbon tab
# So they are set in self.BuildPanels()
#
# Set the scroll buttons on the tabbar
ScrollLeftButton_Tab: QToolButton = self.tabBar().findChildren(QToolButton)[0]
ScrollRightButton_Tab: QToolButton = self.tabBar().findChildren(QToolButton)[1]
# get the icons
ScrollLeftButton_Tab_Icon = StyleMapping.ReturnStyleItem("ScrollLeftButton_Tab")
ScrollRightButton_Tab_Icon = StyleMapping.ReturnStyleItem("ScrollRightButton_Tab")
# Set the icons
StyleSheet = "QToolButton {image: none};QToolButton::arrow {image: none};"
BackgroundColor = StyleMapping.ReturnStyleItem("Background_Color")
if int(App.Version()[0]) == 0 and int(App.Version()[1]) <= 21 and BackgroundColor is not None:
StyleSheet = (
"""QToolButton {image: none;background: """
+ BackgroundColor
+ """};QToolButton::arrow {image: none};"""
)
if ScrollLeftButton_Tab_Icon is not None:
ScrollLeftButton_Tab.setStyleSheet(StyleSheet)
ScrollLeftButton_Tab.setIcon(ScrollLeftButton_Tab_Icon)
else:
ScrollRightButton_Tab.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextOnly)
if ScrollRightButton_Tab_Icon is not None:
ScrollRightButton_Tab.setStyleSheet(StyleSheet)
ScrollRightButton_Tab.setIcon(ScrollRightButton_Tab_Icon)
else:
ScrollRightButton_Tab.setArrowType(Qt.ArrowType.RightArrow)
# Add a custom close event to show the original menubar again
self.closeEvent = lambda close: self.closeEvent(close)
# Remove persistant toolbars
PersistentToolbars = App.ParamGet("User parameter:Tux/PersistentToolbars/User").GetGroups()
for Group in PersistentToolbars:
Parameter = App.ParamGet("User parameter:Tux/PersistentToolbars/User/" + Group)
Parameter.SetString("Top", "")
Parameter.SetString("Left", "")
Parameter.SetString("Right", "")
Parameter.SetString("Bottom", "")
# Connect shortcuts
#
# Application menu
KeyCombination = Parameters_Ribbon.SHORTCUT_APPLICATION
self.ShortCutApp = QShortcut(QKeySequence(KeyCombination), self)
self.ShortCutApp.activated.connect(self.ToggleApplicationButton)
# ToolTip = self.applicationOptionButton().toolTip()
ToolTip = f"{KeyCombination}"
self.applicationOptionButton().setToolTip(ToolTip)
return
def closeEvent(self, event):
if self.isEnabled() is False:
mw.menuBar().show()
return True
def eventFilter(self, obj, event):
if int(App.Version()[0]) > 1:
if event.type() == QEvent.Type.HoverMove:
# swallow events
# print("Event swallowed")
event.ignore()
return False
else:
# bubble events
return True
else:
return True
def enterEvent(self, QEvent):
# In FreeCAD 1.0, Overlays are introduced. These have also an enterEvent which results in strange behavior
# Therefore this function is only activated on older versions of FreeCAD.
if (
int(App.Version()[0]) == 0
and int(App.Version()[1]) <= 21
and Parameters_Ribbon.Settings.GetBoolSetting("ShowOnHover") is True
):
TB: QDockWidget = mw.findChildren(QDockWidget, "Ribbon")[0]
if self.RibbonHeight > 0:
TB.setFixedHeight(self.RibbonHeight)
self.setRibbonHeight(self.RibbonHeight)
# Make sure that the ribbon remains visible
self.setRibbonVisible(True)
return
def leaveEvent(self, QEvent):
if self.LeaveEventEnabled is True:
TB: QDockWidget = mw.findChildren(QDockWidget, "Ribbon")[0]
if Parameters_Ribbon.AUTOHIDE_RIBBON is True:
TB.setMinimumHeight(self.RibbonMinimalHeight)
TB.setMaximumHeight(self.RibbonMinimalHeight)
# Make sure that the ribbon remains visible
self.setRibbonVisible(True)
pass
# implementation to add actions to the Filemenu. Needed for the accessories menu
def addAction(self, action: QAction):
menu = self.findChild(RibbonMenu, "Ribbon")
if menu is None:
menu = self.addFileMenu()
menu.addAction(action)
return
# used to scroll a ribbon horizontally, when it's wider than the screen
def wheelEvent_CC(self, event):
if self.currentCategory().underMouse():
x = 0
# Get the scroll value (1 or -1)
delta = event.angleDelta().y()
x += delta and delta // abs(delta)
NoClicks = Parameters_Ribbon.Settings.GetIntSetting("Ribbon_Scroll")
if NoClicks == 0 or NoClicks is None:
NoClicks = 1
# go back or forward based on x.
if x == 1:
for i in range(NoClicks):
self.currentCategory().scrollPrevious()
if x == -1:
for i in range(NoClicks):
self.currentCategory().scrollNext()
return
# used to scroll the tabbar horizontally, when it's wider than the screen
def wheelEvent_TabBar(self, event):
if self.tabBar().underMouse():
x = 0
# Get the scroll value (1 or -1)
delta = event.angleDelta().y()
x += delta and delta // abs(delta)
ScrollButtons_Tab = self.tabBar().children()
ScrollLeftButton_Tab: QToolButton = ScrollButtons_Tab[0]
ScrollRightButton_Tab: QToolButton = ScrollButtons_Tab[1]
NoClicks = Parameters_Ribbon.Settings.GetIntSetting("TabBar_Scroll")
if NoClicks == 0 or NoClicks is None:
NoClicks = 1
# go back or forward based on x.
if x == 1:
for i in range(NoClicks):
ScrollLeftButton_Tab.click()
if x == -1:
for i in range(NoClicks):
ScrollRightButton_Tab.click()
return
def connectSignals(self):
self.tabBar().currentChanged.connect(self.onUserChangedWorkbench)
mw.workbenchActivated.connect(self.onWbActivated)
return
def disconnectSignals(self):
self.tabBar().currentChanged.disconnect(self.onUserChangedWorkbench)
mw.workbenchActivated.disconnect(self.onWbActivated)
return
def createModernMenu(self):
"""
Create menu tabs.
"""
# Define a label for the menu
Text = QLabel()
Text.setText(translate("FreeCAD Ribbon", "Menu"))
# Get its metrics
FontMetrics = QFontMetrics(Text.font())
# Define a layout and add the label
Layout = QHBoxLayout()
Layout.addWidget(Text, 0, Qt.AlignmentFlag.AlignRight)
Layout.setContentsMargins(0, 0, 0, 0)
# Add the layout to the menu button
self.applicationOptionButton().setLayout(Layout)
self.applicationOptionButton().setContentsMargins(0, 0, 9, 0)
# Set the size of the menu button
self.applicationOptionButton().setFixedSize(
self.QuickAccessButtonSize + FontMetrics.boundingRect(Text.text()).width() + 12,
self.QuickAccessButtonSize,
)
# Set the icon
self.setApplicationIcon(Gui.getIcon("freecad"))
# Set the styling of the button including padding (Text widht + 2*maring)
self.applicationOptionButton().setStyleSheet(
StyleMapping.ReturnStyleSheet(
"applicationbutton",
padding_right=str(FontMetrics.horizontalAdvance(Text.text(), -1) + 12) + "px",
radius="4px",
)
)
# Add the default tooltip
self.applicationOptionButton().setToolTip(translate("FreeCAD Ribbon", "FreeCAD Ribbon"))
# add the menus from the menubar to the application button
self.ApplicationMenus()
# add quick access buttons
i = 1 # Start value for button count. Used for width of quickaccess toolbar
toolBarWidth = ((self.QuickAccessButtonSize * self.sizeFactor) * i) + self.applicationOptionButton().width()
for commandName in self.ribbonStructure["quickAccessCommands"]:
i = i + 1
# Define a width
width = 0
# Define a button
button = QToolButton()
# set the default padding to zero
padding = 0
try:
# If it is a standard freecad button, set the command accordingly
if commandName.endswith("_ddb") is False:
try:
# Check if the workbench is loaded. If not, actions will be an empty list
# Find the command its workbench and activate it
QuickAction = Gui.Command.get(commandName).getAction()
if len(QuickAction) == 0:
for CommandItem in self.List_Commands:
if CommandItem[0] == commandName:
Gui.activateWorkbench(CommandItem[3])
break
except Exception:
pass
QuickAction = Gui.Command.get(commandName).getAction()
if len(QuickAction) == 1:
button.setDefaultAction(QuickAction[0])
width = self.QuickAccessButtonSize
height = self.QuickAccessButtonSize
button.setFixedSize(width, height)
# Set the stylesheet
button.setStyleSheet(StyleMapping.ReturnStyleSheet("toolbutton", "2px", f"{padding}px"))
elif len(QuickAction) > 1:
# set the padding for a dropdown button
padding = self.PaddingRight
button.addActions(QuickAction)
button.setDefaultAction(QuickAction[0])
# Set the width and height
width = self.QuickAccessButtonSize + padding
height = self.QuickAccessButtonSize
button.setFixedSize(width, height)
# Set the PopupMode
button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
# Set the stylesheet
button.setStyleSheet(StyleMapping.ReturnStyleSheet("toolbutton", "2px", f"{padding}px"))
# If it is a custom dropdown, add the actions one by one.
if commandName.endswith("_ddb") is True:
# set the padding for a dropdown button
padding = self.PaddingRight
# Get the actions and add them one by one
QuickAction = self.returnCustomDropDown(commandName)
for action in QuickAction:
button.addAction(action[0])
# Set the default action
button.setDefaultAction(button.actions()[0])
# Set the width and height
width = self.QuickAccessButtonSize + padding
height = self.QuickAccessButtonSize
button.setFixedSize(width, height)
# Set the PopupMode
button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
# Set the stylesheet
button.setStyleSheet(StyleMapping.ReturnStyleSheet("toolbutton", "2px", f"{padding}px"))
# Set the height
self.setQuickAccessButtonHeight(self.RibbonMinimalHeight)
button.setContentsMargins(3, 3, 3, 3)
# Add the button to the quickaccess toolbar
if len(button.actions()) > 0:
self.addQuickAccessButton(button)
else:
StandardFunctions.Print(f"{commandName} did not contain any actions!", "Log")
toolBarWidth = toolBarWidth + width
except Exception as e:
if Parameters_Ribbon.DEBUG_MODE is True:
StandardFunctions.Print(f"{commandName}, {e}", "Warning")
# raise (e)
continue
self.quickAccessToolBar().show()
# Set the height of the quickaccess toolbar
self.quickAccessToolBar().setMinimumHeight(self.QuickAccessButtonSize)
# Set the width of the quickaccess toolbar.
self.quickAccessToolBar().setMinimumWidth(toolBarWidth)
# Set the size policy
self.quickAccessToolBar().setSizePolicy(
QSizePolicy.Policy.MinimumExpanding, QSizePolicy.Policy.MinimumExpanding
)
# needed for excluding from hiding toolbars
self.quickAccessToolBar().setObjectName("quickAccessToolBar")
self.quickAccessToolBar().setWindowTitle("quickAccessToolBar")
# Set the tabbar height and textsize
self.tabBar().setContentsMargins(0, 0, 0, 0)
font = self.tabBar().font()
font.setPixelSize(14)
self.tabBar().setFont(font)
self.tabBar().setIconSize(QSize(self.TabBar_Size - 6, self.TabBar_Size - 6))
self.tabBar().setStyleSheet("margin: 0px;padding: 0px;height: " + str(self.QuickAccessButtonSize) + ";")
# self.RibbonOffset = self.RibbonOffset + (self.tabBar().height() - self.QuickAccessButtonSize)
# Correct colors when no stylesheet is selected for FreeCAD.
self.quickAccessToolBar().setStyleSheet("")
if Parameters_Ribbon.BUTTON_BACKGROUND_ENABLED is True:
FreeCAD_preferences = App.ParamGet("User parameter:BaseApp/Preferences/MainWindow")
currentStyleSheet = FreeCAD_preferences.GetString("StyleSheet")
if currentStyleSheet == "":
hexColor = StyleMapping.ReturnStyleItem("Background_Color")
# Set the quickaccess toolbar background color
self.quickAccessToolBar().setStyleSheet("background-color: " + hexColor + ";")
# Get the order of workbenches from Parameters
WorkbenchOrderedList: list = Parameters_Ribbon.TAB_ORDER.split(",")
# Check if there are workbenches that are not in the orderlist
IsInList = False
for InstalledWB in Gui.listWorkbenches():
for i in range(len(WorkbenchOrderedList)):
if WorkbenchOrderedList[i] == InstalledWB:
IsInList = True
if IsInList is False:
WorkbenchOrderedList.append(InstalledWB)
IsInList = False
# There is an issue with the internal assembly wb showing the wrong panel
# when assembly4 wb is installed and positioned for the internal assembly wb
for i in range(len(WorkbenchOrderedList)):
if WorkbenchOrderedList[i] == "Assembly4Workbench" or WorkbenchOrderedList[i] == "Assembly3Workbench":
try:
index_1 = WorkbenchOrderedList.index(WorkbenchOrderedList[i])
index_2 = WorkbenchOrderedList.index("AssemblyWorkbench")
WorkbenchOrderedList.pop(index_2)
WorkbenchOrderedList.insert(index_1, "AssemblyWorkbench")
break
except Exception:
pass
param_string = ""
for i in range(len(WorkbenchOrderedList)):
if WorkbenchOrderedList[i] != "":
param_string = param_string + "," + WorkbenchOrderedList[i]
Parameters_Ribbon.Settings.SetStringSetting("TabOrder", param_string)
# add category for each workbench
for i in range(len(WorkbenchOrderedList)):
for workbenchName, workbench in list(Gui.listWorkbenches().items()):
if workbenchName == WorkbenchOrderedList[i]:
name = workbench.MenuText.replace("&", "")
if (
name != ""
and name not in self.ribbonStructure["ignoredWorkbenches"]
and name != "<none>"
and name is not None
):
self.wbNameMapping[name] = workbenchName
self.isWbLoaded[name] = False
# Set the title
self.addCategory(name)
# Set the tabbar according the style setting
if Parameters_Ribbon.TABBAR_STYLE <= 1:
# set tab icon
icon: QIcon = self.ReturnWorkbenchIcon(workbenchName)
self.tabBar().setTabIcon(len(self.categories()) - 1, icon)
if Parameters_Ribbon.TABBAR_STYLE == 2:
self.tabBar().setTabIcon(len(self.categories()) - 1, QIcon())
# Set the tab data
self.tabBar().setTabData(len(self.categories()) - 1, workbenchName)
# Set the tooltip
MenuText = workbench.MenuText
ToolTipText = workbench.ToolTip
if (
ToolTipText.lower() != MenuText.lower() + " workbench"
and MenuText.lower() != ToolTipText.lower()
):
MenuText = f"<b>{workbench.MenuText}</b><br>{workbench.ToolTip}"
else:
MenuText = f"<b>{MenuText}<b>"
self.tabBar().setTabToolTip(len(self.categories()) - 1, MenuText)
# Set the size of the collapseRibbonButton
self.collapseRibbonButton().setFixedSize(self.RightToolBarButtonSize, self.RightToolBarButtonSize)
# add the searchbar if available
SearchBarWidth = self.AddSearchBar()
# add an overlay menu if Ribbon's overlay is enabled
if self.OverlayMenu is not None:
OverlayMenu = QToolButton()
OverlayMenu.setIcon(QIcon(QPixmap(os.path.join(pathIcons, "Draft_Layer.svg"))))
OverlayMenu.setToolTip(translate("FreeCAD Ribbon", "Overlay functions") + "...")
OverlayMenu.setMenu(self.OverlayMenu)
OverlayMenu.setFixedSize(self.RightToolBarButtonSize + 12, self.RightToolBarButtonSize)
OverlayMenu.setStyleSheet(StyleMapping.ReturnStyleSheet(control="toolbutton", padding_right="12px"))
OverlayMenu.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
# add the settingsmenu to the right toolbar
self.rightToolBar().addWidget(OverlayMenu)
# add a settings button with menu
SettingsMenu = QToolButton()
# Get the freecad preference button
editMenu = mw.findChildren(QMenu, "&Edit")[0]
preferenceButton_FreeCAD = editMenu.actions()[len(editMenu.actions()) - 1]
# preferenceButton_FreeCAD.setText(translate("FreeCAD Ribbon", "FreeCAD prefences"))
# add the preference button for FreeCAD
SettingsMenu.addAction(preferenceButton_FreeCAD)
# add the ribbon settings menu
SettingsMenu.addAction(self.RibbonMenu.menuAction())
SettingsMenu.setIcon(Gui.getIcon("Std_DlgParameter.svg"))
SettingsMenu.setToolTip(translate("FreeCAD Ribbon", "Preferences") + "...")
SettingsMenu.setFixedSize(self.RightToolBarButtonSize + 12, self.RightToolBarButtonSize)
SettingsMenu.setStyleSheet(StyleMapping.ReturnStyleSheet(control="toolbutton", padding_right="12px"))
SettingsMenu.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
# add the settingsmenu to the right toolbar
self.rightToolBar().addWidget(SettingsMenu)
# Set the helpbutton
self.helpRibbonButton().setEnabled(True)
self.helpRibbonButton().setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.helpRibbonButton().setToolTip(translate("FreeCAD Ribbon", "Help") + "...")
# Get the default help action from FreeCAD
helpMenu = mw.findChildren(QMenu, "&Help")[0]
helpAction = helpMenu.actions()[0]
self.helpRibbonButton().setIcon(helpAction.icon())
self.helpRibbonButton().setMenu(self.HelpMenu)
self.helpRibbonButton().setFixedSize(self.RightToolBarButtonSize + 12, self.RightToolBarButtonSize)
self.helpRibbonButton().setStyleSheet(StyleMapping.ReturnStyleSheet(control="toolbutton", padding_right="12px"))
self.helpRibbonButton().setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
# Add a button the enable or disable AutoHide
pinButton = QToolButton()
pinButton.setCheckable(True)
pinButton.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
pinButton.setFixedSize(self.RightToolBarButtonSize, self.RightToolBarButtonSize)
pinButton.setIconSize(QSize(self.RightToolBarButtonSize, self.RightToolBarButtonSize))
# Set the correct icon
if Parameters_Ribbon.AUTOHIDE_RIBBON is True:
pinButtonIcon = StyleMapping.ReturnStyleItem("PinButton_closed")
if Parameters_Ribbon.AUTOHIDE_RIBBON is False:
pinButtonIcon = StyleMapping.ReturnStyleItem("PinButton_open")
# Set the icon
if pinButtonIcon is not None:
pinButton.setIcon(pinButtonIcon)
# Set the text and objectname
pinButton.setText(translate("FreeCAD Ribbon", "Pin Ribbon"))
pinButton.setObjectName("Pin Ribbon")
# Set the tooltip
pinButton.setToolTip(translate("FreeCAD Ribbon", "Click to toggle the autohide function on or off"))
# Set the correct checkstate
if Parameters_Ribbon.AUTOHIDE_RIBBON is True:
pinButton.setChecked(False)
if Parameters_Ribbon.AUTOHIDE_RIBBON is False:
pinButton.setChecked(True)
pinButton.setStyleSheet(StyleMapping.ReturnStyleSheet("toolbutton", "2px"))
# If FreeCAD's overlay function is active, set the pinbutton to checked and then to disabled
preferences = App.ParamGet("User parameter:BaseApp/Preferences/DockWindows")
if preferences.GetBool("ActivateOverlay") is True:
pinButton.setChecked(True)
pinButton.setDisabled(True)
else:
pinButton.clicked.connect(self.onPinClicked)
self.rightToolBar().addWidget(pinButton)
# Set the width of the right toolbar
RightToolbarWidth = SearchBarWidth + 3 * (self.RightToolBarButtonSize + 16) + self.RightToolBarButtonSize
if Parameters_Ribbon.USE_FC_OVERLAY is True:
RightToolbarWidth = SearchBarWidth + 2 * (self.RightToolBarButtonSize + 16)
self.rightToolBar().setMinimumWidth(RightToolbarWidth)
# Set the size policy