Debian Codegraph @

src/Gui/StartupProcess.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /***************************************************************************
4 * Copyright (c) 2024 Werner Mayer <wmayer[at]users.sourceforge.net> *
5 * *
6 * This file is part of FreeCAD. *
7 * *
8 * FreeCAD is free software: you can redistribute it and/or modify it *
9 * under the terms of the GNU Lesser General Public License as *
10 * published by the Free Software Foundation, either version 2.1 of the *
11 * License, or (at your option) any later version. *
12 * *
13 * FreeCAD is distributed in the hope that it will be useful, but *
14 * WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
16 * Lesser General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Lesser General Public *
19 * License along with FreeCAD. If not, see *
20 * <https://www.gnu.org/licenses/>. *
21 * *
22 **************************************************************************/
23
24 #include <FCConfig.h>
25 #include <ParamHandler.h>
26
27 #ifdef FC_OS_WIN32
28 # include <windows.h>
29 #endif
30
31 #include <QApplication>
32 #include <QImageReader>
33 #include <QLabel>
34 #include <QOpenGLContext>
35 #include <QOpenGLFunctions>
36 #include <QProcess>
37 #include <QStatusBar>
38 #include <QThread>
39 #include <QTimer>
40 #include <QWindow>
41
42 #include <Inventor/SoDB.h>
43
44 #include <set>
45 #include <string>
46 #include <ranges>
47
48 #include "StartupProcess.h"
49 #include "PreferencePackManager.h"
50 #include "Application.h"
51 #include "AutoSaver.h"
52 #include "Dialogs/DlgCheckableMessageBox.h"
53 #include "FileDialog.h"
54 #include "GuiApplication.h"
55 #include "MainWindow.h"
56 #include "Language/Translator.h"
57 #include "Dialogs/DlgVersionMigrator.h"
58 #include "FreeCADStyle.h"
59
60 #include <App/Application.h>
61 #include <App/ApplicationDirectories.h>
62 #include <Base/Console.h>
63
64
65 using namespace Gui;
66
67
68 StartupProcess::StartupProcess() = default;
69
70 void StartupProcess::setupApplication()
71 {
72 QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
73 QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL);
74
75 // Automatic scaling for legacy apps (disable once all parts of GUI are aware of HiDpi)
76 ParameterGrp::handle hDPI = App::GetApplication().GetParameterGroupByPath(
77 "User parameter:BaseApp/Preferences/HighDPI"
78 );
79 bool disableDpiScaling = hDPI->GetBool("DisableDpiScaling", false);
80 if (disableDpiScaling) {
81 #ifdef FC_OS_WIN32
82 SetProcessDPIAware(); // call before the main event loop
83 #endif
84 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
85 QApplication::setAttribute(Qt::AA_DisableHighDpiScaling);
86 #endif
87 }
88 else {
89 // Enable automatic scaling based on pixel density of display (added in Qt 5.6)
90 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
91 QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
92 #endif
93 #if defined(Q_OS_WIN)
94 QGuiApplication::setHighDpiScaleFactorRoundingPolicy(
95 Qt::HighDpiScaleFactorRoundingPolicy::PassThrough
96 );
97 #endif
98 }
99
100 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
101 // Enable support for highres images (added in Qt 5.1, but off by default)
102 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
103 #endif
104
105 // Use software rendering for OpenGL
106 ParameterGrp::handle hOpenGL = App::GetApplication().GetParameterGroupByPath(
107 "User parameter:BaseApp/Preferences/OpenGL"
108 );
109 bool useSoftwareOpenGL = hOpenGL->GetBool("UseSoftwareOpenGL", false);
110 if (useSoftwareOpenGL) {
111 QApplication::setAttribute(Qt::AA_UseSoftwareOpenGL);
112 }
113 // By default (on platforms that support it, see docs for
114 // Qt::AA_CompressHighFrequencyEvents) QT applies compression
115 // for high frequency events (mouse move, touch, window resizes)
116 // to keep things smooth even when handling the event takes a
117 // while (e.g. to calculate snapping).
118 // However, tablet pen move events (and mouse move events
119 // synthesised from those) are not compressed by default (to
120 // allow maximum precision when e.g. hand-drawing curves),
121 // leading to unacceptable slowdowns using a tablet pen. Enable
122 // compression for tablet events here to solve that.
123 QCoreApplication::setAttribute(Qt::AA_CompressTabletEvents);
124 }
125
126 void StartupProcess::execute()
127 {
128 setLibraryPath();
129 setStyleSheetPaths();
130 setImagePaths();
131 registerEventType();
132 setThemePaths();
133 setupFileDialog();
134 }
135
136 void StartupProcess::setLibraryPath()
137 {
138 QString plugin;
139 plugin = QString::fromStdString(App::Application::getHomePath());
140 plugin += QLatin1String("/plugins");
141 QCoreApplication::addLibraryPath(plugin);
142 }
143
144 void StartupProcess::setStyleSheetPaths()
145 {
146 // setup the search paths for Qt style sheets
147 QStringList qssPaths;
148 qssPaths << QString::fromUtf8((App::Application::getUserAppDataDir() + "Gui/Stylesheets/").c_str())
149 << QString::fromUtf8((App::Application::getResourceDir() + "Gui/Stylesheets/").c_str())
150 << QLatin1String(":/stylesheets");
151 QDir::setSearchPaths(QStringLiteral("qss"), qssPaths);
152 // setup the search paths for Qt overlay style sheets
153 QStringList qssOverlayPaths;
154 qssOverlayPaths << QString::fromUtf8(
155 (App::Application::getUserAppDataDir() + "Gui/Stylesheets/overlay").c_str()
156 ) << QString::fromUtf8((App::Application::getResourceDir() + "Gui/Stylesheets/overlay").c_str());
157 QDir::setSearchPaths(QStringLiteral("overlay"), qssOverlayPaths);
158 }
159
160 void StartupProcess::setImagePaths()
161 {
162 // set search paths for images
163 QStringList imagePaths;
164 imagePaths << QString::fromUtf8((App::Application::getUserAppDataDir() + "Gui/images").c_str())
165 << QString::fromUtf8((App::Application::getUserAppDataDir() + "pixmaps").c_str())
166 << QLatin1String(":/icons");
167 QDir::setSearchPaths(QStringLiteral("images"), imagePaths);
168 }
169
170 void StartupProcess::registerEventType()
171 {
172 // register action style event type
173 ActionStyleEvent::EventType = QEvent::registerEventType(QEvent::User + 1);
174 }
175
176 void StartupProcess::setThemePaths()
177 {
178 #if !defined(Q_OS_LINUX)
179 QIcon::setThemeSearchPaths(QIcon::themeSearchPaths() << QStringLiteral(":/icons/FreeCAD-default"));
180 #endif
181
182 ParameterGrp::handle hTheme = App::GetApplication().GetParameterGroupByPath(
183 "User parameter:BaseApp/Preferences/Bitmaps/Theme"
184 );
185
186 std::string searchpath = hTheme->GetASCII("SearchPath");
187 if (!searchpath.empty()) {
188 QStringList searchPaths = QIcon::themeSearchPaths();
189 searchPaths.prepend(QString::fromUtf8(searchpath.c_str()));
190 QIcon::setThemeSearchPaths(searchPaths);
191 }
192
193 std::string name = hTheme->GetASCII("Name");
194 if (!name.empty()) {
195 QIcon::setThemeName(QString::fromLatin1(name.c_str()));
196 }
197 }
198
199 void StartupProcess::setupFileDialog()
200 {
201 #if defined(FC_OS_LINUX)
202 // See #0001588
203 QString path = FileDialog::restoreLocation();
204 FileDialog::setWorkingDirectory(QDir::currentPath());
205 FileDialog::saveLocation(path);
206 #else
207 FileDialog::setWorkingDirectory(FileDialog::restoreLocation());
208 #endif
209 }
210
211 // ------------------------------------------------------------------------------------------------
212
213 StartupPostProcess::StartupPostProcess(MainWindow* mw, Application& guiApp, QApplication* app)
214 : mainWindow {mw}
215 , guiApp {guiApp}
216 , qtApp(app)
217 {}
218
219 void StartupPostProcess::setLoadFromPythonModule(bool value)
220 {
221 loadFromPythonModule = value;
222 }
223
224 void StartupPostProcess::execute()
225 {
226 setWindowTitle();
227 setProcessMessages();
228 setAutoSaving();
229 setToolBarIconSize();
230 setWheelEventFilter();
231 setLocale();
232 setCursorFlashing();
233 setQtStyle();
234 setStyleSheet();
235 checkOpenGL();
236 loadOpenInventor();
237 setBranding();
238 showMainWindow();
239 activateWorkbench();
240 checkParameters();
241 checkVersionMigration();
242 }
243
244 void StartupPostProcess::setWindowTitle()
245 {
246 // empty window title QString sets default title (app + version)
247 mainWindow->setWindowTitle(QString());
248 }
249
250 void StartupPostProcess::setProcessMessages()
251 {
252 if (!loadFromPythonModule) {
253 QObject::connect(
254 qtApp,
255 SIGNAL(messageReceived(const QList<QString>&)),
256 mainWindow,
257 SLOT(processMessages(const QList<QString>&))
258 );
259 }
260 }
261
262 void StartupPostProcess::setAutoSaving()
263 {
264 ParameterGrp::handle hDocGrp = WindowParameter::getDefaultParameter()->GetGroup("Document");
265 int timeout = int(hDocGrp->GetInt("AutoSaveTimeout", 15L)); // 15 min
266 if (!hDocGrp->GetBool("AutoSaveEnabled", true)) {
267 timeout = 0;
268 }
269
270 AutoSaver::instance()->setTimeout(timeout * 60000); // NOLINT
271 AutoSaver::instance()->setCompressed(hDocGrp->GetBool("AutoSaveCompressed", true));
272 }
273
274 void StartupPostProcess::setToolBarIconSize()
275 {
276 // set toolbar icon size
277 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("General");
278 int size = int(hGrp->GetInt("ToolbarIconSize", 0));
279 // must not be lower than this
280 if (size >= 16) { // NOLINT
281 mainWindow->setIconSize(QSize(size, size));
282 }
283 }
284
285 void StartupPostProcess::setWheelEventFilter()
286 {
287 // filter wheel events for combo boxes
288 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("General");
289 if (hGrp->GetBool("ComboBoxWheelEventFilter", false)) {
290 auto filter = new WheelEventFilter(qtApp);
291 qtApp->installEventFilter(filter);
292 }
293 }
294
295 void StartupPostProcess::setLocale()
296 {
297 // For values different to 1 and 2 use the OS locale settings
298 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("General");
299 auto localeFormat = hGrp->GetInt("UseLocaleFormatting", 0);
300 if (localeFormat == 1) {
301 Translator::instance()->setLocale(
302 hGrp->GetASCII("Language", Translator::instance()->activeLanguage().c_str())
303 );
304 }
305 else if (localeFormat == 2) {
306 Translator::instance()->setLocale("C.UTF-8");
307 }
308 }
309
310 void StartupPostProcess::setCursorFlashing()
311 {
312 // set text cursor blinking state
313 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("General");
314 int blinkTime = hGrp->GetBool("EnableCursorBlinking", true) ? -1 : 0;
315 QApplication::setCursorFlashTime(blinkTime);
316 }
317
318
319 void StartupPostProcess::setQtStyle()
320 {
321 static ParamHandlers handlers;
322
323 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("MainWindow");
324
325 const auto setStyleFromParameters = [hGrp]() {
326 const auto style = hGrp->GetASCII("QtStyle");
327
328 Application::Instance->setStyle(QString::fromStdString(style));
329 };
330
331 auto handler = handlers.addHandler(hGrp, "QtStyle", [setStyleFromParameters](const ParamKey*) {
332 setStyleFromParameters();
333 });
334
335 setStyleFromParameters();
336 }
337
338 void StartupPostProcess::migrateOldTheme(const std::string& style)
339 {
340 auto prefPackManager = Application::Instance->prefPackManager();
341
342 if (style == "FreeCAD Light.qss") {
343 prefPackManager->apply("FreeCAD Light");
344 }
345 else if (style == "FreeCAD Dark.qss") {
346 prefPackManager->apply("FreeCAD Dark");
347 }
348 }
349
350 void StartupPostProcess::checkOpenGL()
351 {
352 QWindow window;
353 window.setSurfaceType(QWindow::OpenGLSurface);
354 window.create();
355
356 QOpenGLContext context;
357 if (context.create()) {
358 context.makeCurrent(&window);
359 if (!context.functions()->hasOpenGLFeature(QOpenGLFunctions::Framebuffers)) {
360 Base::Console().log("This system does not support framebuffer objects\n");
361 }
362 if (!context.functions()->hasOpenGLFeature(QOpenGLFunctions::NPOTTextures)) {
363 Base::Console().log("This system does not support NPOT textures\n");
364 }
365
366 int major = context.format().majorVersion();
367 int minor = context.format().minorVersion();
368
369 #ifdef NDEBUG
370 // In release mode, issue a warning to users that their version of OpenGL is
371 // potentially going to cause problems
372 if (major < 2) {
373 auto message = QObject::tr(
374 "This system is running OpenGL %1.%2. "
375 "FreeCAD requires OpenGL 2.0 or above. "
376 "Upgrade the graphics driver and/or card as required."
377 )
378 .arg(major)
379 .arg(minor)
380 + QStringLiteral("\n");
381 Base::Console().warning(message.toStdString().c_str());
382 Dialog::DlgCheckableMessageBox::showMessage(
383 QCoreApplication::applicationName() + QStringLiteral(" - ")
384 + QObject::tr("Invalid OpenGL Version"),
385 message
386 );
387 }
388 #endif
389 const char* glVersion = reinterpret_cast<const char*>(glGetString(GL_VERSION));
390 Base::Console().log("OpenGL version is: %d.%d (%s)\n", major, minor, glVersion);
391 }
392 }
393
394 void StartupPostProcess::loadOpenInventor()
395 {
396 bool loadedInventor = false;
397 if (loadFromPythonModule) {
398 loadedInventor = SoDB::isInitialized();
399 }
400
401 if (!loadedInventor) {
402 // init the Inventor subsystem
403 Application::initOpenInventor();
404 }
405 }
406
407 void StartupPostProcess::setBranding()
408 {
409 QString home = QString::fromStdString(App::Application::getHomePath());
410
411 const std::map<std::string, std::string>& cfg = App::Application::Config();
412 std::map<std::string, std::string>::const_iterator it;
413 it = cfg.find("WindowTitle");
414 if (it != cfg.end()) {
415 QString title = QString::fromUtf8(it->second.c_str());
416 mainWindow->setWindowTitle(title);
417 }
418 it = cfg.find("WindowIcon");
419 if (it != cfg.end()) {
420 QString path = QString::fromUtf8(it->second.c_str());
421 if (QDir(path).isRelative()) {
422 path = QFileInfo(QDir(home), path).absoluteFilePath();
423 }
424 QApplication::setWindowIcon(QIcon(path));
425 }
426 it = cfg.find("ProgramLogo");
427 if (it != cfg.end()) {
428 QString path = QString::fromUtf8(it->second.c_str());
429 if (QDir(path).isRelative()) {
430 path = QFileInfo(QDir(home), path).absoluteFilePath();
431 }
432 QPixmap px(path);
433 if (!px.isNull()) {
434 auto logo = new QLabel();
435 logo->setPixmap(px.scaledToHeight(32));
436 mainWindow->statusBar()->addPermanentWidget(logo, 0);
437 logo->setFrameShape(QFrame::NoFrame);
438 }
439 }
440 }
441
442 void StartupPostProcess::setImportImageFormats()
443 {
444 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
445 std::stringstream str;
446 str << "Image formats (";
447 for (const auto& ext : supportedFormats) {
448 str << "*." << ext.constData() << " *." << ext.toUpper().constData() << " ";
449 }
450 str << ")";
451
452 std::string filter = str.str();
453 App::GetApplication().addImportType(filter.c_str(), "FreeCADGui");
454 }
455
456 void StartupPostProcess::showMainWindow()
457 {
458 // show splasher while initializing the GUI
459 if (!Application::hiddenMainWindow() && !loadFromPythonModule) {
460 mainWindow->startSplasher();
461 }
462
463 // running the GUI init script
464 try {
465 Base::Console().log("Run Gui init script\n");
466 Application::runInitGuiScript();
467 setImportImageFormats();
468 }
469 catch (const Base::Exception& e) {
470 Base::Console().error("Error in FreeCADGuiInit.py: %s\n", e.what());
471 mainWindow->stopSplasher();
472 throw;
473 }
474
475 // stop splash screen and set immediately the active window that may be of interest
476 // for scripts using Python binding for Qt
477 mainWindow->stopSplasher();
478 mainWindow->activateWindow();
479 }
480
481 void StartupPostProcess::activateWorkbench()
482 {
483 // Activate the correct workbench
484 std::string start = App::Application::Config()["StartWorkbench"];
485 Base::Console().log("Init: Activating default workbench %s\n", start.c_str());
486 std::string autoload = App::GetApplication()
487 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")
488 ->GetASCII("AutoloadModule", start.c_str());
489 if ("$LastModule" == autoload) {
490 start = App::GetApplication()
491 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")
492 ->GetASCII("LastModule", start.c_str());
493 }
494 else {
495 start = autoload;
496 }
497 // if the auto workbench is not visible then force to use the default workbech
498 // and replace the wrong entry in the parameters
499 QStringList wb = guiApp.workbenches();
500 if (!wb.contains(QString::fromLatin1(start.c_str()))) {
501 start = App::Application::Config()["StartWorkbench"];
502 if ("$LastModule" == autoload) {
503 App::GetApplication()
504 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")
505 ->SetASCII("LastModule", start.c_str());
506 }
507 else {
508 App::GetApplication()
509 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")
510 ->SetASCII("AutoloadModule", start.c_str());
511 }
512 }
513
514 // Call this before showing the main window because otherwise:
515 // 1. it shows a white window for a few seconds which doesn't look nice
516 // 2. the layout of the toolbars is completely broken
517 guiApp.activateWorkbench(start.c_str());
518
519 // show the main window
520 if (!Application::hiddenMainWindow()) {
521 Base::Console().log("Init: Showing main window\n");
522 mainWindow->loadWindowSettings();
523 }
524
525 // initialize spaceball.
526 if (auto fcApp = qobject_cast<GUIApplicationNativeEventAware*>(qtApp)) {
527 fcApp->initSpaceball(mainWindow);
528 }
529
530 // Now run the background autoload, for workbenches that should be loaded at startup, but not
531 // displayed to the user immediately
532 autoloadModules(wb);
533
534 // Reactivate the startup workbench
535 guiApp.activateWorkbench(start.c_str());
536 }
537
538 void StartupPostProcess::setStyleSheet()
539 {
540 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
541 "User parameter:BaseApp/Preferences/MainWindow"
542 );
543 std::string style = hGrp->GetASCII("StyleSheet");
544 if (style.empty()) {
545 // check the branding settings
546 const auto& config = App::Application::Config();
547 auto it = config.find("StyleSheet");
548 if (it != config.end()) {
549 style = it->second;
550 }
551 }
552
553 // In 1.1 we migrated to a common parametrized stylesheet.
554 // if we detect an old style, we need to reapply the theme pack.
555 migrateOldTheme(style);
556
557 guiApp.setStyleSheet(QString::fromStdString(style), hGrp->GetBool("TiledBackground", false));
558 }
559
560 void StartupPostProcess::autoloadModules(const QStringList& wb)
561 {
562 // Now run the background autoload, for workbenches that should be loaded at startup, but not
563 // displayed to the user immediately
564 std::string autoloadCSV = App::GetApplication()
565 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")
566 ->GetASCII("BackgroundAutoloadModules", "");
567
568 // Tokenize the comma-separated list and load the requested workbenches if they exist in this
569 // installation
570 std::stringstream stream(autoloadCSV);
571 std::string workbench;
572 while (std::getline(stream, workbench, ',')) {
573 if (wb.contains(QString::fromLatin1(workbench.c_str()))) {
574 guiApp.activateWorkbench(workbench.c_str());
575 }
576 }
577 }
578
579 void StartupPostProcess::checkParameters()
580 {
581 if (App::GetApplication().GetSystemParameter().IgnoreSave()) {
582 Base::Console().warning(
583 "System parameter file couldn't be opened.\n"
584 "Continue with an empty configuration that won't be saved.\n"
585 );
586 }
587 if (App::GetApplication().GetUserParameter().IgnoreSave()) {
588 Base::Console().warning(
589 "User parameter file couldn't be opened.\n"
590 "Continue with an empty configuration that won't be saved.\n"
591 );
592 }
593
594 // Prior to the release of v1.1, MacroPath was stored in the config file, even if it was just
595 // set to the default value. However, for a short time during the development of v1.1, when
596 // that directory was migrated, the config value was not updated. This code block corrects for
597 // that oversight by detecting when the path is set to the old default, and updates it to the
598 // new one -- but only once, so that if the user does manually set the path to the old default
599 // intentionally after this is run, it doesn't undo that action.
600 auto macroPrefs = App::GetApplication().GetParameterGroupByPath(
601 "User parameter:BaseApp/Preferences/Macro"
602 );
603 auto v11MacroLocationChecked = macroPrefs->GetBool("MacroPathCheckedForMigrationTov1-1", false);
604 if (!v11MacroLocationChecked) {
605 std::filesystem::path newDefaultPath {App::Application::getUserMacroDir()};
606 if (newDefaultPath.filename().empty()) {
607 newDefaultPath = newDefaultPath.parent_path();
608 }
609 int major = std::stoi(App::Application::Config()["BuildVersionMajor"]);
610 int minor = std::stoi(App::Application::Config()["BuildVersionMinor"]);
611 auto versionString = App::ApplicationDirectories::versionStringForPath(major, minor);
612 if (newDefaultPath.filename() == "Macro"
613 && (newDefaultPath.parent_path().filename() == versionString)) {
614 std::filesystem::path oldDefaultPath {newDefaultPath.parent_path().parent_path() / "Macro"};
615 std::filesystem::path macroDir
616 = macroPrefs->GetASCII("MacroPath", newDefaultPath.string().c_str());
617 if (macroDir.filename().empty()) {
618 macroDir = macroDir.parent_path();
619 }
620 if (macroDir == oldDefaultPath) {
621 Base::Console().warning(
622 "Removing 'MacroPath' parameter in order to default to the new versioned path\n"
623 );
624 macroPrefs->RemoveASCII("MacroPath");
625 }
626 }
627 macroPrefs->SetBool("MacroPathCheckedForMigrationTov1-1", true);
628 }
629 }
630
631 void StartupPostProcess::checkVersionMigration() const
632 {
633 auto migrator = new Dialog::DlgVersionMigrator(mainWindow);
634 migrator->exec();
635 migrator->deleteLater();
636 }