61 lines · 1.9 KB
Raw Download
1
"""
2
SaveUtils FreeCAD Addon - InitGui.py
3
4
FreeCAD runs Init.py/InitGui.py with `globals` and `locals` as two different
5
dicts. Top-level statements bind into locals, but functions defined here capture
6
globals as their `__globals__` — so *nothing* bound at the top of this file is
7
visible from inside a function here. Names FreeCAD already put in `__main__`
8
(FreeCAD, FreeCADGui) do resolve, which makes the trap easy to miss.
9
10
Consequence: every function below must import what it needs locally, and the
11
real work lives in SaveUtils.py where module globals behave normally.
12
"""
13
14
import FreeCAD
15
import FreeCADGui
16
17
FreeCAD.Console.PrintLog("=== SaveUtils: InitGui.py loading ===\n")
18
19
20
class SaveUtilsWorkbench(FreeCADGui.Workbench):
21
    MenuText = "SaveUtils"
22
    ToolTip = "Save utility commands"
23
24
    def Initialize(self):
25
        pass
26
27
    def Activated(self):
28
        pass
29
30
    def Deactivated(self):
31
        pass
32
33
34
FreeCADGui.addWorkbench(SaveUtilsWorkbench())
35
36
37
def _on_workbench_activated(name):
38
    # Local imports only — see the module docstring.
39
    import FreeCAD
40
    from PySide import QtCore
41
42
    # NoneWorkbench fires before the UI is ready — skip it
43
    if name == "NoneWorkbench":
44
        return
45
46
    try:
47
        import SaveUtils
48
49
        # FreeCAD rebuilds the menu bar around this signal, so right now some of
50
        # the QMenus it hands out are Python wrappers whose C++ half has already
51
        # been destroyed. Let the event loop come back round before touching
52
        # them. install_safely() is idempotent, so running it again on later
53
        # workbench switches is harmless and re-adds the items if a rebuild
54
        # dropped them.
55
        QtCore.QTimer.singleShot(0, SaveUtils.install_safely)
56
    except Exception as exc:
57
        FreeCAD.Console.PrintError(f"=== SaveUtils install error: {exc} ===\n")
58
59
60
FreeCADGui.getMainWindow().workbenchActivated.connect(_on_workbench_activated)
61