Debian Codegraph @

src/App/Application.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU Library General Public License (LGPL) *
8 * as published by the Free Software Foundation; either version 2 of *
9 * the License, or (at your option) any later version. *
10 * for detail see the LICENCE text file. *
11 * *
12 * FreeCAD is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU Library General Public License for more details. *
16 * *
17 * You should have received a copy of the GNU Library General Public *
18 * License along with FreeCAD; if not, write to the Free Software *
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
20 * USA *
21 * *
22 ***************************************************************************/
23
24 #include <FCConfig.h>
25
26 # if defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD)
27 # include <unistd.h>
28 # include <pwd.h>
29 # include <sys/types.h>
30 # elif defined(__MINGW32__)
31 # undef WINVER
32 # define WINVER 0x502 // needed for SetDllDirectory
33 # include <Windows.h>
34 # endif
35 # include <boost/algorithm/string.hpp>
36 # include <boost/program_options.hpp>
37 # include <boost/date_time/posix_time/posix_time.hpp>
38 # include <boost/scope_exit.hpp>
39 # include <chrono>
40 # include <random>
41 # include <memory>
42 # include <utility>
43 # include <set>
44 # include <list>
45 # include <algorithm>
46 # include <iostream>
47 # include <map>
48 # include <tuple>
49 # include <vector>
50 # include <fmt/format.h>
51
52 #ifdef FC_OS_WIN32
53 # include <Shlobj.h>
54 # include <codecvt>
55 #endif
56
57 #if defined(FC_OS_BSD)
58 #include <sys/param.h>
59 #include <sys/sysctl.h>
60 #endif
61
62 #include <QCoreApplication>
63 #include <QDir>
64 #include <QFileInfo>
65 #include <QProcessEnvironment>
66 #include <QRegularExpression>
67 #include <QSettings>
68 #include <QStandardPaths>
69 #include <LibraryVersions.h>
70
71 #include <App/MaterialPy.h>
72 #include <App/MetadataPy.h>
73 // FreeCAD Base header
74 #include <Base/AxisPy.h>
75 #include <Base/BaseClass.h>
76 #include <Base/BoundBoxPy.h>
77 #include <Base/ConsoleObserver.h>
78 #include <Base/ServiceProvider.h>
79 #include <Base/CoordinateSystemPy.h>
80 #include <Base/Exception.h>
81 #include <Base/ExceptionFactory.h>
82 #include <Base/FileInfo.h>
83 #include <Base/GeometryPyCXX.h>
84 #include <Base/Interpreter.h>
85 #include <Base/MatrixPy.h>
86 #include <Base/QuantityPy.h>
87 #include <Base/Parameter.h>
88 #include <Base/Persistence.h>
89 #include <Base/PlacementPy.h>
90 #include <Base/PrecisionPy.h>
91 #include <Base/ProgressIndicatorPy.h>
92 #include <Base/RotationPy.h>
93 #include <Base/UniqueNameManager.h>
94 #include <Base/Tools.h>
95 #include <Base/Translate.h>
96 #include <Base/Type.h>
97 #include <Base/TypePy.h>
98 #include <Base/UnitPy.h>
99 #include <Base/UnitsApi.h>
100 #include <Base/VectorPy.h>
101
102 #include "Annotation.h"
103 #include "Application.h"
104 #include "ApplicationDirectories.h"
105 #include "ApplicationDirectoriesPy.h"
106 #include "CleanupProcess.h"
107 #include "ComplexGeoData.h"
108 #include "Services.h"
109 #include "DocumentObjectFileIncluded.h"
110 #include "DocumentObjectGroup.h"
111 #include "DocumentObjectGroupPy.h"
112 #include "DocumentObserver.h"
113 #include "DocumentPy.h"
114 #include "ExpressionParser.h"
115 #include "FeatureTest.h"
116 #include "FeaturePython.h"
117 #include "GeoFeature.h"
118 #include "GeoFeatureGroupExtension.h"
119 #include "ImagePlane.h"
120 #include "InventorObject.h"
121 #include "Link.h"
122 #include "LinkBaseExtensionPy.h"
123 #include "VarSet.h"
124 #include "MaterialObject.h"
125 #include "MeasureManagerPy.h"
126 #include "Origin.h"
127 #include "Datums.h"
128 #include "OriginGroupExtension.h"
129 #include "OriginGroupExtensionPy.h"
130 #include "SuppressibleExtension.h"
131 #include "Part.h"
132 #include "GeoFeaturePy.h"
133 #include "Placement.h"
134 #include "ProgramOptionsUtilities.h"
135 #include "Property.h"
136 #include "PropertyContainer.h"
137 #include "PropertyExpressionEngine.h"
138 #include "PropertyFile.h"
139 #include "PropertyLinks.h"
140 #include "PropertyPythonObject.h"
141 #include "StringHasherPy.h"
142 #include "StringIDPy.h"
143 #include "TextDocument.h"
144 #include "Transactions.h"
145 #include "VRMLObject.h"
146
147 // If you stumble here, run the target "BuildExtractRevision" on Windows systems
148 // or the Python script "SubWCRev.py" on Linux based systems which builds
149 // src/Build/Version.h. Or create your own from src/Build/Version.h.in!
150 #include <Build/Version.h>
151 #include "Branding.h"
152
153
154 // scriptings (scripts are built-in but can be overridden by command line option)
155 #include <App/InitScript.h>
156 #include <App/TestScript.h>
157 #include <App/CMakeScript.h>
158
159 #include "SafeMode.h"
160
161 #ifdef _MSC_VER // New handler for Microsoft Visual C++ compiler
162 # pragma warning( disable : 4535 )
163 # if !defined(_DEBUG) && defined(HAVE_SEH)
164 # define FC_SE_TRANSLATOR
165 # endif
166
167 # include <new.h>
168 # include <eh.h> // VC exception handling
169 #else // Ansi C/C++ new handler
170 # include <new>
171 #endif
172
173 FC_LOG_LEVEL_INIT("App", true, true)
174
175 using namespace App;
176 namespace sp = std::placeholders;
177 namespace fs = std::filesystem;
178
179 //==========================================================================
180 // Application
181 //==========================================================================
182
183 Base::Reference<ParameterManager> Application::_pcSysParamMngr;
184 Base::Reference<ParameterManager> Application::_pcUserParamMngr;
185 Base::ConsoleObserverStd *Application::_pConsoleObserverStd = nullptr;
186 Base::ConsoleObserverFile *Application::_pConsoleObserverFile = nullptr;
187
188 AppExport std::map<std::string, std::string> Application::mConfig;
189 std::unique_ptr<ApplicationDirectories> Application::_appDirs;
190
191
192 //**************************************************************************
193 // Construction and destruction
194
195 // clang-format off
196 PyDoc_STRVAR(FreeCAD_doc,
197 "The functions in the FreeCAD module allow working with documents.\n"
198 "The FreeCAD instance provides a list of references of documents which\n"
199 "can be addressed by a string. Hence the document name must be unique.\n"
200 "\n"
201 "The document has the read-only attribute FileName which points to the\n"
202 "file the document should be stored to.\n"
203 );
204
205 PyDoc_STRVAR(Console_doc,
206 "FreeCAD Console module.\n\n"
207 "The Console module contains functions to manage log entries, messages,\n"
208 "warnings and errors.\n"
209 "There are also functions to get/set the status of the observers used as\n"
210 "logging interfaces."
211 );
212
213 PyDoc_STRVAR(Base_doc,
214 "The Base module contains the classes for the geometric basics\n"
215 "like vector, matrix, bounding box, placement, rotation, axis, ...\n"
216 );
217
218 // This is called via the PyImport_AppendInittab mechanism called
219 // during initialization, to make the built-in __FreeCADBase__
220 // module known to Python.
221 PyMODINIT_FUNC
222 init_freecad_base_module(void)
223 {
224 static struct PyModuleDef BaseModuleDef = {
225 PyModuleDef_HEAD_INIT,
226 "__FreeCADBase__", Base_doc, -1,
227 nullptr, nullptr, nullptr, nullptr, nullptr
228 };
229 return PyModule_Create(&BaseModuleDef);
230 }
231
232 // Set in inside Application
233 static PyMethodDef* ApplicationMethods = nullptr;
234
235 PyMODINIT_FUNC
236 init_freecad_module(void)
237 {
238 static struct PyModuleDef FreeCADModuleDef = {
239 PyModuleDef_HEAD_INIT,
240 "FreeCAD", FreeCAD_doc, -1,
241 ApplicationMethods,
242 nullptr, nullptr, nullptr, nullptr
243 };
244 return PyModule_Create(&FreeCADModuleDef);
245 }
246
247 PyMODINIT_FUNC
248 init_image_module()
249 {
250 static struct PyModuleDef ImageModuleDef = {
251 PyModuleDef_HEAD_INIT,
252 "Image", "", -1,
253 nullptr,
254 nullptr, nullptr, nullptr, nullptr
255 };
256 return PyModule_Create(&ImageModuleDef);
257 }
258 // clang-format on
259
260 Application::Application(std::map<std::string,std::string> &mConfig)
261 : _mConfig(mConfig)
262 {
263 mpcPramManager["System parameter"] = _pcSysParamMngr;
264 mpcPramManager["User parameter"] = _pcUserParamMngr;
265
266 setupPythonTypes();
267 }
268
269 Application::~Application() = default;
270
271 void Application::setupPythonTypes()
272 {
273 // setting up Python binding
274 Base::PyGILStateLocker lock;
275 PyObject* modules = PyImport_GetModuleDict();
276
277 ApplicationMethods = Application::Methods;
278 PyObject* pAppModule = PyImport_ImportModule ("FreeCAD");
279 if (!pAppModule) {
280 PyErr_Clear();
281 pAppModule = init_freecad_module();
282 PyDict_SetItemString(modules, "FreeCAD", pAppModule);
283 }
284 Py::Module(pAppModule).setAttr(std::string("ActiveDocument"),Py::None());
285
286 // clang-format off
287 static struct PyModuleDef ConsoleModuleDef = {
288 PyModuleDef_HEAD_INIT,
289 "__FreeCADConsole__", Console_doc, -1,
290 Base::ConsoleSingleton::Methods,
291 nullptr, nullptr, nullptr, nullptr
292 };
293 PyObject* pConsoleModule = PyModule_Create(&ConsoleModuleDef);
294
295 // fake Image module
296 PyObject* imageModule = init_image_module();
297 PyDict_SetItemString(modules, "Image", imageModule);
298
299 // introducing additional classes
300
301 // NOTE: To finish the initialization of our own type objects we must
302 // call PyType_Ready, otherwise we run into a segmentation fault, later on.
303 // This function is responsible for adding inherited slots from a type's base class.
304 Base::InterpreterSingleton::addType(&Base::VectorPy::Type, pAppModule, "Vector");
305 Base::InterpreterSingleton::addType(&Base::MatrixPy::Type, pAppModule, "Matrix");
306 Base::InterpreterSingleton::addType(&Base::BoundBoxPy::Type, pAppModule, "BoundBox");
307 Base::InterpreterSingleton::addType(&Base::PlacementPy::Type, pAppModule, "Placement");
308 Base::InterpreterSingleton::addType(&Base::RotationPy::Type, pAppModule, "Rotation");
309 Base::InterpreterSingleton::addType(&Base::AxisPy::Type, pAppModule, "Axis");
310
311 // Note: Create an own module 'Base' which should provide the python
312 // binding classes from the base module. At a later stage we should
313 // remove these types from the FreeCAD module.
314
315 PyObject* pBaseModule = PyImport_ImportModule ("__FreeCADBase__");
316 if (!pBaseModule) {
317 PyErr_Clear();
318 pBaseModule = init_freecad_base_module();
319 PyDict_SetItemString(modules, "__FreeCADBase__", pBaseModule);
320 }
321
322 setupPythonException(pBaseModule);
323
324
325 // Python types
326 Base::InterpreterSingleton::addType(&Base::VectorPy ::Type,pBaseModule,"Vector");
327 Base::InterpreterSingleton::addType(&Base::MatrixPy ::Type,pBaseModule,"Matrix");
328 Base::InterpreterSingleton::addType(&Base::BoundBoxPy ::Type,pBaseModule,"BoundBox");
329 Base::InterpreterSingleton::addType(&Base::PlacementPy ::Type,pBaseModule,"Placement");
330 Base::InterpreterSingleton::addType(&Base::RotationPy ::Type,pBaseModule,"Rotation");
331 Base::InterpreterSingleton::addType(&Base::AxisPy ::Type,pBaseModule,"Axis");
332 Base::InterpreterSingleton::addType(&Base::CoordinateSystemPy::Type,pBaseModule,"CoordinateSystem");
333 Base::InterpreterSingleton::addType(&Base::TypePy ::Type,pBaseModule,"TypeId");
334 Base::InterpreterSingleton::addType(&Base::PrecisionPy ::Type,pBaseModule,"Precision");
335
336 Base::InterpreterSingleton::addType(&ApplicationDirectoriesPy::Type, pAppModule, "ApplicationDirectories");
337 Base::InterpreterSingleton::addType(&MaterialPy::Type, pAppModule, "Material");
338 Base::InterpreterSingleton::addType(&MetadataPy::Type, pAppModule, "Metadata");
339
340 Base::InterpreterSingleton::addType(&MeasureManagerPy::Type, pAppModule, "MeasureManager");
341
342 Base::InterpreterSingleton::addType(&StringHasherPy::Type, pAppModule, "StringHasher");
343 Base::InterpreterSingleton::addType(&StringIDPy::Type, pAppModule, "StringID");
344
345 // Add document types
346 Base::InterpreterSingleton::addType(&PropertyContainerPy::Type, pAppModule, "PropertyContainer");
347 Base::InterpreterSingleton::addType(&ExtensionContainerPy::Type, pAppModule, "ExtensionContainer");
348 Base::InterpreterSingleton::addType(&DocumentPy::Type, pAppModule, "Document");
349 Base::InterpreterSingleton::addType(&DocumentObjectPy::Type, pAppModule, "DocumentObject");
350 Base::InterpreterSingleton::addType(&DocumentObjectGroupPy::Type, pAppModule, "DocumentObjectGroup");
351 Base::InterpreterSingleton::addType(&GeoFeaturePy::Type, pAppModule, "GeoFeature");
352
353 // Add extension types
354 Base::InterpreterSingleton::addType(&ExtensionPy::Type, pAppModule, "Extension");
355 Base::InterpreterSingleton::addType(&DocumentObjectExtensionPy::Type, pAppModule, "DocumentObjectExtension");
356 Base::InterpreterSingleton::addType(&GroupExtensionPy::Type, pAppModule, "GroupExtension");
357 Base::InterpreterSingleton::addType(&GeoFeatureGroupExtensionPy::Type, pAppModule, "GeoFeatureGroupExtension");
358 Base::InterpreterSingleton::addType(&OriginGroupExtensionPy::Type, pAppModule, "OriginGroupExtension");
359 Base::InterpreterSingleton::addType(&LinkBaseExtensionPy::Type, pAppModule, "LinkBaseExtension");
360
361 //insert Base and Console
362 Py_INCREF(pBaseModule);
363 PyModule_AddObject(pAppModule, "Base", pBaseModule);
364 Py_INCREF(pConsoleModule);
365 PyModule_AddObject(pAppModule, "Console", pConsoleModule);
366
367 // Translate module
368 PyObject* pTranslateModule = Base::Interpreter().addModule(new Base::Translate);
369 Py_INCREF(pTranslateModule);
370 PyModule_AddObject(pAppModule, "Qt", pTranslateModule);
371
372 //insert Units module
373 static struct PyModuleDef UnitsModuleDef = {
374 PyModuleDef_HEAD_INIT,
375 "Units", "The Unit API", -1,
376 Base::UnitsApi::Methods,
377 nullptr, nullptr, nullptr, nullptr
378 };
379 PyObject* pUnitsModule = PyModule_Create(&UnitsModuleDef);
380 Base::InterpreterSingleton::addType(&Base::QuantityPy ::Type,pUnitsModule,"Quantity");
381 // make sure to set the 'nb_true_divide' slot
382 Base::InterpreterSingleton::addType(&Base::UnitPy ::Type,pUnitsModule,"Unit");
383
384 Py_INCREF(pUnitsModule);
385 PyModule_AddObject(pAppModule, "Units", pUnitsModule);
386
387 Base::ProgressIndicatorPy::init_type();
388 Base::InterpreterSingleton::addType(Base::ProgressIndicatorPy::type_object(),
389 pBaseModule,"ProgressIndicator");
390
391 Base::Vector2dPy::init_type();
392 Base::InterpreterSingleton::addType(Base::Vector2dPy::type_object(),
393 pBaseModule,"Vector2d");
394 // clang-format on
395 }
396
397 /*
398 * Define custom Python exception types
399 */
400 void Application::setupPythonException(PyObject* module)
401 {
402 auto setup = [&module, str {"Base."}](const std::string& ename, auto pyExcType) {
403 auto exception = PyErr_NewException((str + ename).c_str(), pyExcType, nullptr);
404 Py_INCREF(exception);
405 PyModule_AddObject(module, ename.c_str(), exception);
406 return exception;
407 };
408
409 Base::PyExc_FC_GeneralError = setup("FreeCADError", PyExc_RuntimeError);
410 Base::PyExc_FC_FreeCADAbort = setup("FreeCADAbort", PyExc_BaseException);
411 Base::PyExc_FC_XMLBaseException = setup("XMLBaseException", PyExc_Exception);
412 Base::PyExc_FC_XMLParseException = setup("XMLParseException", Base::PyExc_FC_XMLBaseException);
413 Base::PyExc_FC_XMLAttributeError = setup("XMLAttributeError", Base::PyExc_FC_XMLBaseException);
414 Base::PyExc_FC_UnknownProgramOption = setup("UnknownProgramOption", PyExc_BaseException);
415 Base::PyExc_FC_BadFormatError = setup("BadFormatError", Base::PyExc_FC_GeneralError);
416 Base::PyExc_FC_BadGraphError = setup("BadGraphError", Base::PyExc_FC_GeneralError);
417 Base::PyExc_FC_ExpressionError = setup("ExpressionError", Base::PyExc_FC_GeneralError);
418 Base::PyExc_FC_ParserError = setup("ParserError", Base::PyExc_FC_GeneralError);
419 Base::PyExc_FC_CADKernelError = setup("CADKernelError", Base::PyExc_FC_GeneralError);
420 Base::PyExc_FC_PropertyError = setup("PropertyError", PyExc_AttributeError);
421 Base::PyExc_FC_AbortIOException = setup("AbortIOException", PyExc_BaseException);
422 }
423
424 //**************************************************************************
425 // Interface
426
427 /// get called by the document when the name is changing
428 void Application::renameDocument(const char *OldName, const char *NewName)
429 {
430 (void)OldName;
431 (void)NewName;
432 throw Base::RuntimeError("Renaming document internal name is no longer allowed!");
433 }
434
435 Document* Application::newDocument(const char * proposedName, const char * proposedLabel, DocumentInitFlags CreateFlags)
436 {
437 bool isUsingDefaultName = Base::Tools::isNullOrEmpty(proposedName);
438 // get a valid name anyway!
439 if (isUsingDefaultName) {
440 proposedName = "Unnamed";
441 }
442 std::string name(getUniqueDocumentName(proposedName, CreateFlags.temporary));
443
444 // return the temporary document if it exists
445 if (CreateFlags.temporary) {
446 auto it = DocMap.find(name);
447 if (it != DocMap.end() && it->second->testStatus(Document::TempDoc)) {
448 return it->second;
449 }
450 }
451
452 // Determine the document's Label
453 std::string label;
454 if (!Base::Tools::isNullOrEmpty(proposedLabel)) {
455 // If a label is supplied it is used even if not unique
456 label = proposedLabel;
457 }
458 else {
459 label = isUsingDefaultName ? QObject::tr("Unnamed").toStdString() : proposedName;
460
461 if (!DocMap.empty()) {
462 // The assumption here is that there are not many documents and
463 // documents are rarely created so the cost
464 // of building this manager each time is inconsequential
465 Base::UniqueNameManager names;
466 for (const auto& pos : DocMap) {
467 names.addExactName(pos.second->Label.getValue());
468 }
469
470 label = names.makeUniqueName(label);
471 }
472 }
473 // create the FreeCAD document
474 auto doc = new Document(name.c_str());
475 doc->setStatus(Document::TempDoc, CreateFlags.temporary);
476
477 // add the document to the internal list
478 DocMap[name] = doc;
479
480 //NOLINTBEGIN
481 // clang-format off
482 // connect the signals to the application for the new document
483 doc->signalBeforeChange.connect(std::bind(&Application::slotBeforeChangeDocument, this, sp::_1, sp::_2));
484 doc->signalChanged.connect(std::bind(&Application::slotChangedDocument, this, sp::_1, sp::_2));
485 doc->signalNewObject.connect(std::bind(&Application::slotNewObject, this, sp::_1));
486 doc->signalDeletedObject.connect(std::bind(&Application::slotDeletedObject, this, sp::_1));
487 doc->signalBeforeChangeObject.connect(std::bind(&Application::slotBeforeChangeObject, this, sp::_1, sp::_2));
488 doc->signalChangedObject.connect(std::bind(&Application::slotChangedObject, this, sp::_1, sp::_2));
489 doc->signalRelabelObject.connect(std::bind(&Application::slotRelabelObject, this, sp::_1));
490 doc->signalActivatedObject.connect(std::bind(&Application::slotActivatedObject, this, sp::_1));
491 doc->signalUndo.connect(std::bind(&Application::slotUndoDocument, this, sp::_1));
492 doc->signalRedo.connect(std::bind(&Application::slotRedoDocument, this, sp::_1));
493 doc->signalRecomputedObject.connect(std::bind(&Application::slotRecomputedObject, this, sp::_1));
494 doc->signalRecomputed.connect(std::bind(&Application::slotRecomputed, this, sp::_1));
495 doc->signalBeforeRecompute.connect(std::bind(&Application::slotBeforeRecompute, this, sp::_1));
496 doc->signalOpenTransaction.connect(std::bind(&Application::slotOpenTransaction, this, sp::_1, sp::_2));
497 doc->signalCommitTransaction.connect(std::bind(&Application::slotCommitTransaction, this, sp::_1));
498 doc->signalAbortTransaction.connect(std::bind(&Application::slotAbortTransaction, this, sp::_1));
499 doc->signalStartSave.connect(std::bind(&Application::slotStartSaveDocument, this, sp::_1, sp::_2));
500 doc->signalFinishSave.connect(std::bind(&Application::slotFinishSaveDocument, this, sp::_1, sp::_2));
501 doc->signalChangePropertyEditor.connect(std::bind(&Application::slotChangePropertyEditor, this, sp::_1, sp::_2));
502 // clang-format on
503 //NOLINTEND
504
505 // (temporarily) make this the active document for the upcoming notifications.
506 // Signal NewDocument rather than ActiveDocument (which is what setActiveDocument would do)
507 auto oldActiveDoc = _pActiveDoc;
508 setActiveDocumentNoSignal(doc);
509 signalNewDocument(*doc, CreateFlags.createView);
510
511 doc->Label.setValue(label);
512
513 // set the old document active again if the new is temporary
514 if (CreateFlags.temporary && oldActiveDoc) {
515 setActiveDocument(oldActiveDoc);
516 }
517 return doc;
518 }
519
520 bool Application::closeDocument(const char* name)
521 {
522 const auto pos = DocMap.find( name );
523 if (pos == DocMap.end()) // no such document
524 return false;
525
526 Base::ConsoleRefreshDisabler disabler;
527
528 // Trigger observers before removing the document from the internal map.
529 // Some observers might rely on this document still being there.
530 signalDeleteDocument(*pos->second);
531
532 // For exception-safety use a smart pointer
533 if (_pActiveDoc == pos->second) {
534 setActiveDocument(static_cast<Document*>(nullptr));
535 }
536 const std::unique_ptr<Document> delDoc (pos->second);
537 DocMap.erase( pos );
538 DocFileMap.erase(Base::FileInfo(delDoc->FileName.getValue()).filePath());
539
540 _objCount = -1;
541
542 // Trigger observers after removing the document from the internal map.
543 signalDeletedDocument();
544
545 return true;
546 }
547
548 void Application::closeAllDocuments()
549 {
550 Base::FlagToggler<bool> flag(_isClosingAll);
551 std::map<std::string,Document*>::iterator pos;
552 while((pos = DocMap.begin()) != DocMap.end())
553 closeDocument(pos->first.c_str());
554 }
555
556 Document* Application::getDocument(const char *Name) const
557 {
558
559 const auto pos = DocMap.find(Name);
560
561 if (pos == DocMap.end())
562 return nullptr;
563
564 return pos->second;
565 }
566
567 const char * Application::getDocumentName(const Document* doc) const
568 {
569 for (const auto & it : DocMap) {
570 if (it.second == doc) {
571 return it.first.c_str();
572 }
573 }
574
575 return nullptr;
576 }
577
578 std::vector<Document*> Application::getDocuments() const
579 {
580 std::vector<Document*> docs;
581 docs.reserve(DocMap.size());
582 for (const auto & it : DocMap)
583 docs.push_back(it.second);
584 return docs;
585 }
586
587 std::string Application::getUniqueDocumentName(const char* Name, bool tempDoc) const
588 {
589 if (!Name || *Name == '\0') {
590 return {};
591 }
592 std::string CleanName = Base::Tools::getIdentifier(Name);
593
594 // name in use?
595 auto pos = DocMap.find(CleanName);
596
597 if (pos == DocMap.end() || (tempDoc && pos->second->testStatus(Document::TempDoc))) {
598 // if not, name is OK
599 return CleanName;
600 }
601 // The assumption here is that there are not many documents and
602 // documents are rarely created so the cost
603 // of building this manager each time is inconsequential
604 Base::UniqueNameManager names;
605 for (const auto& pos : DocMap) {
606 if (!tempDoc || !pos.second->testStatus(Document::TempDoc)) {
607 names.addExactName(pos.first);
608 }
609 }
610
611 return names.makeUniqueName(CleanName);
612 }
613
614 int Application::addPendingDocument(const char *FileName, const char *objName, bool allowPartial)
615 {
616 if(!_isRestoring)
617 return 0;
618 if(allowPartial && _allowPartial)
619 return -1;
620 assert(!Base::Tools::isNullOrEmpty(FileName));
621 assert(!Base::Tools::isNullOrEmpty(objName));
622 if(!_docReloadAttempts[FileName].emplace(objName).second)
623 return -1;
624 const auto ret = _pendingDocMap.emplace(FileName,std::vector<std::string>());
625 ret.first->second.emplace_back(objName);
626 if(ret.second) {
627 _pendingDocs.emplace_back(ret.first->first.c_str());
628 return 1;
629 }
630 return -1;
631 }
632
633 bool Application::isRestoring() const {
634 return _isRestoring || Document::isAnyRestoring();
635 }
636
637 bool Application::isClosingAll() const {
638 return _isClosingAll;
639 }
640
641 struct DocTiming {
642 FC_DURATION_DECLARE(d1);
643 FC_DURATION_DECLARE(d2);
644 DocTiming() {
645 FC_DURATION_INIT(d1);
646 FC_DURATION_INIT(d2);
647 }
648 };
649
650 class DocOpenGuard {
651 public:
652 bool &flag;
653 boost::signals2::signal<void ()> &signal;
654 DocOpenGuard(bool &f, boost::signals2::signal<void ()> &s)
655 :flag(f),signal(s)
656 {
657 flag = true;
658 }
659 ~DocOpenGuard() {
660 if(flag) {
661 flag = false;
662 try {
663 signal();
664 }
665 catch (const boost::exception&) {
666 // reported by code analyzers
667 Base::Console().warning("~DocOpenGuard: Unexpected boost exception\n");
668 }
669 }
670 }
671 };
672
673 Document* Application::openDocument(const char * FileName, DocumentInitFlags initFlags) {
674 std::vector<std::string> filenames(1,FileName);
675 auto docs = openDocuments(filenames, nullptr, nullptr, nullptr, initFlags);
676 if(!docs.empty())
677 return docs.front();
678 return nullptr;
679 }
680
681 Document *Application::getDocumentByPath(const char *path, PathMatchMode checkCanonical) const {
682 if(Base::Tools::isNullOrEmpty(path))
683 return nullptr;
684 if (DocFileMap.empty()) {
685 for(const auto &v : DocMap) {
686 const auto &file = v.second->FileName.getStrValue();
687 if(!file.empty())
688 DocFileMap[Base::FileInfo(file.c_str()).filePath()] = v.second;
689 }
690 }
691 const auto it = DocFileMap.find(Base::FileInfo(path).filePath());
692 if(it != DocFileMap.end())
693 return it->second;
694
695 if (checkCanonical == PathMatchMode::MatchAbsolute) {
696 return nullptr;
697 }
698
699 const std::string filepath = Base::FileInfo(path).filePath();
700 const QString canonicalPath = QFileInfo(QString::fromUtf8(path)).canonicalFilePath();
701 for (const auto &v : DocMap) {
702 QFileInfo fi(QString::fromUtf8(v.second->FileName.getValue()));
703 if (canonicalPath == fi.canonicalFilePath()) {
704 if (checkCanonical == PathMatchMode::MatchCanonical) {
705 return v.second;
706 }
707 const bool samePath = (canonicalPath == QString::fromUtf8(filepath.c_str()));
708 FC_WARN("Identical physical path '" << canonicalPath.toUtf8().constData() << "'\n"
709 << (samePath?"":" for file '") << (samePath?"":filepath.c_str()) << (samePath?"":"'\n")
710 << " with existing document '" << v.second->Label.getValue()
711 << "' in path: '" << v.second->FileName.getValue() << "'");
712 break;
713 }
714 }
715 return nullptr;
716 }
717
718 std::vector<Document*> Application::openDocuments(const std::vector<std::string> &filenames,
719 const std::vector<std::string> *paths,
720 const std::vector<std::string> *labels,
721 std::vector<std::string> *errs,
722 DocumentInitFlags initFlags)
723 {
724 std::vector<Document*> res(filenames.size(), nullptr);
725 if (filenames.empty())
726 return res;
727
728 if (errs)
729 errs->resize(filenames.size());
730
731 DocOpenGuard guard(_isRestoring, signalFinishOpenDocument);
732 _pendingDocs.clear();
733 _pendingDocsReopen.clear();
734 _pendingDocMap.clear();
735 _docReloadAttempts.clear();
736
737 signalStartOpenDocument();
738
739 ParameterGrp::handle hGrp = GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document");
740 _allowPartial = !hGrp->GetBool("NoPartialLoading",false);
741
742 for (auto &name : filenames)
743 _pendingDocs.emplace_back(name.c_str());
744
745 std::map<DocumentT, DocTiming> timings;
746
747 FC_TIME_INIT(t);
748
749 std::vector<DocumentT> openedDocs;
750
751 int pass = 0;
752 do {
753 std::set<DocumentT> newDocs;
754 for (std::size_t count=0;; ++count) {
755 std::string name = std::move(_pendingDocs.front());
756 _pendingDocs.pop_front();
757 bool isMainDoc = (pass == 0 && count < filenames.size());
758
759 try {
760 _objCount = -1;
761 std::vector<std::string> objNames;
762 if (_allowPartial) {
763 auto it = _pendingDocMap.find(name);
764 if (it != _pendingDocMap.end()) {
765 if(isMainDoc)
766 it->second.clear();
767 else
768 objNames.swap(it->second);
769 _pendingDocMap.erase(it);
770 }
771 }
772
773 FC_TIME_INIT(t1);
774 DocTiming timing;
775
776 const char *path = name.c_str();
777 const char *label = nullptr;
778 if (isMainDoc) {
779 if (paths && paths->size()>count)
780 path = (*paths)[count].c_str();
781
782 if (labels && labels->size()>count)
783 label = (*labels)[count].c_str();
784 }
785
786 auto doc = openDocumentPrivate(path, name.c_str(), label, isMainDoc, initFlags, std::move(objNames));
787 FC_DURATION_PLUS(timing.d1,t1);
788 if (doc) {
789 timings[doc].d1 += timing.d1;
790 newDocs.emplace(doc);
791 }
792
793 if (isMainDoc)
794 res[count] = doc;
795 _objCount = -1;
796 }
797 catch (const Base::Exception &e) {
798 e.reportException();
799 if (!errs && isMainDoc)
800 throw;
801 if (errs && isMainDoc)
802 (*errs)[count] = e.what();
803 else
804 Base::Console().error("Exception opening file: %s [%s]\n", name.c_str(), e.what());
805 }
806 catch (const std::exception &e) {
807 if (!errs && isMainDoc)
808 throw;
809 if (errs && isMainDoc)
810 (*errs)[count] = e.what();
811 else
812 Base::Console().error("Exception opening file: %s [%s]\n", name.c_str(), e.what());
813 }
814 catch (...) {
815 if (errs) {
816 if (isMainDoc)
817 (*errs)[count] = "unknown error";
818 }
819 else {
820 _pendingDocs.clear();
821 _pendingDocsReopen.clear();
822 _pendingDocMap.clear();
823 throw;
824 }
825 }
826
827 if (_pendingDocs.empty()) {
828 if(_pendingDocsReopen.empty())
829 break;
830 _pendingDocs = std::move(_pendingDocsReopen);
831 _pendingDocsReopen.clear();
832 for(const auto &file : _pendingDocs) {
833 auto doc = getDocumentByPath(file.c_str());
834 if(doc)
835 closeDocument(doc->getName());
836 }
837 }
838 }
839
840 ++pass;
841 _pendingDocMap.clear();
842
843 std::vector<Document*> docs;
844 docs.reserve(newDocs.size());
845 for(const auto &d : newDocs) {
846 auto doc = d.getDocument();
847 if(!doc)
848 continue;
849 // Notify PropertyXLink to attach newly opened documents and restore
850 // relevant external links
851 PropertyXLink::restoreDocument(*doc);
852 docs.push_back(doc);
853 }
854
855 Base::SequencerLauncher seq("Postprocessing...", docs.size());
856
857 // After external links has been restored, we can now sort the document
858 // according to their dependency order.
859 try {
860 docs = Document::getDependentDocuments(docs, true);
861 } catch (Base::Exception &e) {
862 e.reportException();
863 }
864 for(auto it=docs.begin(); it!=docs.end();) {
865 auto doc = *it;
866
867 // It is possible that the newly opened document depends on an existing
868 // document, which will be included with the above call to
869 // Document::getDependentDocuments(). Make sure to exclude that.
870 if(!newDocs.contains(doc)) {
871 it = docs.erase(it);
872 continue;
873 }
874
875 auto &timing = timings[doc];
876 FC_TIME_INIT(t1);
877 // Finalize document restoring with the correct order
878 if(doc->afterRestore(true)) {
879 openedDocs.emplace_back(doc);
880 it = docs.erase(it);
881 } else {
882 ++it;
883 // Here means this is a partial loaded document, and we need to
884 // reload it fully because of touched objects. The reason of
885 // reloading a partial document with touched object is because
886 // partial document is supposed to be readonly, while a
887 // 'touched' object requires recomputation. And an object may
888 // become touched during restoring if externally linked
889 // document time stamp mismatches with the stamp saved.
890 _pendingDocs.emplace_back(doc->FileName.getValue());
891 _pendingDocMap.erase(doc->FileName.getValue());
892 }
893 FC_DURATION_PLUS(timing.d2,t1);
894 seq.next();
895 }
896 // Close the document for reloading
897 for(const auto doc : docs)
898 closeDocument(doc->getName());
899
900 }while(!_pendingDocs.empty());
901
902 // Set the active document using the first successfully restored main
903 // document (i.e. documents explicitly asked for by caller).
904 for (auto doc : res) {
905 if (doc) {
906 setActiveDocument(doc);
907 break;
908 }
909 }
910
911 for (auto &doc : openedDocs) {
912 auto &timing = timings[doc];
913 FC_DURATION_LOG(timing.d1, doc.getDocumentName() << " restore");
914 FC_DURATION_LOG(timing.d2, doc.getDocumentName() << " postprocess");
915 }
916 FC_TIME_LOG(t,"total");
917 PropertyLinkBase::updateAllElementReferences();
918 _isRestoring = false;
919
920 signalFinishOpenDocument();
921 return res;
922 }
923
924 Document* Application::openDocumentPrivate(const char * FileName,
925 const char *propFileName, const char *label,
926 bool isMainDoc, DocumentInitFlags initFlags,
927 std::vector<std::string> &&objNames)
928 {
929 Base::FileInfo File(FileName);
930
931 if (!File.exists()) {
932 std::stringstream str;
933 str << "File '" << FileName << "' does not exist!";
934 throw Base::FileSystemError(str.str());
935 }
936
937 // Before creating a new document we check whether the document is already open
938 auto doc = getDocumentByPath(File.filePath().c_str(), PathMatchMode::MatchCanonicalWarning);
939 if(doc) {
940 if(doc->testStatus(Document::PartialDoc)
941 || doc->testStatus(Document::PartialRestore)) {
942 // Here means a document is already partially loaded, but the document
943 // is requested again, either partial or not. We must check if the
944 // document contains the required object
945
946 if(isMainDoc) {
947 // Main document must be open fully, so close and reopen
948 closeDocument(doc->getName());
949 doc = nullptr;
950 } else if(_allowPartial) {
951 bool reopen = false;
952 for(const auto &name : objNames) {
953 auto obj = doc->getObject(name.c_str());
954 if(!obj || obj->testStatus(PartialObject)) {
955 reopen = true;
956 // NOTE: We are about to reload this document with
957 // extra objects. However, it is possible to repeat
958 // this process several times, if it is linked by
959 // multiple documents and each with a different set of
960 // objects. To partially solve this problem, we do not
961 // close and reopen the document immediately here, but
962 // add it to _pendingDocsReopen to delay reloading.
963 for(auto obj2 : doc->getObjects())
964 objNames.emplace_back(obj2->getNameInDocument());
965 _pendingDocMap[doc->FileName.getValue()] = std::move(objNames);
966 break;
967 }
968 }
969 if(!reopen)
970 return nullptr;
971 }
972
973 if(doc) {
974 _pendingDocsReopen.emplace_back(FileName);
975 return nullptr;
976 }
977 }
978
979 if (!isMainDoc) {
980 return nullptr;
981 }
982
983 if (doc) {
984 return doc;
985 }
986 }
987
988 std::string name;
989 if(propFileName != FileName) {
990 Base::FileInfo fi(propFileName);
991 name = fi.fileNamePure();
992 }else
993 name = File.fileNamePure();
994
995 // Use the same name for the internal and user name.
996 // The file name is UTF-8 encoded which means that the internal name will be modified
997 // to only contain valid ASCII characters but the user name will be kept.
998 if(!label)
999 label = name.c_str();
1000
1001 initFlags.createView &= isMainDoc;
1002 Document* newDoc = newDocument(name.c_str(), label, initFlags);
1003 newDoc->FileName.setValue(propFileName==FileName?File.filePath():propFileName);
1004
1005 try {
1006 // read the document
1007 newDoc->restore(File.filePath().c_str(),true,objNames);
1008 if(!DocFileMap.empty())
1009 DocFileMap[Base::FileInfo(newDoc->FileName.getValue()).filePath()] = newDoc;
1010 return newDoc;
1011 }
1012 // if the project file itself is corrupt then
1013 // close the document
1014 catch (const Base::FileException&) {
1015 closeDocument(newDoc->getName());
1016 throw;
1017 }
1018 catch (const std::ios_base::failure&) {
1019 closeDocument(newDoc->getName());
1020 throw;
1021 }
1022 // but for any other exceptions leave it open to give the
1023 // user a chance to fix it
1024 catch (...) {
1025 throw;
1026 }
1027 }
1028
1029 Document* Application::getActiveDocument() const
1030 {
1031 return _pActiveDoc;
1032 }
1033
1034 void Application::setActiveDocument(Document* pDoc)
1035 {
1036 setActiveDocumentNoSignal(pDoc);
1037
1038 if (pDoc) {
1039 signalActiveDocument(*pDoc);
1040 }
1041 }
1042
1043 void Application::setActiveDocumentNoSignal(Document* pDoc)
1044 {
1045 _pActiveDoc = pDoc;
1046
1047 // make sure that the active document is set in case no GUI is up
1048 if (pDoc) {
1049 Base::PyGILStateLocker lock;
1050 const Py::Object active(pDoc->getPyObject(), true);
1051 Py::Module("FreeCAD").setAttr(std::string("ActiveDocument"), active);
1052 }
1053 else {
1054 Base::PyGILStateLocker lock;
1055 Py::Module("FreeCAD").setAttr(std::string("ActiveDocument"), Py::None());
1056 }
1057 }
1058
1059 void Application::setActiveDocument(const char* Name)
1060 {
1061 // If no active document is set, resort to a default.
1062 if (*Name == '\0') {
1063 _pActiveDoc = nullptr;
1064 return;
1065 }
1066
1067 if (const auto pos = DocMap.find(Name); pos != DocMap.end()) {
1068 setActiveDocument(pos->second);
1069 }
1070 else {
1071 std::stringstream s;
1072 s << "Try to activate unknown document '" << Name << "'";
1073 throw Base::RuntimeError(s.str());
1074 }
1075 }
1076
1077 static int _TransSignalCount;
1078 static bool _TransSignalled;
1079 Application::TransactionSignaller::TransactionSignaller(bool abort, bool signal)
1080 :abort(abort)
1081 {
1082 ++_TransSignalCount;
1083 if(signal && !_TransSignalled) {
1084 _TransSignalled = true;
1085 GetApplication().signalBeforeCloseTransaction(abort);
1086 }
1087 }
1088
1089 Application::TransactionSignaller::~TransactionSignaller() {
1090 if(--_TransSignalCount == 0 && _TransSignalled) {
1091 _TransSignalled = false;
1092 try {
1093 GetApplication().signalCloseTransaction(abort);
1094 }
1095 catch (const boost::exception&) {
1096 // reported by code analyzers
1097 Base::Console().warning("~TransactionSignaller: Unexpected boost exception\n");
1098 }
1099 }
1100 }
1101
1102 int64_t Application::applicationPid()
1103 {
1104 static int64_t randomNumber = []() {
1105 const auto tp = std::chrono::high_resolution_clock::now();
1106 const auto dur = tp.time_since_epoch();
1107 const auto seed = dur.count();
1108 std::mt19937 generator(static_cast<unsigned>(seed));
1109 constexpr int64_t minValue {1};
1110 constexpr int64_t maxValue {1000000};
1111 std::uniform_int_distribution<int64_t> distribution(minValue, maxValue);
1112 return distribution(generator);
1113 }();
1114 return randomNumber;
1115 }
1116
1117 std::string Application::getHomePath()
1118 {
1119 return Base::FileInfo::pathToString(Application::directories()->getHomePath()) + PATHSEP;
1120 }
1121
1122 std::string Application::getExecutableName()
1123 {
1124 return mConfig["ExeName"];
1125 }
1126
1127 std::string Application::getNameWithVersion()
1128 {
1129 auto appname = QCoreApplication::applicationName().toStdString();
1130 auto config = Application::Config();
1131 auto major = config["BuildVersionMajor"];
1132 auto minor = config["BuildVersionMinor"];
1133 auto point = config["BuildVersionPoint"];
1134 auto suffix = config["BuildVersionSuffix"];
1135 return fmt::format("{} {}.{}.{}{}", appname, major, minor, point, suffix);
1136 }
1137
1138 bool Application::isDevelopmentVersion()
1139 {
1140 static std::string suffix = []() constexpr {
1141 return FCVersionSuffix;
1142 }();
1143 return suffix == "dev";
1144 }
1145
1146 const std::unique_ptr<ApplicationDirectories>& Application::directories() {
1147 return _appDirs;
1148 }
1149
1150 std::string Application::getTempPath()
1151 {
1152 return Base::FileInfo::pathToString(_appDirs->getTempPath()) + PATHSEP;
1153 }
1154
1155 std::string Application::getTempFileName(const char* FileName)
1156 {
1157 return Base::FileInfo::pathToString(_appDirs->getTempFileName(FileName ? FileName : std::string()));
1158 }
1159
1160 std::string Application::getUserCachePath()
1161 {
1162 return Base::FileInfo::pathToString(_appDirs->getUserCachePath()) + PATHSEP;
1163 }
1164
1165 std::string Application::getUserConfigPath()
1166 {
1167 return Base::FileInfo::pathToString(_appDirs->getUserConfigPath()) + PATHSEP;
1168 }
1169
1170 std::string Application::getUserAppDataDir()
1171 {
1172 return Base::FileInfo::pathToString(_appDirs->getUserAppDataDir()) + PATHSEP;
1173 }
1174
1175 std::string Application::getUserMacroDir()
1176 {
1177 return Base::FileInfo::pathToString(_appDirs->getUserMacroDir()) + PATHSEP;
1178 }
1179
1180 std::string Application::getResourceDir()
1181 {
1182 return Base::FileInfo::pathToString(_appDirs->getResourceDir()) + PATHSEP;
1183 }
1184
1185 std::string Application::getLibraryDir()
1186 {
1187 return Base::FileInfo::pathToString(_appDirs->getLibraryDir()) + PATHSEP;
1188 }
1189
1190 std::string Application::getHelpDir()
1191 {
1192 return Base::FileInfo::pathToString(_appDirs->getHelpDir()) + PATHSEP;
1193 }
1194
1195 int Application::checkLinkDepth(int depth, MessageOption option)
1196 {
1197 if (_objCount < 0) {
1198 _objCount = 0;
1199 for (const auto &v : DocMap) {
1200 _objCount += v.second->countObjects();
1201 }
1202 }
1203
1204 if (depth > _objCount + 2) {
1205 const auto msg = "Link recursion limit reached. "
1206 "Please check for cyclic reference.";
1207 switch (option) {
1208 case MessageOption::Quiet:
1209 return 0;
1210 case MessageOption::Error:
1211 FC_ERR(msg);
1212 return 0;
1213 case MessageOption::Throw:
1214 throw Base::RuntimeError(msg);
1215 }
1216 }
1217
1218 return _objCount + 2;
1219 }
1220
1221 std::set<DocumentObject *> Application::getLinksTo(
1222 const DocumentObject *obj, int options, int maxCount) const
1223 {
1224 std::set<DocumentObject *> links;
1225 if(!obj) {
1226 for(auto &v : DocMap) {
1227 v.second->getLinksTo(links,obj,options,maxCount);
1228 if(maxCount && static_cast<int>(links.size())>=maxCount)
1229 break;
1230 }
1231 } else {
1232 std::set<Document*> docs;
1233 for (const auto o : obj->getInList()) {
1234 if(o && o->isAttachedToDocument() && docs.insert(o->getDocument()).second) {
1235 o->getDocument()->getLinksTo(links,obj,options,maxCount);
1236 if(maxCount && static_cast<int>(links.size())>=maxCount)
1237 break;
1238 }
1239 }
1240 }
1241 return links;
1242 }
1243
1244 bool Application::hasLinksTo(const DocumentObject *obj) const {
1245 return !getLinksTo(obj,0,1).empty();
1246 }
1247
1248 ParameterManager & Application::GetSystemParameter()
1249 {
1250 return *_pcSysParamMngr;
1251 }
1252
1253 ParameterManager & Application::GetUserParameter()
1254 {
1255 return *_pcUserParamMngr;
1256 }
1257
1258 ParameterManager * Application::GetParameterSet(const char* sName) const
1259 {
1260 const auto it = mpcPramManager.find(sName);
1261
1262 return it != mpcPramManager.end() ? it->second : nullptr;
1263 }
1264
1265 const std::map<std::string,Base::Reference<ParameterManager>> &
1266 Application::GetParameterSetList() const
1267 {
1268 return mpcPramManager;
1269 }
1270
1271 void Application::AddParameterSet(const char* sName)
1272 {
1273 const auto it = mpcPramManager.find(sName);
1274 if ( it != mpcPramManager.end() )
1275 return;
1276 mpcPramManager[sName] = ParameterManager::Create();
1277 }
1278
1279 void Application::RemoveParameterSet(const char* sName)
1280 {
1281 const auto it = mpcPramManager.find(sName);
1282 // Must not delete user or system parameter
1283 if ( it == mpcPramManager.end() || it->second == _pcUserParamMngr || it->second == _pcSysParamMngr )
1284 return;
1285 mpcPramManager.erase(it);
1286 }
1287
1288 Base::Reference<ParameterGrp> Application::GetParameterGroupByPath(const char* sName)
1289 {
1290 std::string cName = sName, cTemp;
1291
1292 const std::string::size_type pos = cName.find(':');
1293
1294 // is there a path separator ?
1295 if (pos == std::string::npos) {
1296 throw Base::ValueError("Application::GetParameterGroupByPath() no parameter set name specified");
1297 }
1298 // assigning the parameter set name
1299 cTemp.assign(cName,0,pos);
1300 cName.erase(0,pos+1);
1301
1302 // test if name is valid
1303 const auto It = mpcPramManager.find(cTemp);
1304 if (It == mpcPramManager.end())
1305 throw Base::ValueError("Application::GetParameterGroupByPath() unknown parameter set name specified");
1306
1307 return It->second->GetGroup(cName.c_str());
1308 }
1309
1310 void Application::addImportType(const char* Type, const char* ModuleName)
1311 {
1312 FileTypeItem item;
1313 item.filter = Type;
1314 item.module = ModuleName;
1315
1316 // Extract each filetype from 'Type' literal
1317 std::string::size_type pos = item.filter.find("*.");
1318 while ( pos != std::string::npos ) {
1319 const std::string::size_type next = item.filter.find_first_of(" )", pos + 1);
1320 const std::string::size_type len = next-pos-2;
1321 std::string type = item.filter.substr(pos+2,len);
1322 item.types.push_back(std::move(type));
1323 pos = item.filter.find("*.", next);
1324 }
1325
1326 // Due to branding stuff replace "FreeCAD" with the branded application name
1327 if (strncmp(Type, "FreeCAD", 7) == 0) {
1328 std::string AppName = Config()["ExeName"];
1329 AppName += item.filter.substr(7);
1330 item.filter = std::move(AppName);
1331 // put to the front of the array
1332 _mImportTypes.insert(_mImportTypes.begin(),std::move(item));
1333 }
1334 else {
1335 _mImportTypes.push_back(std::move(item));
1336 }
1337 }
1338
1339 void Application::changeImportModule(const char* Type, const char* OldModuleName, const char* NewModuleName)
1340 {
1341 for (auto& it : _mImportTypes) {
1342 if (it.filter == Type && it.module == OldModuleName) {
1343 it.module = NewModuleName;
1344 break;
1345 }
1346 }
1347 }
1348
1349 std::vector<std::string> Application::getImportModules(const std::string& extension) const
1350 {
1351 std::vector<std::string> modules;
1352 for (const auto & it : _mImportTypes) {
1353 const std::vector<std::string>& types = it.types;
1354 for (const auto & jt : types) {
1355 if (boost::iequals(extension, jt)) {
1356 modules.push_back(it.module);
1357 }
1358 }
1359 }
1360
1361 return modules;
1362 }
1363
1364 std::vector<std::string> Application::getImportModules() const
1365 {
1366 std::vector<std::string> modules;
1367 modules.reserve(_mImportTypes.size());
1368 for (const auto& it : _mImportTypes) {
1369 modules.push_back(it.module);
1370 }
1371 std::sort(modules.begin(), modules.end());
1372 modules.erase(std::unique(modules.begin(), modules.end()), modules.end());
1373 return modules;
1374 }
1375
1376 std::vector<std::string> Application::getImportTypes(const std::string& Module) const
1377 {
1378 std::vector<std::string> types;
1379 for (const auto & it : _mImportTypes) {
1380 if (boost::iequals(Module, it.module)) {
1381 types.insert(types.end(), it.types.begin(), it.types.end());
1382 }
1383 }
1384
1385 return types;
1386 }
1387
1388 std::vector<std::string> Application::getImportTypes() const
1389 {
1390 std::vector<std::string> types;
1391 for (const auto & it : _mImportTypes) {
1392 types.insert(types.end(), it.types.begin(), it.types.end());
1393 }
1394
1395 std::sort(types.begin(), types.end());
1396 types.erase(std::unique(types.begin(), types.end()), types.end());
1397
1398 return types;
1399 }
1400
1401 std::map<std::string, std::string> Application::getImportFilters(const std::string& extension) const
1402 {
1403 std::map<std::string, std::string> moduleFilter;
1404 for (const auto & it : _mImportTypes) {
1405 const std::vector<std::string>& types = it.types;
1406 for (const auto & jt : types) {
1407 if (boost::iequals(extension, jt)) {
1408 moduleFilter[it.filter] = it.module;
1409 }
1410 }
1411 }
1412
1413 return moduleFilter;
1414 }
1415
1416 std::map<std::string, std::string> Application::getImportFilters() const
1417 {
1418 std::map<std::string, std::string> filter;
1419 for (const auto & it : _mImportTypes) {
1420 filter[it.filter] = it.module;
1421 }
1422
1423 return filter;
1424 }
1425
1426 void Application::addExportType(const char* Type, const char* ModuleName)
1427 {
1428 FileTypeItem item;
1429 item.filter = Type;
1430 item.module = ModuleName;
1431
1432 // Extract each filetype from 'Type' literal
1433 std::string::size_type pos = item.filter.find("*.");
1434 while ( pos != std::string::npos ) {
1435 const std::string::size_type next = item.filter.find_first_of(" )", pos + 1);
1436 const std::string::size_type len = next-pos-2;
1437 std::string type = item.filter.substr(pos+2,len);
1438 item.types.push_back(std::move(type));
1439 pos = item.filter.find("*.", next);
1440 }
1441
1442 // Due to branding stuff replace "FreeCAD" with the branded application name
1443 if (strncmp(Type, "FreeCAD", 7) == 0) {
1444 std::string AppName = Config()["ExeName"];
1445 AppName += item.filter.substr(7);
1446 item.filter = std::move(AppName);
1447 // put to the front of the array
1448 _mExportTypes.insert(_mExportTypes.begin(),std::move(item));
1449 }
1450 else {
1451 _mExportTypes.push_back(std::move(item));
1452 }
1453 }
1454
1455 void Application::changeExportModule(const char* Type, const char* OldModuleName, const char* NewModuleName)
1456 {
1457 for (auto& it : _mExportTypes) {
1458 if (it.filter == Type && it.module == OldModuleName) {
1459 it.module = NewModuleName;
1460 break;
1461 }
1462 }
1463 }
1464
1465 std::vector<std::string> Application::getExportModules(const std::string& extension) const
1466 {
1467 std::vector<std::string> modules;
1468 for (const auto & it : _mExportTypes) {
1469 const std::vector<std::string>& types = it.types;
1470 for (const auto & jt : types) {
1471 if (boost::iequals(extension, jt)) {
1472 modules.push_back(it.module);
1473 }
1474 }
1475 }
1476
1477 return modules;
1478 }
1479
1480 std::vector<std::string> Application::getExportModules() const
1481 {
1482 std::vector<std::string> modules;
1483 modules.reserve(_mExportTypes.size());
1484 for (const auto& it : _mExportTypes) {
1485 modules.push_back(it.module);
1486 }
1487 std::sort(modules.begin(), modules.end());
1488 modules.erase(std::unique(modules.begin(), modules.end()), modules.end());
1489 return modules;
1490 }
1491
1492 std::vector<std::string> Application::getExportTypes(const std::string& Module) const
1493 {
1494 std::vector<std::string> types;
1495 for (const auto & it : _mExportTypes) {
1496 if (boost::iequals(Module, it.module)) {
1497 types.insert(types.end(), it.types.begin(), it.types.end());
1498 }
1499 }
1500
1501 return types;
1502 }
1503
1504 std::vector<std::string> Application::getExportTypes() const
1505 {
1506 std::vector<std::string> types;
1507 for (const FileTypeItem& it : _mExportTypes) {
1508 types.insert(types.end(), it.types.begin(), it.types.end());
1509 }
1510
1511 std::sort(types.begin(), types.end());
1512 types.erase(std::unique(types.begin(), types.end()), types.end());
1513
1514 return types;
1515 }
1516
1517 std::map<std::string, std::string> Application::getExportFilters(const std::string& extension) const
1518 {
1519 std::map<std::string, std::string> moduleFilter;
1520 for (const auto & it : _mExportTypes) {
1521 const std::vector<std::string>& types = it.types;
1522 for (const auto & jt : types) {
1523 if (boost::iequals(extension, jt)) {
1524 moduleFilter[it.filter] = it.module;
1525 }
1526 }
1527 }
1528
1529 return moduleFilter;
1530 }
1531
1532 std::map<std::string, std::string> Application::getExportFilters() const
1533 {
1534 std::map<std::string, std::string> filter;
1535 for (const FileTypeItem& it : _mExportTypes) {
1536 filter[it.filter] = it.module;
1537 }
1538
1539 return filter;
1540 }
1541
1542 //**************************************************************************
1543 // signaling
1544 void Application::slotBeforeChangeDocument(const Document& doc, const Property& prop)
1545 {
1546 this->signalBeforeChangeDocument(doc, prop);
1547 }
1548
1549 void Application::slotChangedDocument(const Document& doc, const Property& prop)
1550 {
1551 this->signalChangedDocument(doc, prop);
1552 }
1553
1554 void Application::slotNewObject(const DocumentObject& obj)
1555 {
1556 this->signalNewObject(obj);
1557 _objCount = -1;
1558 }
1559
1560 void Application::slotDeletedObject(const DocumentObject& obj)
1561 {
1562 this->signalDeletedObject(obj);
1563 _objCount = -1;
1564 }
1565
1566 void Application::slotBeforeChangeObject(const DocumentObject& obj, const Property& prop)
1567 {
1568 this->signalBeforeChangeObject(obj, prop);
1569 }
1570
1571 void Application::slotChangedObject(const DocumentObject& obj, const Property& prop)
1572 {
1573 this->signalChangedObject(obj, prop);
1574 }
1575
1576 void Application::slotRelabelObject(const DocumentObject& obj)
1577 {
1578 this->signalRelabelObject(obj);
1579 }
1580
1581 void Application::slotActivatedObject(const DocumentObject& obj)
1582 {
1583 this->signalActivatedObject(obj);
1584 }
1585
1586 void Application::slotUndoDocument(const Document& doc)
1587 {
1588 this->signalUndoDocument(doc);
1589 }
1590
1591 void Application::slotRedoDocument(const Document& doc)
1592 {
1593 this->signalRedoDocument(doc);
1594 }
1595
1596 void Application::slotRecomputedObject(const DocumentObject& obj)
1597 {
1598 this->signalObjectRecomputed(obj);
1599 }
1600
1601 void Application::slotRecomputed(const Document& doc)
1602 {
1603 this->signalRecomputed(doc);
1604 }
1605
1606 void Application::slotBeforeRecompute(const Document& doc)
1607 {
1608 this->signalBeforeRecomputeDocument(doc);
1609 }
1610
1611 void Application::slotOpenTransaction(const Document &doc, std::string name)
1612 {
1613 this->signalOpenTransaction(doc, std::move(name));
1614 }
1615
1616 void Application::slotCommitTransaction(const Document& doc)
1617 {
1618 this->signalCommitTransaction(doc);
1619 }
1620
1621 void Application::slotAbortTransaction(const Document& doc)
1622 {
1623 this->signalAbortTransaction(doc);
1624 }
1625
1626 void Application::slotStartSaveDocument(const Document& doc, const std::string& filename)
1627 {
1628 this->signalStartSaveDocument(doc, filename);
1629 }
1630
1631 void Application::slotFinishSaveDocument(const Document& doc, const std::string& filename)
1632 {
1633 DocFileMap.clear();
1634 this->signalFinishSaveDocument(doc, filename);
1635 }
1636
1637 void Application::slotChangePropertyEditor(const Document& doc, const Property& prop)
1638 {
1639 this->signalChangePropertyEditor(doc, prop);
1640 }
1641
1642 //**************************************************************************
1643 // Init, Destruct and singleton
1644
1645 Application * Application::_pcSingleton = nullptr;
1646
1647 int Application::_argc;
1648 char ** Application::_argv;
1649
1650
1651 void Application::cleanupUnits()
1652 {
1653 try {
1654 Base::PyGILStateLocker lock;
1655 Py::Module mod (Py::Module("FreeCAD").getAttr("Units").ptr());
1656
1657 Py::List attr(mod.dir());
1658 for (Py::List::iterator it = attr.begin(); it != attr.end(); ++it) {
1659 mod.delAttr(Py::String(*it));
1660 }
1661 }
1662 catch (Py::Exception& e) {
1663 Base::PyGILStateLocker lock;
1664 e.clear();
1665 }
1666 }
1667
1668 void Application::destruct()
1669 {
1670 // saving system parameter
1671 if (_pcSysParamMngr->IgnoreSave()) {
1672 Base::Console().warning("Discard system parameter\n");
1673 }
1674 else {
1675 Base::Console().log("Saving system parameter...\n");
1676 _pcSysParamMngr->SaveDocument();
1677 Base::Console().log("Saving system parameter...done\n");
1678 }
1679 // saving the User parameter
1680 if (_pcUserParamMngr->IgnoreSave()) {
1681 Base::Console().warning("Discard user parameter\n");
1682 }
1683 else {
1684 Base::Console().log("Saving user parameter...\n");
1685 _pcUserParamMngr->SaveDocument();
1686 Base::Console().log("Saving user parameter...done\n");
1687 }
1688
1689 // now save all other parameter files
1690 auto& paramMgr = _pcSingleton->mpcPramManager;
1691 for (const auto &it : paramMgr) {
1692 if ((it.second != _pcSysParamMngr) && (it.second != _pcUserParamMngr)) {
1693 if (it.second->HasSerializer() && !it.second->IgnoreSave()) {
1694 Base::Console().log("Saving %s...\n", it.first.c_str());
1695 it.second->SaveDocument();
1696 Base::Console().log("Saving %s...done\n", it.first.c_str());
1697 }
1698 }
1699 }
1700
1701 paramMgr.clear();
1702 _pcSysParamMngr = nullptr;
1703 _pcUserParamMngr = nullptr;
1704
1705 #ifdef FC_DEBUG
1706 // Do this only in debug mode for memory leak checkers
1707 cleanupUnits();
1708 #endif
1709
1710 CleanupProcess::callCleanup();
1711
1712 // not initialized or double destruct!
1713 assert(_pcSingleton);
1714 delete _pcSingleton;
1715
1716 // We must detach from console and delete the observer to save our file
1717 destructObserver();
1718
1719 Base::Interpreter().finalize();
1720
1721 Base::ScriptFactorySingleton::Destruct();
1722 Base::InterpreterSingleton::Destruct();
1723 Base::Type::destruct();
1724 ParameterManager::Terminate();
1725 SafeMode::Destruct();
1726 }
1727
1728 void Application::destructObserver()
1729 {
1730 if ( _pConsoleObserverFile ) {
1731 Base::Console().detachObserver(_pConsoleObserverFile);
1732 delete _pConsoleObserverFile;
1733 _pConsoleObserverFile = nullptr;
1734 }
1735 if ( _pConsoleObserverStd ) {
1736 Base::Console().detachObserver(_pConsoleObserverStd);
1737 delete _pConsoleObserverStd;
1738 _pConsoleObserverStd = nullptr;
1739 }
1740 }
1741
1742 /** freecadNewHandler()
1743 * prints an error message and throws an exception
1744 */
1745 #ifdef _MSC_VER // New handler for Microsoft Visual C++ compiler
1746 int __cdecl freecadNewHandler(size_t size )
1747 {
1748 // throw an exception
1749 throw Base::MemoryException();
1750 return 0;
1751 }
1752 #else // Ansi C/C++ new handler
1753 static void freecadNewHandler ()
1754 {
1755 // throw an exception
1756 throw Base::MemoryException();
1757 }
1758 #endif
1759
1760 #if defined(FC_OS_LINUX)
1761 #include <execinfo.h>
1762 #include <dlfcn.h>
1763 #include <cxxabi.h>
1764
1765 #include <cstdio>
1766 #include <cstdlib>
1767 #include <string>
1768 #include <sstream>
1769
1770 #if HAVE_CONFIG_H
1771 #include <config.h>
1772 #endif // HAVE_CONFIG_H
1773
1774 // This function produces a stack backtrace with demangled function & method names.
1775 void printBacktrace(size_t skip=0)
1776 {
1777 #if defined HAVE_BACKTRACE_SYMBOLS
1778 void *callstack[128];
1779 size_t nMaxFrames = sizeof(callstack) / sizeof(callstack[0]);
1780 size_t nFrames = backtrace(callstack, nMaxFrames);
1781 char **symbols = backtrace_symbols(callstack, nFrames);
1782
1783 for (size_t i = skip; i < nFrames; i++) {
1784 char *demangled = nullptr;
1785 int status = -1;
1786 Dl_info info;
1787 if (dladdr(callstack[i], &info) && info.dli_sname && info.dli_fname) {
1788 if (info.dli_sname[0] == '_') {
1789 demangled = abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, &status);
1790 }
1791 }
1792
1793 std::stringstream str;
1794 if (status == 0) {
1795 void* offset = (void*)((char*)callstack[i] - (char*)info.dli_saddr);
1796 str << "#" << (i-skip) << " " << callstack[i] << " in " << demangled << " from " << info.dli_fname << "+" << offset << '\n';
1797 free(demangled);
1798 }
1799 else {
1800 str << "#" << (i-skip) << " " << symbols[i] << '\n';
1801 }
1802
1803 // cannot directly print to cerr when using --write-log
1804 std::cerr << str.str();
1805 }
1806
1807 free(symbols);
1808 #else //HAVE_BACKTRACE_SYMBOLS
1809 (void)skip;
1810 std::cerr << "Cannot print the stacktrace because the C runtime library doesn't provide backtrace or backtrace_symbols\n";
1811 #endif
1812 }
1813 #endif
1814
1815 void segmentation_fault_handler(int sig)
1816 {
1817 #if defined(FC_OS_LINUX)
1818 (void)sig;
1819 std::cerr << "Program received signal SIGSEGV, Segmentation fault.\n";
1820 printBacktrace(2);
1821 #if defined(FC_DEBUG)
1822 abort();
1823 #else
1824 _exit(1);
1825 #endif
1826 #else
1827 switch (sig) {
1828 case SIGSEGV:
1829 std::cerr << "Illegal storage access..." << '\n';
1830 #if !defined(_DEBUG)
1831 throw Base::AccessViolation("Illegal storage access! Please save your work under a new file name and restart the application!");
1832 #endif
1833 break;
1834 case SIGABRT:
1835 std::cerr << "Abnormal program termination..." << '\n';
1836 #if !defined(_DEBUG)
1837 throw Base::AbnormalProgramTermination("Break signal occurred");
1838 #endif
1839 break;
1840 default:
1841 std::cerr << "Unknown error occurred..." << '\n';
1842 break;
1843 }
1844 #endif // FC_OS_LINUX
1845 }
1846
1847 void unhandled_exception_handler()
1848 {
1849 std::cerr << "Terminating..." << '\n';
1850 }
1851
1852 void unexpection_error_handler()
1853 {
1854 std::cerr << "Unexpected error occurred..." << '\n';
1855 // try to throw an exception and give the user chance to save their work
1856 #if !defined(_DEBUG)
1857 throw Base::AbnormalProgramTermination("Unexpected error occurred! Please save your work under a new file name and restart the application!");
1858 #else
1859 terminate();
1860 #endif
1861 }
1862
1863 #if defined(FC_SE_TRANSLATOR) // Microsoft compiler
1864 void my_se_translator_filter(unsigned int code, EXCEPTION_POINTERS* pExp)
1865 {
1866 Q_UNUSED(pExp)
1867 switch (code)
1868 {
1869 case EXCEPTION_ACCESS_VIOLATION:
1870 throw Base::AccessViolation();
1871 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
1872 case EXCEPTION_INT_DIVIDE_BY_ZERO:
1873 Base::Console().error("SEH exception (%u): Division by zero\n", code);
1874 return;
1875 }
1876
1877 std::stringstream str;
1878 str << "SEH exception of type: " << code;
1879 // general C++ SEH exception for things we don't need to handle separately....
1880 throw Base::RuntimeError(str.str());
1881 }
1882 #endif
1883
1884 void Application::init(int argc, char ** argv)
1885 {
1886 try {
1887 // install our own new handler
1888 #ifdef _MSC_VER // Microsoft compiler
1889 _set_new_handler ( freecadNewHandler ); // Setup new handler
1890 _set_new_mode( 1 ); // Re-route malloc failures to new handler !
1891 #else // Ansi compiler
1892 std::set_new_handler (freecadNewHandler); // ANSI new handler
1893 #endif
1894 // if an unexpected crash occurs we can install a handler function to
1895 // write some additional information
1896 #if defined (_MSC_VER) // Microsoft compiler
1897 std::signal(SIGSEGV,segmentation_fault_handler);
1898 std::signal(SIGABRT,segmentation_fault_handler);
1899 std::set_terminate(unhandled_exception_handler);
1900 ::set_unexpected(unexpection_error_handler);
1901 #elif defined(FC_OS_LINUX)
1902 std::signal(SIGSEGV,segmentation_fault_handler);
1903 #endif
1904 #if defined(FC_SE_TRANSLATOR)
1905 _set_se_translator(my_se_translator_filter);
1906 #endif
1907 initTypes();
1908
1909 initConfig(argc,argv);
1910 initApplication();
1911 }
1912 catch (...) {
1913 // force the log to flush
1914 destructObserver();
1915 throw;
1916 }
1917 }
1918
1919 // clang-format off
1920 void Application::initTypes()
1921 {
1922 // Base types
1923 Base::Type ::init();
1924 Base::BaseClass ::init();
1925 Base::Exception ::init();
1926 Base::AbortException ::init();
1927 Base::Persistence ::init();
1928
1929 // Complex data classes
1930 Data::ComplexGeoData ::init();
1931 Data::Segment ::init();
1932
1933 // Properties
1934 // Note: the order matters
1935 App::Property ::init();
1936 App::PropertyContainer ::init();
1937 App::PropertyLists ::init();
1938 App::PropertyBool ::init();
1939 App::PropertyBoolList ::init();
1940 App::PropertyFloat ::init();
1941 App::PropertyFloatList ::init();
1942 App::PropertyFloatConstraint ::init();
1943 App::PropertyPrecision ::init();
1944 App::PropertyQuantity ::init();
1945 App::PropertyQuantityConstraint ::init();
1946 App::PropertyInteger ::init();
1947 App::PropertyIntegerConstraint ::init();
1948 App::PropertyPercent ::init();
1949 App::PropertyEnumeration ::init();
1950 App::PropertyIntegerList ::init();
1951 App::PropertyIntegerSet ::init();
1952 App::PropertyMap ::init();
1953 App::PropertyString ::init();
1954 App::PropertyPersistentObject ::init();
1955 App::PropertyUUID ::init();
1956 App::PropertyFont ::init();
1957 App::PropertyStringList ::init();
1958 App::PropertyLinkBase ::init();
1959 App::PropertyLinkListBase ::init();
1960 App::PropertyLink ::init();
1961 App::PropertyLinkChild ::init();
1962 App::PropertyLinkGlobal ::init();
1963 App::PropertyLinkHidden ::init();
1964 App::PropertyLinkSub ::init();
1965 App::PropertyLinkSubChild ::init();
1966 App::PropertyLinkSubGlobal ::init();
1967 App::PropertyLinkSubHidden ::init();
1968 App::PropertyLinkList ::init();
1969 App::PropertyLinkListChild ::init();
1970 App::PropertyLinkListGlobal ::init();
1971 App::PropertyLinkListHidden ::init();
1972 App::PropertyLinkSubList ::init();
1973 App::PropertyLinkSubListChild ::init();
1974 App::PropertyLinkSubListGlobal ::init();
1975 App::PropertyLinkSubListHidden ::init();
1976 App::PropertyXLink ::init();
1977 App::PropertyXLinkSub ::init();
1978 App::PropertyXLinkSubHidden ::init();
1979 App::PropertyXLinkSubList ::init();
1980 App::PropertyXLinkList ::init();
1981 App::PropertyXLinkContainer ::init();
1982 App::PropertyMatrix ::init();
1983 App::PropertyVector ::init();
1984 App::PropertyVectorDistance ::init();
1985 App::PropertyPosition ::init();
1986 App::PropertyDirection ::init();
1987 App::PropertyVectorList ::init();
1988 App::PropertyPlacement ::init();
1989 App::PropertyPlacementList ::init();
1990 App::PropertyPlacementLink ::init();
1991 App::PropertyRotation ::init();
1992 App::PropertyGeometry ::init();
1993 App::PropertyComplexGeoData ::init();
1994 App::PropertyColor ::init();
1995 App::PropertyColorList ::init();
1996 App::PropertyMaterial ::init();
1997 App::PropertyMaterialList ::init();
1998 App::PropertyPath ::init();
1999 App::PropertyFile ::init();
2000 App::PropertyFileIncluded ::init();
2001 App::PropertyPythonObject ::init();
2002 App::PropertyExpressionContainer::init();
2003 App::PropertyExpressionEngine ::init();
2004 // all know unit properties
2005 App::PropertyAcceleration ::init();
2006 App::PropertyAmountOfSubstance ::init();
2007 App::PropertyAngle ::init();
2008 App::PropertyArea ::init();
2009 App::PropertyCompressiveStrength ::init();
2010 App::PropertyCurrentDensity ::init();
2011 App::PropertyDensity ::init();
2012 App::PropertyDissipationRate ::init();
2013 App::PropertyDistance ::init();
2014 App::PropertyDynamicViscosity ::init();
2015 App::PropertyElectricalCapacitance ::init();
2016 App::PropertyElectricalConductance ::init();
2017 App::PropertyElectricalConductivity ::init();
2018 App::PropertyElectricalInductance ::init();
2019 App::PropertyElectricalResistance ::init();
2020 App::PropertyElectricCharge ::init();
2021 App::PropertySurfaceChargeDensity ::init();
2022 App::PropertyVolumeChargeDensity ::init();
2023 App::PropertyElectricCurrent ::init();
2024 App::PropertyElectricPotential ::init();
2025 App::PropertyElectromagneticPotential ::init();
2026 App::PropertyFrequency ::init();
2027 App::PropertyForce ::init();
2028 App::PropertyHeatFlux ::init();
2029 App::PropertyInverseArea ::init();
2030 App::PropertyInverseLength ::init();
2031 App::PropertyInverseVolume ::init();
2032 App::PropertyKinematicViscosity ::init();
2033 App::PropertyLength ::init();
2034 App::PropertyLuminousIntensity ::init();
2035 App::PropertyMagneticFieldStrength ::init();
2036 App::PropertyMagneticFlux ::init();
2037 App::PropertyMagneticFluxDensity ::init();
2038 App::PropertyMagnetization ::init();
2039 App::PropertyMass ::init();
2040 App::PropertyMoment ::init();
2041 App::PropertyPressure ::init();
2042 App::PropertyPower ::init();
2043 App::PropertyShearModulus ::init();
2044 App::PropertySpecificEnergy ::init();
2045 App::PropertySpecificHeat ::init();
2046 App::PropertySpeed ::init();
2047 App::PropertyStiffness ::init();
2048 App::PropertyStiffnessDensity ::init();
2049 App::PropertyStress ::init();
2050 App::PropertyTemperature ::init();
2051 App::PropertyThermalConductivity ::init();
2052 App::PropertyThermalExpansionCoefficient::init();
2053 App::PropertyThermalTransferCoefficient ::init();
2054 App::PropertyTime ::init();
2055 App::PropertyUltimateTensileStrength ::init();
2056 App::PropertyVacuumPermittivity ::init();
2057 App::PropertyVelocity ::init();
2058 App::PropertyVolume ::init();
2059 App::PropertyVolumeFlowRate ::init();
2060 App::PropertyVolumetricThermalExpansionCoefficient::init();
2061 App::PropertyWork ::init();
2062 App::PropertyYieldStrength ::init();
2063 App::PropertyYoungsModulus ::init();
2064
2065 // Extension classes
2066 App::Extension ::init();
2067 App::ExtensionContainer ::init();
2068 App::DocumentObjectExtension ::init();
2069 App::GroupExtension ::init();
2070 App::GroupExtensionPython ::init();
2071 App::GeoFeatureGroupExtension ::init();
2072 App::GeoFeatureGroupExtensionPython::init();
2073 App::OriginGroupExtension ::init();
2074 App::OriginGroupExtensionPython ::init();
2075 App::LinkBaseExtension ::init();
2076 App::LinkBaseExtensionPython ::init();
2077 App::LinkExtension ::init();
2078 App::LinkExtensionPython ::init();
2079 App::SuppressibleExtension ::init();
2080 App::SuppressibleExtensionPython ::init();
2081
2082 // Document classes
2083 App::TransactionalObject ::init();
2084 App::DocumentObject ::init();
2085 App::GeoFeature ::init();
2086
2087 // Test features
2088 App::FeatureTest ::init();
2089 App::FeatureTestException ::init();
2090 App::FeatureTestColumn ::init();
2091 App::FeatureTestRow ::init();
2092 App::FeatureTestAbsAddress ::init();
2093 App::FeatureTestPlacement ::init();
2094 App::FeatureTestAttribute ::init();
2095
2096 // Feature class
2097 App::FeaturePython ::init();
2098 App::GeometryPython ::init();
2099 App::Document ::init();
2100 App::DocumentObjectGroup ::init();
2101 App::DocumentObjectGroupPython ::init();
2102 App::DocumentObjectFileIncluded::init();
2103 Image::ImagePlane ::init();
2104 App::InventorObject ::init();
2105 App::VRMLObject ::init();
2106 App::Annotation ::init();
2107 App::AnnotationLabel ::init();
2108 App::MaterialObject ::init();
2109 App::MaterialObjectPython ::init();
2110 App::TextDocument ::init();
2111 App::Placement ::init();
2112 App::PlacementPython ::init();
2113 App::DatumElement ::init();
2114 App::Plane ::init();
2115 App::Line ::init();
2116 App::Point ::init();
2117 App::LocalCoordinateSystem ::init();
2118 App::Part ::init();
2119 App::Origin ::init();
2120 App::Link ::init();
2121 App::LinkPython ::init();
2122 App::LinkElement ::init();
2123 App::LinkElementPython ::init();
2124 App::LinkGroup ::init();
2125 App::LinkGroupPython ::init();
2126 App::VarSet ::init();
2127
2128 // Expression classes
2129 App::Expression ::init();
2130 App::UnitExpression ::init();
2131 App::NumberExpression ::init();
2132 App::ConstantExpression ::init();
2133 App::OperatorExpression ::init();
2134 App::VariableExpression ::init();
2135 App::ConditionalExpression ::init();
2136 App::StringExpression ::init();
2137 App::FunctionExpression ::init();
2138 App::RangeExpression ::init();
2139 App::PyObjectExpression ::init();
2140
2141 // Topological naming classes
2142 App::StringHasher ::init();
2143 App::StringID ::init();
2144
2145 // register transaction type
2146 new App::TransactionProducer<TransactionDocumentObject>
2147 (DocumentObject::getClassTypeId());
2148
2149 // register exception producer types
2150 new Base::ExceptionProducer<Base::AbortException>;
2151 new Base::ExceptionProducer<Base::XMLBaseException>;
2152 new Base::ExceptionProducer<Base::XMLParseException>;
2153 new Base::ExceptionProducer<Base::XMLAttributeError>;
2154 new Base::ExceptionProducer<Base::FileException>;
2155 new Base::ExceptionProducer<Base::FileSystemError>;
2156 new Base::ExceptionProducer<Base::BadFormatError>;
2157 new Base::ExceptionProducer<Base::MemoryException>;
2158 new Base::ExceptionProducer<Base::AccessViolation>;
2159 new Base::ExceptionProducer<Base::AbnormalProgramTermination>;
2160 new Base::ExceptionProducer<Base::UnknownProgramOption>;
2161 new Base::ExceptionProducer<Base::ProgramInformation>;
2162 new Base::ExceptionProducer<Base::TypeError>;
2163 new Base::ExceptionProducer<Base::ValueError>;
2164 new Base::ExceptionProducer<Base::IndexError>;
2165 new Base::ExceptionProducer<Base::NameError>;
2166 new Base::ExceptionProducer<Base::ImportError>;
2167 new Base::ExceptionProducer<Base::AttributeError>;
2168 new Base::ExceptionProducer<Base::RuntimeError>;
2169 new Base::ExceptionProducer<Base::BadGraphError>;
2170 new Base::ExceptionProducer<Base::NotImplementedError>;
2171 new Base::ExceptionProducer<Base::ZeroDivisionError>;
2172 new Base::ExceptionProducer<Base::ReferenceError>;
2173 new Base::ExceptionProducer<Base::ExpressionError>;
2174 new Base::ExceptionProducer<Base::ParserError>;
2175 new Base::ExceptionProducer<Base::UnicodeError>;
2176 new Base::ExceptionProducer<Base::OverflowError>;
2177 new Base::ExceptionProducer<Base::UnderflowError>;
2178 new Base::ExceptionProducer<Base::UnitsMismatchError>;
2179 new Base::ExceptionProducer<Base::CADKernelError>;
2180 new Base::ExceptionProducer<Base::RestoreError>;
2181 new Base::ExceptionProducer<Base::PropertyError>;
2182
2183 Base::registerServiceImplementation<CenterOfMassProvider>(new NullCenterOfMass);
2184 }
2185
2186 namespace {
2187
2188 void parseProgramOptions(int ac, char ** av, const std::string& exe, boost::program_options::variables_map& vm)
2189 {
2190 // Declare a group of options that will be
2191 // allowed only on the command line
2192 boost::program_options::options_description generic("Generic options");
2193 generic.add_options()
2194 ("version,v", "Prints version string")
2195 ("verbose", "Prints verbose version string")
2196 ("help,h", "Prints help message")
2197 ("console,c", "Starts in console mode")
2198 ("response-file", boost::program_options::value<std::string>(),"Can be specified with '@name', too")
2199 ("dump-config", "Dumps configuration")
2200 ("get-config", boost::program_options::value<std::string>(), "Prints the value of the requested configuration key")
2201 ("set-config", boost::program_options::value< std::vector<std::string> >()->multitoken(), "Sets the value of a configuration key")
2202 ("keep-deprecated-paths", "If set then config files are kept on the old location")
2203 ;
2204
2205 // Declare a group of options that will be
2206 // allowed both on the command line and in
2207 // the config file
2208 std::stringstream descr;
2209 descr << "Writes " << exe << ".log to the user directory.";
2210 boost::program_options::options_description config("Configuration");
2211 config.add_options()
2212 ("write-log,l", descr.str().c_str())
2213 ("log-file", boost::program_options::value<std::string>(), "Unlike --write-log this allows logging to an arbitrary file")
2214 ("user-cfg,u", boost::program_options::value<std::string>(),"User config file to load/save user settings")
2215 ("system-cfg,s", boost::program_options::value<std::string>(),"System config file to load/save system settings")
2216 ("run-test,t", boost::program_options::value<std::string>()->implicit_value(""),"Run a given test case (use 0 (zero) to run all tests). If no argument is provided then return list of all available tests.")
2217 ("run-open,r", boost::program_options::value<std::string>()->implicit_value(""),"Run a given test case (use 0 (zero) to run all tests). If no argument is provided then return list of all available tests. Keeps UI open after test(s) complete.")
2218 ("module-path,M", boost::program_options::value< std::vector<std::string> >()->composing(),"Additional module paths")
2219 ("macro-path,E", boost::program_options::value< std::vector<std::string> >()->composing(),"Additional macro paths")
2220 ("python-path,P", boost::program_options::value< std::vector<std::string> >()->composing(),"Additional python paths")
2221 ("disable-addon", boost::program_options::value< std::vector<std::string> >()->composing(),"Disable a given addon.")
2222 ("single-instance", "Allow to run a single instance of the application")
2223 ("safe-mode", "Force enable safe mode")
2224 ("pass", boost::program_options::value< std::vector<std::string> >()->multitoken(), "Ignores the following arguments and pass them through to be used by a script")
2225 ;
2226
2227
2228 // Hidden options, will be allowed both on the command line and
2229 // in the config file, but will not be shown to the user.
2230 boost::program_options::options_description hidden("Hidden options");
2231 hidden.add_options()
2232 ("input-file", boost::program_options::value< std::vector<std::string> >(), "input file")
2233 ("output", boost::program_options::value<std::string>(),"output file")
2234 ("hidden", "don't show the main window")
2235 // this are to ignore for the window system (QApplication)
2236 ("style", boost::program_options::value< std::string >(), "set the application GUI style")
2237 ("stylesheet", boost::program_options::value< std::string >(), "set the application stylesheet")
2238 ("session", boost::program_options::value< std::string >(), "restore the application from an earlier session")
2239 ("reverse", "set the application's layout direction from right to left")
2240 ("widgetcount", "print debug messages about widgets")
2241 ("graphicssystem", boost::program_options::value< std::string >(), "backend to be used for on-screen widgets and pixmaps")
2242 ("display", boost::program_options::value< std::string >(), "set the X-Server")
2243 ("geometry ", boost::program_options::value< std::string >(), "set the X-Window geometry")
2244 ("font", boost::program_options::value< std::string >(), "set the X-Window font")
2245 ("fn", boost::program_options::value< std::string >(), "set the X-Window font")
2246 ("background", boost::program_options::value< std::string >(), "set the X-Window background color")
2247 ("bg", boost::program_options::value< std::string >(), "set the X-Window background color")
2248 ("foreground", boost::program_options::value< std::string >(), "set the X-Window foreground color")
2249 ("fg", boost::program_options::value< std::string >(), "set the X-Window foreground color")
2250 ("button", boost::program_options::value< std::string >(), "set the X-Window button color")
2251 ("btn", boost::program_options::value< std::string >(), "set the X-Window button color")
2252 ("name", boost::program_options::value< std::string >(), "set the X-Window name")
2253 ("title", boost::program_options::value< std::string >(), "set the X-Window title")
2254 ("visual", boost::program_options::value< std::string >(), "set the X-Window to color scheme")
2255 ("ncols", boost::program_options::value< int >(), "set the X-Window to color scheme")
2256 ("cmap", "set the X-Window to color scheme")
2257 #if defined(FC_OS_MACOSX)
2258 ("psn", boost::program_options::value< std::string >(), "process serial number")
2259 #endif
2260 ;
2261
2262
2263 //0000723: improper handling of qt specific command line arguments
2264 std::vector<std::string> args;
2265 bool merge=false;
2266 for (int i=1; i<ac; i++) {
2267 if (merge) {
2268 merge = false;
2269 args.back() += "=";
2270 args.back() += av[i];
2271 }
2272 else {
2273 args.emplace_back(av[i]);
2274 }
2275 if (strcmp(av[i],"-style") == 0) {
2276 merge = true;
2277 }
2278 else if (strcmp(av[i],"-stylesheet") == 0) {
2279 merge = true;
2280 }
2281 else if (strcmp(av[i],"-session") == 0) {
2282 merge = true;
2283 }
2284 else if (strcmp(av[i],"-graphicssystem") == 0) {
2285 merge = true;
2286 }
2287 }
2288
2289 // 0000659: SIGABRT on startup in boost::program_options (Boost 1.49)
2290 // Add some text to the constructor
2291 boost::program_options::options_description cmdline_options("Command-line options");
2292 cmdline_options.add(generic).add(config).add(hidden);
2293
2294 boost::program_options::options_description config_file_options("Config");
2295 config_file_options.add(config).add(hidden);
2296
2297 boost::program_options::options_description visible("Allowed options");
2298 visible.add(generic).add(config);
2299
2300 boost::program_options::positional_options_description p;
2301 p.add("input-file", -1);
2302
2303 try {
2304 store( boost::program_options::command_line_parser(args).
2305 options(cmdline_options).positional(p).extra_parser(Util::customSyntax).run(), vm);
2306
2307 std::ifstream ifs("FreeCAD.cfg");
2308 if (ifs)
2309 store(parse_config_file(ifs, config_file_options), vm);
2310 notify(vm);
2311 }
2312 catch (const std::exception& e) {
2313 std::stringstream str;
2314 str << e.what() << '\n' << '\n' << visible << '\n';
2315 throw Base::UnknownProgramOption(str.str());
2316 }
2317 catch (...) {
2318 std::stringstream str;
2319 str << "Wrong or unknown option, bailing out!" << '\n' << '\n' << visible << '\n';
2320 throw Base::UnknownProgramOption(str.str());
2321 }
2322
2323 if (vm.contains("help")) {
2324 std::stringstream str;
2325 str << exe << '\n' << '\n';
2326 str << "For a detailed description see https://www.freecad.org/wiki/Start_up_and_Configuration" << '\n'<<'\n';
2327 str << "Usage: " << exe << " [options] File1 File2 ..." << '\n' << '\n';
2328 str << visible << '\n';
2329 throw Base::ProgramInformation(str.str());
2330 }
2331
2332 if (vm.contains("response-file")) {
2333 // Load the file and tokenize it
2334 std::ifstream ifs(vm["response-file"].as<std::string>().c_str());
2335 if (!ifs) {
2336 Base::Console().error("Could no open the response file\n");
2337 std::stringstream str;
2338 str << "Could no open the response file: '"
2339 << vm["response-file"].as<std::string>() << "'" << '\n';
2340 throw Base::UnknownProgramOption(str.str());
2341 }
2342 // Read the whole file into a string
2343 std::stringstream ss;
2344 ss << ifs.rdbuf();
2345 // Split the file content
2346 boost::char_separator<char> sep(" \n\r");
2347 boost::tokenizer<boost::char_separator<char> > tok(ss.str(), sep);
2348 std::vector<std::string> args2;
2349 copy(tok.begin(), tok.end(), back_inserter(args2));
2350 // Parse the file and store the options
2351 store( boost::program_options::command_line_parser(args2).
2352 options(cmdline_options).positional(p).extra_parser(Util::customSyntax).run(), vm);
2353 }
2354 }
2355
2356 void processProgramOptions(const boost::program_options::variables_map& vm, std::map<std::string,std::string>& mConfig)
2357 {
2358 if (vm.contains("version") && !vm.contains("verbose")) {
2359 std::stringstream str;
2360 str << mConfig["ExeName"] << " " << mConfig["ExeVersion"]
2361 << " Revision: " << mConfig["BuildRevision"] << '\n';
2362 throw Base::ProgramInformation(str.str());
2363 }
2364
2365 if (vm.contains("module-path")) {
2366 auto Mods = vm["module-path"].as< std::vector<std::string> >();
2367 std::string temp;
2368 for (const auto & It : Mods)
2369 temp += It + ";";
2370 temp.erase(temp.end()-1);
2371 mConfig["AdditionalModulePaths"] = temp;
2372 }
2373
2374 if (vm.contains("macro-path")) {
2375 std::vector<std::string> Macros = vm["macro-path"].as< std::vector<std::string> >();
2376 std::string temp;
2377 for (const auto & It : Macros)
2378 temp += It + ";";
2379 temp.erase(temp.end()-1);
2380 mConfig["AdditionalMacroPaths"] = std::move(temp);
2381 }
2382
2383 if (vm.contains("python-path")) {
2384 auto Paths = vm["python-path"].as< std::vector<std::string> >();
2385 for (const auto & It : Paths)
2386 Base::Interpreter().addPythonPath(It.c_str());
2387 }
2388
2389 if (vm.contains("disable-addon")) {
2390 auto Addons = vm["disable-addon"].as< std::vector<std::string> >();
2391 std::string temp;
2392 for (const auto & It : Addons) {
2393 temp += It + ";";
2394 }
2395 temp.erase(temp.end()-1);
2396 mConfig["DisabledAddons"] = temp;
2397 }
2398
2399 if (vm.contains("input-file")) {
2400 auto files(vm["input-file"].as< std::vector<std::string> >());
2401 int OpenFileCount=0;
2402 for (const auto & It : files) {
2403
2404 std::ostringstream temp;
2405 temp << "OpenFile" << OpenFileCount;
2406 mConfig[temp.str()] = It;
2407 OpenFileCount++;
2408 }
2409 std::ostringstream buffer;
2410 buffer << OpenFileCount;
2411 mConfig["OpenFileCount"] = buffer.str();
2412 }
2413
2414 if (vm.contains("output")) {
2415 mConfig["SaveFile"] = vm["output"].as<std::string>();
2416 }
2417
2418 if (vm.contains("hidden")) {
2419 mConfig["StartHidden"] = "1";
2420 }
2421
2422 if (vm.contains("write-log")) {
2423 mConfig["LoggingFile"] = "1";
2424 mConfig["LoggingFileName"] = mConfig["UserAppData"] + mConfig["ExeName"] + ".log";
2425 }
2426
2427 if (vm.contains("log-file")) {
2428 mConfig["LoggingFile"] = "1";
2429 mConfig["LoggingFileName"] = vm["log-file"].as<std::string>();
2430 }
2431
2432 if (vm.contains("user-cfg")) {
2433 mConfig["UserParameter"] = vm["user-cfg"].as<std::string>();
2434 }
2435
2436 if (vm.contains("system-cfg")) {
2437 mConfig["SystemParameter"] = vm["system-cfg"].as<std::string>();
2438 }
2439
2440 if (vm.contains("run-test") || vm.contains("run-open")) {
2441 std::string testCase = vm.contains("run-open") ? vm["run-open"].as<std::string>() : vm["run-test"].as<std::string>();
2442
2443 if ( "0" == testCase) {
2444 testCase = "TestApp.All";
2445 }
2446 else if (testCase.empty()) {
2447 testCase = "TestApp.PrintAll";
2448 }
2449 mConfig["TestCase"] = std::move(testCase);
2450 mConfig["RunMode"] = "Internal";
2451 mConfig["ScriptFileName"] = "FreeCADTest";
2452 mConfig["ExitTests"] = vm.contains("run-open") ? "no" : "yes";
2453 }
2454
2455 if (vm.contains("single-instance")) {
2456 mConfig["SingleInstance"] = "1";
2457 }
2458
2459 if (vm.contains("dump-config")) {
2460 std::stringstream str;
2461 for (const auto & it : mConfig) {
2462 str << it.first << "=" << it.second << '\n';
2463 }
2464 throw Base::ProgramInformation(str.str());
2465 }
2466
2467 if (vm.contains("get-config")) {
2468 auto configKey = vm["get-config"].as<std::string>();
2469 std::stringstream str;
2470 std::map<std::string,std::string>::iterator pos;
2471 pos = mConfig.find(configKey);
2472 if (pos != mConfig.end()) {
2473 str << pos->second;
2474 }
2475 str << '\n';
2476 throw Base::ProgramInformation(str.str());
2477 }
2478
2479 if (vm.contains("set-config")) {
2480 auto configKeyValue = vm["set-config"].as< std::vector<std::string> >();
2481 for (const auto& it : configKeyValue) {
2482 auto pos = it.find('=');
2483 if (pos != std::string::npos) {
2484 std::string key = it.substr(0, pos);
2485 std::string val = it.substr(pos + 1);
2486 mConfig[key] = std::move(val);
2487 }
2488 }
2489 }
2490 }
2491
2492 }
2493 // clang-format on
2494
2495 void Application::initConfig(int argc, char ** argv)
2496 {
2497 // find the home path....
2498 mConfig["AppHomePath"] = Base::FileInfo::pathToString(
2499 ApplicationDirectories::findHomePath(argv[0])
2500 );
2501
2502 // Version of the application extracted from SubWCRef into src/Build/Version.h
2503 // We only set these keys if not yet defined. Therefore it suffices to search
2504 // only for 'BuildVersionMajor'.
2505 if (Application::Config().find("BuildVersionMajor") == Application::Config().end()) {
2506 std::stringstream str;
2507 str << FCVersionMajor
2508 << "." << FCVersionMinor
2509 << "." << FCVersionPoint;
2510 Application::Config()["ExeVersion" ] = str.str();
2511 Application::Config()["BuildVersionMajor" ] = FCVersionMajor;
2512 Application::Config()["BuildVersionMinor" ] = FCVersionMinor;
2513 Application::Config()["BuildVersionPoint" ] = FCVersionPoint;
2514 Application::Config()["BuildVersionSuffix" ] = FCVersionSuffix;
2515 Application::Config()["BuildRevision" ] = FCRevision;
2516 Application::Config()["BuildRepositoryURL" ] = FCRepositoryURL;
2517 Application::Config()["BuildRevisionDate" ] = FCRevisionDate;
2518 #if defined(FCRepositoryHash)
2519 Application::Config()["BuildRevisionHash" ] = FCRepositoryHash;
2520 #endif
2521 #if defined(FCRepositoryBranch)
2522 Application::Config()["BuildRevisionBranch"] = FCRepositoryBranch;
2523 #endif
2524 }
2525
2526 _argc = argc;
2527 _argv = argv;
2528
2529 // Now it's time to read-in the file branding.xml if it exists
2530 Branding brand;
2531 QString binDir = QString::fromUtf8((mConfig["AppHomePath"] + "bin").c_str());
2532 QFileInfo fi(binDir, QStringLiteral("branding.xml"));
2533 if (fi.exists() && brand.readFile(fi.absoluteFilePath())) {
2534 Branding::XmlConfig cfg = brand.getUserDefines();
2535 for (Branding::XmlConfig::iterator it = cfg.begin(); it != cfg.end(); ++it) {
2536 Application::Config()[it.key()] = it.value();
2537 }
2538 }
2539
2540 boost::program_options::variables_map vm;
2541 {
2542 BOOST_SCOPE_EXIT_ALL(&) {
2543 // console-mode needs to be set (if possible) also in case parseProgramOptions
2544 // throws, as it's needed when reporting such exceptions
2545 if (vm.contains("console")) {
2546 mConfig["Console"] = "1";
2547 mConfig["RunMode"] = "Cmd";
2548 }
2549 };
2550 parseProgramOptions(argc, argv, mConfig["ExeName"], vm);
2551 }
2552
2553 if (vm.contains("keep-deprecated-paths")) {
2554 mConfig["KeepDeprecatedPaths"] = "1";
2555 }
2556
2557 if (vm.contains("safe-mode")) {
2558 mConfig["SafeMode"] = "1";
2559 }
2560
2561 // extract home paths
2562 _appDirs = std::make_unique<ApplicationDirectories>(mConfig);
2563
2564 # ifdef FC_DEBUG
2565 mConfig["Debug"] = "1";
2566 # else
2567 mConfig["Debug"] = "0";
2568 # endif
2569
2570 if (!Py_IsInitialized()) {
2571 // init python
2572 PyImport_AppendInittab ("FreeCAD", init_freecad_module);
2573 PyImport_AppendInittab ("__FreeCADBase__", init_freecad_base_module);
2574 }
2575 else {
2576 // "import FreeCAD" in a normal Python 3.12 interpreter would raise
2577 // Fatal Python error: PyImport_AppendInittab:
2578 // PyImport_AppendInittab() may not be called after Py_Initialize()
2579 // because the (external) interpreter is already initialized.
2580 // Therefore we use a workaround as described in https://stackoverflow.com/a/57019607
2581
2582 PyObject* sysModules = PyImport_GetModuleDict();
2583
2584 auto moduleName = "FreeCAD";
2585 PyImport_AddModule(moduleName);
2586 ApplicationMethods = Application::Methods;
2587 PyObject *pyModule = init_freecad_module();
2588 PyDict_SetItemString(sysModules, moduleName, pyModule);
2589 Py_DECREF(pyModule);
2590
2591 moduleName = "__FreeCADBase__";
2592 PyImport_AddModule(moduleName);
2593 pyModule = init_freecad_base_module();
2594 PyDict_SetItemString(sysModules, moduleName, pyModule);
2595 Py_DECREF(pyModule);
2596 }
2597
2598 std::string pythonpath = Base::Interpreter().init(argc,argv);
2599 if (!pythonpath.empty())
2600 mConfig["PythonSearchPath"] = pythonpath;
2601 else
2602 Base::Console().warning("Encoding of Python paths failed\n");
2603
2604 // Handle the options that have impact on the init process
2605 processProgramOptions(vm, mConfig);
2606
2607 // Init console ===========================================================
2608 Base::PyGILStateLocker lock;
2609 _pConsoleObserverStd = new Base::ConsoleObserverStd();
2610 Base::Console().attachObserver(_pConsoleObserverStd);
2611 if (mConfig["LoggingConsole"] != "1") {
2612 _pConsoleObserverStd->bMsg = false;
2613 _pConsoleObserverStd->bLog = false;
2614 _pConsoleObserverStd->bWrn = false;
2615 _pConsoleObserverStd->bErr = false;
2616 }
2617
2618 // file logging Init ===========================================================
2619 if (mConfig["LoggingFile"] == "1") {
2620 _pConsoleObserverFile = new Base::ConsoleObserverFile(mConfig["LoggingFileName"].c_str());
2621 Base::Console().attachObserver(_pConsoleObserverFile);
2622 }
2623 else
2624 _pConsoleObserverFile = nullptr;
2625
2626 // Banner ===========================================================
2627 if (mConfig["RunMode"] != "Cmd" && !(vm.contains("verbose") && vm.contains("version"))) {
2628 // Remove banner if FreeCAD is invoked via the -c command as regular
2629 // Python interpreter
2630 if (mConfig["Verbose"] != "Strict")
2631 Base::Console().message("%s %s, Libs: %s.%s.%s%sR%s\n%s",
2632 mConfig["ExeName"].c_str(),
2633 mConfig["ExeVersion"].c_str(),
2634 mConfig["BuildVersionMajor"].c_str(),
2635 mConfig["BuildVersionMinor"].c_str(),
2636 mConfig["BuildVersionPoint"].c_str(),
2637 mConfig["BuildVersionSuffix"].c_str(),
2638 mConfig["BuildRevision"].c_str(),
2639 mConfig["CopyrightInfo"].c_str());
2640 else
2641 Base::Console().message("%s %s, Libs: %s.%s.%s%sR%s\n",
2642 mConfig["ExeName"].c_str(),
2643 mConfig["ExeVersion"].c_str(),
2644 mConfig["BuildVersionMajor"].c_str(),
2645 mConfig["BuildVersionMinor"].c_str(),
2646 mConfig["BuildVersionPoint"].c_str(),
2647 mConfig["BuildVersionSuffix"].c_str(),
2648 mConfig["BuildRevision"].c_str());
2649
2650 if (SafeMode::SafeModeEnabled()) {
2651 Base::Console().message("FreeCAD is running in _SAFE_MODE_.\n"
2652 "Safe mode temporarily disables your configurations and "
2653 "addons. Restart the application to exit safe mode.\n\n");
2654 }
2655 }
2656 LoadParameters();
2657
2658 auto loglevelParam = _pcUserParamMngr->GetGroup("BaseApp/LogLevels");
2659 const auto &loglevels = loglevelParam->GetIntMap();
2660 bool hasDefault = false;
2661 for (const auto &v : loglevels) {
2662 if (v.first == "Default") {
2663 #ifndef FC_DEBUG
2664 if (v.second>=0) {
2665 hasDefault = true;
2666 Base::Console().setDefaultLogLevel(v.second);
2667 }
2668 #endif
2669 }
2670 else if (v.first == "DebugDefault") {
2671 #ifdef FC_DEBUG
2672 if (v.second>=0) {
2673 hasDefault = true;
2674 Base::Console().setDefaultLogLevel(static_cast<int>(v.second));
2675 }
2676 #endif
2677 }
2678 else {
2679 *Base::Console().getLogLevel(v.first.c_str()) = static_cast<int>(v.second);
2680 }
2681 }
2682
2683 if (!hasDefault) {
2684 #ifdef FC_DEBUG
2685 loglevelParam->SetInt("DebugDefault", Base::Console().logLevel(-1));
2686 #else
2687 loglevelParam->SetInt("Default", Base::Console().logLevel(-1));
2688 #endif
2689 }
2690
2691 // Change application tmp. directory
2692 std::string tmpPath = _pcUserParamMngr->GetGroup("BaseApp/Preferences/General")->GetASCII("TempPath");
2693 Base::FileInfo di(tmpPath);
2694 if (di.exists() && di.isDir()) {
2695 mConfig["AppTempPath"] = tmpPath + PATHSEP;
2696 }
2697
2698
2699 // capture python variables
2700 SaveEnv("PYTHONPATH");
2701 SaveEnv("PYTHONHOME");
2702 SaveEnv("TCL_LIBRARY");
2703 SaveEnv("TCLLIBPATH");
2704
2705 // capture CasCade variables
2706 SaveEnv("CSF_MDTVFontDirectory");
2707 SaveEnv("CSF_MDTVTexturesDirectory");
2708 SaveEnv("CSF_UnitsDefinition");
2709 SaveEnv("CSF_UnitsLexicon");
2710 SaveEnv("CSF_StandardDefaults");
2711 SaveEnv("CSF_PluginDefaults");
2712 SaveEnv("CSF_LANGUAGE");
2713 SaveEnv("CSF_SHMessage");
2714 SaveEnv("CSF_XCAFDefaults");
2715 SaveEnv("CSF_GraphicShr");
2716 SaveEnv("CSF_IGESDefaults");
2717 SaveEnv("CSF_STEPDefaults");
2718
2719 // capture path
2720 SaveEnv("PATH");
2721
2722 // Save version numbers of the libraries
2723 #ifdef OCC_VERSION_STRING_EXT
2724 mConfig["OCC_VERSION"] = OCC_VERSION_STRING_EXT;
2725 #endif
2726 mConfig["BOOST_VERSION"] = BOOST_LIB_VERSION;
2727 mConfig["PYTHON_VERSION"] = PY_VERSION;
2728 mConfig["QT_VERSION"] = QT_VERSION_STR;
2729 mConfig["EIGEN_VERSION"] = fcEigen3Version;
2730 mConfig["PYSIDE_VERSION"] = fcPysideVersion;
2731 #ifdef SMESH_VERSION_STR
2732 mConfig["SMESH_VERSION"] = SMESH_VERSION_STR;
2733 #endif
2734 mConfig["XERCESC_VERSION"] = fcXercescVersion;
2735
2736
2737 logStatus();
2738
2739 if (vm.contains("verbose") && vm.contains("version")) {
2740 Application::_pcSingleton = new Application(mConfig);
2741 throw Base::ProgramInformation(Application::verboseVersionEmitMessage);
2742 }
2743 }
2744
2745 void Application::SaveEnv(const char* s)
2746 {
2747 const char *c = getenv(s);
2748 if (c)
2749 mConfig[s] = c;
2750 }
2751
2752 void Application::initApplication()
2753 {
2754 // interpreter and Init script ==========================================================
2755 // register scripts
2756 new Base::ScriptProducer( "CMakeVariables", CMakeVariables );
2757 new Base::ScriptProducer( "FreeCADInit", FreeCADInit );
2758 new Base::ScriptProducer( "FreeCADTest", FreeCADTest );
2759
2760 // creating the application
2761 if (mConfig["Verbose"] != "Strict")
2762 Base::Console().log("Create Application\n");
2763 Application::_pcSingleton = new Application(mConfig);
2764
2765 // set up Unit system default
2766 const ParameterGrp::handle hGrp = GetApplication().GetParameterGroupByPath
2767 ("User parameter:BaseApp/Preferences/Units");
2768 Base::UnitsApi::setSchema(hGrp->GetInt("UserSchema", Base::UnitsApi::getDefSchemaNum()));
2769 Base::UnitsApi::setDecimals(hGrp->GetInt("Decimals", Base::UnitsApi::getDecimals()));
2770 Base::UnitsApi::setDenominator(hGrp->GetInt("FracInch", Base::UnitsApi::getDenominator()));
2771
2772 #if defined (_DEBUG)
2773 Base::Console().log("Application is built with debug information\n");
2774 #endif
2775
2776 // starting the init script
2777 Base::Console().log("Run App init script\n");
2778 try {
2779 Base::Interpreter().runString(Base::ScriptFactory().ProduceScript("CMakeVariables"));
2780 Base::Interpreter().runString(Base::ScriptFactory().ProduceScript("FreeCADInit"));
2781 }
2782 catch (const Base::Exception& e) {
2783 e.reportException();
2784 }
2785
2786 // seed randomizer
2787 srand(time(nullptr));
2788 }
2789
2790 std::list<std::string> Application::getCmdLineFiles()
2791 {
2792 std::list<std::string> files;
2793
2794 // cycling through all the open files
2795 unsigned short count = 0;
2796 count = atoi(mConfig["OpenFileCount"].c_str());
2797 std::string File;
2798
2799 for (unsigned short i=0; i<count; i++) {
2800 // getting file name
2801 std::ostringstream temp;
2802 temp << "OpenFile" << i;
2803 files.emplace_back(mConfig[temp.str()]);
2804 }
2805
2806 return files;
2807 }
2808
2809 std::list<std::string> Application::processFiles(const std::list<std::string>& files)
2810 {
2811 std::list<std::string> processed;
2812 Base::Console().log("Init: Processing command line files\n");
2813 for (const auto & it : files) {
2814
2815 Base::FileInfo file(it);
2816 // Can we safely remove the isSymlink check and directly query the canonical
2817 // path for every string? The reason for avoiding it currently is that
2818 // getCannonicalPath will log an error if the file doesn't exist
2819 if (file.isSymlink()) {
2820 if (auto cannonicalPath = file.getCannonicalPath()) {
2821 file = Base::FileInfo(*cannonicalPath);
2822 } else {
2823 Base::Console().error("Failed to process symlink file: %s\n", file.filePath());
2824 }
2825 }
2826
2827 Base::Console().log("Init: Processing file: %s\n",file.filePath().c_str());
2828
2829 try {
2830 if (file.hasExtension("fcstd") || file.hasExtension("std")) {
2831 // try to open
2832 Application::_pcSingleton->openDocument(file.filePath().c_str());
2833 processed.push_back(it);
2834 }
2835 else if (file.hasExtension("fcscript") || file.hasExtension("fcmacro")) {
2836 Base::Interpreter().runFile(file.filePath().c_str(), true);
2837 processed.push_back(it);
2838 }
2839 else if (file.hasExtension("py")) {
2840 try {
2841 Base::Interpreter().addPythonPath(file.dirPath().c_str());
2842 Base::Interpreter().loadModule(file.fileNamePure().c_str());
2843 processed.push_back(it);
2844 }
2845 catch (const Base::PyException&) {
2846 // if loading the module does not work, try just running the script (run in __main__)
2847 Base::Interpreter().runFile(file.filePath().c_str(),true);
2848 processed.push_back(it);
2849 }
2850 }
2851 else {
2852 std::vector<std::string> mods = GetApplication().getImportModules(file.extension());
2853 if (!mods.empty()) {
2854 std::string escapedstr = Base::Tools::escapedUnicodeFromUtf8(file.filePath().c_str());
2855 escapedstr = Base::Tools::escapeEncodeFilename(escapedstr);
2856
2857 Base::Interpreter().loadModule(mods.front().c_str());
2858 Base::Interpreter().runStringArg("import %s",mods.front().c_str());
2859 Base::Interpreter().runStringArg("%s.open(u\"%s\")",mods.front().c_str(),
2860 escapedstr.c_str());
2861 processed.push_back(it);
2862 Base::Console().log("Command line open: %s.open(u\"%s\")\n",mods.front().c_str(),escapedstr.c_str());
2863 }
2864 else if (file.exists()) {
2865 Base::Console().warning("File format not supported: %s \n", file.filePath().c_str());
2866 }
2867 }
2868 }
2869 catch (const Base::SystemExitException&) {
2870 throw; // re-throw to main() function
2871 }
2872 catch (const Base::Exception& e) {
2873 Base::Console().error("Exception while processing file: %s [%s]\n", file.filePath().c_str(), e.what());
2874 }
2875 catch (...) {
2876 Base::Console().error("Unknown exception while processing file: %s \n", file.filePath().c_str());
2877 }
2878 }
2879
2880 return processed; // successfully processed files
2881 }
2882
2883 void Application::processCmdLineFiles()
2884 {
2885 // process files passed to command line
2886 const std::list<std::string> files = getCmdLineFiles();
2887 const std::list<std::string> processed = processFiles(files);
2888
2889 if (files.empty()) {
2890 if (mConfig["RunMode"] == "Exit")
2891 mConfig["RunMode"] = "Cmd";
2892 }
2893 else if (processed.empty() && files.size() == 1 && mConfig["RunMode"] == "Cmd") {
2894 // In case we are in console mode and the argument is not a file but Python code
2895 // then execute it. This is to behave like the standard Python executable.
2896 const Base::FileInfo file(files.front());
2897 if (!file.exists()) {
2898 Base::Interpreter().runString(files.front().c_str());
2899 mConfig["RunMode"] = "Exit";
2900 }
2901 }
2902
2903 const std::map<std::string, std::string>& cfg = Application::Config();
2904 const auto it = cfg.find("SaveFile");
2905 if (it != cfg.end()) {
2906 std::string output = it->second;
2907 output = Base::Tools::escapeEncodeFilename(output);
2908
2909 const Base::FileInfo fi(output);
2910 try {
2911 const std::vector<std::string> mods = GetApplication().getExportModules(fi.extension());
2912 if (!mods.empty()) {
2913 Base::Interpreter().loadModule(mods.front().c_str());
2914 Base::Interpreter().runStringArg("import %s",mods.front().c_str());
2915 Base::Interpreter().runStringArg("%s.export(App.ActiveDocument.Objects, '%s')"
2916 ,mods.front().c_str(),output.c_str());
2917 }
2918 else {
2919 Base::Console().warning("File format not supported: %s \n", output.c_str());
2920 }
2921 }
2922 catch (const Base::Exception& e) {
2923 Base::Console().error("Exception while saving to file: %s [%s]\n", output.c_str(), e.what());
2924 }
2925 catch (...) {
2926 Base::Console().error("Unknown exception while saving to file: %s \n", output.c_str());
2927 }
2928 }
2929 }
2930
2931 void Application::runApplication()
2932 {
2933 // process all files given through command line interface
2934 processCmdLineFiles();
2935
2936 if (mConfig["RunMode"] == "Cmd") {
2937 // Run the commandline interface
2938 Base::Interpreter().runCommandLine("FreeCAD Console mode");
2939 }
2940 else if (mConfig["RunMode"] == "Internal") {
2941 // run internal script
2942 Base::Console().log("Running internal script:\n");
2943 Base::Interpreter().runString(Base::ScriptFactory().ProduceScript(mConfig["ScriptFileName"].c_str()));
2944 }
2945 else if (mConfig["RunMode"] == "Exit") {
2946 // getting out
2947 Base::Console().log("Exiting on purpose\n");
2948 }
2949 else {
2950 Base::Console().log("Unknown Run mode (%d) in main()?!?\n\n", mConfig["RunMode"].c_str());
2951 }
2952 }
2953
2954 void Application::logStatus()
2955 {
2956 const std::string time_str = boost::posix_time::to_simple_string(
2957 boost::posix_time::second_clock::local_time());
2958 Base::Console().log("Time = %s\n", time_str.c_str());
2959
2960 for (const auto & It : mConfig) {
2961 Base::Console().log("%s = %s\n", It.first.c_str(), It.second.c_str());
2962 }
2963 }
2964
2965 void Application::LoadParameters()
2966 {
2967 // Init parameter sets ===========================================================
2968 //
2969 if (mConfig.find("UserParameter") == mConfig.end())
2970 mConfig["UserParameter"] = mConfig["UserConfigPath"] + "user.cfg";
2971 if (mConfig.find("SystemParameter") == mConfig.end())
2972 mConfig["SystemParameter"] = mConfig["UserConfigPath"] + "system.cfg";
2973
2974 // create standard parameter sets
2975 _pcSysParamMngr = ParameterManager::Create();
2976 _pcSysParamMngr->SetSerializer(new ParameterSerializer(mConfig["SystemParameter"]));
2977
2978 _pcUserParamMngr = ParameterManager::Create();
2979 _pcUserParamMngr->SetSerializer(new ParameterSerializer(mConfig["UserParameter"]));
2980
2981 try {
2982 if (_pcSysParamMngr->LoadOrCreateDocument() && mConfig["Verbose"] != "Strict") {
2983 // Configuration file optional when using as Python module
2984 if (!Py_IsInitialized()) {
2985 Base::Console().warning(" Parameter does not exist, writing initial one\n");
2986 Base::Console().message(" This warning normally means that FreeCAD is running for the first time\n"
2987 " or the configuration was deleted or moved. FreeCAD is generating the standard\n"
2988 " configuration.\n");
2989 }
2990 }
2991 }
2992 catch (const Base::Exception& e) {
2993 // try to proceed with an empty XML document
2994 Base::Console().error("%s in file %s.\n"
2995 "Continue with an empty configuration.\n",
2996 e.what(), mConfig["SystemParameter"].c_str());
2997 _pcSysParamMngr->CreateDocument();
2998 }
2999
3000 try {
3001 if (_pcUserParamMngr->LoadOrCreateDocument() && mConfig["Verbose"] != "Strict") {
3002 // The user parameter file doesn't exist. When an alternative parameter file is offered
3003 // this will be used.
3004 const auto it = mConfig.find("UserParameterTemplate");
3005 if (it != mConfig.end()) {
3006 QString path = QString::fromUtf8(it->second.c_str());
3007 if (QDir(path).isRelative()) {
3008 const QString home = QString::fromUtf8(mConfig["AppHomePath"].c_str());
3009 path = QFileInfo(QDir(home), path).absoluteFilePath();
3010 }
3011 const QFileInfo fi(path);
3012 if (fi.exists()) {
3013 _pcUserParamMngr->LoadDocument(path.toUtf8().constData());
3014 }
3015 }
3016
3017 // Configuration file optional when using as Python module
3018 if (!Py_IsInitialized()) {
3019 Base::Console().warning(" User settings do not exist, writing initial one\n");
3020 Base::Console().message(" This warning normally means that FreeCAD is running for the first time\n"
3021 " or your configuration was deleted or moved. The system defaults\n"
3022 " will be automatically generated for you.\n");
3023 }
3024 }
3025 }
3026 catch (const Base::Exception& e) {
3027 // try to proceed with an empty XML document
3028 Base::Console().error("%s in file %s.\n"
3029 "Continue with an empty configuration.\n",
3030 e.what(), mConfig["UserParameter"].c_str());
3031 _pcUserParamMngr->CreateDocument();
3032 }
3033 }
3034
3035 #if defined(_MSC_VER) && BOOST_VERSION < 108200
3036 // fix weird error while linking boost (all versions of VC)
3037 // VS2010: https://forum.freecad.org/viewtopic.php?f=4&t=1886&p=12553&hilit=boost%3A%3Afilesystem%3A%3Aget#p12553
3038 namespace boost { namespace program_options { std::string arg="arg"; } }
3039 namespace boost { namespace program_options {
3040 const unsigned options_description::m_default_line_length = 80;
3041 } }
3042 #endif
3043
3044 // A helper function to simplify the main part.
3045 template<class T>
3046 std::ostream& operator<<(std::ostream& os, const std::vector<T>& v)
3047 {
3048 copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
3049 return os;
3050 }
3051
3052 namespace {
3053
3054 /*!
3055 * \brief getUserHome
3056 * Returns the user's home directory.
3057 */
3058 QString getUserHome()
3059 {
3060 QString path;
3061 #if defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_BSD) || defined(FC_OS_MACOSX)
3062 // Default paths for the user specific stuff
3063 struct passwd pwd;
3064 struct passwd *result;
3065 const std::size_t buflen = 16384;
3066 std::vector<char> buffer(buflen);
3067 const int error = getpwuid_r(getuid(), &pwd, buffer.data(), buffer.size(), &result);
3068 Q_UNUSED(error)
3069 if (!result)
3070 throw Base::RuntimeError("Getting HOME path from system failed!");
3071 path = QString::fromUtf8(result->pw_dir);
3072 #else
3073 path = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
3074 #endif
3075
3076 return path;
3077 }
3078
3079 /*!
3080 * \brief getOldGenericDataLocation
3081 * Returns a directory location where persistent data shared across applications can be stored.
3082 * This method returns the old non-XDG-compliant root path where to store config files and application data.
3083 */
3084 #if defined(FC_OS_WIN32)
3085 QString getOldGenericDataLocation(QString home)
3086 {
3087 #if defined(FC_OS_WIN32)
3088 WCHAR szPath[MAX_PATH];
3089 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
3090 if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, szPath))) {
3091 return QString::fromStdString(converter.to_bytes(szPath));
3092 }
3093 #elif defined(FC_OS_MACOSX)
3094 QFileInfo fi(home, QStringLiteral("Library/Preferences"));
3095 home = fi.absoluteFilePath();
3096 #endif
3097
3098 return home;
3099 }
3100 #endif
3101
3102 /*!
3103 * \brief getSubDirectories
3104 * To a given path it adds the sub-directories where to store application specific files.
3105 */
3106 void getSubDirectories(std::map<std::string,std::string>& mConfig, std::vector<std::string>& appData)
3107 {
3108 // If 'AppDataSkipVendor' is defined, the value of 'ExeVendor' must not be part of
3109 // the path.
3110 if (mConfig.find("AppDataSkipVendor") == mConfig.end()) {
3111 appData.push_back(mConfig["ExeVendor"]);
3112 }
3113 appData.push_back(mConfig["ExeName"]);
3114 }
3115
3116 /*!
3117 * \brief getOldDataLocation
3118 * To a given path it adds the sub-directories where to store application specific files.
3119 * On Linux or BSD a hidden directory (i.e. starting with a dot) is added.
3120 */
3121 void getOldDataLocation(std::map<std::string,std::string>& mConfig, std::vector<std::string>& appData)
3122 {
3123 // Actually the name of the directory where the parameters are stored should be the name of
3124 // the application due to branding reasons.
3125 #if defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_BSD)
3126 // If 'AppDataSkipVendor' is defined, the value of 'ExeVendor' must not be part of
3127 // the path.
3128 if (mConfig.find("AppDataSkipVendor") == mConfig.end()) {
3129 appData.push_back(std::string(".") + mConfig["ExeVendor"]);
3130 appData.push_back(mConfig["ExeName"]);
3131 } else {
3132 appData.push_back(std::string(".") + mConfig["ExeName"]);
3133 }
3134
3135 #elif defined(FC_OS_MACOSX) || defined(FC_OS_WIN32)
3136 getSubDirectories(mConfig, appData);
3137 #endif
3138 }
3139
3140 /*!
3141 * \brief findUserHomePath
3142 * If the passed path name is not empty it will be returned, otherwise
3143 * the user home path of the system will be returned.
3144 */
3145 QString findUserHomePath(const QString& userHome)
3146 {
3147 return userHome.isEmpty() ? getUserHome() : userHome;
3148 }
3149
3150 /*!
3151 * \brief findPath
3152 * Returns the path where to store application files to.
3153 * If \a customHome is not empty it will be used, otherwise a path starting from \a stdHome will be used.
3154 */
3155 std::filesystem::path findPath(const QString& stdHome, const QString& customHome,
3156 const std::vector<std::string>& paths, bool create)
3157 {
3158 QString dataPath = customHome;
3159 if (dataPath.isEmpty()) {
3160 dataPath = stdHome;
3161 }
3162
3163 std::filesystem::path appData(Base::FileInfo::stringToPath(dataPath.toStdString()));
3164
3165 // If a custom user home path is given then don't modify it
3166 if (customHome.isEmpty()) {
3167 for (const auto& it : paths)
3168 appData = appData / it;
3169 }
3170
3171 // In order to write to our data path, we must create some directories, first.
3172 if (create && !std::filesystem::exists(appData) && !Py_IsInitialized()) {
3173 try {
3174 std::filesystem::create_directories(appData);
3175 } catch (const std::filesystem::filesystem_error& e) {
3176 throw Base::FileSystemError("Could not create directories. Failed with: " + e.code().message());
3177 }
3178 }
3179
3180 return appData;
3181 }
3182
3183 /*!
3184 * \brief getCustomPaths
3185 * Returns a tuple of path names where to store config, data and temp. files.
3186 * The method therefore reads the environment variables:
3187 * \list
3188 * \li FREECAD_USER_HOME
3189 * \li FREECAD_USER_DATA
3190 * \li FREECAD_USER_TEMP
3191 * \endlist
3192 */
3193 std::tuple<QString, QString, QString> getCustomPaths()
3194 {
3195 const QProcessEnvironment env(QProcessEnvironment::systemEnvironment());
3196 QString userHome = env.value(QStringLiteral("FREECAD_USER_HOME"));
3197 QString userData = env.value(QStringLiteral("FREECAD_USER_DATA"));
3198 QString userTemp = env.value(QStringLiteral("FREECAD_USER_TEMP"));
3199
3200 auto toNativePath = [](QString& path) {
3201 if (!path.isEmpty()) {
3202 const QDir dir(path);
3203 if (dir.exists())
3204 path = QDir::toNativeSeparators(dir.canonicalPath());
3205 else
3206 path.clear();
3207 }
3208 };
3209
3210 // verify env. variables
3211 toNativePath(userHome);
3212 toNativePath(userData);
3213 toNativePath(userTemp);
3214
3215 // if FREECAD_USER_HOME is set but not FREECAD_USER_DATA
3216 if (!userHome.isEmpty() && userData.isEmpty()) {
3217 userData = userHome;
3218 }
3219
3220 // if FREECAD_USER_HOME is set but not FREECAD_USER_TEMP
3221 if (!userHome.isEmpty() && userTemp.isEmpty()) {
3222 const QDir dir(userHome);
3223 dir.mkdir(QStringLiteral("temp"));
3224 const QFileInfo fi(dir, QStringLiteral("temp"));
3225 userTemp = fi.absoluteFilePath();
3226 }
3227
3228 return {userHome, userData, userTemp};
3229 }
3230
3231 /*!
3232 * \brief getStandardPaths
3233 * Returns a tuple of XDG-compliant standard paths names where to store config, data and cached files.
3234 * The method therefore reads the environment variables:
3235 * \list
3236 * \li XDG_CONFIG_HOME
3237 * \li XDG_DATA_HOME
3238 * \li XDG_CACHE_HOME
3239 * \endlist
3240 */
3241 std::tuple<QString, QString, QString, QString> getStandardPaths()
3242 {
3243 QString configHome = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation);
3244 QString dataHome = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
3245 QString cacheHome = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation);
3246 QString tempPath = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
3247
3248 // Keep the old behaviour
3249 #if defined(FC_OS_WIN32)
3250 configHome = getOldGenericDataLocation(QString());
3251 dataHome = configHome;
3252
3253 // On systems with non-7-bit-ASCII application data directories
3254 // GetTempPathW will return a path in DOS format. This path will be
3255 // accepted by boost's file_lock class.
3256 // Since boost 1.76 there is now a version that accepts a wide string.
3257 #if (BOOST_VERSION < 107600)
3258 tempPath = QString::fromStdString(Base::FileInfo::getTempPath());
3259 cacheHome = tempPath;
3260 #endif
3261 #endif
3262
3263 return std::make_tuple(configHome, dataHome, cacheHome, tempPath);
3264 }
3265 }
3266
3267 void Application::ExtractUserPath()
3268 {
3269 bool keepDeprecatedPaths = mConfig.contains("KeepDeprecatedPaths");
3270
3271 // std paths
3272 mConfig["BinPath"] = mConfig["AppHomePath"] + "bin" + PATHSEP;
3273 mConfig["DocPath"] = mConfig["AppHomePath"] + "doc" + PATHSEP;
3274
3275 // this is to support a portable version of FreeCAD
3276 auto paths = getCustomPaths();
3277 QString customHome = std::get<0>(paths);
3278 QString customData = std::get<1>(paths);
3279 QString customTemp = std::get<2>(paths);
3280
3281 // get the system standard paths
3282 auto stdPaths = getStandardPaths();
3283 QString configHome = std::get<0>(stdPaths);
3284 QString dataHome = std::get<1>(stdPaths);
3285 QString cacheHome = std::get<2>(stdPaths);
3286 QString tempPath = std::get<3>(stdPaths);
3287
3288 // User home path
3289 //
3290 QString homePath = findUserHomePath(customHome);
3291 mConfig["UserHomePath"] = homePath.toUtf8().data();
3292
3293 // the old path name to save config and data files
3294 std::vector<std::string> subdirs;
3295 if (keepDeprecatedPaths) {
3296 configHome = homePath;
3297 dataHome = homePath;
3298 cacheHome = homePath;
3299 getOldDataLocation(mConfig, subdirs);
3300 }
3301 else {
3302 getSubDirectories(mConfig, subdirs);
3303 }
3304
3305 // User data path
3306 //
3307 std::filesystem::path data = findPath(dataHome, customData, subdirs, true);
3308 mConfig["UserAppData"] = Base::FileInfo::pathToString(data) + PATHSEP;
3309
3310
3311 // User config path
3312 //
3313 std::filesystem::path config = findPath(configHome, customHome, subdirs, true);
3314 mConfig["UserConfigPath"] = Base::FileInfo::pathToString(config) + PATHSEP;
3315
3316
3317 // User cache path
3318 //
3319 std::vector<std::string> cachedirs = subdirs;
3320 cachedirs.emplace_back("Cache");
3321 std::filesystem::path cache = findPath(cacheHome, customTemp, cachedirs, true);
3322 mConfig["UserCachePath"] = Base::FileInfo::pathToString(cache) + PATHSEP;
3323
3324
3325 // Set application tmp. directory
3326 //
3327 std::vector<std::string> empty;
3328 std::filesystem::path tmp = findPath(tempPath, customTemp, empty, true);
3329 mConfig["AppTempPath"] = Base::FileInfo::pathToString(tmp) + PATHSEP;
3330
3331
3332 // Set the default macro directory
3333 //
3334 std::vector<std::string> macrodirs = std::move(subdirs); // Last use in this method, just move
3335 macrodirs.emplace_back("Macro");
3336 std::filesystem::path macro = findPath(dataHome, customData, macrodirs, true);
3337 mConfig["UserMacroPath"] = Base::FileInfo::pathToString(macro) + PATHSEP;
3338 }
3339
3340 // TODO: Consider using this for all UNIX-like OSes
3341 #if defined(__OpenBSD__)
3342 #include <cstdio>
3343 #include <cstdlib>
3344 #include <sys/param.h>
3345 #include <QCoreApplication>
3346
3347 std::string Application::FindHomePath(const char* sCall)
3348 {
3349 // We have three ways to start this application either use one of the two executables or
3350 // import the FreeCAD.so module from a running Python session. In the latter case the
3351 // Python interpreter is already initialized.
3352 std::string absPath;
3353 std::string homePath;
3354 if (Py_IsInitialized()) {
3355 // Note: realpath is known to cause a buffer overflow because it
3356 // expands the given path to an absolute path of unknown length.
3357 // Even setting PATH_MAX does not necessarily solve the problem
3358 // for sure but the risk of overflow is rather small.
3359 char resolved[PATH_MAX];
3360 char* path = realpath(sCall, resolved);
3361 if (path)
3362 absPath = path;
3363 }
3364 else {
3365 int argc = 1;
3366 QCoreApplication app(argc, (char**)(&sCall));
3367 absPath = QCoreApplication::applicationFilePath().toStdString();
3368 }
3369
3370 // should be an absolute path now
3371 std::string::size_type pos = absPath.find_last_of("/");
3372 homePath.assign(absPath,0,pos);
3373 pos = homePath.find_last_of("/");
3374 homePath.assign(homePath,0,pos+1);
3375
3376 return homePath;
3377 }
3378
3379 #elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_BSD)
3380 #include <cstdio>
3381 #include <cstdlib>
3382 #include <sys/param.h>
3383
3384 std::string Application::FindHomePath(const char* sCall)
3385 {
3386 // We have three ways to start this application either use one of the two executables or
3387 // import the FreeCAD.so module from a running Python session. In the latter case the
3388 // Python interpreter is already initialized.
3389 std::string absPath;
3390 std::string homePath;
3391 if (Py_IsInitialized()) {
3392 // Note: realpath is known to cause a buffer overflow because it
3393 // expands the given path to an absolute path of unknown length.
3394 // Even setting PATH_MAX does not necessarily solve the problem
3395 // for sure but the risk of overflow is rather small.
3396 char resolved[PATH_MAX];
3397 char* path = realpath(sCall, resolved);
3398 if (path)
3399 absPath = path;
3400 }
3401 else {
3402 // Find the path of the executable. Theoretically, there could occur a
3403 // race condition when using readlink, but we only use this method to
3404 // get the absolute path of the executable to compute the actual home
3405 // path. In the worst case we simply get q wrong path and FreeCAD is not
3406 // able to load its modules.
3407 char resolved[PATH_MAX];
3408 #if defined(FC_OS_BSD)
3409 int mib[4];
3410 mib[0] = CTL_KERN;
3411 mib[1] = KERN_PROC;
3412 mib[2] = KERN_PROC_PATHNAME;
3413 mib[3] = -1;
3414 size_t cb = sizeof(resolved);
3415 sysctl(mib, 4, resolved, &cb, NULL, 0);
3416 int nchars = strlen(resolved);
3417 #else
3418 int nchars = readlink("/proc/self/exe", resolved, PATH_MAX);
3419 #endif
3420 if (nchars < 0 || nchars >= PATH_MAX)
3421 throw Base::FileSystemError("Cannot determine the absolute path of the executable");
3422 resolved[nchars] = '\0'; // enforce null termination
3423 absPath = resolved;
3424 }
3425
3426 // should be an absolute path now
3427 std::string::size_type pos = absPath.find_last_of("/");
3428 homePath.assign(absPath,0,pos);
3429 pos = homePath.find_last_of("/");
3430 homePath.assign(homePath,0,pos+1);
3431
3432 return homePath;
3433 }
3434
3435 #elif defined(FC_OS_MACOSX)
3436 #include <mach-o/dyld.h>
3437 #include <string>
3438 #include <cstdlib>
3439 #include <sys/param.h>
3440
3441 std::string Application::FindHomePath(const char* sCall)
3442 {
3443 // If Python is initialized at this point, then we're being run from
3444 // MainPy.cpp, which hopefully rewrote argv[0] to point at the
3445 // FreeCAD shared library.
3446 if (!Py_IsInitialized()) {
3447 uint32_t sz = 0;
3448
3449 // function only returns "sz" if first arg is to small to hold value
3450 _NSGetExecutablePath(nullptr, &sz);
3451
3452 if (const auto buf = new char[++sz]; _NSGetExecutablePath(buf, &sz) == 0) {
3453 char resolved[PATH_MAX];
3454 const char* path = realpath(buf, resolved);
3455 delete [] buf;
3456
3457 if (path) {
3458 const std::string Call(resolved);
3459 std::string TempHomePath;
3460 std::string::size_type pos = Call.find_last_of(PATHSEP);
3461 TempHomePath.assign(Call,0,pos);
3462 pos = TempHomePath.find_last_of(PATHSEP);
3463 TempHomePath.assign(TempHomePath,0,pos+1);
3464 return TempHomePath;
3465 }
3466 } else {
3467 delete [] buf;
3468 }
3469 }
3470
3471 return sCall;
3472 }
3473
3474 #elif defined (FC_OS_WIN32)
3475 std::string Application::FindHomePath(const char* sCall)
3476 {
3477 // We have several ways to start this application:
3478 // * use one of the two executables
3479 // * import the FreeCAD.pyd module from a running Python session. In this case the
3480 // Python interpreter is already initialized.
3481 // * use a custom dll that links FreeCAD core dlls and that is loaded by its host application
3482 // In this case the calling name should be set to FreeCADBase.dll or FreeCADApp.dll in order
3483 // to locate the correct home directory
3484 wchar_t szFileName [MAX_PATH];
3485 QString dll(QString::fromUtf8(sCall));
3486 if (Py_IsInitialized() || dll.endsWith(QLatin1String(".dll"))) {
3487 GetModuleFileNameW(GetModuleHandleA(sCall),szFileName, MAX_PATH-1);
3488 }
3489 else {
3490 GetModuleFileNameW(0, szFileName, MAX_PATH-1);
3491 }
3492
3493 std::wstring Call(szFileName), homePath;
3494 std::wstring::size_type pos = Call.find_last_of(PATHSEP);
3495 homePath.assign(Call,0,pos);
3496 pos = homePath.find_last_of(PATHSEP);
3497 homePath.assign(homePath,0,pos+1);
3498
3499 // fixes #0001638 to avoid to load DLLs from Windows' system directories before FreeCAD's bin folder
3500 std::wstring binPath = homePath;
3501 binPath += L"bin";
3502 SetDllDirectoryW(binPath.c_str());
3503
3504 // https://stackoverflow.com/questions/5625884/conversion-of-stdwstring-to-qstring-throws-linker-error
3505 #ifdef _MSC_VER
3506 QString str = QString::fromUtf16(reinterpret_cast<const ushort *>(homePath.c_str()));
3507 #else
3508 QString str = QString::fromStdWString(homePath);
3509 #endif
3510 // convert to utf-8
3511 return str.toUtf8().data();
3512 }
3513
3514 #else
3515 # error "std::string Application::FindHomePath(const char*) not implemented"
3516 #endif
3517
3518 QString Application::prettyProductInfoWrapper()
3519 {
3520 auto productName = QSysInfo::prettyProductName();
3521 #ifdef FC_OS_MACOSX
3522 auto macosVersionFile =
3523 QStringLiteral("/System/Library/CoreServices/.SystemVersionPlatform.plist");
3524 auto fi = QFileInfo(macosVersionFile);
3525 if (fi.exists() && fi.isReadable()) {
3526 auto plistFile = QFile(macosVersionFile);
3527 plistFile.open(QIODevice::ReadOnly);
3528 while (!plistFile.atEnd()) {
3529 auto line = plistFile.readLine();
3530 if (line.contains("ProductUserVisibleVersion")) {
3531 auto nextLine = plistFile.readLine();
3532 if (nextLine.contains("<string>")) {
3533 QRegularExpression re(QStringLiteral("\\s*<string>(.*)</string>"));
3534 auto matches = re.match(QString::fromUtf8(nextLine));
3535 if (matches.hasMatch()) {
3536 productName = QStringLiteral("macOS ") + matches.captured(1);
3537 break;
3538 }
3539 }
3540 }
3541 }
3542 }
3543 #endif
3544 #ifdef FC_OS_WIN64
3545 QSettings regKey {
3546 QStringLiteral("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"),
3547 QSettings::NativeFormat};
3548 if (regKey.contains(QStringLiteral("CurrentBuildNumber"))) {
3549 auto buildNumber = regKey.value(QStringLiteral("CurrentBuildNumber")).toInt();
3550 if (buildNumber > 0) {
3551 if (buildNumber < 9200) {
3552 productName = QStringLiteral("Windows 7 build %1").arg(buildNumber);
3553 }
3554 else if (buildNumber < 10240) {
3555 productName = QStringLiteral("Windows 8 build %1").arg(buildNumber);
3556 }
3557 else if (buildNumber < 22000) {
3558 productName = QStringLiteral("Windows 10 build %1").arg(buildNumber);
3559 }
3560 else {
3561 productName = QStringLiteral("Windows 11 build %1").arg(buildNumber);
3562 }
3563 }
3564 }
3565 #endif
3566 return productName;
3567 }
3568
3569 void Application::addModuleInfo(QTextStream& str, const QString& modPath, bool& firstMod)
3570 {
3571 QFileInfo mod(modPath);
3572 if (mod.isHidden()) { // Ignore hidden directories
3573 return;
3574 }
3575 if (firstMod) {
3576 firstMod = false;
3577 str << "Installed mods: \n";
3578 }
3579 QString addonName = mod.isDir() ? QDir(modPath).dirName() : mod.fileName();
3580 QString versionString;
3581 try {
3582 auto metadataFile =
3583 std::filesystem::path(mod.absoluteFilePath().toStdString()) / "package.xml";
3584 if (std::filesystem::exists(metadataFile)) {
3585 App::Metadata metadata(metadataFile);
3586 if (!metadata.name().empty()) {
3587 addonName = QString::fromStdString(metadata.name());
3588 }
3589 if (metadata.version() != App::Meta::Version()) {
3590 versionString = QString::fromStdString(" " + metadata.version().str());
3591 }
3592 }
3593 }
3594 catch (const Base::Exception& e) {
3595 auto what = QString::fromUtf8(e.what()).trimmed().replace(QChar::fromLatin1('\n'),
3596 QChar::fromLatin1(' '));
3597 str << " (Malformed metadata: " << what << ")";
3598 }
3599 str << " * " << addonName << versionString;
3600 QFileInfo disablingFile(mod.absoluteFilePath(), QStringLiteral("ADDON_DISABLED"));
3601 if (disablingFile.exists()) {
3602 str << " (Disabled)";
3603 }
3604
3605 str << "\n";
3606 }
3607
3608 QString Application::getValueOrEmpty(const std::map<std::string, std::string>& map, const std::string& key) {
3609 auto it = map.find(key);
3610 return (it != map.end()) ? QString::fromStdString(it->second) : QString();
3611 }
3612
3613 void Application::getVerboseCommonInfo(QTextStream& str, const std::map<std::string,std::string>& mConfig)
3614 {
3615 std::map<std::string, std::string>::iterator it;
3616 const QString deskEnv =
3617 QProcessEnvironment::systemEnvironment().value(QStringLiteral("XDG_CURRENT_DESKTOP"),
3618 QString());
3619 const QString deskSess =
3620 QProcessEnvironment::systemEnvironment().value(QStringLiteral("DESKTOP_SESSION"),
3621 QString());
3622
3623 const QString major = getValueOrEmpty(mConfig, "BuildVersionMajor");
3624 const QString minor = getValueOrEmpty(mConfig, "BuildVersionMinor");
3625 const QString point = getValueOrEmpty(mConfig, "BuildVersionPoint");
3626 const QString suffix = getValueOrEmpty(mConfig, "BuildVersionSuffix");
3627 const QString build = getValueOrEmpty(mConfig, "BuildRevision");
3628 const QString buildDate = getValueOrEmpty(mConfig, "BuildRevisionDate");
3629
3630 QStringList deskInfoList;
3631 QString deskInfo;
3632
3633 if (!deskEnv.isEmpty()) {
3634 deskInfoList.append(deskEnv);
3635 }
3636 if (!deskSess.isEmpty()) {
3637 deskInfoList.append(deskSess);
3638 }
3639
3640 const QString sysType = QSysInfo::productType();
3641 if (sysType != QLatin1String("windows") && sysType != QLatin1String("macos")) {
3642 QString sessionType = QProcessEnvironment::systemEnvironment().value(QStringLiteral("XDG_SESSION_TYPE"),
3643 QString());
3644 if (sessionType == QLatin1String("x11")) {
3645 sessionType = QStringLiteral("xcb");
3646 }
3647 deskInfoList.append(sessionType);
3648 }
3649 if (!deskInfoList.isEmpty()) {
3650 deskInfo = QLatin1String(" (") + deskInfoList.join(QLatin1String("/")) + QLatin1String(")");
3651 }
3652
3653 str << "OS: " << prettyProductInfoWrapper() << deskInfo << '\n';
3654 if (QSysInfo::buildCpuArchitecture() == QSysInfo::currentCpuArchitecture()) {
3655 str << "Architecture: " << QSysInfo::buildCpuArchitecture() << "\n";
3656 }
3657 else {
3658 str << "Architecture: " << QSysInfo::buildCpuArchitecture()
3659 << "(running on: " << QSysInfo::currentCpuArchitecture() << ")\n";
3660 }
3661 str << "Version: " << major << "." << minor << "." << point << suffix << "." << build;
3662
3663 #ifdef FC_CONDA
3664 str << " Conda";
3665 #endif
3666 #ifdef FC_FLATPAK
3667 str << " Flatpak";
3668 #endif
3669 const char* appimage = getenv("APPIMAGE");
3670 if (appimage) {
3671 str << " AppImage";
3672 }
3673 const char* snap = getenv("SNAP_REVISION");
3674 if (snap) {
3675 str << " Snap " << snap;
3676 }
3677 str << '\n';
3678 str << "Build date: " << buildDate << "\n";
3679
3680 #if defined(_DEBUG) || defined(DEBUG)
3681 str << "Build type: Debug\n";
3682 #elif defined(NDEBUG)
3683 str << "Build type: Release\n";
3684 #elif defined(CMAKE_BUILD_TYPE)
3685 str << "Build type: " << CMAKE_BUILD_TYPE << '\n';
3686 #else
3687 str << "Build type: Unknown\n";
3688 #endif
3689 const QString buildRevisionBranch = getValueOrEmpty(mConfig, "BuildRevisionBranch");
3690 if (!buildRevisionBranch.isEmpty()) {
3691 str << "Branch: " << buildRevisionBranch << '\n';
3692 }
3693 const QString buildRevisionHash = getValueOrEmpty(mConfig, "BuildRevisionHash");
3694 if (!buildRevisionHash.isEmpty()) {
3695 str << "Hash: " << buildRevisionHash << '\n';
3696 }
3697 // report also the version numbers of the most important libraries in FreeCAD
3698 str << "Python " << PY_VERSION << ", ";
3699 str << "Qt " << QT_VERSION_STR << ", ";
3700 str << "Coin " << fcCoin3dVersion << ", ";
3701 str << "Vtk " << fcVtkVersion << ", ";
3702 str << "boost " << BOOST_LIB_VERSION << ", ";
3703 str << "Eigen3 " << fcEigen3Version << ", ";
3704 str << "PySide " << fcPysideVersion << '\n';
3705 str << "shiboken " << fcShibokenVersion << ", ";
3706 #ifdef SMESH_VERSION_STR
3707 str << "SMESH " << SMESH_VERSION_STR << ", ";
3708 #endif
3709 str << "xerces-c " << fcXercescVersion << ", ";
3710
3711 try {
3712 Base::PyGILStateLocker lock;
3713 Py::Module module(PyImport_ImportModule("ifcopenshell"), true);
3714 if (!module.isNull() && module.hasAttr("version")) {
3715 Py::String version(module.getAttr("version"));
3716 auto ver_str = static_cast<std::string>(version);
3717 str << "IfcOpenShell " << ver_str.c_str() << ", ";
3718 }
3719 else {
3720 Base::Console().log("Module 'ifcopenshell' not found (safe to ignore, unless using "
3721 "the BIM workbench and IFC).\n");
3722 }
3723 }
3724 catch (const Py::Exception&) {
3725 Base::PyGILStateLocker lock;
3726 Base::PyException e;
3727 Base::Console().log("%s\n", e.what());
3728 }
3729
3730 #if defined(HAVE_OCC_VERSION)
3731 str << "OCC " << OCC_VERSION_MAJOR << "." << OCC_VERSION_MINOR << "." << OCC_VERSION_MAINTENANCE
3732 #ifdef OCC_VERSION_DEVELOPMENT
3733 << "." OCC_VERSION_DEVELOPMENT
3734 #endif
3735 << '\n';
3736 #endif
3737 QLocale loc;
3738 str << "Locale: " << QLocale::languageToString(loc.language()) << "/"
3739 #if QT_VERSION < QT_VERSION_CHECK(6, 6, 0)
3740 << QLocale::countryToString(loc.country())
3741 #else
3742 << QLocale::territoryToString(loc.territory())
3743 #endif
3744 << " (" << loc.name() << ")";
3745 if (loc != QLocale::system()) {
3746 loc = QLocale::system();
3747 str << " [ OS: " << QLocale::languageToString(loc.language()) << "/"
3748 #if QT_VERSION < QT_VERSION_CHECK(6, 6, 0)
3749 << QLocale::countryToString(loc.country())
3750 #else
3751 << QLocale::territoryToString(loc.territory())
3752 #endif
3753 << " (" << loc.name() << ") ]";
3754 }
3755 str << "\n";
3756
3757 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View");
3758
3759 QString navStyle = QString::fromStdString(hGrp->GetASCII("NavigationStyle", "Gui::CADNavigationStyle"));
3760 // All navigation styles are named on the format "Gui::<Name>NavigationStyle"
3761 // so we remove the "Gui::" prefix and the "NavigationStyle" suffix before printing.
3762 navStyle.replace(QRegularExpression(QLatin1String("^Gui::")), {});
3763 navStyle.replace(QRegularExpression(QLatin1String("NavigationStyle$")), {});
3764
3765 const QString orbitStyle = QStringLiteral("Turntable,Trackball,Free Turntable,Trackball Classic,Rounded Arcball")
3766 .split(QLatin1Char(','))
3767 .at(hGrp->GetInt("OrbitStyle", 4));
3768 const QString rotMode = QStringLiteral("Window center,Drag at cursor,Object center")
3769 .split(QLatin1Char(','))
3770 .at(hGrp->GetInt("RotationMode", 0));
3771
3772 str << QStringLiteral("Navigation Style/Orbit Style/Rotation Mode: %1/%2/%3\n").arg(navStyle, orbitStyle, rotMode);
3773 }
3774
3775 void Application::getVerboseAddOnsInfo(QTextStream& str, const std::map<std::string,std::string>& mConfig) {
3776 // Add installed module information:
3777 const auto modDir = fs::path(Application::getUserAppDataDir()) / "Mod";
3778 bool firstMod = true;
3779 if (fs::exists(modDir) && fs::is_directory(modDir)) {
3780 for (const auto& mod : fs::directory_iterator(modDir)) {
3781 if (!fs::is_directory(mod)) {
3782 continue; // Ignore files, only show directories
3783 }
3784 auto dirName = mod.path().string();
3785 addModuleInfo(str, QString::fromStdString(dirName), firstMod);
3786 }
3787 }
3788 const QString additionalModules = getValueOrEmpty(mConfig, "AdditionalModulePaths");
3789
3790 if (!additionalModules.isEmpty()) {
3791 auto mods = additionalModules.split(QChar::fromLatin1(';'));
3792 for (const auto& mod : mods) {
3793 addModuleInfo(str, mod, firstMod);
3794 }
3795 }
3796 }