Debian Codegraph @

src/Gui/Application.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2004 Jürgen Riegel <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23 #include <FCConfig.h>
24
25 #include <boost/interprocess/sync/file_lock.hpp>
26 #include <Inventor/errors/SoDebugError.h>
27 #include <Inventor/errors/SoError.h>
28 #include <QCheckBox>
29 #include <QCloseEvent>
30 #include <QDir>
31 #include <QFileInfo>
32 #include <QLocale>
33 #include <QMessageBox>
34 #include <QMessageLogContext>
35 #include <QRegularExpression>
36 #include <QRegularExpressionMatch>
37 #include <QScreen>
38 #include <QStatusBar>
39 #include <QStyle>
40 #include <QSurfaceFormat>
41 #include <QTextStream>
42 #include <QTimer>
43 #include <QWindow>
44 #include <QStyleFactory>
45
46 #include <QLoggingCategory>
47 #include <fmt/format.h>
48 #include <list>
49 #include <ranges>
50
51 #include <App/Document.h>
52 #include <App/DocumentObjectPy.h>
53 #include <Base/Console.h>
54 #include <Base/Interpreter.h>
55 #include <Base/Exception.h>
56 #include <Base/FileInfo.h>
57 #include <Base/Parameter.h>
58 #include <Base/Stream.h>
59 #include <Base/Tools.h>
60
61 #include <Base/UnitsApi.h>
62
63 #include <Language/Translator.h>
64 #include <Quarter/Quarter.h>
65
66 #include "Application.h"
67 #include "ApplicationPy.h"
68 #include "AxisOriginPy.h"
69 #include "BitmapFactory.h"
70 #include "Command.h"
71 #include "CommandActionPy.h"
72 #include "CommandPy.h"
73 #include "Control.h"
74 #include "PreferencePages/DlgSettingsCacheDirectory.h"
75 #include "DocumentPy.h"
76 #include "DocumentRecovery.h"
77 #include "EditorView.h"
78 #include "ExpressionBindingPy.h"
79 #include "FileDialog.h"
80 #include "GuiApplication.h"
81 #include "GuiInitScript.h"
82 #include "InputHintPy.h"
83 #include "LinkViewPy.h"
84 #include "MainWindow.h"
85 #include "Macro.h"
86 #include "PreferencePackManager.h"
87 #include "PythonConsolePy.h"
88 #include "PythonDebugger.h"
89 #include "MainWindowPy.h"
90 #include "MDIViewPy.h"
91 #include "Placement.h"
92 #include "SoFCDB.h"
93 #include "Selection.h"
94 #include "SelectionFilterPy.h"
95 #include "SoQtOffscreenRendererPy.h"
96 #include "SplitView3DInventor.h"
97 #include "StartupProcess.h"
98 #include "TaskView/TaskView.h"
99 #include "TaskView/TaskDialogPython.h"
100 #include "TransactionObject.h"
101 #include "TextDocumentEditorView.h"
102 #include "UiLoader.h"
103 #include "View3DPy.h"
104 #include "View3DViewerPy.h"
105 #include "View3DInventor.h"
106 #include "ViewProviderAnnotation.h"
107 #include "ViewProviderDocumentObject.h"
108 #include "ViewProviderDocumentObjectGroup.h"
109 #include "ViewProviderDragger.h"
110 #include "ViewProviderExtension.h"
111 #include "ViewProviderExtern.h"
112 #include "ViewProviderFeature.h"
113 #include "ViewProviderGeoFeatureGroup.h"
114 #include "ViewProviderGeometryObject.h"
115 #include "ViewProviderGeometryObjectPy.h"
116 #include "ViewProviderGroupExtension.h"
117 #include "ViewProviderSuppressibleExtension.h"
118 #include "ViewProviderImagePlane.h"
119 #include "ViewProviderInventorObject.h"
120 #include "ViewProviderLine.h"
121 #include "ViewProviderLink.h"
122 #include "ViewProviderLinkPy.h"
123 #include "ViewProviderMaterialObject.h"
124 #include "ViewProviderCoordinateSystem.h"
125 #include "ViewProviderDatum.h"
126 #include "ViewProviderOriginGroup.h"
127 #include "ViewProviderPlacement.h"
128 #include "ViewProviderPlane.h"
129 #include "ViewProviderPoint.h"
130 #include "ViewProviderPart.h"
131 #include "ViewProviderFeaturePython.h"
132 #include "ViewProviderTextDocument.h"
133 #include "ViewProviderTextureExtension.h"
134 #include "ViewProviderVRMLObject.h"
135 #include "ViewProviderVarSet.h"
136 #include "WaitCursor.h"
137 #include "Workbench.h"
138 #include "WorkbenchManager.h"
139 #include "WorkbenchManipulator.h"
140 #include "WidgetFactory.h"
141 #include "3Dconnexion/navlib/NavlibInterface.h"
142 #include "Inventor/SoFCPlacementIndicatorKit.h"
143 #include "QtWidgets.h"
144
145 #include <FreeCADStyle.h>
146 #include <OverlayManager.h>
147 #include <ParamHandler.h>
148 #include <Base/ServiceProvider.h>
149
150 #ifdef BUILD_TRACY_FRAME_PROFILER
151 # include <tracy/Tracy.hpp>
152 #endif
153
154 using namespace Gui;
155 using namespace Gui::DockWnd;
156 using namespace std;
157 namespace sp = std::placeholders;
158
159 FC_LOG_LEVEL_INIT("Gui")
160
161 Application* Application::Instance = nullptr;
162
163 namespace Gui
164 {
165
166 class ViewProviderMap
167 {
168 std::unordered_map<const App::DocumentObject*, ViewProvider*> map;
169
170 public:
171 void newObject(const ViewProvider& vp)
172 {
173 auto vpd = freecad_cast<ViewProviderDocumentObject*>(const_cast<ViewProvider*>(&vp));
174 if (vpd && vpd->getObject()) {
175 map[vpd->getObject()] = vpd;
176 }
177 }
178 void deleteObject(const ViewProvider& vp)
179 {
180 auto vpd = freecad_cast<ViewProviderDocumentObject*>(const_cast<ViewProvider*>(&vp));
181 if (vpd && vpd->getObject()) {
182 map.erase(vpd->getObject());
183 }
184 }
185 void deleteDocument(const App::Document& doc)
186 {
187 for (auto obj : doc.getObjects()) {
188 map.erase(obj);
189 }
190 }
191 Gui::ViewProvider* getViewProvider(const App::DocumentObject* obj) const
192 {
193 auto it = map.find(obj);
194 if (it == map.end()) {
195 return nullptr;
196 }
197 return it->second;
198 }
199 };
200
201 // Pimpl class
202 struct ApplicationP
203 {
204 explicit ApplicationP(bool GUIenabled)
205 {
206 // create the macro manager
207 if (GUIenabled) {
208 macroMngr = new MacroManager();
209 }
210 else {
211 macroMngr = nullptr;
212 }
213
214 // Create the Theme Manager
215 prefPackManager = new PreferencePackManager();
216 // Create the Style Parameter Manager
217 styleParameterManager = new StyleParameters::ParameterManager();
218 }
219
220 ~ApplicationP()
221 {
222 delete macroMngr;
223 delete prefPackManager;
224 }
225
226 /// list of all handled documents
227 std::map<const App::Document*, Gui::Document*> documents;
228 /// Active document
229 Gui::Document* activeDocument {nullptr};
230 Gui::Document* editDocument {nullptr};
231
232 MacroManager* macroMngr;
233 PreferencePackManager* prefPackManager;
234 StyleParameters::ParameterManager* styleParameterManager;
235
236 /// List of all registered views
237 std::list<Gui::BaseView*> passive;
238 bool isClosing {false};
239 bool startingUp {true};
240 /// Handles all commands
241 CommandManager commandManager;
242 ViewProviderMap viewproviderMap;
243 std::bitset<32> StatusBits;
244 };
245
246 static PyObject* FreeCADGui_subgraphFromObject(PyObject* /*self*/, PyObject* args)
247 {
248 PyObject* o;
249 if (!PyArg_ParseTuple(args, "O!", &(App::DocumentObjectPy::Type), &o)) {
250 return nullptr;
251 }
252 App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(o)->getDocumentObjectPtr();
253 std::string vp = obj->getViewProviderName();
254 SoNode* node = nullptr;
255 try {
256 auto base = static_cast<Base::BaseClass*>(Base::Type::createInstanceByName(vp.c_str(), true));
257 if (base && base->isDerivedFrom<Gui::ViewProviderDocumentObject>()) {
258 std::unique_ptr<Gui::ViewProviderDocumentObject> vp(
259 static_cast<Gui::ViewProviderDocumentObject*>(base)
260 );
261 std::map<std::string, App::Property*> Map;
262 obj->getPropertyMap(Map);
263 vp->attach(obj);
264
265 // this is needed to initialize Python-based view providers
266 App::Property* pyproxy = vp->getPropertyByName("Proxy");
267 if (pyproxy && pyproxy->is<App::PropertyPythonObject>()) {
268 static_cast<App::PropertyPythonObject*>(pyproxy)->setValue(Py::Long(1));
269 }
270
271 for (const auto& it : Map) {
272 vp->updateData(it.second);
273 }
274
275 std::vector<std::string> modes = vp->getDisplayModes();
276 if (!modes.empty()) {
277 vp->setDisplayMode(modes.front().c_str());
278 }
279 node = vp->getRoot()->copy();
280 node->ref();
281 std::string prefix = "So";
282 std::string type = node->getTypeId().getName().getString();
283 // doesn't start with the prefix 'So'
284 if (type.rfind("So", 0) != 0) {
285 type = prefix + type;
286 }
287 else if (type == "SoFCSelectionRoot") {
288 type = "SoSeparator";
289 }
290
291 type += " *";
292 PyObject* proxy = nullptr;
293 proxy = Base::Interpreter()
294 .createSWIGPointerObj("pivy.coin", type.c_str(), static_cast<void*>(node), 1);
295 return Py::new_reference_to(Py::Object(proxy, true));
296 }
297 }
298 catch (const Base::Exception& e) {
299 if (node) {
300 node->unref();
301 }
302 PyErr_SetString(PyExc_RuntimeError, e.what());
303 return nullptr;
304 }
305
306 Py_INCREF(Py_None);
307 return Py_None;
308 }
309
310 static PyObject* FreeCADGui_exportSubgraph(PyObject* /*self*/, PyObject* args)
311 {
312 const char* format = "VRML";
313 PyObject* proxy;
314 PyObject* output;
315 if (!PyArg_ParseTuple(args, "OO|s", &proxy, &output, &format)) {
316 return nullptr;
317 }
318
319 void* ptr = nullptr;
320 try {
321 Base::Interpreter().convertSWIGPointerObj("pivy.coin", "SoNode *", proxy, &ptr, 0);
322 auto node = static_cast<SoNode*>(ptr);
323 if (node) {
324 std::string formatStr(format);
325 std::string buffer;
326
327 if (formatStr == "VRML") {
328 SoFCDB::writeToVRML(node, buffer);
329 }
330 else if (formatStr == "IV") {
331 buffer = SoFCDB::writeNodesToString(node);
332 }
333 else {
334 throw Base::ValueError("Unsupported format");
335 }
336
337 Base::PyStreambuf buf(output);
338 std::ostream str(nullptr);
339 str.rdbuf(&buf);
340 str << buffer;
341 }
342
343 Py_INCREF(Py_None);
344 return Py_None;
345 }
346 catch (const Base::Exception& e) {
347 PyErr_SetString(PyExc_RuntimeError, e.what());
348 return nullptr;
349 }
350 }
351
352 static PyObject* FreeCADGui_getSoDBVersion(PyObject* /*self*/, PyObject* args)
353 {
354 if (!PyArg_ParseTuple(args, "")) {
355 return nullptr;
356 }
357 return PyUnicode_FromString(SoDB::getVersion());
358 }
359
360 struct PyMethodDef FreeCADGui_methods[] = {
361 {"subgraphFromObject",
362 FreeCADGui_subgraphFromObject,
363 METH_VARARGS,
364 "subgraphFromObject(object) -> Node\n\n"
365 "Return the Inventor subgraph to an object"},
366 {"exportSubgraph",
367 FreeCADGui_exportSubgraph,
368 METH_VARARGS,
369 "exportSubgraph(Node, File or Buffer, [Format='VRML']) -> None\n\n"
370 "Exports the sub-graph in the requested format"
371 "The format string can be VRML or IV"},
372 {"getSoDBVersion",
373 FreeCADGui_getSoDBVersion,
374 METH_VARARGS,
375 "getSoDBVersion() -> String\n\n"
376 "Return a text string containing the name\n"
377 "of the Coin library and version information"},
378 {nullptr, nullptr, 0, nullptr} /* sentinel */
379 };
380
381 } // namespace Gui
382
383 void Application::initStyleParameterManager()
384 {
385 static ParamHandlers handlers;
386
387 const auto deduceParametersFilePath = []() -> std::string {
388 const auto hMainWindowGrp = App::GetApplication().GetParameterGroupByPath(
389 "User parameter:BaseApp/Preferences/MainWindow"
390 );
391
392 if (const std::string& path = hMainWindowGrp->GetASCII("ThemeStyleParametersFile");
393 !path.empty()) {
394 return path;
395 }
396
397 return fmt::format("qss:parameters/{}.yaml", hMainWindowGrp->GetASCII("Theme", "Classic"));
398 };
399
400 auto themeParametersSource = new StyleParameters::YamlParameterSource(
401 deduceParametersFilePath(),
402 {.name = QT_TR_NOOP("Theme Parameters"),
403 .options = StyleParameters::ParameterSourceOption::UserEditable}
404 );
405
406 auto reloadStylesheetHandler = handlers.addDelayedHandler(
407 "BaseApp/Preferences/MainWindow",
408 {"ThemeStyleParametersFiles", "Theme", "StyleSheet"},
409 [themeParametersSource, deduceParametersFilePath, this](ParameterGrp::handle hGrp) {
410 themeParametersSource->changeFilePath(deduceParametersFilePath());
411 styleParameterManager()->reload();
412
413 std::string sheet = hGrp->GetASCII("StyleSheet");
414 bool tiledBG = hGrp->GetBool("TiledBackground", false);
415
416 setStyleSheet(QString::fromStdString(sheet), tiledBG);
417 }
418 );
419
420 handlers.addHandler(
421 "BaseApp/Preferences/Themes",
422 {"ThemeAccentColor1", "ThemeAccentColor2", "ThemeAccentColor2"},
423 reloadStylesheetHandler
424 );
425
426 Base::registerServiceImplementation<StyleParameters::ParameterSource>(
427 new StyleParameters::BuiltInParameterSource({.name = QT_TR_NOOP("Built-in Parameters")})
428 );
429
430 // todo: left for compatibility with older theme versions, to be removed before release
431 Base::registerServiceImplementation<StyleParameters::ParameterSource>(
432 new StyleParameters::UserParameterSource(
433 App::GetApplication().GetParameterGroupByPath(
434 "User parameter:BaseApp/Preferences/Themes/UserTokens"
435 ),
436 {.name = QT_TR_NOOP("Theme Parameters - Fallback"),
437 .options = StyleParameters::ParameterSourceOption::ReadOnly}
438 )
439 );
440
441 Base::registerServiceImplementation<StyleParameters::ParameterSource>(themeParametersSource);
442
443 Base::registerServiceImplementation<StyleParameters::ParameterSource>(
444 new StyleParameters::UserParameterSource(
445 App::GetApplication().GetParameterGroupByPath(
446 "User parameter:BaseApp/Preferences/Themes/UserParameters"
447 ),
448 {.name = QT_TR_NOOP("User Parameters"),
449 .options = StyleParameters::ParameterSource::UserEditable}
450 )
451 );
452
453 const auto sources = Base::provideServiceImplementations<StyleParameters::ParameterSource>();
454 for (auto* source : std::views::all(sources) | std::views::reverse) {
455 d->styleParameterManager->addSource(source);
456 }
457
458 Base::registerServiceImplementation(d->styleParameterManager);
459 }
460 // clang-format off
461 Application::Application(bool GUIenabled)
462 {
463 // App::GetApplication().Attach(this);
464 if (GUIenabled) {
465 // NOLINTBEGIN
466 App::GetApplication().signalNewDocument.connect(
467 std::bind(&Gui::Application::slotNewDocument, this, sp::_1, sp::_2));
468 App::GetApplication().signalDeleteDocument.connect(
469 std::bind(&Gui::Application::slotDeleteDocument, this, sp::_1));
470 App::GetApplication().signalRenameDocument.connect(
471 std::bind(&Gui::Application::slotRenameDocument, this, sp::_1));
472 App::GetApplication().signalActiveDocument.connect(
473 std::bind(&Gui::Application::slotActiveDocument, this, sp::_1));
474 App::GetApplication().signalRelabelDocument.connect(
475 std::bind(&Gui::Application::slotRelabelDocument, this, sp::_1));
476 App::GetApplication().signalShowHidden.connect(
477 std::bind(&Gui::Application::slotShowHidden, this, sp::_1));
478 // NOLINTEND
479 // install the last active language
480 ParameterGrp::handle hPGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp");
481 hPGrp = hPGrp->GetGroup("Preferences")->GetGroup("General");
482 QString lang = QLocale::languageToString(QLocale().language());
483 Translator::instance()->activateLanguage(
484 hPGrp->GetASCII("Language", (const char*)lang.toLatin1()).c_str());
485 GetWidgetFactorySupplier();
486
487 // Coin3d disabled VBO support for all Intel drivers but in the meantime they have improved
488 // so we can try to override the workaround by setting COIN_VBO
489 ParameterGrp::handle hViewGrp = App::GetApplication().GetParameterGroupByPath(
490 "User parameter:BaseApp/Preferences/View");
491 if (hViewGrp->GetBool("UseVBO", false)) {
492 (void)coin_setenv("COIN_VBO", "0", true);
493 }
494
495 // Check for the symbols for group separator and decimal point. They must be different
496 // otherwise Qt doesn't work properly.
497 #if defined(Q_OS_WIN32)
498 if (QLocale().groupSeparator() == QLocale().decimalPoint()) {
499 QMessageBox::critical(
500 0,
501 QLatin1String("Invalid system settings"),
502 QLatin1String(
503 "The system locale uses the same symbol for the decimal point and the thousands separator.\n\n"
504 "This may prevent the application from functioning correctly."
505 "Go to the system configuration panel of the OS and fix this issue."));
506 throw Base::RuntimeError("Invalid system settings");
507 }
508 #endif
509
510 // setting up Python binding
511 Base::PyGILStateLocker lock;
512
513 PyDoc_STRVAR(
514 FreeCADGui_doc,
515 "The functions in the FreeCADGui module allow working with GUI documents,\n"
516 "view providers, views, workbenches and much more.\n\n"
517 "The FreeCADGui instance provides a list of references of GUI documents which\n"
518 "can be addressed by a string. These documents contain the view providers for\n"
519 "objects in the associated App document. An App and GUI document can be\n"
520 "accessed with the same name.\n\n"
521 "The FreeCADGui module also provides a set of functions to work with so called\n"
522 "workbenches.");
523
524 // if this returns a valid pointer then the 'FreeCADGui' Python module was loaded,
525 // otherwise the executable was launched
526 PyObject* modules = PyImport_GetModuleDict();
527 PyObject* module = PyDict_GetItemString(modules, "FreeCADGui");
528 if (!module) {
529 static struct PyModuleDef FreeCADGuiModuleDef = {PyModuleDef_HEAD_INIT,
530 "FreeCADGui",
531 FreeCADGui_doc,
532 -1,
533 ApplicationPy::Methods,
534 nullptr,
535 nullptr,
536 nullptr,
537 nullptr};
538 module = PyModule_Create(&FreeCADGuiModuleDef);
539
540 PyDict_SetItemString(modules, "FreeCADGui", module);
541 }
542 else {
543 // extend the method list
544 PyModule_AddFunctions(module, ApplicationPy::Methods);
545 }
546 Py::Module(module).setAttr(std::string("ActiveDocument"), Py::None());
547 Py::Module(module).setAttr(std::string("HasQtBug_129596"),
548 #ifdef HAS_QTBUG_129596
549 Py::True()
550 #else
551 Py::False()
552 #endif
553 );
554
555 UiLoaderPy::init_type();
556 Base::Interpreter().addType(UiLoaderPy::type_object(), module, "UiLoader");
557 PyResource::init_type();
558
559 Gui::Dialog::TaskPlacementPy::init_type();
560 Base::Interpreter().addType(Gui::Dialog::TaskPlacementPy::type_object(),
561 module, "TaskPlacement");
562
563 // PySide additions
564 PyModule_AddObject(module, "PySideUic", Base::Interpreter().addModule(new PySideUicModule));
565
566 ExpressionBindingPy::init_type();
567 Base::Interpreter().addType(ExpressionBindingPy::type_object(),
568 module,
569 "ExpressionBinding");
570
571 // insert Selection module
572 static struct PyModuleDef SelectionModuleDef = {PyModuleDef_HEAD_INIT,
573 "Selection",
574 "Selection module",
575 -1,
576 SelectionSingleton::Methods,
577 nullptr,
578 nullptr,
579 nullptr,
580 nullptr};
581 PyObject* pSelectionModule = PyModule_Create(&SelectionModuleDef);
582 Py_INCREF(pSelectionModule);
583 PyModule_AddObject(module, "Selection", pSelectionModule);
584
585 SelectionFilterPy::init_type();
586 Base::Interpreter().addType(SelectionFilterPy::type_object(), pSelectionModule, "Filter");
587
588 Gui::TaskView::ControlPy::init_type();
589 Py::Module(module).setAttr(std::string("Control"),
590 Py::Object(Gui::TaskView::ControlPy::getInstance(), true));
591 Gui::TaskView::TaskDialogPy::init_type();
592
593 registerUserInputEnumInPython(module);
594 Base::PyRegisterEnum<SoFCPlacementIndicatorKit::Part>(module, "PlacementIndicatorParts", {
595 {"Axes", SoFCPlacementIndicatorKit::Axes},
596 {"ArrowHeads", SoFCPlacementIndicatorKit::ArrowHeads},
597 {"Labels", SoFCPlacementIndicatorKit::Labels},
598 {"PlaneIndicator", SoFCPlacementIndicatorKit::PlaneIndicator},
599 {"OriginIndicator", SoFCPlacementIndicatorKit::OriginIndicator},
600
601 // common configurations
602 {"AllParts", SoFCPlacementIndicatorKit::AllParts},
603 {"AxisCross", SoFCPlacementIndicatorKit::AxisCross},
604 });
605
606 Base::PyRegisterEnum<Gui::BitmapFactoryInst::Position>(module, "IconPosition", {
607 {"TopLeft", Gui::BitmapFactoryInst::TopLeft},
608 {"TopRight", Gui::BitmapFactoryInst::TopRight},
609 {"BottomLeft", Gui::BitmapFactoryInst::BottomLeft},
610 {"BottomRight", Gui::BitmapFactoryInst::BottomRight}
611 });
612
613 CommandActionPy::init_type();
614 Base::Interpreter().addType(CommandActionPy::type_object(), module, "CommandAction");
615
616 Base::Interpreter().addType(&LinkViewPy::Type, module, "LinkView");
617 Base::Interpreter().addType(&AxisOriginPy::Type, module, "AxisOrigin");
618 Base::Interpreter().addType(&CommandPy::Type, module, "Command");
619 Base::Interpreter().addType(&DocumentPy::Type, module, "Document");
620 Base::Interpreter().addType(&ViewProviderPy::Type, module, "ViewProvider");
621 Base::Interpreter().addType(&ViewProviderDocumentObjectPy::Type,
622 module,
623 "ViewProviderDocumentObject");
624 Base::Interpreter().addType(&ViewProviderGeometryObjectPy::Type,
625 module,
626 "ViewProviderGeometryObject");
627 Base::Interpreter().addType(&ViewProviderLinkPy::Type, module, "ViewProviderLink");
628 }
629
630 Base::PyGILStateLocker lock;
631 PyObject* module = PyImport_AddModule("FreeCADGui");
632 PyMethodDef* meth = FreeCADGui_methods;
633 PyObject* dict = PyModule_GetDict(module);
634 for (; meth->ml_name != nullptr; meth++) {
635 PyObject* descr;
636 descr = PyCFunction_NewEx(meth, nullptr, nullptr);
637 if (!descr) {
638 break;
639 }
640 if (PyDict_SetItemString(dict, meth->ml_name, descr) != 0) {
641 break;
642 }
643 Py_DECREF(descr);
644 }
645
646 SoQtOffscreenRendererPy::init_type();
647 Base::Interpreter().addType(SoQtOffscreenRendererPy::type_object(),
648 module,
649 "SoQtOffscreenRenderer");
650
651 App::Application::Config()["COIN_VERSION"] = COIN_VERSION;
652
653 // clang-format off
654 // Python console binding
655 PythonDebugModule ::init_module();
656 PythonStdout ::init_type();
657 PythonStderr ::init_type();
658 OutputStdout ::init_type();
659 OutputStderr ::init_type();
660 PythonStdin ::init_type();
661 MainWindowPy ::init_type();
662 MDIViewPy ::init_type();
663 View3DInventorPy ::init_type();
664 View3DInventorViewerPy ::init_type();
665 AbstractSplitViewPy ::init_type();
666 // clang-format on
667
668 d = new ApplicationP(GUIenabled);
669
670 initStyleParameterManager();
671
672 // global access
673 Instance = this;
674
675 // instantiate the workbench dictionary
676 _pcWorkbenchDictionary = PyDict_New();
677
678 #ifdef USE_3DCONNEXION_NAVLIB
679 ParameterGrp::handle hViewGrp = App::GetApplication().GetParameterGroupByPath(
680 "User parameter:BaseApp/Preferences/View"
681 );
682 if (!hViewGrp->GetBool("LegacySpaceMouseDevices", false)) {
683 // Instantiate the 3Dconnexion controller
684 pNavlibInterface = new NavlibInterface();
685 }
686 else {
687 pNavlibInterface = nullptr;
688 }
689 #endif
690
691 if (GUIenabled) {
692 createStandardOperations();
693 MacroCommand::load();
694 }
695 }
696 // clang-format on
697
698 Application::~Application()
699 {
700 Base::Console().log("Destruct Gui::Application\n");
701 #ifdef USE_3DCONNEXION_NAVLIB
702 delete pNavlibInterface;
703 #endif
704 WorkbenchManager::destruct();
705 WorkbenchManipulator::removeAll();
706 SelectionSingleton::destruct();
707 Translator::destruct();
708 WidgetFactorySupplier::destruct();
709 BitmapFactoryInst::destruct();
710
711 Base::PyGILStateLocker lock;
712 Py_DECREF(_pcWorkbenchDictionary);
713
714 // save macros
715 try {
716 MacroCommand::save();
717 }
718 catch (const Base::Exception& e) {
719 std::cerr << "Saving macros failed: " << e.what() << std::endl;
720 }
721
722 delete d;
723 Instance = nullptr;
724 }
725
726
727 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
728 // creating std commands
729 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
730
731
732 void Application::open(const char* FileName, const char* Module)
733 {
734 WaitCursor wc;
735 wc.setIgnoreEvents(WaitCursor::NoEvents);
736 Base::FileInfo File(FileName);
737 string te = File.extension();
738 string unicodepath = Base::Tools::escapedUnicodeFromUtf8(File.filePath().c_str());
739 unicodepath = Base::Tools::escapeEncodeFilename(unicodepath);
740
741 // if the active document is empty and not modified, close it
742 // in case of an automatically created empty document at startup
743 App::Document* act = App::GetApplication().getActiveDocument();
744 Gui::Document* gui = this->getDocument(act);
745 if (act && act->countObjects() == 0 && gui && !gui->isModified() && act->isAutoCreated()) {
746 Command::doCommand(Command::App, "App.closeDocument('%s')", act->getName());
747 qApp->processEvents(); // an update is needed otherwise the new view isn't shown
748 }
749
750 if (Module) {
751 try {
752 if (File.hasExtension("FCStd")) {
753 bool handled = false;
754 std::string filepath = File.filePath();
755 for (auto& v : d->documents) {
756 auto doc = v.second->getDocument();
757 std::string fi = Base::FileInfo(doc->FileName.getValue()).filePath();
758 if (filepath == fi) {
759 handled = true;
760 Command::doCommand(Command::App, "FreeCADGui.reload('%s')", doc->getName());
761 break;
762 }
763 }
764
765 if (!handled) {
766 Command::doCommand(Command::App, "FreeCAD.openDocument('%s')", unicodepath.c_str());
767 Gui::Application::checkForRecomputes();
768 }
769 }
770 else {
771 std::string code = fmt::format(
772 "from freecad import module_io\n"
773 "module_io.OpenInsertObject(\"{}\", \"{}\", \"{}\")\n",
774 Module,
775 unicodepath,
776 "open"
777 );
778 Gui::Command::runCommand(Gui::Command::App, code.c_str());
779
780 // ViewFit
781 if (sendHasMsgToActiveView("ViewFit")) {
782 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
783 "User parameter:BaseApp/Preferences/View"
784 );
785 if (hGrp->GetBool("AutoFitToView", true)) {
786 Command::doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"ViewFit\")");
787 }
788 }
789 }
790
791 // the original file name is required
792 QString filename = QString::fromUtf8(File.filePath().c_str());
793 getMainWindow()->appendRecentFile(filename);
794 FileDialog::setWorkingDirectory(filename);
795 }
796 catch (const Base::Exception& e) {
797 // Usually thrown if the file is invalid somehow
798 e.reportException();
799 }
800 }
801 else {
802 wc.restoreCursor();
803 QMessageBox::warning(
804 getMainWindow(),
805 QObject::tr("Unknown filetype"),
806 QObject::tr("Cannot open unknown filetype: %1").arg(QLatin1String(te.c_str()))
807 );
808 wc.setWaitCursor();
809 return;
810 }
811 }
812
813 void Application::importFrom(const char* FileName, const char* DocName, const char* Module)
814 {
815 WaitCursor wc;
816 wc.setIgnoreEvents(WaitCursor::NoEvents);
817 Base::FileInfo File(FileName);
818 std::string te = File.extension();
819 string unicodepath = File.filePath().c_str();
820 unicodepath = Base::Tools::escapeEncodeFilename(unicodepath);
821
822 if (Module) {
823 try {
824 // issue module loading
825 Command::doCommand(Command::App, "import %s", Module);
826
827 // load the file with the module
828 if (File.hasExtension("FCStd")) {
829 Command::doCommand(Command::App, "%s.open(u\"%s\")", Module, unicodepath.c_str());
830 setStatus(UserInitiatedOpenDocument, false);
831 App::Document* doc = App::GetApplication().getActiveDocument();
832 checkPartialRestore(doc);
833 checkRestoreError(doc);
834 checkForRecomputes();
835 if (activeDocument()) {
836 activeDocument()->setModified(false);
837 }
838 }
839 else {
840 // Open transaction when importing a file
841 Gui::Document* doc = DocName ? getDocument(DocName) : activeDocument();
842 bool pendingCommand = false;
843 if (doc) {
844 pendingCommand = doc->hasPendingCommand();
845 if (!pendingCommand) {
846 doc->openCommand(QT_TRANSLATE_NOOP("Command", "Import"));
847 }
848 }
849
850 std::string code = fmt::format(
851 "from freecad import module_io\n"
852 "module_io.OpenInsertObject(\"{}\", \"{}\", \"{}\", \"{}\")\n",
853 Module,
854 unicodepath,
855 "insert",
856 DocName
857 );
858 Gui::Command::runCommand(Gui::Command::App, code.c_str());
859
860 // Commit the transaction
861 if (doc && !pendingCommand) {
862 doc->commitCommand();
863 }
864
865 // It's possible that before importing a file the document with the
866 // given name doesn't exist or there is no active document.
867 // The import function then may create a new document.
868 if (!doc) {
869 doc = activeDocument();
870 }
871
872 if (doc) {
873 doc->setModified(true);
874
875 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
876 "User parameter:BaseApp/Preferences/View"
877 );
878 if (hGrp->GetBool("AutoFitToView", true)) {
879 MDIView* view = doc->getActiveView();
880 if (view) {
881 const char* ret = nullptr;
882 if (view->onMsg("ViewFit", &ret)) {
883 updateActions(true);
884 }
885 }
886 }
887 }
888 }
889
890 // the original file name is required
891 QString filename = QString::fromUtf8(File.filePath().c_str());
892 auto parameterGroup = App::GetApplication().GetParameterGroupByPath(
893 "User parameter:BaseApp/Preferences/General"
894 );
895 bool addToRecent = parameterGroup->GetBool("RecentIncludesImported", true);
896 parameterGroup->SetBool(
897 "RecentIncludesImported",
898 addToRecent
899 ); // Make sure it gets added to the parameter list
900 if (addToRecent) {
901 getMainWindow()->appendRecentFile(filename);
902 }
903 FileDialog::setWorkingDirectory(filename);
904 }
905 catch (const Base::Exception& e) {
906 // Usually thrown if the file is invalid somehow
907 e.reportException();
908 }
909 }
910 else {
911 wc.restoreCursor();
912 QMessageBox::warning(
913 getMainWindow(),
914 QObject::tr("Unknown filetype"),
915 QObject::tr("Cannot open unknown filetype: %1").arg(QLatin1String(te.c_str()))
916 );
917 wc.setWaitCursor();
918 }
919 }
920
921 void Application::exportTo(const char* FileName, const char* DocName, const char* Module)
922 {
923 WaitCursor wc;
924 wc.setIgnoreEvents(WaitCursor::NoEvents);
925 Base::FileInfo File(FileName);
926 std::string te = File.extension();
927 string unicodepath = Base::Tools::escapedUnicodeFromUtf8(File.filePath().c_str());
928 unicodepath = Base::Tools::escapeEncodeFilename(unicodepath);
929
930 if (strcmp(Module, "Part") == 0) {
931 FC_WARN("Exporting with 'Part' is deprecated, use 'ImportGui' instead");
932 }
933
934 if (Module) {
935 try {
936 std::vector<App::DocumentObject*> sel
937 = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId(), DocName);
938 if (sel.empty()) {
939 App::Document* doc = App::GetApplication().getDocument(DocName);
940 sel = doc->getObjectsOfType(App::DocumentObject::getClassTypeId());
941 }
942
943 std::stringstream str;
944 std::set<App::DocumentObject*> unique_objs;
945 str << "__objs__ = []\n";
946 for (auto it : sel) {
947 if (unique_objs.insert(it).second) {
948 str << "__objs__.append(FreeCAD.getDocument(\"" << DocName << "\").getObject(\""
949 << it->getNameInDocument() << "\"))\n";
950 }
951 }
952
953 // check for additional export options
954 str << "import " << Module << '\n';
955 str << "if hasattr(" << Module << ", \"exportOptions\"):\n"
956 << " options = " << Module << ".exportOptions(u\"" << unicodepath << "\")\n"
957 << " " << Module << ".export(__objs__, u\"" << unicodepath << "\", options)\n"
958 << "else:\n"
959 << " " << Module << ".export(__objs__, u\"" << unicodepath << "\")\n";
960
961 std::string code = str.str();
962 // the original file name is required
963 Gui::Command::runCommand(Gui::Command::App, code.c_str());
964
965 auto parameterGroup = App::GetApplication().GetParameterGroupByPath(
966 "User parameter:BaseApp/Preferences/General"
967 );
968 bool addToRecent = parameterGroup->GetBool("RecentIncludesExported", false);
969 parameterGroup->SetBool(
970 "RecentIncludesExported",
971 addToRecent
972 ); // Make sure it gets added to the parameter list
973 if (addToRecent) {
974 // search for a module that is able to open the exported file because otherwise
975 // it doesn't need to be added to the recent files list (#0002047)
976 std::map<std::string, std::string> importMap
977 = App::GetApplication().getImportFilters(te.c_str());
978 if (!importMap.empty()) {
979 getMainWindow()->appendRecentFile(QString::fromUtf8(File.filePath().c_str()));
980 }
981 }
982 // allow exporters to pass _objs__ to submodules before deleting it
983 Gui::Command::runCommand(Gui::Command::App, "del __objs__");
984 }
985 catch (const Base::PyException& e) {
986 // Usually thrown if the file is invalid somehow
987 e.reportException();
988 wc.restoreCursor();
989 QMessageBox::critical(
990 getMainWindow(),
991 QObject::tr("Export failed"),
992 QString::fromUtf8(e.what())
993 );
994 wc.setWaitCursor();
995 }
996 }
997 else {
998 wc.restoreCursor();
999 QMessageBox::warning(
1000 getMainWindow(),
1001 QObject::tr("Unknown filetype"),
1002 QObject::tr("Cannot save to unknown filetype: %1").arg(QLatin1String(te.c_str()))
1003 );
1004 wc.setWaitCursor();
1005 }
1006 }
1007
1008 void Application::createStandardOperations()
1009 {
1010 // register the application Standard commands from CommandStd.cpp
1011 Gui::CreateStdCommands();
1012 Gui::CreateDocCommands();
1013 Gui::CreateFeatCommands();
1014 Gui::CreateMacroCommands();
1015 Gui::CreateViewStdCommands();
1016 Gui::CreateWindowStdCommands();
1017 Gui::CreateStructureCommands();
1018 Gui::CreateTestCommands();
1019 Gui::CreateLinkCommands();
1020 }
1021
1022 void Application::slotNewDocument(const App::Document& Doc, bool isMainDoc)
1023 {
1024 #ifdef FC_DEBUG
1025 assert(d->documents.find(&Doc) == d->documents.end());
1026 #endif
1027 auto pDoc = new Gui::Document(const_cast<App::Document*>(&Doc), this);
1028 d->documents[&Doc] = pDoc;
1029
1030 // NOLINTBEGIN
1031 // connect the signals to the application for the new document
1032 pDoc->signalNewObject.connect(std::bind(&Gui::Application::slotNewObject, this, sp::_1));
1033 pDoc->signalDeletedObject.connect(std::bind(&Gui::Application::slotDeletedObject, this, sp::_1));
1034 pDoc->signalChangedObject.connect(
1035 std::bind(&Gui::Application::slotChangedObject, this, sp::_1, sp::_2)
1036 );
1037 pDoc->signalRelabelObject.connect(std::bind(&Gui::Application::slotRelabelObject, this, sp::_1));
1038 pDoc->signalActivatedObject.connect(
1039 std::bind(&Gui::Application::slotActivatedObject, this, sp::_1)
1040 );
1041 pDoc->signalInEdit.connect(std::bind(&Gui::Application::slotInEdit, this, sp::_1));
1042 pDoc->signalResetEdit.connect(std::bind(&Gui::Application::slotResetEdit, this, sp::_1));
1043 // NOLINTEND
1044
1045 signalNewDocument(*pDoc, isMainDoc);
1046 if (isMainDoc) {
1047 pDoc->createView(View3DInventor::getClassTypeId());
1048 }
1049 }
1050
1051 void Application::slotDeleteDocument(const App::Document& Doc)
1052 {
1053 // Capture dependencies and their CURRENT view state before the document is destroyed.
1054 struct Candidate
1055 {
1056 std::string name;
1057 bool hadViews;
1058 };
1059 std::vector<Candidate> candidates;
1060
1061 try {
1062 std::vector<App::Document*> deps = const_cast<App::Document&>(Doc).getDependentDocuments();
1063
1064 for (auto d : deps) {
1065 if (d == &Doc) { // Skip self
1066 continue;
1067 }
1068
1069 // Check if this dependency currently has a visible tab/view
1070 Gui::Document* gDoc = getDocument(d);
1071 bool hasViews = (gDoc && !gDoc->getMDIViews().empty());
1072
1073 candidates.push_back({d->getName(), hasViews});
1074 }
1075 }
1076 catch (Base::Exception& e) {
1077 e.reportException();
1078 }
1079
1080 std::map<const App::Document*, Gui::Document*>::iterator doc = d->documents.find(&Doc);
1081 if (doc == d->documents.end()) {
1082 Base::Console().log("GUI document '%s' already deleted\n", Doc.getName());
1083 return;
1084 }
1085
1086 // Inside beforeDelete() a view provider may finish editing mode
1087 // and therefore can alter the selection.
1088 doc->second->beforeDelete();
1089
1090 // We must clear the selection here to notify all observers.
1091 // And because of possible cross document link, better clear all selection
1092 // to be safe
1093 Gui::Selection().clearCompleteSelection();
1094 doc->second->signalDeleteDocument(*doc->second);
1095 signalDeleteDocument(*doc->second);
1096
1097 // If the active document gets destructed we must set it to 0. If there are further existing
1098 // documents then the view that becomes active sets the active document again. So, we needn't
1099 // worry about this.
1100 if (d->activeDocument == doc->second) {
1101 setActiveDocument(nullptr);
1102 }
1103
1104 d->viewproviderMap.deleteDocument(Doc);
1105
1106 // For exception-safety use a smart pointer
1107 unique_ptr<Document> delDoc(doc->second);
1108 d->documents.erase(doc);
1109
1110 if (!candidates.empty()) {
1111 QTimer::singleShot(0, [candidates]() {
1112 for (const auto& cand : candidates) {
1113 App::Document* child = App::GetApplication().getDocument(cand.name.c_str());
1114 if (!child || child->isTouched() || cand.hadViews) {
1115 continue;
1116 }
1117
1118 // Reference Check: Is it used by any OTHER open document?
1119 bool isStillReferenced = false;
1120 std::vector<App::Document*> openDocs = App::GetApplication().getDocuments();
1121 for (App::Document* openDoc : openDocs) {
1122 if (openDoc == child) {
1123 continue; // Don't check self-reference
1124 }
1125
1126 try {
1127 std::vector<App::Document*> otherDeps = openDoc->getDependentDocuments();
1128 if (std::find(otherDeps.begin(), otherDeps.end(), child) != otherDeps.end()) {
1129 isStillReferenced = true;
1130 break;
1131 }
1132 }
1133 catch (Base::Exception& e) {
1134 e.reportException();
1135 continue;
1136 }
1137 }
1138
1139 // 5. Close if truly orphan
1140 if (!isStillReferenced) {
1141 App::GetApplication().closeDocument(cand.name.c_str());
1142 }
1143 }
1144 });
1145 }
1146 }
1147
1148 void Application::slotRelabelDocument(const App::Document& Doc)
1149 {
1150 std::map<const App::Document*, Gui::Document*>::iterator doc = d->documents.find(&Doc);
1151 #ifdef FC_DEBUG
1152 assert(doc != d->documents.end());
1153 #endif
1154
1155 signalRelabelDocument(*doc->second);
1156 doc->second->onRelabel();
1157 }
1158
1159 void Application::slotRenameDocument(const App::Document& Doc)
1160 {
1161 std::map<const App::Document*, Gui::Document*>::iterator doc = d->documents.find(&Doc);
1162 #ifdef FC_DEBUG
1163 assert(doc != d->documents.end());
1164 #endif
1165
1166 signalRenameDocument(*doc->second);
1167 }
1168
1169 void Application::slotShowHidden(const App::Document& Doc)
1170 {
1171 std::map<const App::Document*, Gui::Document*>::iterator doc = d->documents.find(&Doc);
1172 #ifdef FC_DEBUG
1173 assert(doc != d->documents.end());
1174 #endif
1175
1176 signalShowHidden(*doc->second);
1177 }
1178
1179 void Application::checkForRecomputes()
1180 {
1181 std::vector<App::Document*> docs;
1182 for (auto doc : App::GetApplication().getDocuments()) {
1183 if (doc->testStatus(App::Document::RecomputeOnRestore)) {
1184 docs.push_back(doc);
1185 doc->setStatus(App::Document::RecomputeOnRestore, false);
1186 }
1187 }
1188 // Certain tests want to use very old .FCStd files. We should not prompt during those tests, so
1189 // this allows them to 'FreeCAD.ConfigSet("SuppressRecomputeRequiredDialog", "True")`
1190 const std::map<std::string, std::string>& Map = App::Application::Config();
1191 auto value = Map.find("SuppressRecomputeRequiredDialog");
1192 bool skip = value != Map.end() && !value->second.empty(); // Any non empty string is true.
1193 if (docs.empty() || skip) {
1194 return;
1195 }
1196 WaitCursor wc;
1197 wc.restoreCursor();
1198 auto res = QMessageBox::warning(
1199 getMainWindow(),
1200 QObject::tr("Recomputation required"),
1201 QObject::tr(
1202 "Some documents require recomputation for migration purposes. "
1203 "It is highly recommended to perform a recomputation before "
1204 "any modification to avoid compatibility problems.\n\n"
1205 "Recompute now?"
1206 ),
1207 QMessageBox::Yes | QMessageBox::No,
1208 QMessageBox::Yes
1209 );
1210 if (res != QMessageBox::Yes) {
1211 return;
1212 }
1213 bool hasError = false;
1214 for (auto doc : App::Document::getDependentDocuments(docs, true)) {
1215 try {
1216 doc->recompute({}, false, &hasError);
1217 }
1218 catch (Base::Exception& e) {
1219 e.reportException();
1220 hasError = true;
1221 }
1222 }
1223 if (hasError) {
1224 QMessageBox::critical(
1225 getMainWindow(),
1226 QObject::tr("Recompute error"),
1227 QObject::tr(
1228 "Failed to recompute some documents.\n"
1229 "Check the report view for more details."
1230 )
1231 );
1232 }
1233 }
1234
1235 void Application::checkPartialRestore(App::Document* doc)
1236 {
1237 if (doc && doc->testStatus(App::Document::PartialRestore)) {
1238 QMessageBox::critical(
1239 getMainWindow(),
1240 QObject::tr("Error"),
1241 QObject::tr(
1242 "There were errors while loading the file. Some data might have been "
1243 "modified or not recovered at all. Look in the report view for more "
1244 "specific information about the objects involved."
1245 )
1246 );
1247 }
1248 }
1249
1250 void Application::checkRestoreError(App::Document* doc)
1251 {
1252 if (doc && doc->testStatus(App::Document::RestoreError)) {
1253 QMessageBox::critical(
1254 getMainWindow(),
1255 QObject::tr("Error"),
1256 QObject::tr(
1257 "There were serious errors while loading the file. Some data might have "
1258 "been modified or not recovered at all. Saving the project will most "
1259 "likely result in loss of data."
1260 )
1261 );
1262 }
1263 }
1264
1265 void Application::slotActiveDocument(const App::Document& Doc)
1266 {
1267 std::map<const App::Document*, Gui::Document*>::iterator doc = d->documents.find(&Doc);
1268 // this can happen when closing a document with two views opened
1269 if (doc != d->documents.end()) {
1270 // this can happen when calling App.setActiveDocument directly from Python
1271 // because no MDI view will be activated
1272 if (d->activeDocument != doc->second) {
1273 d->activeDocument = doc->second;
1274 if (d->activeDocument) {
1275 Base::PyGILStateLocker lock;
1276 Py::Object active(d->activeDocument->getPyObject(), true);
1277 Py::Module("FreeCADGui").setAttr(std::string("ActiveDocument"), active);
1278
1279 auto view = getMainWindow()->activeWindow();
1280 if (!view || view->getAppDocument() != &Doc) {
1281 Gui::MDIView* view = d->activeDocument->getActiveView();
1282 getMainWindow()->setActiveWindow(view);
1283 }
1284 }
1285 else {
1286 Base::PyGILStateLocker lock;
1287 Py::Module("FreeCADGui").setAttr(std::string("ActiveDocument"), Py::None());
1288 }
1289 }
1290
1291 // Update the application to show the unit change
1292 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
1293 "User parameter:BaseApp/Preferences/Units"
1294 );
1295 if (!hGrp->GetBool("IgnoreProjectSchema")) {
1296 int userSchema = Doc.UnitSystem.getValue();
1297 Base::UnitsApi::setSchema(userSchema);
1298 getMainWindow()->setUserSchema(userSchema);
1299 Application::Instance->onUpdate();
1300 }
1301 else { // set up Unit system default
1302 Base::UnitsApi::setSchema(hGrp->GetInt("UserSchema", 0));
1303 Base::UnitsApi::setDecimals(hGrp->GetInt("Decimals", Base::UnitsApi::getDecimals()));
1304 }
1305 signalActiveDocument(*doc->second);
1306 updateActions();
1307 }
1308 }
1309
1310 void Application::slotNewObject(const ViewProvider& vp)
1311 {
1312 d->viewproviderMap.newObject(vp);
1313 this->signalNewObject(vp);
1314 }
1315
1316 void Application::slotDeletedObject(const ViewProvider& vp)
1317 {
1318 this->signalDeletedObject(vp);
1319 d->viewproviderMap.deleteObject(vp);
1320 }
1321
1322 void Application::slotChangedObject(const ViewProvider& vp, const App::Property& prop)
1323 {
1324 this->signalChangedObject(vp, prop);
1325 updateActions(true);
1326 }
1327
1328 void Application::slotRelabelObject(const ViewProvider& vp)
1329 {
1330 this->signalRelabelObject(vp);
1331 }
1332
1333 void Application::slotActivatedObject(const ViewProvider& vp)
1334 {
1335 this->signalActivatedObject(vp);
1336 updateActions();
1337 }
1338
1339 void Application::slotInEdit(const Gui::ViewProviderDocumentObject& vp)
1340 {
1341 this->signalInEdit(vp);
1342 }
1343
1344 void Application::slotResetEdit(const Gui::ViewProviderDocumentObject& vp)
1345 {
1346 this->signalResetEdit(vp);
1347 }
1348
1349 void Application::onLastWindowClosed(Gui::Document* pcDoc)
1350 {
1351 try {
1352 if (!d->isClosing && pcDoc) {
1353 // Call the closing mechanism from Python. This also checks whether pcDoc is the last
1354 // open document.
1355 Command::doCommand(
1356 Command::Doc,
1357 "App.closeDocument(\"%s\")",
1358 pcDoc->getDocument()->getName()
1359 );
1360 if (!d->activeDocument && !d->documents.empty()) {
1361 Document* gdoc = nullptr;
1362 for (auto& v : d->documents) {
1363 if (v.second->getDocument()->testStatus(App::Document::TempDoc)) {
1364 continue;
1365 }
1366 else if (!gdoc) {
1367 gdoc = v.second;
1368 }
1369
1370 Gui::MDIView* view = v.second->getActiveView();
1371 if (view) {
1372 setActiveDocument(v.second);
1373 getMainWindow()->setActiveWindow(view);
1374 return;
1375 }
1376 }
1377
1378 if (gdoc) {
1379 setActiveDocument(gdoc);
1380 activateView(View3DInventor::getClassTypeId(), true);
1381 }
1382 }
1383 }
1384 }
1385 catch (const Base::Exception& e) {
1386 e.reportException();
1387 }
1388 catch (const Py::Exception&) {
1389 Base::PyException e;
1390 e.reportException();
1391 }
1392 catch (const std::exception& e) {
1393 Base::Console().error(
1394 "Unhandled std::exception caught in Application::onLastWindowClosed.\n"
1395 "The error message is: %s\n",
1396 e.what()
1397 );
1398 }
1399 catch (...) {
1400 Base::Console().error(
1401 "Unhandled unknown exception caught in Application::onLastWindowClosed.\n"
1402 );
1403 }
1404 }
1405
1406 /// send Messages to the active view
1407 bool Application::sendMsgToActiveView(const char* pMsg, const char** ppReturn)
1408 {
1409 MDIView* pView = getMainWindow()->activeWindow();
1410 bool res = pView ? pView->onMsg(pMsg, ppReturn) : false;
1411 updateActions(true);
1412 return res;
1413 }
1414
1415 bool Application::sendHasMsgToActiveView(const char* pMsg)
1416 {
1417 MDIView* pView = getMainWindow()->activeWindow();
1418 return pView ? pView->onHasMsg(pMsg) : false;
1419 }
1420
1421 /// send Messages to the active view
1422 bool Application::sendMsgToFocusView(const char* pMsg, const char** ppReturn)
1423 {
1424 MDIView* pView = getMainWindow()->activeWindow();
1425 if (!pView) {
1426 return false;
1427 }
1428 for (auto focus = qApp->focusWidget(); focus; focus = focus->parentWidget()) {
1429 if (focus == pView) {
1430 bool res = pView->onMsg(pMsg, ppReturn);
1431 updateActions(true);
1432 return res;
1433 }
1434 }
1435 return false;
1436 }
1437
1438 bool Application::sendHasMsgToFocusView(const char* pMsg)
1439 {
1440 MDIView* pView = getMainWindow()->activeWindow();
1441 if (!pView) {
1442 return false;
1443 }
1444 for (auto focus = qApp->focusWidget(); focus; focus = focus->parentWidget()) {
1445 if (focus == pView) {
1446 return pView->onHasMsg(pMsg);
1447 }
1448 }
1449 return false;
1450 }
1451
1452 Gui::MDIView* Application::activeView() const
1453 {
1454 if (activeDocument()) {
1455 return activeDocument()->getActiveView();
1456 }
1457 else {
1458 return nullptr;
1459 }
1460 }
1461
1462 /**
1463 * @brief Application::activateView
1464 * Activates a view of the given type of the active document.
1465 * If a view of this type doesn't exist and \a create is true
1466 * a new view of this type will be created.
1467 * @param type
1468 * @param create
1469 */
1470 void Application::activateView(const Base::Type& type, bool create)
1471 {
1472 Document* doc = activeDocument();
1473 if (doc) {
1474 MDIView* mdiView = doc->getActiveView();
1475 if (mdiView && mdiView->isDerivedFrom(type)) {
1476 return;
1477 }
1478 std::list<MDIView*> mdiViews = doc->getMDIViewsOfType(type);
1479 if (!mdiViews.empty()) {
1480 doc->setActiveWindow(mdiViews.back());
1481 }
1482 else if (create) {
1483 doc->createView(type);
1484 }
1485 }
1486 }
1487
1488 /// Getter for the active view
1489 Gui::Document* Application::activeDocument() const
1490 {
1491 return d->activeDocument;
1492 }
1493
1494 Gui::Document* Application::editDocument() const
1495 {
1496 return d->editDocument;
1497 }
1498
1499 Gui::MDIView* Application::editViewOfNode(SoNode* node) const
1500 {
1501 return d->editDocument ? d->editDocument->getViewOfNode(node) : nullptr;
1502 }
1503
1504 void Application::setEditDocument(Gui::Document* doc)
1505 {
1506 if (!doc) {
1507 d->editDocument = nullptr;
1508 }
1509 else if (doc == d->editDocument) {
1510 return;
1511 }
1512 for (auto& v : d->documents) {
1513 v.second->_resetEdit();
1514 }
1515 d->editDocument = doc;
1516 updateActions();
1517 }
1518
1519 void Application::setActiveDocument(Gui::Document* pcDocument)
1520 {
1521 if (d->activeDocument == pcDocument) {
1522 return; // nothing needs to be done
1523 }
1524
1525 updateActions();
1526
1527 if (pcDocument) {
1528 // This happens if a document with more than one view is about being
1529 // closed and a second view is activated. The document is still not
1530 // removed from the map.
1531 App::Document* doc = pcDocument->getDocument();
1532 if (d->documents.find(doc) == d->documents.end()) {
1533 return;
1534 }
1535 }
1536 d->activeDocument = pcDocument;
1537 std::string nameApp, nameGui;
1538
1539 // This adds just a line to the macro file but does not set the active document
1540 // Macro recording of this is problematic, thus it's written out as comment.
1541 if (pcDocument) {
1542 nameApp += "App.setActiveDocument(\"";
1543 nameApp += pcDocument->getDocument()->getName();
1544 nameApp += "\")\n";
1545 nameApp += "App.ActiveDocument=App.getDocument(\"";
1546 nameApp += pcDocument->getDocument()->getName();
1547 nameApp += "\")";
1548 macroManager()->addLine(MacroManager::Cmt, nameApp.c_str());
1549 nameGui += "Gui.ActiveDocument=Gui.getDocument(\"";
1550 nameGui += pcDocument->getDocument()->getName();
1551 nameGui += "\")";
1552 macroManager()->addLine(MacroManager::Cmt, nameGui.c_str());
1553 }
1554 else {
1555 nameApp += "App.setActiveDocument(\"\")\n";
1556 nameApp += "App.ActiveDocument=None";
1557 macroManager()->addLine(MacroManager::Cmt, nameApp.c_str());
1558 nameGui += "Gui.ActiveDocument=None";
1559 macroManager()->addLine(MacroManager::Cmt, nameGui.c_str());
1560 }
1561
1562 // Sets the currently active document
1563 try {
1564 Base::Interpreter().runString(nameApp.c_str());
1565 Base::Interpreter().runString(nameGui.c_str());
1566 }
1567 catch (const Base::Exception& e) {
1568 Base::Console().warning(e.what());
1569 return;
1570 }
1571
1572 #ifdef FC_DEBUG
1573 // May be useful for error detection
1574 if (d->activeDocument) {
1575 App::Document* doc = d->activeDocument->getDocument();
1576 Base::Console().log("Active document is %s (at %p)\n", doc->getName(), static_cast<void*>(doc));
1577 }
1578 else {
1579 Base::Console().log("No active document\n");
1580 }
1581 #endif
1582
1583 // notify all views attached to the application (not views belong to a special document)
1584 for (list<Gui::BaseView*>::iterator It = d->passive.begin(); It != d->passive.end(); ++It) {
1585 (*It)->setDocument(pcDocument);
1586 }
1587 }
1588
1589 Gui::Document* Application::getDocument(const char* name) const
1590 {
1591 App::Document* pDoc = App::GetApplication().getDocument(name);
1592 std::map<const App::Document*, Gui::Document*>::const_iterator it = d->documents.find(pDoc);
1593 if (it != d->documents.end()) {
1594 return it->second;
1595 }
1596 else {
1597 return nullptr;
1598 }
1599 }
1600
1601 Gui::Document* Application::getDocument(const App::Document* pDoc) const
1602 {
1603 std::map<const App::Document*, Gui::Document*>::const_iterator it = d->documents.find(pDoc);
1604 if (it != d->documents.end()) {
1605 return it->second;
1606 }
1607 else {
1608 return nullptr;
1609 }
1610 }
1611
1612 void Application::showViewProvider(const App::DocumentObject* obj)
1613 {
1614 ViewProvider* vp = getViewProvider(obj);
1615 if (vp) {
1616 vp->show();
1617 }
1618 }
1619
1620 void Application::hideViewProvider(const App::DocumentObject* obj)
1621 {
1622 ViewProvider* vp = getViewProvider(obj);
1623 if (vp) {
1624 vp->hide();
1625 }
1626 }
1627
1628 Gui::ViewProvider* Application::getViewProvider(const App::DocumentObject* obj) const
1629 {
1630 return d->viewproviderMap.getViewProvider(obj);
1631 }
1632
1633 void Application::attachView(Gui::BaseView* pcView)
1634 {
1635 d->passive.push_back(pcView);
1636 }
1637
1638 void Application::detachView(Gui::BaseView* pcView)
1639 {
1640 d->passive.remove(pcView);
1641 }
1642
1643 void Application::onUpdate()
1644 {
1645 // update all documents
1646 std::map<const App::Document*, Gui::Document*>::iterator It;
1647 for (It = d->documents.begin(); It != d->documents.end(); ++It) {
1648 It->second->onUpdate();
1649 }
1650 // update all the independent views
1651 for (std::list<Gui::BaseView*>::iterator It2 = d->passive.begin(); It2 != d->passive.end();
1652 ++It2) {
1653 (*It2)->onUpdate();
1654 }
1655 }
1656
1657 /// Gets called if a view gets activated, this manages the whole activation scheme
1658 void Application::viewActivated(MDIView* pcView)
1659 {
1660 #ifdef FC_DEBUG
1661 // May be useful for error detection
1662 Base::Console().log(
1663 "Active view is %s (at %p)\n",
1664 (const char*)pcView->windowTitle().toUtf8(),
1665 static_cast<void*>(pcView)
1666 );
1667 #endif
1668
1669 signalActivateView(pcView);
1670 getMainWindow()->setWindowTitle(pcView->buildWindowTitle());
1671 if (auto document = pcView->getGuiDocument()) {
1672 getMainWindow()->setWindowModified(document->isModified());
1673 }
1674
1675 // Set the new active document which is taken of the activated view. If, however,
1676 // this view is passive we let the currently active document unchanged as we would
1677 // have no document active which is causing a lot of trouble.
1678 if (!pcView->isPassive()) {
1679 setActiveDocument(pcView->getGuiDocument());
1680 }
1681 }
1682
1683 /// Gets called if a view gets closed
1684 void Application::viewClosed(MDIView* pcView)
1685 {
1686 signalCloseView(pcView);
1687 }
1688
1689 void Application::updateActive()
1690 {
1691 activeDocument()->onUpdate();
1692 }
1693
1694 void Application::updateActions(bool delay)
1695 {
1696 getMainWindow()->updateActions(delay);
1697 }
1698
1699 void Application::tryClose(QCloseEvent* e)
1700 {
1701 e->setAccepted(getMainWindow()->closeAllDocuments(false));
1702 if (!e->isAccepted()) {
1703 return;
1704 }
1705
1706 // ask all passive views if closable
1707 for (std::list<Gui::BaseView*>::iterator It = d->passive.begin(); It != d->passive.end(); ++It) {
1708 e->setAccepted((*It)->canClose());
1709 if (!e->isAccepted()) {
1710 return;
1711 }
1712 }
1713
1714 if (e->isAccepted()) {
1715 d->isClosing = true;
1716
1717 std::map<const App::Document*, Gui::Document*>::iterator It;
1718
1719 // detach the passive views
1720 // SetActiveDocument(0);
1721 std::list<Gui::BaseView*>::iterator itp = d->passive.begin();
1722 while (itp != d->passive.end()) {
1723 (*itp)->onClose();
1724 itp = d->passive.begin();
1725 }
1726
1727 App::GetApplication().closeAllDocuments();
1728 }
1729 }
1730
1731 int Application::getUserEditMode(const std::string& mode) const
1732 {
1733 if (mode.empty()) {
1734 return userEditMode;
1735 }
1736 for (auto const& uem : userEditModes) {
1737 if (uem.second.first == mode) {
1738 return uem.first;
1739 }
1740 }
1741 return -1;
1742 }
1743
1744 std::pair<std::string, std::string> Application::getUserEditModeUIStrings(int mode) const
1745 {
1746 if (mode == -1) {
1747 return userEditModes.at(userEditMode);
1748 }
1749 if (userEditModes.find(mode) != userEditModes.end()) {
1750 return userEditModes.at(mode);
1751 }
1752 return std::make_pair(std::string(), std::string());
1753 }
1754
1755 bool Application::setUserEditMode(int mode)
1756 {
1757 if (userEditModes.find(mode) != userEditModes.end() && userEditMode != mode) {
1758 userEditMode = mode;
1759 this->signalUserEditModeChanged(userEditMode);
1760 return true;
1761 }
1762 return false;
1763 }
1764
1765 bool Application::setUserEditMode(const std::string& mode)
1766 {
1767 for (auto const& uem : userEditModes) {
1768 if (uem.second.first == mode) {
1769 return setUserEditMode(uem.first);
1770 }
1771 }
1772 return false;
1773 }
1774
1775 /**
1776 * Activate the matching workbench to the registered workbench handler with name \a name.
1777 * The handler must be an instance of a class written in Python.
1778 * Normally, if a handler gets activated a workbench with the same name gets created unless it
1779 * already exists.
1780 *
1781 * The old workbench gets deactivated before. If the workbench to the handler is already
1782 * active or if the switch fails false is returned.
1783 */
1784 bool Application::activateWorkbench(const char* name)
1785 {
1786 bool ok = false;
1787 WaitCursor wc;
1788 Workbench* oldWb = WorkbenchManager::instance()->active();
1789 if (oldWb && oldWb->name() == name) {
1790 return false; // already active
1791 }
1792
1793 Base::PyGILStateLocker lock;
1794 // we check for the currently active workbench and call its 'Deactivated'
1795 // method, if available
1796 PyObject* pcOldWorkbench = nullptr;
1797 if (oldWb) {
1798 pcOldWorkbench = PyDict_GetItemString(_pcWorkbenchDictionary, oldWb->name().c_str());
1799 }
1800
1801 // get the python workbench object from the dictionary
1802 PyObject* pcWorkbench = nullptr;
1803 pcWorkbench = PyDict_GetItemString(_pcWorkbenchDictionary, name);
1804 // test if the workbench exists
1805 if (!pcWorkbench) {
1806 return false;
1807 }
1808
1809 try {
1810 std::string type;
1811 Py::Object handler(pcWorkbench);
1812 if (!handler.hasAttr(std::string("__Workbench__"))) {
1813 // call its GetClassName method if possible
1814 Py::Callable method(handler.getAttr(std::string("GetClassName")));
1815 Py::Tuple args;
1816 Py::String result(method.apply(args));
1817 type = result.as_std_string("ascii");
1818 if (Base::Type::fromName(type.c_str())
1819 .isDerivedFrom(Gui::PythonBaseWorkbench::getClassTypeId())) {
1820 Workbench* wb = WorkbenchManager::instance()->createWorkbench(name, type);
1821 if (!wb) {
1822 throw Py::RuntimeError("Failed to instantiate workbench of type " + type);
1823 }
1824 handler.setAttr(std::string("__Workbench__"), Py::Object(wb->getPyObject(), true));
1825 }
1826
1827 // import the matching module first
1828 Py::Callable activate(handler.getAttr(std::string("Initialize")));
1829 activate.apply(args);
1830
1831 // Dependent on the implementation of a workbench handler the type
1832 // can be defined after the call of Initialize()
1833 if (type.empty()) {
1834 Py::String result(method.apply(args));
1835 type = result.as_std_string("ascii");
1836 }
1837 }
1838
1839 // does the Python workbench handler have changed the workbench?
1840 Workbench* curWb = WorkbenchManager::instance()->active();
1841 if (curWb && curWb->name() == name) {
1842 ok = true; // already active
1843 }
1844 // now try to create and activate the matching workbench object
1845 else if (WorkbenchManager::instance()->activate(name, type)) {
1846 getMainWindow()->activateWorkbench(QString::fromLatin1(name));
1847 this->signalActivateWorkbench(name);
1848 ok = true;
1849 }
1850
1851 // if we still not have this member then it must be built-in C++ workbench
1852 // which could be created after loading the appropriate module
1853 if (!handler.hasAttr(std::string("__Workbench__"))) {
1854 Workbench* wb = WorkbenchManager::instance()->getWorkbench(name);
1855 if (wb) {
1856 handler.setAttr(std::string("__Workbench__"), Py::Object(wb->getPyObject(), true));
1857 }
1858 }
1859
1860 // If the method Deactivate is available we call it
1861 if (pcOldWorkbench) {
1862 Py::Object handler(pcOldWorkbench);
1863 if (handler.hasAttr(std::string("Deactivated"))) {
1864 Py::Object method(handler.getAttr(std::string("Deactivated")));
1865 if (method.isCallable()) {
1866 Py::Tuple args;
1867 Py::Callable activate(method);
1868 activate.apply(args);
1869 }
1870 }
1871 }
1872
1873 if (oldWb) {
1874 oldWb->deactivated();
1875 }
1876
1877 // If the method Activate is available we call it
1878 if (handler.hasAttr(std::string("Activated"))) {
1879 Py::Object method(handler.getAttr(std::string("Activated")));
1880 if (method.isCallable()) {
1881 Py::Tuple args;
1882 Py::Callable activate(method);
1883 activate.apply(args);
1884 }
1885 }
1886
1887 // now get the newly activated workbench
1888 Workbench* newWb = WorkbenchManager::instance()->active();
1889 if (newWb) {
1890 if (!Instance->d->startingUp) {
1891 std::string nameWb = newWb->name();
1892 App::GetApplication()
1893 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")
1894 ->SetASCII("LastModule", nameWb.c_str());
1895 }
1896 newWb->activated();
1897 }
1898 }
1899 catch (Py::Exception&) {
1900 Base::PyException e; // extract the Python error text
1901 QString msg = QString::fromUtf8(e.what());
1902 QRegularExpression rx;
1903 // ignore '<type 'exceptions.ImportError'>' prefixes
1904 rx.setPattern(QLatin1String("^\\s*<type 'exceptions.ImportError'>:\\s*"));
1905 auto match = rx.match(msg);
1906 while (match.hasMatch()) {
1907 msg = msg.mid(match.capturedLength());
1908 match = rx.match(msg);
1909 }
1910
1911 Base::Console().error("%s\n", (const char*)msg.toUtf8());
1912 if (!d->startingUp) {
1913 Base::Console().error("%s\n", e.getStackTrace().c_str());
1914 }
1915 else {
1916 Base::Console().log("%s\n", e.getStackTrace().c_str());
1917 }
1918
1919 if (!d->startingUp) {
1920 wc.restoreCursor();
1921 QMessageBox::critical(
1922 getMainWindow(),
1923 QObject::tr("Workbench failure"),
1924 QObject::tr("%1").arg(msg)
1925 );
1926 wc.setWaitCursor();
1927 }
1928 }
1929
1930 return ok;
1931 }
1932
1933 QPixmap Application::workbenchIcon(const QString& wb) const
1934 {
1935 Base::PyGILStateLocker lock;
1936 // get the python workbench object from the dictionary
1937 PyObject* pcWorkbench = PyDict_GetItemString(_pcWorkbenchDictionary, wb.toLatin1());
1938 // test if the workbench exists
1939 if (pcWorkbench) {
1940 // make a unique icon name
1941 std::stringstream str;
1942 str << static_cast<const void*>(pcWorkbench) << std::ends;
1943 std::string iconName = str.str();
1944 QPixmap icon;
1945 if (BitmapFactory().findPixmapInCache(iconName.c_str(), icon)) {
1946 return icon;
1947 }
1948
1949 // get its Icon member if possible
1950 try {
1951 Py::Object handler(pcWorkbench);
1952 if (handler.hasAttr(std::string("Icon"))) {
1953 Py::Object member = handler.getAttr(std::string("Icon"));
1954 Py::String data(member);
1955 std::string content = data.as_std_string("utf-8");
1956
1957 // test if in XPM format
1958 QByteArray ary;
1959 int strlen = (int)content.size();
1960 ary.resize(strlen);
1961 for (int j = 0; j < strlen; j++) {
1962 ary[j] = content[j];
1963 }
1964 if (ary.indexOf("/* XPM */") > 0) {
1965 // Make sure to remove crap around the XPM data
1966 QList<QByteArray> lines = ary.split('\n');
1967 QByteArray buffer;
1968 buffer.reserve(ary.size() + lines.size());
1969 for (QList<QByteArray>::iterator it = lines.begin(); it != lines.end(); ++it) {
1970 QByteArray trim = it->trimmed();
1971 if (!trim.isEmpty()) {
1972 buffer.append(trim);
1973 buffer.append('\n');
1974 }
1975 }
1976 icon.loadFromData(buffer, "XPM");
1977 }
1978 else {
1979 // is it a file name...
1980 QString file = QString::fromUtf8(content.c_str());
1981 icon.load(file);
1982 if (icon.isNull()) {
1983 // ... or the name of another icon?
1984 icon = BitmapFactory().pixmap(file.toUtf8());
1985 }
1986 }
1987
1988 if (!icon.isNull()) {
1989 BitmapFactory().addPixmapToCache(iconName.c_str(), icon);
1990 }
1991
1992 return icon;
1993 }
1994 }
1995 catch (Py::Exception& e) {
1996 e.clear();
1997 }
1998 }
1999
2000 QIcon icon = QApplication::windowIcon();
2001 if (!icon.isNull()) {
2002 QList<QSize> s = icon.availableSizes();
2003 if (!s.isEmpty()) {
2004 return icon.pixmap(s[0]);
2005 }
2006 }
2007 return {};
2008 }
2009
2010 QString Application::workbenchToolTip(const QString& wb) const
2011 {
2012 // get the python workbench object from the dictionary
2013 Base::PyGILStateLocker lock;
2014 PyObject* pcWorkbench = PyDict_GetItemString(_pcWorkbenchDictionary, wb.toLatin1());
2015 // test if the workbench exists
2016 if (pcWorkbench) {
2017 // get its ToolTip member if possible
2018 try {
2019 Py::Object handler(pcWorkbench);
2020 Py::Object member = handler.getAttr(std::string("ToolTip"));
2021 if (member.isString()) {
2022 Py::String tip(member);
2023 return QString::fromUtf8(tip.as_std_string("utf-8").c_str());
2024 }
2025 }
2026 catch (Py::Exception& e) {
2027 e.clear();
2028 }
2029 }
2030
2031 return {};
2032 }
2033
2034 QString Application::workbenchMenuText(const QString& wb) const
2035 {
2036 // get the python workbench object from the dictionary
2037 Base::PyGILStateLocker lock;
2038 PyObject* pcWorkbench = PyDict_GetItemString(_pcWorkbenchDictionary, wb.toLatin1());
2039 // test if the workbench exists
2040 if (pcWorkbench) {
2041 // get its ToolTip member if possible
2042 Base::PyGILStateLocker locker;
2043 try {
2044 Py::Object handler(pcWorkbench);
2045 Py::Object member = handler.getAttr(std::string("MenuText"));
2046 if (member.isString()) {
2047 Py::String tip(member);
2048 return QString::fromUtf8(tip.as_std_string("utf-8").c_str());
2049 }
2050 }
2051 catch (Py::Exception& e) {
2052 e.clear();
2053 }
2054 }
2055
2056 return {};
2057 }
2058
2059 QStringList Application::workbenches() const
2060 {
2061 // If neither 'HiddenWorkbench' nor 'ExtraWorkbench' is set then all workbenches are returned.
2062 const std::map<std::string, std::string>& config = App::Application::Config();
2063 auto ht = config.find("HiddenWorkbench");
2064 auto et = config.find("ExtraWorkbench");
2065 auto st = config.find("StartWorkbench");
2066 const char* start = (st != config.end() ? st->second.c_str() : "<none>");
2067 QStringList hidden, extra;
2068 if (ht != config.end()) {
2069 QString items = QString::fromLatin1(ht->second.c_str());
2070 hidden = items.split(QLatin1Char(';'), Qt::SkipEmptyParts);
2071
2072 if (hidden.isEmpty()) {
2073 hidden.push_back(QLatin1String(""));
2074 }
2075 }
2076 if (et != config.end()) {
2077 QString items = QString::fromLatin1(et->second.c_str());
2078
2079 extra = items.split(QLatin1Char(';'), Qt::SkipEmptyParts);
2080 if (extra.isEmpty()) {
2081 extra.push_back(QLatin1String(""));
2082 }
2083 }
2084
2085 PyObject *key, *value;
2086 Py_ssize_t pos = 0;
2087 QStringList wb;
2088 // insert all items
2089 while (PyDict_Next(_pcWorkbenchDictionary, &pos, &key, &value)) {
2090 /* do something interesting with the values... */
2091 const char* wbName = PyUnicode_AsUTF8(key);
2092 // add only allowed workbenches
2093 bool ok = true;
2094 if (!extra.isEmpty() && ok) {
2095 ok = (extra.indexOf(QString::fromLatin1(wbName)) != -1);
2096 }
2097 if (!hidden.isEmpty() && ok) {
2098 ok = (hidden.indexOf(QString::fromLatin1(wbName)) == -1);
2099 }
2100
2101 // okay the item is visible
2102 if (ok) {
2103 wb.push_back(QString::fromLatin1(wbName));
2104 }
2105 // also allow start workbench in case it is hidden
2106 else if (strcmp(wbName, start) == 0) {
2107 wb.push_back(QString::fromLatin1(wbName));
2108 }
2109 }
2110
2111 return wb;
2112 }
2113
2114 void Application::setupContextMenu(const char* recipient, MenuItem* items) const
2115 {
2116 Workbench* actWb = WorkbenchManager::instance()->active();
2117 if (actWb) {
2118 // when populating the context-menu of a Python workbench invoke the method
2119 // 'ContextMenu' of the handler object
2120 if (actWb->isDerivedFrom<PythonWorkbench>()) {
2121 static_cast<PythonWorkbench*>(actWb)->clearContextMenu();
2122 Base::PyGILStateLocker lock;
2123 PyObject* pWorkbench = nullptr;
2124 pWorkbench = PyDict_GetItemString(_pcWorkbenchDictionary, actWb->name().c_str());
2125
2126 try {
2127 // call its GetClassName method if possible
2128 Py::Object handler(pWorkbench);
2129 Py::Callable method(handler.getAttr(std::string("ContextMenu")));
2130 Py::Tuple args(1);
2131 args.setItem(0, Py::String(recipient));
2132 method.apply(args);
2133 }
2134 catch (Py::Exception& e) {
2135 Py::Object o = Py::type(e);
2136 e.clear();
2137 if (o.isString()) {
2138 Py::String s(o);
2139 std::clog << "Application::setupContextMenu: " << s.as_std_string("utf-8")
2140 << std::endl;
2141 }
2142 }
2143 }
2144 actWb->createContextMenu(recipient, items);
2145 }
2146 }
2147
2148 bool Application::isClosing()
2149 {
2150 return d->isClosing;
2151 }
2152
2153 MacroManager* Application::macroManager()
2154 {
2155 return d->macroMngr;
2156 }
2157
2158 CommandManager& Application::commandManager()
2159 {
2160 return d->commandManager;
2161 }
2162
2163 Gui::PreferencePackManager* Application::prefPackManager()
2164 {
2165 return d->prefPackManager;
2166 }
2167
2168 Gui::StyleParameters::ParameterManager* Application::styleParameterManager()
2169 {
2170 return d->styleParameterManager;
2171 }
2172
2173
2174 //**************************************************************************
2175 // Init, Destruct and singleton
2176
2177 namespace
2178 {
2179 void setCategoryFilterRules()
2180 {
2181 QString filter;
2182 QTextStream stream(&filter);
2183 stream << "qt.qpa.xcb.warning=false\n";
2184 stream << "qt.qpa.mime.warning=false\n";
2185 stream << "qt.qpa.wayland.warning=false\n";
2186 stream << "qt.qpa.wayland.*.warning=false\n";
2187 stream << "qt.svg.warning=false\n";
2188 stream << "qt.xkb.compose.warning=false\n";
2189 stream << "kf.*.warning=false\n";
2190 stream.flush();
2191 QLoggingCategory::setFilterRules(filter);
2192 }
2193 } // namespace
2194
2195 using _qt_msg_handler_old = void (*)(QtMsgType, const QMessageLogContext&, const QString&);
2196 _qt_msg_handler_old old_qtmsg_handler = nullptr;
2197
2198 void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)
2199 {
2200 QByteArray output;
2201 if (context.category && strcmp(context.category, "default") != 0) {
2202 output.append('(');
2203 output.append(context.category);
2204 output.append(')');
2205 output.append(' ');
2206 }
2207
2208 output.append(msg.toUtf8());
2209
2210 switch (type) {
2211 case QtInfoMsg:
2212 case QtDebugMsg:
2213 #ifdef FC_DEBUG
2214 Base::Console().message("%s\n", output.constData());
2215 #else
2216 // do not stress user with Qt internals but write to log file if enabled
2217 Base::Console().log("%s\n", output.constData());
2218 #endif
2219 break;
2220 case QtWarningMsg:
2221 Base::Console().warning("%s\n", output.constData());
2222 break;
2223 case QtCriticalMsg:
2224 Base::Console().error("%s\n", output.constData());
2225 break;
2226 case QtFatalMsg:
2227 Base::Console().error("%s\n", output.constData());
2228 abort(); // deliberately core dump
2229 }
2230 #ifdef FC_OS_WIN32
2231 if (old_qtmsg_handler) {
2232 (*old_qtmsg_handler)(type, context, msg);
2233 }
2234 #endif
2235 }
2236
2237 #ifdef FC_DEBUG // redirect Coin messages to FreeCAD
2238 void messageHandlerCoin(const SoError* error, void* /*userdata*/)
2239 {
2240 if (error && error->getTypeId() == SoDebugError::getClassTypeId()) {
2241 const SoDebugError* dbg = static_cast<const SoDebugError*>(error);
2242 const char* msg = error->getDebugString().getString();
2243 switch (dbg->getSeverity()) {
2244 case SoDebugError::INFO:
2245 Base::Console().message("%s\n", msg);
2246 break;
2247 case SoDebugError::WARNING:
2248 Base::Console().warning("%s\n", msg);
2249 break;
2250 default: // error
2251 Base::Console().error("%s\n", msg);
2252 break;
2253 }
2254 # ifdef FC_OS_WIN32
2255 if (old_qtmsg_handler) {
2256 (*old_qtmsg_handler)(QtDebugMsg, QMessageLogContext(), QString::fromLatin1(msg));
2257 }
2258 # endif
2259 }
2260 else if (error) {
2261 const char* msg = error->getDebugString().getString();
2262 Base::Console().log(msg);
2263 }
2264 }
2265
2266 #endif
2267
2268 // To fix bug #0000345 move Q_INIT_RESOURCE() outside initApplication()
2269 static void init_resources()
2270 {
2271 // init resources
2272 Q_INIT_RESOURCE(resource);
2273 Q_INIT_RESOURCE(translation);
2274 Q_INIT_RESOURCE(FreeCAD_translation);
2275 }
2276
2277 void Application::initApplication()
2278 {
2279 static bool init = false;
2280 if (init) {
2281 Base::Console().error("Tried to run Gui::Application::initApplication() twice!\n");
2282 return;
2283 }
2284
2285 try {
2286 initTypes();
2287 new Base::ScriptProducer("FreeCADGuiInit", FreeCADGuiInit);
2288 init_resources();
2289 setCategoryFilterRules();
2290 old_qtmsg_handler = qInstallMessageHandler(messageHandler);
2291 init = true;
2292 }
2293 catch (...) {
2294 // force to flush the log
2295 App::Application::destructObserver();
2296 throw;
2297 }
2298 }
2299
2300 void Application::initTypes()
2301 {
2302 // clang-format off
2303 // views
2304 Gui::BaseView ::init();
2305 Gui::MDIView ::init();
2306 Gui::View3DInventor ::init();
2307 Gui::AbstractSplitView ::init();
2308 Gui::SplitView3DInventor ::init();
2309 Gui::TextDocumentEditorView ::init();
2310 Gui::EditorView ::init();
2311 Gui::PythonEditorView ::init();
2312 // View Provider
2313 Gui::ViewProvider ::init();
2314 Gui::ViewProviderExtension ::init();
2315 Gui::ViewProviderExtensionPython ::init();
2316 Gui::ViewProviderGroupExtension ::init();
2317 Gui::ViewProviderGroupExtensionPython ::init();
2318 Gui::ViewProviderGeoFeatureGroupExtension ::init();
2319 Gui::ViewProviderGeoFeatureGroupExtensionPython::init();
2320 Gui::ViewProviderOriginGroupExtension ::init();
2321 Gui::ViewProviderOriginGroupExtensionPython ::init();
2322 Gui::ViewProviderSuppressibleExtension ::init();
2323 Gui::ViewProviderSuppressibleExtensionPython::init();
2324 Gui::ViewProviderExtern ::init();
2325 Gui::ViewProviderDocumentObject ::init();
2326 Gui::ViewProviderFeature ::init();
2327 Gui::ViewProviderDocumentObjectGroup ::init();
2328 Gui::ViewProviderDocumentObjectGroupPython ::init();
2329 Gui::ViewProviderDragger ::init();
2330 Gui::ViewProviderGeometryObject ::init();
2331 Gui::ViewProviderImagePlane ::init();
2332 Gui::ViewProviderInventorObject ::init();
2333 Gui::ViewProviderVRMLObject ::init();
2334 Gui::ViewProviderAnnotation ::init();
2335 Gui::ViewProviderAnnotationLabel ::init();
2336 Gui::ViewProviderFeaturePython ::init();
2337 Gui::ViewProviderGeometryPython ::init();
2338 Gui::ViewProviderPlacement ::init();
2339 Gui::ViewProviderPlacementPython ::init();
2340 Gui::ViewProviderDatum ::init();
2341 Gui::ViewProviderPlane ::init();
2342 Gui::ViewProviderPoint ::init();
2343 Gui::ViewProviderLine ::init();
2344 Gui::ViewProviderGeoFeatureGroup ::init();
2345 Gui::ViewProviderGeoFeatureGroupPython ::init();
2346 Gui::ViewProviderOriginGroup ::init();
2347 Gui::ViewProviderPart ::init();
2348 Gui::ViewProviderCoordinateSystem ::init();
2349 Gui::ViewProviderMaterialObject ::init();
2350 Gui::ViewProviderMaterialObjectPython ::init();
2351 Gui::ViewProviderTextDocument ::init();
2352 Gui::ViewProviderTextureExtension ::init();
2353 Gui::ViewProviderFaceTexture ::init();
2354 Gui::ViewProviderLinkObserver ::init();
2355 Gui::LinkView ::init();
2356 Gui::ViewProviderLink ::init();
2357 Gui::ViewProviderLinkPython ::init();
2358 Gui::ViewProviderVarSet ::init();
2359 Gui::AxisOrigin ::init();
2360
2361 // Workbench
2362 Gui::Workbench ::init();
2363 Gui::StdWorkbench ::init();
2364 Gui::BlankWorkbench ::init();
2365 Gui::NoneWorkbench ::init();
2366 Gui::TestWorkbench ::init();
2367 Gui::PythonBaseWorkbench ::init();
2368 Gui::PythonBlankWorkbench ::init();
2369 Gui::PythonWorkbench ::init();
2370
2371 // register transaction type
2372 new App::TransactionProducer<TransactionViewProvider>
2373 (ViewProviderDocumentObject::getClassTypeId());
2374 // clang-format on
2375 }
2376
2377 void Application::initOpenInventor()
2378 {
2379 // init the Inventor subsystem
2380 SoDB::init();
2381 SIM::Coin3D::Quarter::Quarter::init();
2382 SoFCDB::init();
2383 }
2384
2385 void Application::runInitGuiScript()
2386 {
2387 Base::Interpreter().runString(Base::ScriptFactory().ProduceScript("FreeCADGuiInit"));
2388 }
2389
2390 namespace
2391 {
2392 bool onlySingleInstance(GUISingleApplication& mainApp)
2393 {
2394 const std::map<std::string, std::string>& cfg = App::Application::Config();
2395 auto it = cfg.find("SingleInstance");
2396 if (it != cfg.end() && mainApp.isRunning()) {
2397 // send the file names to be opened to the server application so that this
2398 // opens them
2399 QDir cwd = QDir::current();
2400 std::list<std::string> files = App::Application::getCmdLineFiles();
2401 for (const auto& file : files) {
2402 QString fn = QString::fromUtf8(file.c_str(), static_cast<int>(file.size()));
2403 QFileInfo fi(fn);
2404 // if path name is relative make it absolute because the running instance
2405 // cannot determine the full path when trying to load the file
2406 if (fi.isRelative()) {
2407 fn = cwd.absoluteFilePath(fn);
2408 fn = QDir::cleanPath(fn);
2409 }
2410
2411 fn.prepend(QLatin1String("OpenFile:"));
2412 if (!mainApp.sendMessage(fn)) {
2413 qWarning("Failed to send OpenFile message to server");
2414 break;
2415 }
2416 }
2417
2418 return true;
2419 }
2420
2421 return false;
2422 }
2423
2424 void setAppNameAndIcon()
2425 {
2426 const std::map<std::string, std::string>& cfg = App::Application::Config();
2427
2428 // set application icon and window title
2429 auto it = cfg.find("Application");
2430 if (it != cfg.end()) {
2431 QApplication::setApplicationName(QString::fromUtf8(it->second.c_str()));
2432 }
2433 else {
2434 QApplication::setApplicationName(QString::fromStdString(App::Application::getExecutableName()));
2435 }
2436 #ifndef Q_OS_MACOS
2437 QApplication::setWindowIcon(
2438 Gui::BitmapFactory().pixmap(App::Application::Config()["AppIcon"].c_str())
2439 );
2440 #endif
2441 }
2442
2443 void tryRunEventLoop(GUISingleApplication& mainApp)
2444 {
2445 std::stringstream out;
2446 out << App::Application::getUserCachePath() << App::Application::getExecutableName() << "_"
2447 << App::Application::applicationPid() << ".lock";
2448
2449 // open a lock file with the PID
2450 Base::FileInfo fi(out.str());
2451 Base::ofstream lock(fi);
2452
2453 #if !defined(FC_OS_WIN32) || (BOOST_VERSION < 107600)
2454 std::string filename = out.str();
2455 #else
2456 std::wstring filename = fi.toStdWString();
2457 #endif
2458 try {
2459 boost::interprocess::file_lock flock(filename.c_str());
2460 if (flock.try_lock()) {
2461 Base::Console().log("Init: Executing event loop…\n");
2462 QApplication::exec();
2463
2464 // Qt can't handle exceptions thrown from event handlers, so we need
2465 // to manually rethrow SystemExitExceptions.
2466 if (mainApp.caughtException) {
2467 throw Base::SystemExitException(*mainApp.caughtException.get());
2468 }
2469
2470 // close the lock file, in case of a crash we can see the existing lock file
2471 // on the next restart and try to repair the documents, if needed.
2472 flock.unlock();
2473 lock.close();
2474 fi.deleteFile();
2475 }
2476 else {
2477 Base::Console().error(
2478 "Failed to create a file lock for the IPC.\n"
2479 "The application will be terminated.\n"
2480 "Attempted lock file: %s",
2481 fi.filePath().c_str()
2482 );
2483 }
2484 }
2485 catch (const boost::interprocess::interprocess_exception& e) {
2486 QString msg = QString::fromLocal8Bit(e.what());
2487 Base::Console().error(
2488 "Failed to create a file lock for the IPC: %s\n"
2489 "Attempted lock file: %s\n",
2490 msg.toUtf8().constData(),
2491 fi.filePath().c_str()
2492 );
2493 }
2494 }
2495
2496 void runEventLoop(GUISingleApplication& mainApp)
2497 {
2498 try {
2499 tryRunEventLoop(mainApp);
2500 }
2501 catch (const Base::SystemExitException&) {
2502 Base::Console().message("System exit\n");
2503 throw;
2504 }
2505 catch (const std::exception& e) {
2506 // catching nasty stuff coming out of the event loop
2507 Base::Console().error("Event loop left through unhandled exception: %s\n", e.what());
2508 App::Application::destructObserver();
2509 throw;
2510 }
2511 catch (...) {
2512 // catching nasty stuff coming out of the event loop
2513 Base::Console().error("Event loop left through unknown unhandled exception\n");
2514 App::Application::destructObserver();
2515 throw;
2516 }
2517 }
2518 } // namespace
2519
2520 void Application::runApplication()
2521 {
2522 StartupProcess::setupApplication();
2523
2524 {
2525 QSurfaceFormat defaultFormat;
2526 defaultFormat.setRenderableType(QSurfaceFormat::OpenGL);
2527 defaultFormat.setProfile(QSurfaceFormat::CompatibilityProfile);
2528 defaultFormat.setOption(QSurfaceFormat::DeprecatedFunctions, true);
2529 #if defined(FC_OS_LINUX) || defined(FC_OS_BSD)
2530 // QGuiApplication::platformName() doesn't yet work at this point, so we use the env var
2531 if (getenv("WAYLAND_DISPLAY")) {
2532 // In some settings (at least EGL on Wayland) we get RGB565 by default.
2533 // Request something better.
2534 defaultFormat.setRedBufferSize(8);
2535 defaultFormat.setGreenBufferSize(8);
2536 defaultFormat.setBlueBufferSize(8);
2537 // Qt's behavior with format requests seems opaque, underdocumented and,
2538 // unfortunately, inconsistent between platforms. Requesting an alpha
2539 // channel tends to steer it away from weird legacy choices like RGB565.
2540 defaultFormat.setAlphaBufferSize(8);
2541 // And a depth/stencil buffer is generally useful if we can have it.
2542 defaultFormat.setDepthBufferSize(24);
2543 defaultFormat.setStencilBufferSize(8);
2544 }
2545 #endif
2546 QSurfaceFormat::setDefaultFormat(defaultFormat);
2547 }
2548
2549 // A new QApplication
2550 Base::Console().log("Init: Creating Gui::Application and QApplication\n");
2551
2552 int argc = App::Application::GetARGC();
2553 GUISingleApplication mainApp(argc, App::Application::GetARGV());
2554
2555 #if (COIN_MAJOR_VERSION * 100 + COIN_MINOR_VERSION * 10 + COIN_MICRO_VERSION < 406) \
2556 && (defined(FC_OS_LINUX) || defined(FC_OS_BSD))
2557 // If QT is running with native Wayland then inform Coin to use EGL
2558 if (QGuiApplication::platformName() == QString::fromStdString("wayland")) {
2559 setenv("COIN_EGL", "1", 1);
2560 }
2561 #endif
2562
2563 // Make sure that we use '.' as decimal point. See also
2564 // http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=559846
2565 // and issue #0002891
2566 // http://doc.qt.io/qt-5/qcoreapplication.html#locale-settings
2567 setlocale(LC_NUMERIC, "C");
2568
2569 // check if a single or multiple instances can run
2570 if (onlySingleInstance(mainApp)) {
2571 return;
2572 }
2573
2574 setAppNameAndIcon();
2575
2576 StartupProcess process;
2577 process.execute();
2578
2579 Application app(true);
2580 MainWindow mw;
2581 mw.setProperty("QuitOnClosed", true);
2582
2583 // https://forum.freecad.org/viewtopic.php?f=3&t=15540
2584 // Needs to be set after app is created to override platform defaults (qt commit a2aa1f81a81)
2585 QApplication::setAttribute(Qt::AA_DontShowIconsInMenus, false);
2586
2587 #ifdef FC_DEBUG // redirect Coin messages to FreeCAD
2588 SoDebugError::setHandlerCallback(messageHandlerCoin, 0);
2589 #endif
2590
2591 StartupPostProcess postProcess(&mw, app, &mainApp);
2592 postProcess.execute();
2593
2594 Instance->d->startingUp = false;
2595
2596 // gets called once we start the event loop
2597 QTimer::singleShot(0, &mw, SLOT(delayedStartup()));
2598
2599 // run the Application event loop
2600 Base::Console().log("Init: Entering event loop\n");
2601
2602 // boot phase reference point
2603 // https://forum.freecad.org/viewtopic.php?f=10&t=21665
2604 Gui::getMainWindow()->setProperty("eventLoop", true);
2605
2606 #ifdef USE_3DCONNEXION_NAVLIB
2607 if (Instance->pNavlibInterface) {
2608 Instance->pNavlibInterface->enableNavigation();
2609 }
2610 #endif
2611
2612 runEventLoop(mainApp);
2613
2614 Base::Console().log("Finish: Event loop left\n");
2615 }
2616
2617 bool Application::hiddenMainWindow()
2618 {
2619 const std::map<std::string, std::string>& cfg = App::Application::Config();
2620 auto it = cfg.find("StartHidden");
2621
2622 return it != cfg.end();
2623 }
2624
2625 bool Application::testStatus(Status pos) const
2626 {
2627 return d->StatusBits.test((size_t)pos);
2628 }
2629
2630 void Application::setStatus(Status pos, bool on)
2631 {
2632 d->StatusBits.set((size_t)pos, on);
2633 }
2634
2635 void Application::setStyleSheet(const QString& qssFile, bool tiledBackground)
2636 {
2637 Gui::MainWindow* mw = getMainWindow();
2638 auto mdi = mw->findChild<QMdiArea*>();
2639 mdi->setProperty("showImage", tiledBackground);
2640
2641 // Qt's style sheet doesn't support it to define the link color of a QLabel
2642 // or in the property editor when an expression is set because therefore the
2643 // link color of the application's palette is used.
2644 // A workaround is to set a user-defined property to e.g. a QLabel and then
2645 // define it in the .qss file.
2646 //
2647 // Example:
2648 // QLabel label;
2649 // label.setProperty("haslink", QByteArray("true"));
2650 // label.show();
2651 // QColor link = label.palette().color(QPalette::Text);
2652 //
2653 // The .qss file must define it with:
2654 // QLabel[haslink="true"] {
2655 // color: #rrggbb;
2656 // }
2657 //
2658 // See
2659 // https://stackoverflow.com/questions/5497799/how-do-i-customise-the-appearance-of-links-in-qlabels-using-style-sheets
2660 // and https://forum.freecad.org/viewtopic.php?f=34&t=50744
2661 static bool init = true;
2662 if (init) {
2663 init = false;
2664 mw->setProperty("fc_originalLinkCoor", qApp->palette().color(QPalette::Link));
2665 }
2666 else {
2667 QPalette newPal(qApp->palette());
2668 newPal.setColor(QPalette::Link, mw->property("fc_originalLinkCoor").value<QColor>());
2669 qApp->setPalette(newPal);
2670 }
2671
2672 mw->setProperty("fc_currentStyleSheet", qssFile);
2673 mw->setProperty("fc_tiledBackground", tiledBackground);
2674
2675 QString defaultStyleSheet = [this]() {
2676 QFile f(QLatin1String("qss:defaults.qss"));
2677
2678 if (!f.open(QFile::ReadOnly)) {
2679 return QString();
2680 }
2681
2682 QTextStream in(&f);
2683
2684 return replaceVariablesInQss(in.readAll());
2685 }();
2686
2687 if (!qssFile.isEmpty()) {
2688 // Search for stylesheet in user-defined search paths.
2689 // For qss they are set-up in runApplication() with the prefix "qss"
2690 QString prefix(QLatin1String("qss:"));
2691
2692 QFile f;
2693 if (QFile::exists(qssFile)) {
2694 f.setFileName(qssFile);
2695 }
2696 else if (QFile::exists(prefix + qssFile)) {
2697 f.setFileName(prefix + qssFile);
2698 }
2699
2700 if (!f.fileName().isEmpty() && f.open(QFile::ReadOnly | QFile::Text)) {
2701 mdi->setBackground(QBrush(Qt::NoBrush));
2702 QTextStream str(&f);
2703
2704 QString styleSheetContent = replaceVariablesInQss(str.readAll());
2705
2706 qApp->setStyleSheet(defaultStyleSheet + QStringLiteral("\n") + styleSheetContent);
2707
2708 ActionStyleEvent e(ActionStyleEvent::Clear);
2709 qApp->sendEvent(mw, &e);
2710
2711 // This is a way to retrieve the link color of a .qss file when it's defined there.
2712 // The color will then be set to the application's palette.
2713 // Limitation: it doesn't work if the .qss file on purpose sets the same color as
2714 // for normal text. In this case the default link color is used.
2715 {
2716 QLabel l1, l2;
2717 l2.setProperty("haslink", QByteArray("true"));
2718
2719 l1.show();
2720 l2.show();
2721 QColor text = l1.palette().color(QPalette::Text);
2722 QColor link = l2.palette().color(QPalette::Text);
2723
2724 if (text != link) {
2725 QPalette newPal(qApp->palette());
2726 newPal.setColor(QPalette::Link, link);
2727 qApp->setPalette(newPal);
2728 }
2729 }
2730 }
2731 }
2732 else {
2733 if (tiledBackground) {
2734 qApp->setStyleSheet(defaultStyleSheet);
2735 ActionStyleEvent e(ActionStyleEvent::Restore);
2736 qApp->sendEvent(getMainWindow(), &e);
2737 mdi->setBackground(QPixmap(QLatin1String("images:background.png")));
2738 }
2739 else {
2740 qApp->setStyleSheet(defaultStyleSheet);
2741 ActionStyleEvent e(ActionStyleEvent::Restore);
2742 qApp->sendEvent(getMainWindow(), &e);
2743 mdi->setBackground(QBrush(QColor(160, 160, 160)));
2744 }
2745 }
2746
2747 // At startup time unpolish() mustn't be executed because otherwise the QSint widget
2748 // appear incorrect due to an outdated cache.
2749 // See https://doc.qt.io/qt-5/qstyle.html#unpolish-1
2750 // See https://forum.freecad.org/viewtopic.php?f=17&t=50783
2751 if (!d->startingUp) {
2752 if (mdi->style()) {
2753 mdi->style()->unpolish(qApp);
2754 }
2755 }
2756 }
2757
2758 void Application::reloadStyleSheet()
2759 {
2760 const MainWindow* mw = getMainWindow();
2761
2762 const QString qssFile = mw->property("fc_currentStyleSheet").toString();
2763 const bool tiledBackground = mw->property("fc_tiledBackground").toBool();
2764
2765 d->styleParameterManager->reload();
2766
2767 setStyleSheet(qssFile, tiledBackground);
2768 OverlayManager::instance()->refresh(nullptr, true);
2769 }
2770
2771 QString Application::replaceVariablesInQss(const QString& qssText)
2772 {
2773 return QString::fromStdString(d->styleParameterManager->replacePlaceholders(qssText.toStdString()));
2774 }
2775
2776 void Application::setStyle(const QString& name)
2777 {
2778 const auto createStyleFromName = [](const QString& name) -> QStyle* {
2779 if (name == QStringLiteral("FreeCAD")) {
2780 return new FreeCADStyle();
2781 }
2782
2783 if (name.compare(QStringLiteral("System"), Qt::CaseInsensitive) == 0) {
2784 return nullptr;
2785 }
2786
2787 return QStyleFactory::create(name);
2788 };
2789
2790 const auto requiresEventFilter = [](QStyle* style) {
2791 // for now only FreeCAD style requires additional event processing
2792 return qobject_cast<FreeCADStyle*>(style) != nullptr;
2793 };
2794
2795 if (auto* current = qApp->style(); current != nullptr && requiresEventFilter(current)) {
2796 qApp->removeEventFilter(current);
2797 }
2798
2799 if (auto* style = createStyleFromName(name)) {
2800 qApp->setStyle(style);
2801
2802 if (requiresEventFilter(style)) {
2803 qApp->installEventFilter(style);
2804 }
2805 }
2806 }
2807
2808 void Application::checkForDeprecatedSettings()
2809 {
2810 // From 0.21, `FCBak` will be the intended default backup format
2811 bool makeBackups = App::GetApplication()
2812 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")
2813 ->GetBool("CreateBackupFiles", true);
2814 if (makeBackups) {
2815 bool useFCBakExtension = App::GetApplication()
2816 .GetParameterGroupByPath(
2817 "User parameter:BaseApp/Preferences/Document"
2818 )
2819 ->GetBool("UseFCBakExtension", true);
2820 if (!useFCBakExtension) {
2821 // TODO: This should be translated
2822 Base::Console().warning(
2823 "The `.FCStd#` backup format is deprecated and may "
2824 "be removed in future versions.\n"
2825 "To update, check the 'Preferences->General->Document->Use "
2826 "date and FCBak extension' option.\n"
2827 );
2828 }
2829 }
2830 }
2831
2832 void Application::checkForPreviousCrashes()
2833 {
2834 try {
2835 Gui::Dialog::DocumentRecoveryFinder finder;
2836 if (!finder.checkForPreviousCrashes()) {
2837
2838 // If the recovery dialog wasn't shown check the cache size periodically
2839 Gui::Dialog::ApplicationCache cache;
2840 cache.applyUserSettings();
2841 if (cache.periodicCheckOfSize()) {
2842 qint64 total = cache.size();
2843 cache.performAction(total);
2844 }
2845 }
2846 }
2847 catch (const boost::interprocess::interprocess_exception& e) {
2848 QString msg = QString::fromLocal8Bit(e.what());
2849 Base::Console().warning(
2850 "Failed check for previous crashes because of IPC error: %s\n",
2851 msg.toUtf8().constData()
2852 );
2853 }
2854 }
2855
2856 App::Document* Application::reopen(App::Document* doc)
2857 {
2858 if (!doc) {
2859 return nullptr;
2860 }
2861 std::string name = doc->FileName.getValue();
2862 std::set<const Gui::Document*> untouchedDocs;
2863 for (auto& v : d->documents) {
2864 if (!v.second->isModified() && !v.second->getDocument()->isTouched()) {
2865 untouchedDocs.insert(v.second);
2866 }
2867 }
2868
2869 WaitCursor wc;
2870 wc.setIgnoreEvents(WaitCursor::NoEvents);
2871
2872 if (doc->testStatus(App::Document::PartialDoc) || doc->testStatus(App::Document::PartialRestore)) {
2873 App::GetApplication().openDocument(name.c_str());
2874 }
2875 else {
2876 std::vector<std::string> docs;
2877 for (auto d : doc->getDependentDocuments(true)) {
2878 if (d->testStatus(App::Document::PartialDoc)
2879 || d->testStatus(App::Document::PartialRestore)) {
2880 docs.emplace_back(d->FileName.getValue());
2881 }
2882 }
2883
2884 if (docs.empty()) {
2885 Document* gdoc = getDocument(doc);
2886 if (gdoc) {
2887 setActiveDocument(gdoc);
2888 if (!gdoc->setActiveView()) {
2889 gdoc->setActiveView(nullptr, View3DInventor::getClassTypeId());
2890 }
2891 }
2892 return doc;
2893 }
2894
2895 for (auto& file : docs) {
2896 App::DocumentInitFlags initFlags {.createView = false};
2897 App::GetApplication().openDocument(file.c_str(), initFlags);
2898 }
2899 }
2900
2901 doc = nullptr;
2902 for (auto& v : d->documents) {
2903 if (name == v.first->FileName.getValue()) {
2904 doc = const_cast<App::Document*>(v.first);
2905 }
2906 if (untouchedDocs.contains(v.second)) {
2907 if (!v.second->isModified()) {
2908 continue;
2909 }
2910 bool reset = true;
2911 for (auto obj : v.second->getDocument()->getObjects()) {
2912 if (!obj->isTouched()) {
2913 continue;
2914 }
2915 std::vector<App::Property*> props;
2916 obj->getPropertyList(props);
2917 for (auto prop : props) {
2918 auto link = dynamic_cast<App::PropertyLinkBase*>(prop);
2919 if (link && link->checkRestore()) {
2920 reset = false;
2921 break;
2922 }
2923 }
2924 if (!reset) {
2925 break;
2926 }
2927 }
2928 if (reset) {
2929 v.second->getDocument()->purgeTouched();
2930 v.second->setModified(false);
2931 }
2932 }
2933 }
2934 return doc;
2935 }
2936
2937 void Application::getVerboseDPIStyleInfo(QTextStream& str)
2938 {
2939 // Add Stylesheet/Theme/Qtstyle information
2940 std::string styleSheet = App::GetApplication()
2941 .GetParameterGroupByPath(
2942 "User parameter:BaseApp/Preferences/MainWindow"
2943 )
2944 ->GetASCII("StyleSheet");
2945 std::string theme = App::GetApplication()
2946 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/MainWindow")
2947 ->GetASCII("Theme");
2948 #if QT_VERSION >= QT_VERSION_CHECK(6, 1, 0)
2949 std::string style = qApp->style()->name().toStdString();
2950 #else
2951 std::string style = App::GetApplication()
2952 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/MainWindow")
2953 ->GetASCII("QtStyle");
2954 if (style.empty()) {
2955 style = "Qt default";
2956 }
2957 #endif
2958 if (styleSheet.empty()) {
2959 styleSheet = "unset";
2960 }
2961 if (theme.empty()) {
2962 theme = "unset";
2963 }
2964
2965 str << "Stylesheet/Theme/QtStyle: " << QString::fromStdString(styleSheet) << "/"
2966 << QString::fromStdString(theme) << "/" << QString::fromStdString(style) << "\n";
2967
2968 // Add DPI information
2969 str << "Logical DPI/Physical DPI/Pixel Ratio: "
2970 << QApplication::primaryScreen()->logicalDotsPerInch() << "/"
2971 << QApplication::primaryScreen()->physicalDotsPerInch() << "/"
2972 << QApplication::primaryScreen()->devicePixelRatio() << "\n";
2973 }