-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathStandard_Functions_RIbbon.py
740 lines (629 loc) · 22.9 KB
/
Standard_Functions_RIbbon.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
# *************************************************************************
# * *
# * 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
import math
# Define the translation
translate = App.Qt.translate
def Mbox(
text,
title="",
style=0,
IconType="Information",
default="",
stringList="[,]",
OnTop: bool = False,
):
"""
Message Styles:\n
0 : OK (text, title, style)\n
1 : Yes | No (text, title, style)\n
2 : Ok | Cancel (text, title, style)\n
20 : Inputbox (text, title, style, default)\n
21 : Inputbox with dropdown (text, title, style, default, stringlist)\n
Icontype: string: NoIcon, Question, Warning, Critical. Default Information
"""
from PySide.QtWidgets import QMessageBox, QInputDialog
from PySide.QtCore import Qt
from PySide import QtWidgets
Icon = QMessageBox.Information
if IconType == "NoIcon":
Icon = QMessageBox.NoIcon
if IconType == "Question":
Icon = QMessageBox.Question
if IconType == "Warning":
Icon = QMessageBox.Warning
if IconType == "Critical":
Icon = QMessageBox.Critical
if style == 0:
# Set the messagebox
msgBox = QMessageBox()
msgBox.setIcon(Icon)
msgBox.setText(text)
msgBox.setWindowTitle(title)
reply = msgBox.exec_()
if reply == QMessageBox.Ok:
return "ok"
if style == 1:
# Set the messagebox
msgBox = QMessageBox()
msgBox.setIcon(Icon)
msgBox.setText(text)
msgBox.setWindowTitle(title)
# Set the buttons and default button
msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msgBox.setDefaultButton(QMessageBox.No)
reply = msgBox.exec_()
if reply == QMessageBox.Yes:
return "yes"
if reply == QMessageBox.No:
return "no"
if style == 2:
# Set the messagebox
msgBox = QMessageBox()
msgBox.setIcon(Icon)
msgBox.setText(text)
msgBox.setWindowTitle(title)
# Set the buttons and default button
msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
msgBox.setDefaultButton(QMessageBox.Ok)
reply = msgBox.exec_()
if reply == QMessageBox.Ok:
return "ok"
if reply == QMessageBox.Cancel:
return "cancel"
if style == 20:
Dialog = QInputDialog()
reply = Dialog.getText(
None,
title,
text,
text=default,
)
if reply[1]:
# user clicked OK
replyText = reply[0]
else:
# user clicked Cancel
replyText = reply[0] # which will be "" if they clicked Cancel
return str(replyText)
if style == 21:
Dialog = QInputDialog()
reply = Dialog.getItem(
None,
title,
text,
stringList,
0,
True,
)
if reply[1]:
# user clicked OK
replyText = reply[0]
else:
# user clicked Cancel
replyText = reply[0] # which will be "" if they clicked Cancel
return str(replyText)
def RestartDialog(message="", includeIcons=False):
"""_summary_
shows a restart dialog
Returns:
string: returns 'yes' if restart now is clicked.
otherwise returns 'no'
"""
from PySide.QtWidgets import QMessageBox
# Save the preferences before restarting
App.saveParameter()
# Set the message
if message == "":
message = translate(
"FreeCAD Ribbon",
"You must restart FreeCAD for changes to take effect.",
)
# Set the messagebox
msgBox = QMessageBox()
msgBox.setIcon(QMessageBox.Warning)
msgBox.setText(message)
msgBox.setWindowTitle("FreeCAD Ribbon")
# Set the buttons and default button
msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msgBox.setDefaultButton(QMessageBox.No)
msgBox.button(QMessageBox.Yes).setText(translate("FreeCAD Ribbon", "Restart now"))
msgBox.button(QMessageBox.No).setText(translate("FreeCAD Ribbon", "Restart later"))
if includeIcons is True:
msgBox.button(QMessageBox.No).setIcon(Gui.getIcon("edit_Cancel.svg"))
msgBox.button(QMessageBox.Yes).setIcon(Gui.getIcon("edit_OK.svg"))
reply = msgBox.exec_()
if reply == QMessageBox.Yes:
return "yes"
if reply == QMessageBox.No:
return "no"
def restart_freecad():
from PySide import QtWidgets, QtCore
"""Shuts down and restarts FreeCAD"""
args = QtWidgets.QApplication.arguments()[1:]
if Gui.getMainWindow().close():
QtCore.QProcess.startDetached(
QtWidgets.QApplication.applicationFilePath(), args
)
return
def SaveDialog(files, OverWrite: bool = True):
"""
files must be like:\n
files = [\n
('All Files', '*.*'),\n
('Python Files', '*.py'),\n
('Text Document', '*.txt')\n
]\n
\n
OverWrite:\n
If True, file will be overwritten\n
If False, only the path+filename will be returned\n
"""
import tkinter as tk
from tkinter.filedialog import asksaveasfile
from tkinter.filedialog import askopenfilename
# Create the window
root = tk.Tk()
# Hide the window
root.withdraw()
if OverWrite is True:
file = asksaveasfile(filetypes=files, defaultextension=files)
if file is not None:
return file.name
if OverWrite is False:
file = askopenfilename(filetypes=files, defaultextension=files)
if file is not None:
return file
def GetLetterFromNumber(number: int, UCase: bool = True):
"""Number to Excel-style column name, e.g., 1 = A, 26 = Z, 27 = AA, 703 = AAA."""
Letter = ""
while number > 0:
number, r = divmod(number - 1, 26)
Letter = chr(r + ord("A")) + Letter
return Letter
def GetNumberFromLetter(Letter):
"""Excel-style column name to number, e.g., A = 1, Z = 26, AA = 27, AAA = 703."""
number = 0
for c in Letter:
number = number * 26 + 1 + ord(c) - ord("A")
return number
def ColorConvertor(ColorRGB: [], Alpha: float = 1, Hex=False, KeepHexAlpha=True):
"""
A single function to convert colors to rgba colors as a tuple of float from 0-1
ColorRGB: [255,255,255]
Alpha: 0-1
"""
from matplotlib import colors as mcolors
ColorRed = ColorRGB[0] / 255
colorGreen = ColorRGB[1] / 255
colorBlue = ColorRGB[2] / 255
color = (ColorRed, colorGreen, colorBlue)
result = mcolors.to_rgba(color, Alpha)
if Hex is True:
result = mcolors.to_hex((ColorRed, colorGreen, colorBlue, Alpha), KeepHexAlpha)
return result
def OpenFile(FileName: str):
"""
Filename = full path with filename as string
"""
import subprocess
import os
import platform
try:
if os.path.exists(FileName):
if platform.system() == "Darwin": # macOS
subprocess.call(("open", FileName))
elif platform.system() == "Windows": # Windows
os.startfile(FileName)
else: # linux variants
print(FileName)
try:
subprocess.check_output(["xdg-open", FileName.strip()])
except subprocess.CalledProcessError:
Print(
f"An error occurred when opening {FileName}!\n"
+ "This can happen when running FreeCAD as an AppImage.\n"
+ "Please install FreeCAD directly.",
"Error",
)
else:
print(f"Error: {FileName} does not exist.")
except Exception as e:
raise e
def Print(Input: str, Type: str = ""):
"""_summary_
Args:
Input (str): Text to print.\n
Type (str, optional): Type of message. (enter Warning, Error or Log). Defaults to "".
"""
import FreeCAD as App
if Type == "Warning":
App.Console.PrintWarning(Input + "\n")
elif Type == "Error":
App.Console.PrintError(Input + "\n")
elif Type == "Log":
App.Console.PrintLog(Input + "\n")
else:
App.Console.PrintMessage(Input + "\n")
def LightOrDark(rgbColor=[0, 128, 255, 255]):
"""_summary_
reference: https://alienryderflex.com/hsp.html
Args:
rgbColor (list, optional): RGB color. Defaults to [0, 128, 255, 255].\n
note: The alpha value is added for completeness, but us ignored in the equation.
Returns:
string: "light or dark"
"""
[r, g, b, a] = rgbColor
hsp = math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b))
if hsp > 127.5:
return "light"
else:
return "dark"
def GetFileDialog(Filter="", parent=None, DefaultPath="", SaveAs: bool = True) -> str:
"""
Set filter like:
"Images (*.png *.xpm .jpg);;Text files (.txt);;XML files (*.xml)"
SaveAs:\n
If True, as SaveAs dialog will open and the file will be overwritten\n
If False, an OpenFile dialog will be open and the file will be opened.\n
"""
from PySide.QtWidgets import QFileDialog
file = ""
if SaveAs is False:
file = QFileDialog.getOpenFileName(
parent=parent, caption="Select a file", dir=DefaultPath, filter=Filter
)[0]
if SaveAs is True:
file = QFileDialog.getSaveFileName(
parent=parent, caption="Select a file", dir=DefaultPath, filter=Filter
)[0]
return file
def GetFolder(parent=None, DefaultPath="") -> str:
from PySide.QtWidgets import QFileDialog
Directory = ""
Directory = QFileDialog.getExistingDirectory(
parent=parent, caption="Select Folder", dir=DefaultPath
)
return Directory
def getRepoAdress(base_path):
import pathlib
import os
try:
if base_path == "":
base_path = os.path.dirname(__file__)
git_dir = pathlib.Path(base_path) / ".git"
with (git_dir / "FETCH_HEAD").open("r") as head:
ref = head.readline().split(" ")[-1].strip()
return ref
except Exception:
return ""
def CreateToolbar(Name: str, WorkBenchName: str = "Global", ButtonList: list = []):
# Define the name for the ToolbarGroup in the FreeCAD Parameters
ToolbarGroupName = WorkBenchName
# Define the name for the toolbar
ToolBarName = Name
# define the parameter path for the toolbar
WorkbenchToolBarsParamPath = (
"User parameter:BaseApp/Workbench/" + ToolbarGroupName + "/Toolbar/"
)
# check if there is already a toolbar with the same name
CustomToolbars: list = App.ParamGet(
"User parameter:BaseApp/Workbench/Global/Toolbar"
).GetGroups()
for Group in CustomToolbars:
Parameter = App.ParamGet(
"User parameter:BaseApp/Workbench/Global/Toolbar/" + Group
)
ItemName = Parameter.GetString("Name")
if ItemName == ToolBarName:
return ToolBarName
# add the ToolbarGroup in the FreeCAD Parameters
WorkbenchToolbar = App.ParamGet(WorkbenchToolBarsParamPath + ToolBarName)
# Set the name.
WorkbenchToolbar.SetString("Name", ToolBarName)
# Set the toolbar active
WorkbenchToolbar.SetBool("Active", True)
# add the commands
for Button in ButtonList:
WorkbenchToolbar.SetString(Button, "FreeCAD")
# endregion
App.saveParameter()
return ToolBarName
def RemoveWorkBenchToolbars(Name: str, WorkBenchName: str = "Global") -> None:
# Define the name for the ToolbarGroup in the FreeCAD Parameters
ToolbarGroupName = WorkBenchName
# Define the name for the toolbar
ToolBarName = Name
# define the parameter path for the toolbar
ToolBarsParamPath = (
"User parameter:BaseApp/Workbench/" + ToolbarGroupName + "/Toolbar/"
)
custom_toolbars = App.ParamGet(ToolBarsParamPath)
custom_toolbars.RemGroup(ToolBarName)
return
def ReturnXML_Value(
path: str, ElementName: str, attribKey: str = "", attribValue: str = ""
):
import xml.etree.ElementTree as ET
import os
# Passing the path of the
# xml document to enable the
# parsing process
PackageXML = os.path.join(os.path.dirname(__file__), path)
tree = ET.parse(PackageXML)
# getting the parent tag of
# the xml document
root = tree.getroot()
result = ""
for child in root:
if str(child.tag).split("}")[1] == ElementName:
if attribKey != "" and attribValue != "":
for key, value in child.attrib.items():
if key == attribKey and value == attribValue:
result = child.text
return result
else:
result = child.text
return result
def TranslationsMapping(WorkBenchName: str, string: str):
result = string
ListSpecialWB = [
"Assembly4Workbench",
"A2plusWorkbench",
]
isSpecialWB = False
for wb in ListSpecialWB:
if wb == WorkBenchName:
isSpecialWB = True
if isSpecialWB is False:
contextDict_Standard = {
"WorkFeatureWorkbench": "Workbench",
"SketcherWorkbench": "Workbench",
"PartDesignWorkbench": "Workbench",
"PartWorkbench": "Workbench",
"SMWorkbench": "Workbench",
"FrameWorkbench": "Workbench",
"SurfaceWorkbench": "Workbench",
"TechDrawWorkbench": "Workbench",
"FemWorkbench": "Workbench",
"GearWorkbench": "Workbench",
"FastenersWorkbench": "Workbench",
"SpreadsheetWorkbench": "Workbench",
"InspectionWorkbench": "Workbench",
"RenderWorkbench": "Workbench",
"RobotWorkbench": "Workbench",
"CfdOFWorkbench": "Workbench",
"PlotWorkbench": "Workbench",
"BillOfMaterialsWB": "Workbench",
"DynamicDataWorkbench": "Workbench",
"AssistantWorkbench": "Workbench",
"TestWorkbench": "Workbench",
"ThreadProfileWorkbench": "Workbench",
"AssemblyWorkbench": "Workbench",
"BIMWorkbench": "Workbench",
"CAMWorkbench": "Workbench",
"MaterialWorkbench": "Workbench",
"Assembly3Workbench": "asm3",
}
try:
context = contextDict_Standard[WorkBenchName]
except Exception:
context = "Workbench"
result = translate(context, string)
if WorkBenchName == "Assembly4Workbench":
ListContext = [
"Fasteners",
"Commands",
"Asm4_Help",
"Commands1",
"Asm4_showLcs",
"Asm4_hideLcs",
]
for i in range(len(ListContext)):
context = ListContext[i]
value = translate(context, string)
if value != string:
result = value
if i == len(ListContext) - 1:
result = string
if WorkBenchName == "A2plusWorkbench":
ListContext = [
"A2p_BoM",
"A2plus",
"A2plus_Constraints",
"A2plus_searchConstraintConflicts",
]
for i in range(len(ListContext)):
context = ListContext[i]
value = translate(context, string)
if value != string:
result = value
if i == len(ListContext) - 1:
result = string
return result
# # Add or update the dict for the Ribbon command panel
# self.add_keys_nested_dict(
# self.Dict_RibbonCommandPanel,
# ["workbenches", WorkBenchName, "toolbars", Toolbar, "order"],
# )
def add_keys_nested_dict(dict, keys, default=1):
"""_summary_
Args:
dict (_type_): Enter dict to create or modify
keys (_type_): Enter key or list of keys
Returns:
bool: True if a new dict is created or modified. Otherwise False
"""
for key in keys:
result = False
if key not in dict:
dict[key] = {}
result = True
dict = dict[key]
try:
dict.setdefault(keys[-1], default)
except Exception:
pass
return result
def CommandInfoCorrections(CommandName):
try:
Command = Gui.Command.get(CommandName)
if Command is not None:
CommandInfo = Command.getInfo()
if CommandName == "PartDesign_CompSketches":
CommandInfo["menuText"] = "Create sketch..."
CommandInfo["toolTip"] = "Create or edit a sketch"
CommandInfo["whatsThis"] = "PartDesign_CompSketches"
CommandInfo["statusTip"] = "Create or edit a sketch"
if CommandName == "Sketcher_Grid":
CommandInfo["pixmap"] = "Sketcher_GridToggle_Deactivated.svg"
if CommandName == "Sketcher_Snap":
CommandInfo["pixmap"] = "Sketcher_Snap_Deactivated.svg"
if CommandName == "Sketcher_RenderingOrder":
CommandInfo["pixmap"] = "Sketcher_RenderingOrder_External.svg"
# add an extra entry for action text
add_keys_nested_dict(CommandInfo, "ActionText")
CommandActionList = Command.getAction()
if len(CommandActionList) > 0:
CommandAction = CommandActionList[0]
CommandInfo["ActionText"] = CommandAction.text()
else:
CommandInfo["ActionText"] = CommandInfo["menuText"]
if CommandInfo["ActionText"] == "":
CommandInfo["ActionText"] = CommandInfo["menuText"]
return CommandInfo
else:
CommandInfo = {}
CommandInfo["menuText"] = ""
CommandInfo["toolTip"] = ""
CommandInfo["whatsThis"] = ""
CommandInfo["statusTip"] = ""
CommandInfo["pixmap"] = ""
CommandInfo["ActionText"] = ""
CommandInfo["name"] = ""
except Exception:
CommandInfo = {}
CommandInfo["menuText"] = ""
CommandInfo["toolTip"] = ""
CommandInfo["whatsThis"] = ""
CommandInfo["statusTip"] = ""
CommandInfo["pixmap"] = ""
CommandInfo["ActionText"] = ""
CommandInfo["name"] = ""
return CommandInfo
def addMissingCommands(CommandList: list):
MissingCommands = [
[
"Sketcher_NewSketch", # commandname
"Sketcher_NewSketch", # iconname
"Create sketch", # menu text
"SketcherWorkbench", # workbench
],
["Draft_Line", "Draft_Line", "Line", "DraftWorkbench"],
["Draft_Move", "Draft_Move", "Move", "DraftWorkbench"],
[
"Draft_LayerManager",
"Draft_LayerManager",
"Manage layers...",
"DraftWorkbench",
],
["Draft_Snap_Lock", "Draft_Snap_Lock", "Snap lock", "DraftWorkbench"],
[
"OpenSCAD_ReplaceObject",
"OpenSCAD_ReplaceObject",
"Replace Object",
"OpenSCADWorkbench",
],
[
"Part_CheckGeometry",
"Part_CheckGeometry",
"Check Geometry",
"OpenSCADWorkbench",
],
]
CopyList = CommandList.copy()
for Item in CommandList:
isInList = False
for MissingCommand in MissingCommands:
if Item[0] == MissingCommand:
isInList = True
break
if isInList is False:
CopyList.append(MissingCommand)
return CopyList
def returnQiCons_Commands(CommandName, pixmap=""):
from PySide.QtGui import QIcon
icon = QIcon()
if pixmap != "" and pixmap is not None:
icon = Gui.getIcon(pixmap)
else:
try:
Command = Gui.Command.get(CommandName)
CommandInfo = Command.getInfo()
pixmap = CommandInfo["pixmap"]
icon = Gui.getIcon(pixmap)
except Exception:
pass
if icon is None or (icon is not None and icon.isNull()):
try:
Command = Gui.Command.get(CommandName)
action = Command.getAction()[0]
icon = action.icon()
except Exception:
return None
return icon
def CorrectGetToolbarItems(ToolbarItems: dict):
newCommands = []
if "Structure" in ToolbarItems:
newCommands = ToolbarItems["Structure"]
if "Part_Datums" not in newCommands:
newCommands.append("Part_Datums")
ToolbarItems.update({"Structure": newCommands})
return ToolbarItems
def ShortCutTaken(ShortCut: str):
ListWithCommands = Gui.Command.listByShortcut(ShortCut)
if len(ListWithCommands) > 0:
return True
return False
def ReturnWrappedText(text: str, max_length: int = 50, max_Lines=0, returnList=False):
import textwrap
result = ""
# Wrap the text as list
wrapped_text = textwrap.wrap(text=text, width=max_length)
# remove spaces at the end of each line
for line in wrapped_text:
line = textwrap.dedent(line)
# remove any line that is more then allowed
if max_Lines > 0 and len(wrapped_text) > max_Lines:
for i in range(max_Lines, len(wrapped_text)):
try:
wrapped_text.pop(i)
except Exception:
continue
# return the desired result
if returnList is False:
result = "\n".join(wrapped_text)
else:
result = wrapped_text
return result