forked from APEbbers/FreeCAD-Ribbon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFCBinding.py
More file actions
5919 lines (5359 loc) · 274 KB
/
FCBinding.py
File metadata and controls
5919 lines (5359 loc) · 274 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 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 CustomWidgets
import FreeCAD as App
import FreeCADGui as Gui
from pathlib import Path
from PySide.QtGui import (
QDragEnterEvent,
QDragLeaveEvent,
QDragMoveEvent,
QDropEvent,
QIcon,
QAction,
QPixmap,
QScrollEvent,
QKeyEvent,
QActionGroup,
QRegion,
QFont,
QColor,
QStyleHints,
QFontMetrics,
QTextOption,
QTextItem,
QPainter,
QKeySequence,
QShortcut,
QCursor,
QGuiApplication,
QDrag,
)
from PySide.QtWidgets import (
QCheckBox,
QFrame,
QLineEdit,
QSpinBox,
QTextEdit,
QToolButton,
QToolBar,
QSizePolicy,
QDockWidget,
QWidget,
QMenuBar,
QMenu,
QMainWindow,
QLayout,
QSpacerItem,
QLayoutItem,
QGridLayout,
QScrollArea,
QTabBar,
QWidgetAction,
QStylePainter,
QStyle,
QStyleOptionButton,
QPushButton,
QHBoxLayout,
QLabel,
QVBoxLayout,
QToolTip,
QWidgetItem,
QTreeWidget,
QApplication,
QStatusBar,
QStyleOption,
QDialog,
)
from PySide.QtCore import (
Qt,
QTimer,
Signal,
QObject,
QMetaMethod,
SIGNAL,
QEvent,
QMetaObject,
QCoreApplication,
QSize,
Slot,
QRect,
QPoint,
QSettings,
QSignalBlocker,
QMimeData,
)
from CustomWidgets import CustomControls, DragTargetIndicator, Toggle, ToggleAction, CheckBoxAction, SpinBoxAction, ComboBoxAction, CustomSeparator
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 Standard_Functions_Ribbon
import StyleMapping_Ribbon
import platform
from datetime import datetime
import shutil
# import Ribbon. This contains the ribbon commands for FreeCAD
import Ribbon
# 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")
pathBackup = Parameters_Ribbon.BACKUP_LOCATION
sys.path.append(pathIcons)
sys.path.append(pathStylSheets)
sys.path.append(pathUI)
sys.path.append(pathPackages)
sys.path.append(pathBackup)
translate = App.Qt.translate
import pyqtribbon_local as pyqtribbon
from pyqtribbon_local.ribbonbar import RibbonMenu, RibbonBar, RibbonTitleWidget
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 main window of FreeCAD
mw: QMainWindow = Gui.getMainWindow()
# Define a timer
timer = QTimer()
# Write all settings, if they are not present yet
Parameters_Ribbon.Settings.WriteSettings()
class ModernMenu(RibbonBar):
"""
Create ModernMenu QWidget.
"""
# region - class parameters
# Add workbenches that need to be loaded first or early here
WBtoLoadFirst = ["BillOfMaterialsWB"]
# The datafile version is set in LoadDesign.py
DataFileVersion = LoadDesign_Ribbon.LoadDialog.DataFileVersion
# Define a placeholder for the repro adress
ReproAdress: str = ""
HelpAdress: 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 = 26
# Create an offset for the whole ribbon height
RibbonOffset = (
20 + QuickAccessButtonSize * 2
) # Set to zero to hide the panel titles
# Set the minimum height for the ribbon
RibbonMinimalHeight = QuickAccessButtonSize * 2 + 16
# 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
# Declare the spacing between buttons
ButtonSpacing = 6
# Declare the alignment of the buttons
ButtonAlignment = Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
# Declare the top and bottom margin for the tabbar (category)
TopMargin = 3
BottomMargin = 0
# Create the lists and ditcs for the lists in the ribbon structure,
ignoredToolbars = []
iconOnlyToolbars = []
quickAccessCommands = []
ignoredWorkbenches = []
customToolbars = {}
dropdownButtons = {}
newPanels = {}
# 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
OverlayToggled_Left = False
OverlayToggled_Right = False
OverlayToggled_Bottom = False
TransparancyToggled = False
# Define the menus
RibbonMenu = QMenu()
HelpMenu = QMenu()
OverlayMenu = None
AccessoriesMenu = None
# Define the versions for update and developments
UpdateVersion = ""
DeveloperVersion = ""
# Define a boolan to detect if an menu is entered.
# used to keep the ribbon unfolded, when clicking on a dropdown menu
MenuEntered = False
# Store a value when the ribbon is loaded
# used to hide the ribbon on startup
isLoaded = False
# Used for a message when a datafile update is needed.
LayoutMenuShortCut = ""
# Define a indictor for wether the design menu is loaded or not.
DesignMenuLoaded = False
# Define a indictor for wether beta functions are enabled
BetaFunctionsEnabled = False
# Define a indictor for wether the customize enviroment is enabled
CustomizeEnabled = False
# a action list for the right click event in the customize enviroment.
# Used to store the button states
actionList = []
# Create a dict for the active workbench only
workBenchDict = {}
# Create a empty context menu
contextMenu = None
# Create a holder for the last customized workbench
LastCustomized = []
# Create a list for panels that have a option button which have to be restored when exitiing the customisation enviroment
longPanels = []
# Create a list to store the pin buttons off each category
pinButtonList = []
# Create a dict to store the button states when entering the customization enviroment
ButtonState = {}
MaxRowsPerWB = {}
# endregion
def __init__(self):
"""
Constructor
"""
super().__init__(title="")
self.setObjectName("Ribbon")
# Enable dragdrop
self.setAcceptDrops(True)
self.tabBar().setAcceptDrops(True)
self._titleWidget.quickAccessToolBar().setAcceptDrops(True)
# 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()
if "ignoredToolbars" in self.ribbonStructure:
self.iconOnlyToolbars = self.ribbonStructure["ignoredToolbars"]
if "iconOnlyToolbars" in self.ribbonStructure:
self.iconOnlyToolbars = self.ribbonStructure["iconOnlyToolbars"]
if "quickAccessCommands" in self.ribbonStructure:
self.quickAccessCommands = self.ribbonStructure["quickAccessCommands"]
if "ignoredWorkbenches" in self.ribbonStructure:
self.ignoredWorkbenches = self.ribbonStructure["ignoredWorkbenches"]
if "customToolbars" in self.ribbonStructure:
self.customToolbars = self.ribbonStructure["customToolbars"]
if "dropdownButtons" in self.ribbonStructure:
self.dropdownButtons = self.ribbonStructure["dropdownButtons"]
if "newPanels" in self.ribbonStructure:
self.newPanels = self.ribbonStructure["newPanels"]
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 (
StandardFunctions.checkFreeCADVersion(
Parameters_Ribbon.FreeCAD_Version["mainVersion"],
Parameters_Ribbon.FreeCAD_Version["subVersion"],
Parameters_Ribbon.FreeCAD_Version["patchVersion"],
Parameters_Ribbon.FreeCAD_Version["gitVersion"],
)
is True
):
self.ConvertRibbonStructure()
# check the language and remove texts from the ribbonstructure if the language does not match
self.CheckLanguage()
# 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", "Standard"],
["Std_ViewFitAll", "Standard"],
["Std_ViewFitSelection", "Standard"],
["Std_ViewZoomOut", "Standard"],
["Std_ViewZoomIn", "Standard"],
["Std_ViewBoxZoom", "Standard"],
["Std_AlignToSelection", "Standard"],
["Part_SelectFilter", "Standard"],
]
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:
NeedsUpdating = False
if "Tools_newPanel" in self.ribbonStructure["newPanels"]["Global"]:
for item in self.ribbonStructure["newPanels"]["Global"][
"Tools_newPanel"
]:
if item[1] != "Standard":
NeedsUpdating = True
if (
"Tools_newPanel" not in self.ribbonStructure["newPanels"]["Global"]
and UseToolsPanel is True
) or NeedsUpdating is True:
StandardFunctions.add_keys_nested_dict(
self.ribbonStructure,
["newPanels", "Global", "Tools_newPanel"],
)
self.ribbonStructure["newPanels"]["Global"]["Tools_newPanel"] = [
["Std_Measure", "Standard"],
["Std_UnitsCalculator", "Standard"],
["Std_Properties", "Standard"],
["Std_BoxElementSelection", "Standard"],
["Std_BoxSelection", "Standard"],
["Std_WhatsThis", "Standard"],
]
except Exception:
pass
self.newPanels = self.ribbonStructure["newPanels"]
# 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
self.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"
)
LocalVersion = StandardFunctions.ReturnXML_Value(
PackageXML, "version",
)
if self.ReproAdress != "" or self.ReproAdress is not None:
print(translate("FreeCAD Ribbon", "Ribbon UI: ") + self.ReproAdress)
print(translate("FreeCAD Ribbon", "Ribbon UI: Installed version: ") + LocalVersion)
# Get the location of the help documentation
PackageXML = os.path.join(os.path.dirname(__file__), "package.xml")
self.HelpAdress = StandardFunctions.ReturnXML_Value(
PackageXML, "url", "type", "website"
)
# Activate the workbenches used in the new panels otherwise the panel stays empty
try:
for WorkBenchName in self.newPanels:
for NewPanel in self.newPanels[WorkBenchName]:
# Get the commands from the custom panel
Commands = self.newPanels[WorkBenchName][
NewPanel
]
# Get the command and its original toolbar
for CommandItem in Commands:
if (
CommandItem[1] != "General"
and CommandItem[1] != "Global"
and CommandItem[1] != "Standard"
):
# 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:
for DropDownCommand, Commands in self.dropdownButtons.items():
for CommandItem in Commands:
if (
CommandItem[1] != "General"
and CommandItem[1] != "Global"
and CommandItem[1] != "Standard"
):
# 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
# Check if there is a new version
# Get the latest version
try:
# User = "apebbers"
User = "APEbbers"
Repo = "FreeCAD-Ribbon"
Branch = "main"
File = "package.xml"
ElementName = "version"
attribKey = ""
attribValue = ""
# host: str ="https://codeberg.org"
host = "https://github.com"
LatestVersion = StandardFunctions.ReturnXML_Value_Git(
User=User, Repository=Repo, Branch=Branch, File=File, ElementName=ElementName, attribKey=attribKey, attribValue=attribValue, host=host
)
print(translate("FreeCAD Ribbon", "Ribbon UI: Latest released version: ") + str(LatestVersion))
# Get the current version
PackageXML = os.path.join(os.path.dirname(__file__), "package.xml")
CurrentVersion = StandardFunctions.ReturnXML_Value(
PackageXML, "version"
)
# Check if you are on a developer version. If so set developer version
if CurrentVersion.lower().endswith("x"):
self.DeveloperVersion = CurrentVersion
self.UpdateVersion = ""
# If you are not on a developer version, check if you have the latest version
if CurrentVersion.lower().endswith("x") is False:
if LatestVersion is not None:
# Create arrays from the versions
LatestVersionArray = LatestVersion.split(".")
CurrentVersionArray = CurrentVersion.split(".")
# Set the length to the shortest lenght
ArrayLenght = len(LatestVersionArray)
if len(CurrentVersionArray) < ArrayLenght:
ArrayLenght = len(CurrentVersionArray)
# Check per level if the latest version has the highest number
# if so set update version
for i in range(ArrayLenght):
if LatestVersionArray[i] > CurrentVersionArray[i]:
self.UpdateVersion = LatestVersion
except Exception as e:
raise e
pass
# Create the ribbon
self.CreateMenus() # Create the menus
self.createModernMenu() # Create the ribbon
# Set the custom stylesheet
self.StyleSheet = Path(Parameters_Ribbon.STYLESHEET).read_text()
# modify the stylesheet to set the border and background for a toolbar and menu
hexColor = StyleMapping_Ribbon.ReturnStyleItem("Background_Color")
hexColorTab = StyleMapping_Ribbon.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
+ ";}"
)
self.StyleSheet = StyleSheet_Addition_2 + self.StyleSheet + StyleSheet_Addition
self.setStyleSheet(self.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_Ribbon.ReturnStyleItem(
"Background_Color_Hover", True, True
)
+ """;color: """
+ StyleMapping_Ribbon.ReturnStyleItem(
"Background_Color_Hover", True, True
)
+ """;min-width: """
+ str(self.TabBar_Size-3)
+ """px;
max-width: """
+ str(self.TabBar_Size-3)
+ """px;
padding-left: 6px;
padding-right: 3px;
margin: 3px
}"""
)
self.StyleSheet = StyleSheet_Addition_3 + self.StyleSheet
self.setStyleSheet(self.StyleSheet)
self.StyleSheet = StyleSheet_Addition_3 + self.StyleSheet
self.setStyleSheet(self.StyleSheet)
# Add an addition for selected tabs
StyleSheet_Addition_4 = (
"""QTabBar::tab:selected, QTabBar::tab:hover {
background: """
+ StyleMapping_Ribbon.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_Ribbon.ReturnStyleItem("Background_Color_Hover")
+ """;color: """
+ StyleMapping_Ribbon.ReturnStyleItem("Background_Color_Hover")
+ """;}"""
)
self.StyleSheet = StyleSheet_Addition_4 + self.StyleSheet
self.setStyleSheet(self.StyleSheet)
# add a stylesheet entry for the fontsize for menus
StyleSheet_Addition_5 = (
"QMenu::item, QMenu::menuAction, QMenuBar::item, RibbonMenu, RibbonToolButton, RibbonMenu::item, QMenu>QLabel {font-size: "
+ str(Parameters_Ribbon.FONTSIZE_MENUS)
+ "px;}"
)
self.StyleSheet = self.StyleSheet + StyleSheet_Addition_5
self.setStyleSheet(self.StyleSheet)
# # Add a line at the bottom of the ribbon
# StyleSheet_Addition_6 = (
# """RibbonCategory {
# border-bottom: 0.5px solid"""
# + StyleMapping_Ribbon.ReturnStyleItem("Border_Color")
# + """;}"""
# )
# self.StyleSheet = self.StyleSheet + StyleSheet_Addition_6
# self.setStyleSheet(self.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_Ribbon.ReturnStyleItem(
"ScrollLeftButton_Tab"
)
ScrollRightButton_Tab_Icon = StyleMapping_Ribbon.ReturnStyleItem(
"ScrollRightButton_Tab"
)
# Set the icons
StyleSheet = "QToolButton {image: none;margin-top:6px;margin-bottom:6px;};QToolButton::arrow {image: none};"
BackgroundColor = StyleMapping_Ribbon.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;margin-top:6px;margin-bottom:6px;};"""
)
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)
# 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
ShortcutKey = "Alt+A"
try:
CustomShortCuts = App.ParamGet(
"User parameter:BaseApp/Preferences/Shortcut"
)
if "Ribbon_Menu" in CustomShortCuts.GetStrings():
ShortcutKey = CustomShortCuts.GetString("Ribbon_Menu")
except Exception:
pass
self.applicationOptionButton().setShortcut(ShortcutKey)
ToolTip = f"{ShortcutKey}"
self.applicationOptionButton().setToolTip(ToolTip)
# Add a custom close event to show the original menubar again
self.closeEvent = lambda close: self.closeEvent(close)
# Add a custom enter event to the tabbar
self.tabBar().enterEvent = lambda enter: self.enterEvent_Custom(enter)
# When hovering over the menu button, hide the ribbon
self.applicationOptionButton().enterEvent = lambda enter: self.leaveEvent(enter)
# Rearrange the tabbar and toolbars
if (
Parameters_Ribbon.TOOLBAR_POSITION == 0
or Parameters_Ribbon.TOOLBAR_POSITION == 1
):
# Get the widgets
_quickAccessToolBarWidget = self.quickAccessToolBar()
_titleLabel = self._titleWidget._titleLabel
_rightToolBar = self.rightToolBar()
_tabBar = self.tabBar()
# Remove the widgets
self._titleWidget._tabBarLayout.removeWidget(_quickAccessToolBarWidget)
self._titleWidget._tabBarLayout.removeWidget(_titleLabel)
self._titleWidget._tabBarLayout.removeWidget(_rightToolBar)
self._titleWidget._tabBarLayout.removeWidget(_tabBar)
if Parameters_Ribbon.TOOLBAR_POSITION == 0: # Toolbars above tabbar
# Set the font size for the label
font: QFont = _titleLabel.font()
font.setPixelSize(Parameters_Ribbon.FONTSIZE_MENUS + 1)
_titleLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
_titleLabel.setFont(font)
# Set the label text to FreeCAD's version
text = (
f"FreeCAD {App.Version()[0]}.{App.Version()[1]}.{App.Version()[2]}"
)
_titleLabel.setText(text)
# Create a spacer to set the tab
spacer = QWidget()
spacer.setSizePolicy(
QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Expanding
)
spacer.setFixedWidth(3)
self._titleWidget._tabBarLayout.setContentsMargins(3, 3, 3, 0)
self._titleWidget._tabBarLayout.addWidget(
_quickAccessToolBarWidget, 0, 0, 1, 2, Qt.AlignmentFlag.AlignVCenter
)
self._titleWidget._tabBarLayout.addWidget(
_titleLabel, 0, 2, 1, 1, Qt.AlignmentFlag.AlignVCenter
)
self._titleWidget._tabBarLayout.addWidget(
_rightToolBar, 0, 3, 1, 2, Qt.AlignmentFlag.AlignVCenter
)
self._titleWidget._tabBarLayout.addWidget(
spacer, 1, 0, 1, 1, Qt.AlignmentFlag.AlignVCenter
)
self._titleWidget._tabBarLayout.addWidget(
_tabBar, 1, 1, 1, 4, Qt.AlignmentFlag.AlignVCenter
)
# Change the offsets
self.RibbonMinimalHeight = self.QuickAccessButtonSize * 2 + 20
self.RibbonOffset = 50 + self.QuickAccessButtonSize * 2
self._titleWidget._tabBarLayout.setRowMinimumHeight(
0, self.QuickAccessButtonSize
)
self._titleWidget._tabBarLayout.setRowMinimumHeight(1, self.TabBar_Size)
# self.setTitle("FreeCAD")
if Parameters_Ribbon.TOOLBAR_POSITION == 1: # Toolbars inline with tabbar
# Add the widgets again in a different position
self._titleWidget._tabBarLayout.addWidget(
_quickAccessToolBarWidget, 0, 0, 1, 1, Qt.AlignmentFlag.AlignVCenter
)
self._titleWidget._tabBarLayout.addWidget(
_tabBar, 0, 1, 1, 1, Qt.AlignmentFlag.AlignVCenter
)
self._titleWidget._tabBarLayout.addWidget(
_titleLabel, 0, 2, 1, 1, Qt.AlignmentFlag.AlignVCenter
)
self._titleWidget._tabBarLayout.addWidget(
_rightToolBar, 0, 3, 1, 2, Qt.AlignmentFlag.AlignVCenter
)
# Change the offsets
self.RibbonMinimalHeight = self.QuickAccessButtonSize + 10
self.RibbonOffset = 42 + self.QuickAccessButtonSize
self._titleWidget._tabBarLayout.setRowMinimumHeight(
0, self.QuickAccessButtonSize
)
# Get the main window, its style, the ribbon and the restore button
try:
RestoreButton: QToolButton = self.rightToolBar().findChildren(
QToolButton, "RestoreButton"
)[0]
# If the mainwindow is maximized, set the window state to maximize and set the correct icon
if mw.isMaximized():
try:
RestoreButton.setIcon(
StyleMapping_Ribbon.ReturnStyleItem("TitleBarButtons")[2]
)
except Exception:
pass
# If the mainwindow is not maximized, set the window state to no state and set the correct icon
if mw.isMaximized() is False:
try:
RestoreButton.setIcon(
StyleMapping_Ribbon.ReturnStyleItem("TitleBarButtons")[1]
)
except Exception:
pass
except Exception:
pass
# Install an event filter to catch events from the main window and act on it.
mw.installEventFilter(EventInspector(mw))
# self.installEventFilter(RibbonEventInspector(self))
# Set isLoaded to True, to show that the loading is finished
self.isLoaded = True
# Fold the ribbon if unpinned
self.FoldRibbon()
# Check if an reload of the datafile is needed an show an message
self.CheckDataFile()
# Activate some WB's first to ensure proper loading of the panels
for Wb in self.WBtoLoadFirst:
try:
Gui.activateWorkbench(Wb)
except Exception:
pass
return
# region - Ribbon event fuctions
def closeEvent(self, event):
mw.menuBar().show()
return True
def eventFilter(self, obj, event):
# Disable the standard hover behavior
if event.type() == QEvent.Type.HoverMove:
event.ignore()
return False
return False
def enterEvent_Custom(self, QEvent):
# # Hide any possible toolbar
self.hideClassicToolbars()
TB: QDockWidget = mw.findChildren(QDockWidget, "Ribbon")[0]
TB.show()
# In FreeCAD 1.0, Overlays are introduced. These have also an enterEvent which results in strange behavior
# Therefore this function is only activated when FreeCAD's overlay function is disabled.
if (
Parameters_Ribbon.SHOW_ON_HOVER is True
and Parameters_Ribbon.USE_FC_OVERLAY is False
):
self.UnfoldRibbon()
return
def leaveEvent(self, QEvent):
if Parameters_Ribbon.AUTOHIDE_RIBBON is True and self.MenuEntered is False:
self.FoldRibbon()
# 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()