| 1 |
# *************************************************************************** |
| 2 |
# * Copyright (c) 2002,2003 Jürgen Riegel <[email protected]> * |
| 3 |
# * * |
| 4 |
# * This file is part of the FreeCAD CAx development system. * |
| 5 |
# * * |
| 6 |
# * This program is free software; you can redistribute it and/or modify * |
| 7 |
# * it under the terms of the GNU Lesser General Public License (LGPL) * |
| 8 |
# * as published by the Free Software Foundation; either version 2 of * |
| 9 |
# * the License, or (at your option) any later version. * |
| 10 |
# * for detail see the LICENCE text file. * |
| 11 |
# * * |
| 12 |
# * FreeCAD is distributed in the hope that it will be useful, * |
| 13 |
# * but WITHOUT ANY WARRANTY; without even the implied warranty of * |
| 14 |
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * |
| 15 |
# * GNU Lesser General Public License for more details. * |
| 16 |
# * * |
| 17 |
# * You should have received a copy of the GNU Library General Public * |
| 18 |
# * License along with FreeCAD; if not, write to the Free Software * |
| 19 |
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * |
| 20 |
# * USA * |
| 21 |
# * * |
| 22 |
# ***************************************************************************/ |
| 23 |
from dataclasses import dataclass |
| 24 |
|
| 25 |
# FreeCAD gui init module |
| 26 |
# |
| 27 |
# Gathering all the information to start FreeCAD |
| 28 |
# This is the second one of three init scripts, the third one |
| 29 |
# runs when the gui is up |
| 30 |
|
| 31 |
# imports the one and only |
| 32 |
import FreeCAD, FreeCADGui |
| 33 |
from enum import IntEnum, Enum |
| 34 |
|
| 35 |
# shortcuts |
| 36 |
Gui = FreeCADGui |
| 37 |
|
| 38 |
# this is to keep old code working |
| 39 |
Gui.listCommands = Gui.Command.listAll |
| 40 |
Gui.isCommandActive = lambda cmd: Gui.Command.get(cmd).isActive() |
| 41 |
|
| 42 |
|
| 43 |
# The values must match with that of the C++ enum class ResolveMode |
| 44 |
class ResolveMode(IntEnum): |
| 45 |
NoResolve = 0 |
| 46 |
OldStyleElement = 1 |
| 47 |
NewStyleElement = 2 |
| 48 |
FollowLink = 3 |
| 49 |
|
| 50 |
|
| 51 |
Gui.Selection.ResolveMode = ResolveMode |
| 52 |
|
| 53 |
|
| 54 |
# The values must match with that of the C++ enum class SelectionStyle |
| 55 |
class SelectionStyle(IntEnum): |
| 56 |
NormalSelection = 0 |
| 57 |
GreedySelection = 1 |
| 58 |
|
| 59 |
|
| 60 |
# The values must match with that of the Python enum class in ViewProvider.pyi |
| 61 |
class ToggleVisibilityMode(Enum): |
| 62 |
CanToggleVisibility = "CanToggleVisibility" |
| 63 |
NoToggleVisibility = "NoToggleVisibility" |
| 64 |
|
| 65 |
|
| 66 |
Gui.Selection.SelectionStyle = SelectionStyle |
| 67 |
|
| 68 |
|
| 69 |
# Important definitions |
| 70 |
class Workbench: |
| 71 |
"""The workbench base class.""" |
| 72 |
|
| 73 |
MenuText = "" |
| 74 |
ToolTip = "" |
| 75 |
Icon = None |
| 76 |
|
| 77 |
def Initialize(self): |
| 78 |
"""Initializes this workbench.""" |
| 79 |
App.Console.PrintWarning( |
| 80 |
str(self) + ": Workbench.Initialize() not implemented in subclass!" |
| 81 |
) |
| 82 |
|
| 83 |
def ContextMenu(self, recipient): |
| 84 |
pass |
| 85 |
|
| 86 |
def appendToolbar(self, name, cmds): |
| 87 |
self.__Workbench__.appendToolbar(name, cmds) |
| 88 |
|
| 89 |
def removeToolbar(self, name): |
| 90 |
self.__Workbench__.removeToolbar(name) |
| 91 |
|
| 92 |
def listToolbars(self): |
| 93 |
return self.__Workbench__.listToolbars() |
| 94 |
|
| 95 |
def getToolbarItems(self): |
| 96 |
return self.__Workbench__.getToolbarItems() |
| 97 |
|
| 98 |
def appendCommandbar(self, name, cmds): |
| 99 |
self.__Workbench__.appendCommandbar(name, cmds) |
| 100 |
|
| 101 |
def removeCommandbar(self, name): |
| 102 |
self.__Workbench__.removeCommandbar(name) |
| 103 |
|
| 104 |
def listCommandbars(self): |
| 105 |
return self.__Workbench__.listCommandbars() |
| 106 |
|
| 107 |
def appendMenu(self, name, cmds): |
| 108 |
self.__Workbench__.appendMenu(name, cmds) |
| 109 |
|
| 110 |
def removeMenu(self, name): |
| 111 |
self.__Workbench__.removeMenu(name) |
| 112 |
|
| 113 |
def listMenus(self): |
| 114 |
return self.__Workbench__.listMenus() |
| 115 |
|
| 116 |
def appendContextMenu(self, name, cmds): |
| 117 |
self.__Workbench__.appendContextMenu(name, cmds) |
| 118 |
|
| 119 |
def removeContextMenu(self, name): |
| 120 |
self.__Workbench__.removeContextMenu(name) |
| 121 |
|
| 122 |
def reloadActive(self): |
| 123 |
self.__Workbench__.reloadActive() |
| 124 |
|
| 125 |
def name(self): |
| 126 |
return self.__Workbench__.name() |
| 127 |
|
| 128 |
def GetClassName(self): |
| 129 |
"""Return the name of the associated C++ class.""" |
| 130 |
# as default use this to simplify writing workbenches in Python |
| 131 |
return "Gui::PythonWorkbench" |
| 132 |
|
| 133 |
|
| 134 |
class StandardWorkbench(Workbench): |
| 135 |
"""A workbench defines the tool bars, command bars, menus, |
| 136 |
context menu and dockable windows of the main window. |
| 137 |
""" |
| 138 |
|
| 139 |
def Initialize(self): |
| 140 |
"""Initialize this workbench.""" |
| 141 |
# load the module |
| 142 |
Log("Init: Loading FreeCAD GUI\n") |
| 143 |
|
| 144 |
def GetClassName(self): |
| 145 |
"""Return the name of the associated C++ class.""" |
| 146 |
return "Gui::StdWorkbench" |
| 147 |
|
| 148 |
|
| 149 |
class NoneWorkbench(Workbench): |
| 150 |
"""An empty workbench.""" |
| 151 |
|
| 152 |
MenuText = "<none>" |
| 153 |
ToolTip = "The default empty workbench" |
| 154 |
|
| 155 |
def Initialize(self): |
| 156 |
"""Initialize this workbench.""" |
| 157 |
# load the module |
| 158 |
Log("Init: Loading FreeCAD GUI\n") |
| 159 |
|
| 160 |
def GetClassName(self): |
| 161 |
"""Return the name of the associated C++ class.""" |
| 162 |
return "Gui::NoneWorkbench" |
| 163 |
|
| 164 |
|
| 165 |
@dataclass |
| 166 |
class InputHint: |
| 167 |
""" |
| 168 |
Represents a single input hint (shortcut suggestion). |
| 169 |
|
| 170 |
The message is a Qt formatting string with placeholders like %1, %2, ... |
| 171 |
The placeholders are replaced with input representations - be it keys, mouse buttons etc. |
| 172 |
Each placeholder corresponds to one input sequence. Sequence can either be: |
| 173 |
- one input from Gui.UserInput enum |
| 174 |
- tuple of mentioned enum values representing the input sequence |
| 175 |
|
| 176 |
>>> InputHint("%1 change mode", Gui.UserInput.KeyM) |
| 177 |
will result in a hint displaying `[M] change mode` |
| 178 |
|
| 179 |
>>> InputHint("%1 new line", (Gui.UserInput.KeyControl, Gui.UserInput.KeyEnter)) |
| 180 |
will result in a hint displaying `[ctrl][enter] new line` |
| 181 |
|
| 182 |
>>> InputHint("%1/%2 increase/decrease ...", Gui.UserInput.KeyU, Gui.UserInput.KeyJ) |
| 183 |
will result in a hint displaying `[U]/[J] increase / decrease ...` |
| 184 |
""" |
| 185 |
|
| 186 |
InputSequence = Gui.UserInput | tuple[Gui.UserInput, ...] |
| 187 |
|
| 188 |
message: str |
| 189 |
sequences: list[InputSequence] |
| 190 |
|
| 191 |
def __init__(self, message: str, *sequences: InputSequence): |
| 192 |
self.message = message |
| 193 |
self.sequences = list(sequences) |
| 194 |
|
| 195 |
|
| 196 |
class HintManager: |
| 197 |
""" |
| 198 |
A convenience class for managing input hints (shortcut suggestions) displayed to the user. |
| 199 |
It is here mostly to provide well-defined and easy to reach API from python without developers needing |
| 200 |
to call low-level functions on the main window directly. |
| 201 |
""" |
| 202 |
|
| 203 |
def show(self, *hints: InputHint): |
| 204 |
""" |
| 205 |
Displays the specified input hints to the user. |
| 206 |
|
| 207 |
:param hints: List of hints to show. |
| 208 |
""" |
| 209 |
Gui.getMainWindow().showHint(*hints) |
| 210 |
|
| 211 |
def hide(self): |
| 212 |
""" |
| 213 |
Hides all currently displayed input hints. |
| 214 |
""" |
| 215 |
Gui.getMainWindow().hideHint() |
| 216 |
|
| 217 |
|
| 218 |
Gui.InputHint = InputHint |
| 219 |
Gui.HintManager = HintManager() |
| 220 |
|
| 221 |
|
| 222 |
def InitApplications(): |
| 223 |
import sys, os, traceback |
| 224 |
import io as cStringIO |
| 225 |
|
| 226 |
# Searching modules dirs +++++++++++++++++++++++++++++++++++++++++++++++++++ |
| 227 |
# (additional module paths are already cached) |
| 228 |
ModDirs = FreeCAD.__ModDirs__ |
| 229 |
# print ModDirs |
| 230 |
Log("Init: Searching modules\n") |
| 231 |
|
| 232 |
def RunInitGuiPy(Dir) -> bool: |
| 233 |
InstallFile = os.path.join(Dir, "InitGui.py") |
| 234 |
if os.path.exists(InstallFile): |
| 235 |
try: |
| 236 |
with open(InstallFile, "rt", encoding="utf-8") as f: |
| 237 |
exec(compile(f.read(), InstallFile, "exec")) |
| 238 |
except Exception as inst: |
| 239 |
Log("Init: Initializing " + Dir + "... failed\n") |
| 240 |
Log("-" * 100 + "\n") |
| 241 |
Log(traceback.format_exc()) |
| 242 |
Log("-" * 100 + "\n") |
| 243 |
Err( |
| 244 |
'During initialization the error "' |
| 245 |
+ str(inst) |
| 246 |
+ '" occurred in ' |
| 247 |
+ InstallFile |
| 248 |
+ "\n" |
| 249 |
) |
| 250 |
Err("Look into the log file for further information\n") |
| 251 |
mod_name = os.path.normpath(Dir).split(os.path.sep)[-1].lower() |
| 252 |
if hasattr(FreeCAD, "__failed_mods__"): |
| 253 |
FreeCAD.__failed_mods__.append(mod_name) |
| 254 |
else: |
| 255 |
FreeCAD.__failed_mods__ = [mod_name] |
| 256 |
if mod_name not in FreeCAD.__fallback_mods__: |
| 257 |
Err("Could not evaluate module '" + mod_name + "' for fallbacks\n") |
| 258 |
elif len(FreeCAD.__fallback_mods__[mod_name]) > 1: |
| 259 |
new_path = os.path.normpath(FreeCAD.__fallback_mods__[mod_name][-2]) |
| 260 |
Err(f"A fallback module was found for module '{mod_name}': {new_path}\n") |
| 261 |
Err(f"Rename or remove {os.path.normpath(Dir)} to use the fallback module\n") |
| 262 |
else: |
| 263 |
Log("Init: Initializing " + Dir + "... done\n") |
| 264 |
return True |
| 265 |
else: |
| 266 |
Log("Init: Initializing " + Dir + "(InitGui.py not found)... ignore\n") |
| 267 |
return False |
| 268 |
|
| 269 |
def processMetadataFile(Dir, MetadataFile): |
| 270 |
meta = FreeCAD.Metadata(MetadataFile) |
| 271 |
if not meta.supportsCurrentFreeCAD(): |
| 272 |
return None |
| 273 |
content = meta.Content |
| 274 |
if "workbench" in content: |
| 275 |
FreeCAD.Gui.addIconPath(Dir) |
| 276 |
workbenches = content["workbench"] |
| 277 |
for workbench_metadata in workbenches: |
| 278 |
if not workbench_metadata.supportsCurrentFreeCAD(): |
| 279 |
return None |
| 280 |
subdirectory = ( |
| 281 |
workbench_metadata.Name |
| 282 |
if not workbench_metadata.Subdirectory |
| 283 |
else workbench_metadata.Subdirectory |
| 284 |
) |
| 285 |
subdirectory = subdirectory.replace("/", os.path.sep) |
| 286 |
subdirectory = os.path.join(Dir, subdirectory) |
| 287 |
ran_init = RunInitGuiPy(subdirectory) |
| 288 |
|
| 289 |
if ran_init: |
| 290 |
# Try to generate a new icon from the metadata-specified information |
| 291 |
classname = workbench_metadata.Classname |
| 292 |
if classname: |
| 293 |
try: |
| 294 |
wb_handle = FreeCAD.Gui.getWorkbench(classname) |
| 295 |
except Exception: |
| 296 |
Log( |
| 297 |
f"Failed to get handle to {classname} -- no icon\ |
| 298 |
can be generated,\n check classname in package.xml\n" |
| 299 |
) |
| 300 |
else: |
| 301 |
GeneratePackageIcon(dir, subdirectory, workbench_metadata, wb_handle) |
| 302 |
|
| 303 |
def tryProcessMetadataFile(Dir, MetadataFile): |
| 304 |
try: |
| 305 |
processMetadataFile(Dir, MetadataFile) |
| 306 |
except Exception as exc: |
| 307 |
Err(str(exc)) |
| 308 |
|
| 309 |
def checkIfAddonIsDisabled(Dir): |
| 310 |
DisabledAddons = FreeCAD.ConfigGet("DisabledAddons").split(";") |
| 311 |
Name = os.path.basename(Dir) |
| 312 |
|
| 313 |
if Name in DisabledAddons: |
| 314 |
Msg( |
| 315 |
f'NOTICE: Addon "{Name}" disabled by presence of "--disable-addon {Name}" argument\n' |
| 316 |
) |
| 317 |
return True |
| 318 |
|
| 319 |
stopFileName = "ALL_ADDONS_DISABLED" |
| 320 |
stopFile = os.path.join(Dir, os.path.pardir, stopFileName) |
| 321 |
if os.path.exists(stopFile): |
| 322 |
Msg(f'NOTICE: Addon "{Dir}" disabled by presence of {stopFileName} stopfile\n') |
| 323 |
return True |
| 324 |
|
| 325 |
stopFileName = "ADDON_DISABLED" |
| 326 |
stopFile = os.path.join(Dir, stopFileName) |
| 327 |
if os.path.exists(stopFile): |
| 328 |
Msg(f'NOTICE: Addon "{Dir}" disabled by presence of {stopFileName} stopfile\n') |
| 329 |
return True |
| 330 |
|
| 331 |
return False |
| 332 |
|
| 333 |
for Dir in ModDirs: |
| 334 |
if Dir not in ["", "CVS", "__init__.py"]: |
| 335 |
if checkIfAddonIsDisabled(Dir): |
| 336 |
continue |
| 337 |
MetadataFile = os.path.join(Dir, "package.xml") |
| 338 |
if os.path.exists(MetadataFile): |
| 339 |
tryProcessMetadataFile(Dir, MetadataFile) |
| 340 |
else: |
| 341 |
RunInitGuiPy(Dir) |
| 342 |
Log("All modules with GUIs using InitGui.py are now initialized\n") |
| 343 |
|
| 344 |
try: |
| 345 |
import pkgutil |
| 346 |
import importlib |
| 347 |
import freecad |
| 348 |
|
| 349 |
freecad.gui = FreeCADGui |
| 350 |
for _, freecad_module_name, freecad_module_ispkg in pkgutil.iter_modules( |
| 351 |
freecad.__path__, "freecad." |
| 352 |
): |
| 353 |
# Check for a stopfile |
| 354 |
stopFile = os.path.join( |
| 355 |
FreeCAD.getUserAppDataDir(), "Mod", freecad_module_name[8:], "ADDON_DISABLED" |
| 356 |
) |
| 357 |
if os.path.exists(stopFile): |
| 358 |
continue |
| 359 |
|
| 360 |
# Make sure that package.xml (if present) does not exclude this version of FreeCAD |
| 361 |
MetadataFile = os.path.join( |
| 362 |
FreeCAD.getUserAppDataDir(), "Mod", freecad_module_name[8:], "package.xml" |
| 363 |
) |
| 364 |
if os.path.exists(MetadataFile): |
| 365 |
meta = FreeCAD.Metadata(MetadataFile) |
| 366 |
if not meta.supportsCurrentFreeCAD(): |
| 367 |
continue |
| 368 |
|
| 369 |
if freecad_module_ispkg: |
| 370 |
Log("Init: Initializing " + freecad_module_name + "\n") |
| 371 |
try: |
| 372 |
freecad_module = importlib.import_module(freecad_module_name) |
| 373 |
if any( |
| 374 |
module_name == "init_gui" |
| 375 |
for _, module_name, ispkg in pkgutil.iter_modules(freecad_module.__path__) |
| 376 |
): |
| 377 |
importlib.import_module(freecad_module_name + ".init_gui") |
| 378 |
Log("Init: Initializing " + freecad_module_name + "... done\n") |
| 379 |
else: |
| 380 |
Log( |
| 381 |
"Init: No init_gui module found in " |
| 382 |
+ freecad_module_name |
| 383 |
+ ", skipping\n" |
| 384 |
) |
| 385 |
except Exception as inst: |
| 386 |
Err( |
| 387 |
'During initialization the error "' |
| 388 |
+ str(inst) |
| 389 |
+ '" occurred in ' |
| 390 |
+ freecad_module_name |
| 391 |
+ "\n" |
| 392 |
) |
| 393 |
Err("-" * 80 + "\n") |
| 394 |
Err(traceback.format_exc()) |
| 395 |
Err("-" * 80 + "\n") |
| 396 |
Log("Init: Initializing " + freecad_module_name + "... failed\n") |
| 397 |
Log("-" * 80 + "\n") |
| 398 |
Log(traceback.format_exc()) |
| 399 |
Log("-" * 80 + "\n") |
| 400 |
except ImportError as inst: |
| 401 |
Err('During initialization the error "' + str(inst) + '" occurred\n') |
| 402 |
|
| 403 |
Log("All modules with GUIs initialized using pkgutil are now initialized\n") |
| 404 |
|
| 405 |
|
| 406 |
def GeneratePackageIcon( |
| 407 |
dir: str, subdirectory: str, workbench_metadata: FreeCAD.Metadata, wb_handle: Workbench |
| 408 |
) -> None: |
| 409 |
relative_filename = workbench_metadata.Icon |
| 410 |
if not relative_filename: |
| 411 |
# Although a required element, this content item does not have an icon. Just bail out |
| 412 |
return |
| 413 |
absolute_filename = os.path.join(subdirectory, relative_filename) |
| 414 |
if hasattr(wb_handle, "Icon") and wb_handle.Icon: |
| 415 |
Log( |
| 416 |
f"Init: Packaged workbench {workbench_metadata.Name} specified icon\ |
| 417 |
in class {workbench_metadata.Classname}" |
| 418 |
) |
| 419 |
Log(f" ... replacing with icon from package.xml data.\n") |
| 420 |
wb_handle.__dict__["Icon"] = absolute_filename |
| 421 |
|
| 422 |
|
| 423 |
Log("Init: Running FreeCADGuiInit.py start script...\n") |
| 424 |
|
| 425 |
|
| 426 |
# init the gui |
| 427 |
|
| 428 |
# signal that the gui is up |
| 429 |
App.GuiUp = 1 |
| 430 |
App.Gui = FreeCADGui |
| 431 |
FreeCADGui.Workbench = Workbench |
| 432 |
|
| 433 |
Gui.addWorkbench(NoneWorkbench()) |
| 434 |
|
| 435 |
# init modules |
| 436 |
InitApplications() |
| 437 |
|
| 438 |
# set standard workbench (needed as fallback) |
| 439 |
Gui.activateWorkbench("NoneWorkbench") |
| 440 |
|
| 441 |
# Register .py, .FCScript and .FCMacro |
| 442 |
FreeCAD.addImportType("Inventor V2.1 (*.iv *.IV)", "FreeCADGui") |
| 443 |
FreeCAD.addImportType( |
| 444 |
"VRML V2.0 (*.wrl *.WRL *.vrml *.VRML *.wrz *.WRZ *.wrl.gz *.WRL.GZ)", "FreeCADGui" |
| 445 |
) |
| 446 |
FreeCAD.addImportType("Python (*.py *.FCMacro *.FCScript *.fcmacro *.fcscript)", "FreeCADGui") |
| 447 |
FreeCAD.addExportType("Inventor V2.1 (*.iv)", "FreeCADGui") |
| 448 |
FreeCAD.addExportType("VRML V2.0 (*.wrl *.vrml *.wrz *.wrl.gz)", "FreeCADGui") |
| 449 |
FreeCAD.addExportType("X3D Extensible 3D (*.x3d *.x3dz)", "FreeCADGui") |
| 450 |
FreeCAD.addExportType("WebGL/X3D (*.xhtml)", "FreeCADGui") |
| 451 |
# FreeCAD.addExportType("IDTF (for 3D PDF) (*.idtf)","FreeCADGui") |
| 452 |
# FreeCAD.addExportType("3D View (*.svg)","FreeCADGui") |
| 453 |
FreeCAD.addExportType("Portable Document Format (*.pdf)", "FreeCADGui") |
| 454 |
|
| 455 |
del InitApplications |
| 456 |
del NoneWorkbench |
| 457 |
del StandardWorkbench |
| 458 |
|
| 459 |
Log("Init: Running FreeCADGuiInit.py start script... done\n") |