Debian Codegraph @

src/Gui/MainWindow.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24 #include <QActionGroup>
25 #include <QApplication>
26 #include <QByteArray>
27 #include <QCheckBox>
28 #include <QClipboard>
29 #include <QCloseEvent>
30 #include <QContextMenuEvent>
31 #include <QDesktopServices>
32 #include <QDockWidget>
33 #include <QFontMetrics>
34 #include <QKeySequence>
35 #include <QLabel>
36 #include <QMdiSubWindow>
37 #include <QMenu>
38 #include <QMenuBar>
39 #include <QMessageBox>
40 #include <QMimeData>
41 #include <QOpenGLWidget>
42 #include <QPainter>
43 #include <QRegularExpression>
44 #include <QRegularExpressionMatch>
45 #include <QScreen>
46 #include <QSettings>
47 #include <QSignalMapper>
48 #include <QStatusBar>
49 #include <QThread>
50 #include <QTimer>
51 #include <QToolBar>
52 #include <QUrlQuery>
53 #include <QWhatsThis>
54 #include <QWindow>
55 #include <QPushButton>
56
57
58 #if defined(Q_OS_WIN)
59 # if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
60 # include <QtPlatformHeaders/QWindowsWindowFunctions>
61 # else
62 # include <qpa/qplatformwindow_p.h>
63 # endif
64 #endif
65
66 #include <algorithm>
67 #include <boost/algorithm/string/predicate.hpp>
68
69 #include <App/Application.h>
70 #include <App/Document.h>
71 #include <App/DocumentObject.h>
72 #include <App/DocumentObjectGroup.h>
73 #include <App/ImagePlane.h>
74 #include <App/SafeMode.h>
75 #include <Base/ConsoleObserver.h>
76 #include <Base/Parameter.h>
77 #include <Base/Exception.h>
78 #include <Base/FileInfo.h>
79 #include <Base/Interpreter.h>
80 #include <Base/Stream.h>
81 #include <Base/Tools.h>
82 #include <Base/UnitsApi.h>
83 #include <DAGView/DAGView.h>
84 #include <TaskView/TaskView.h>
85
86 #include "MainWindow.h"
87 #include "Action.h"
88 #include "Assistant.h"
89 #include "BitmapFactory.h"
90 #include "ComboView.h"
91 #include "Command.h"
92 #include "DockWindowManager.h"
93 #include "DownloadManager.h"
94 #include "FileDialog.h"
95 #include "InputHintWidget.h"
96 #include "MenuManager.h"
97 #include "ModuleIO.h"
98 #include "NotificationArea.h"
99 #include "OverlayManager.h"
100 #include "ProgressBar.h"
101 #include "PropertyView.h"
102 #include "PythonConsole.h"
103 #include "ReportView.h"
104 #include "SelectionView.h"
105 #include "SplashScreen.h"
106 #include "StatusBarLabel.h"
107 #include "ToolBarManager.h"
108 #include "ToolBoxManager.h"
109 #include "Tree.h"
110 #include "WaitCursor.h"
111 #include "WorkbenchManager.h"
112 #include "Workbench.h"
113
114 #include "MergeDocuments.h"
115 #include "ViewProviderExtern.h"
116
117 #include "SpaceballEvent.h"
118 #include "View3DInventor.h"
119 #include "View3DInventorViewer.h"
120 #include "Dialogs/DlgObjectSelection.h"
121
122 #include <Base/Color.h>
123 #include "QtWidgets.h"
124
125 FC_LOG_LEVEL_INIT("MainWindow", false, true, true)
126
127 #if defined(Q_OS_WIN32)
128 # define slots
129 #endif
130
131 using namespace Gui;
132 using namespace Gui::DockWnd;
133 using namespace std;
134
135
136 MainWindow* MainWindow::instance = nullptr;
137
138 namespace Gui
139 {
140
141 /**
142 * The CustomMessageEvent class is used to send messages as events in the methods
143 * Error(), Warning() and Message() of the StatusBarObserver class to the main window
144 * to display them on the status bar instead of printing them directly to the status bar.
145 *
146 * This makes the usage of StatusBarObserver thread-safe.
147 * @author Werner Mayer
148 */
149 class CustomMessageEvent: public QEvent
150 {
151 public:
152 CustomMessageEvent(int t, const QString& s, int timeout = 0)
153 : QEvent(QEvent::User)
154 , _type(t)
155 , msg(s)
156 , _timeout(timeout)
157 {}
158 ~CustomMessageEvent() override = default;
159 int type() const
160 {
161 return _type;
162 }
163 const QString& message() const
164 {
165 return msg;
166 }
167 int timeout() const
168 {
169 return _timeout;
170 }
171
172 private:
173 int _type;
174 QString msg;
175 int _timeout;
176 };
177
178 /**
179 * The DimensionWidget class is aiming at providing a widget used in the status bar that will:
180 * - Allow application to display dimension information such as the viewportsize
181 * - Provide a popup menu allowing user to change the used unit schema (and update if changed
182 * elsewhere)
183 */
184 class DimensionWidget: public QPushButton, WindowParameter
185 {
186 Q_OBJECT
187
188 public:
189 explicit DimensionWidget(QWidget* parent)
190 : QPushButton(parent)
191 , WindowParameter("Units")
192 {
193 setFlat(true);
194 setText(qApp->translate("Gui::MainWindow", "Dimension"));
195 setMinimumWidth(120);
196
197 // create the action buttons
198 auto* menu = new QMenu(this);
199 auto* actionGrp = new QActionGroup(menu);
200
201 auto setAction = [&, index {0}](const std::string&) mutable {
202 QAction* action = menu->addAction(QStringLiteral("UnitSchema%1").arg(index));
203 actionGrp->addAction(action);
204 action->setCheckable(true);
205 action->setData(index++);
206 };
207 auto descriptions = Base::UnitsApi::getDescriptions();
208 std::for_each(descriptions.begin(), descriptions.end(), setAction);
209
210 QObject::connect(actionGrp, &QActionGroup::triggered, this, [this](QAction* action) {
211 int userSchema = action->data().toInt();
212 setUserSchema(userSchema);
213 // Force PropertyEditor refresh until we find a better way. Q_EMIT something?
214 const auto views = getMainWindow()->findChildren<PropertyView*>();
215 for (auto view : views) {
216 bool show = view->showAll();
217 view->setShowAll(!show);
218 view->setShowAll(show);
219 }
220 });
221 setMenu(menu);
222 retranslateUi();
223 unitChanged();
224 getWindowParameter()->Attach(this);
225 }
226
227 ~DimensionWidget() override
228 {
229 getWindowParameter()->Detach(this);
230 }
231
232 void OnChange(Base::Subject<const char*>& rCaller, const char* sReason) override
233 {
234 Q_UNUSED(rCaller)
235 if (strcmp(sReason, "UserSchema") == 0) {
236 unitChanged();
237 }
238 }
239
240 void changeEvent(QEvent* event) override
241 {
242 if (event->type() == QEvent::LanguageChange) {
243 retranslateUi();
244 }
245 else {
246 QPushButton::changeEvent(event);
247 }
248 }
249
250 void setUserSchema(int userSchema)
251 {
252 App::Document* doc = App::GetApplication().getActiveDocument();
253 if (doc != nullptr) {
254 if (doc->UnitSystem.getValue() != userSchema) {
255 doc->UnitSystem.setValue(userSchema);
256 }
257 }
258 else {
259 getWindowParameter()->SetInt("UserSchema", userSchema);
260 }
261
262 unitChanged();
263 Base::UnitsApi::setSchema(userSchema);
264 // Update the main window to show the unit change
265 Gui::Application::Instance->onUpdate();
266 }
267
268 private:
269 void unitChanged()
270 {
271 ParameterGrp::handle hGrpu = App::GetApplication().GetParameterGroupByPath(
272 "User parameter:BaseApp/Preferences/Units"
273 );
274 bool ignore = hGrpu->GetBool("IgnoreProjectSchema", false);
275 App::Document* doc = App::GetApplication().getActiveDocument();
276 int userSchema = getWindowParameter()->GetInt("UserSchema", 0);
277 if (doc != nullptr && !ignore) {
278 userSchema = doc->UnitSystem.getValue();
279 }
280 auto actions = menu()->actions();
281 if (Q_UNLIKELY(userSchema < 0 || userSchema >= actions.size())) {
282 userSchema = 0;
283 }
284 actions[userSchema]->setChecked(true);
285 }
286
287 void retranslateUi()
288 {
289 auto actions = menu()->actions();
290 auto addAction = [&, index {0}](const std::string& action) mutable {
291 actions[index++]->setText(QString::fromStdString(action));
292 };
293 auto descriptions = Base::UnitsApi::getDescriptions();
294 assert(actions.size() <= static_cast<qsizetype>(descriptions.size()));
295 std::for_each(descriptions.begin(), descriptions.end(), addAction);
296 }
297 };
298
299 // -------------------------------------
300 // Pimpl class
301 struct MainWindowP
302 {
303 DimensionWidget* sizeLabel;
304 QLabel* actionLabel;
305 InputHintWidget* hintLabel;
306 QLabel* rightSideLabel;
307 QTimer* actionTimer;
308 QTimer* statusTimer;
309 QTimer* activityTimer;
310 QTimer saveStateTimer;
311 QTimer restoreStateTimer;
312 QMdiArea* mdiArea;
313 QPointer<MDIView> activeView;
314 QSignalMapper* windowMapper;
315 SplashScreen* splashscreen;
316 StatusBarObserver* status;
317 bool whatsthis;
318 QString whatstext;
319 Assistant* assistant;
320 int currentStatusType = 100;
321 int actionUpdateDelay = 0;
322 QMap<QString, QPointer<UrlHandler>> urlHandler;
323 std::string hiddenDockWindows;
324 boost::signals2::scoped_connection connParam;
325 ParameterGrp::handle hGrp;
326 bool _restoring = false;
327 QTime _showNormal;
328 void restoreWindowState(const QByteArray&);
329 };
330
331 } // namespace Gui
332
333 /* TRANSLATOR Gui::MainWindow */
334
335 MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags f)
336 : QMainWindow(parent, f /*WDestructiveClose*/)
337 {
338 d = new MainWindowP;
339 d->splashscreen = nullptr;
340 d->activeView = nullptr;
341 d->whatsthis = false;
342 d->assistant = new Assistant();
343
344 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
345 // this forces QT to switch to OpenGL mode, this prevents delay and flickering of the window
346 // after opening project and prevent issues with double initialization of the window
347 //
348 // https://stackoverflow.com/questions/76026196/how-to-force-qt-to-use-the-opengl-window-type
349 auto _OpenGLWidget = new QOpenGLWidget(this);
350 _OpenGLWidget->move(QPoint(-100, -100));
351 #endif
352
353 // global access
354 instance = this;
355
356 d->connParam = App::GetApplication().GetUserParameter().signalParamChanged.connect(
357 [this](ParameterGrp* Param, ParameterGrp::ParamType, const char* Name, const char*) {
358 if (Param != d->hGrp || !Name) {
359 return;
360 }
361 if (boost::equals(Name, "StatusBar")) {
362 if (auto sb = getMainWindow()->statusBar()) {
363 sb->setVisible(d->hGrp->GetBool("StatusBar", sb->isVisible()));
364 }
365 }
366 else if (boost::equals(Name, "MainWindowState")) {
367 OverlayManager::instance()->reload(OverlayManager::ReloadMode::ReloadPause);
368 d->restoreStateTimer.start(100);
369 }
370 }
371 );
372
373 d->hGrp = App::GetApplication().GetParameterGroupByPath(
374 "User parameter:BaseApp/Preferences/MainWindow"
375 );
376 d->saveStateTimer.setSingleShot(true);
377 connect(&d->saveStateTimer, &QTimer::timeout, [this]() { this->saveWindowSettings(); });
378
379 d->restoreStateTimer.setSingleShot(true);
380 connect(&d->restoreStateTimer, &QTimer::timeout, [this]() {
381 d->restoreWindowState(QByteArray::fromBase64(d->hGrp->GetASCII("MainWindowState").c_str()));
382 ToolBarManager::getInstance()->restoreState();
383 OverlayManager::instance()->reload(OverlayManager::ReloadMode::ReloadResume);
384 });
385
386 // support for grouped dragging of dockwidgets
387 // https://woboq.com/blog/qdockwidget-changes-in-56.html
388 setDockOptions(dockOptions() | QMainWindow::GroupedDragging);
389
390 // Create the layout containing the workspace and a tab bar
391 d->mdiArea = new QMdiArea();
392 // Movable tabs
393 d->mdiArea->setTabsMovable(true);
394 d->mdiArea->setTabPosition(QTabWidget::South);
395 d->mdiArea->setViewMode(QMdiArea::TabbedView);
396 auto tab = d->mdiArea->findChild<QTabBar*>();
397 if (tab) {
398 tab->setTabsClosable(true);
399 // The tabs might be very wide
400 tab->setExpanding(false);
401 tab->setObjectName(QStringLiteral("mdiAreaTabBar"));
402 }
403 d->mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
404 d->mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
405 d->mdiArea->setOption(QMdiArea::DontMaximizeSubWindowOnActivation, false);
406 #ifndef HAS_QTBUG_129596
407 d->mdiArea->setActivationOrder(QMdiArea::ActivationHistoryOrder);
408 #endif
409 d->mdiArea->setBackground(QBrush(QColor(160, 160, 160)));
410 setCentralWidget(d->mdiArea);
411
412 statusBar()->setObjectName(QStringLiteral("statusBar"));
413 connect(statusBar(), &QStatusBar::messageChanged, this, &MainWindow::statusMessageChanged);
414
415 // labels and progressbar
416 d->status = new StatusBarObserver();
417 d->actionLabel = new StatusBarLabel(statusBar());
418 d->actionLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
419 d->sizeLabel = new DimensionWidget(statusBar());
420
421 statusBar()->addWidget(d->actionLabel, 1);
422 QProgressBar* progressBar = Gui::SequencerBar::instance()->getProgressBar(statusBar());
423 statusBar()->addPermanentWidget(progressBar, 0);
424 statusBar()->addPermanentWidget(d->sizeLabel, 0);
425
426 // hint label
427 d->hintLabel = new InputHintWidget(statusBar());
428 d->hintLabel->setObjectName(QStringLiteral("hintLabel"));
429 //: A context menu action used to show or hide the input hints in the status bar
430 d->hintLabel->setWindowTitle(tr("Input hints"));
431
432 statusBar()->addWidget(d->hintLabel);
433
434 // right side label
435 d->rightSideLabel = new StatusBarLabel(statusBar(), "QuickMeasureEnabled");
436 d->rightSideLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
437 statusBar()->addPermanentWidget(d->rightSideLabel);
438 d->rightSideLabel->setObjectName(QStringLiteral("rightSideLabel"));
439 //: A context menu action used to enable or disable quick measure in the status bar
440 d->rightSideLabel->setWindowTitle(tr("Quick measure"));
441
442 auto hGrp = App::GetApplication().GetParameterGroupByPath(
443 "User parameter:BaseApp/Preferences/NotificationArea"
444 );
445
446 auto notificationAreaEnabled = hGrp->GetBool("NotificationAreaEnabled", true);
447
448 if (notificationAreaEnabled) {
449 NotificationArea* notificationArea = new NotificationArea(statusBar());
450 notificationArea->setObjectName(QStringLiteral("notificationArea"));
451 //: A context menu action used to show or hide the 'notificationArea' toolbar widget
452 notificationArea->setWindowTitle(tr("Notification Area"));
453 notificationArea->setStyleSheet(QStringLiteral("text-align:center;"));
454 statusBar()->addPermanentWidget(notificationArea);
455 }
456
457 // clears the action label
458 d->actionTimer = new QTimer(this);
459 d->actionTimer->setObjectName(QStringLiteral("actionTimer"));
460 connect(d->actionTimer, &QTimer::timeout, d->actionLabel, &QLabel::clear);
461
462 // clear status type
463 d->statusTimer = new QTimer(this);
464 d->statusTimer->setObjectName(QStringLiteral("statusTimer"));
465 connect(d->statusTimer, &QTimer::timeout, this, &MainWindow::clearStatus);
466
467 // update gui timer
468 d->activityTimer = new QTimer(this);
469 d->activityTimer->setObjectName(QStringLiteral("activityTimer"));
470 connect(d->activityTimer, &QTimer::timeout, this, &MainWindow::_updateActions);
471 d->activityTimer->setSingleShot(false);
472 d->activityTimer->start(150);
473
474 // update view-sensitive commands when clipboard has changed
475 QClipboard* clipbd = QApplication::clipboard();
476 connect(clipbd, &QClipboard::dataChanged, this, &MainWindow::updateEditorActions);
477
478 d->windowMapper = new QSignalMapper(this);
479
480 // connection between workspace, window menu and tab bar
481 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
482 connect(d->windowMapper, &QSignalMapper::mappedWidget, this, &MainWindow::setActiveSubWindow);
483 #else
484 connect(d->windowMapper, &QSignalMapper::mappedObject, this, [=, this](QObject* object) {
485 setActiveSubWindow(qobject_cast<QWidget*>(object));
486 });
487 #endif
488 connect(d->mdiArea, &QMdiArea::subWindowActivated, this, &MainWindow::onWindowActivated);
489
490 setupDockWindows();
491
492 // accept drops on the window, get handled in dropEvent, dragEnterEvent
493 setAcceptDrops(true);
494
495 statusBar()->showMessage(tr("Ready"), 2001);
496 }
497
498 MainWindow::~MainWindow()
499 {
500 delete d->status;
501 delete d;
502 instance = nullptr;
503 }
504
505 MainWindow* MainWindow::getInstance()
506 {
507 // MainWindow has a public constructor
508 return instance;
509 }
510
511 // Helper function to update dock widget according to the user parameter
512 // settings, e.g. register/unregister, enable/disable, show/hide.
513 template<class T>
514 static inline void _updateDockWidget(
515 const char* name,
516 bool enabled,
517 bool show,
518 Qt::DockWidgetArea pos,
519 T callback
520 )
521 {
522 auto pDockMgr = DockWindowManager::instance();
523 auto widget = pDockMgr->findRegisteredDockWindow(name);
524 if (!enabled) {
525 if (widget) {
526 pDockMgr->removeDockWindow(widget);
527 pDockMgr->unregisterDockWindow(name);
528 widget->deleteLater();
529 }
530 return;
531 }
532 // Use callback to perform specific update for each type of dock widget
533 widget = callback(widget);
534 if (!widget) {
535 return;
536 }
537 DockWindowManager::instance()->registerDockWindow(name, widget);
538 if (show) {
539 auto dock = pDockMgr->addDockWindow(widget->objectName().toUtf8().constData(), widget, pos);
540 if (dock) {
541 if (!dock->toggleViewAction()->isChecked()) {
542 dock->toggleViewAction()->activate(QAction::Trigger);
543 }
544 OverlayManager::instance()->refresh(dock);
545 }
546 }
547 }
548
549 void MainWindow::initDockWindows(bool show)
550 {
551 updateTreeView(show);
552 updatePropertyView(show);
553 updateComboView(show);
554 updateTaskView(show);
555 updateDAGView(show);
556 }
557
558 void MainWindow::setupDockWindows()
559 {
560 // Report view must be created before PythonConsole!
561 setupReportView();
562 setupPythonConsole();
563 setupSelectionView();
564 setupTaskView();
565
566 initDockWindows(false);
567
568 std::vector<QTabWidget::TabPosition> tabPos
569 = {QTabWidget::North, QTabWidget::South, QTabWidget::West, QTabWidget::East};
570 long value = d->hGrp->GetInt("LeftDockWidgetAreaTabPos", long(tabPos.front()));
571 if (value >= 0 && value < long(tabPos.size())) {
572 setTabPosition(Qt::LeftDockWidgetArea, tabPos[value]);
573 }
574 }
575
576 bool MainWindow::setupTaskView()
577 {
578 // Task view
579 if (d->hiddenDockWindows.find("Std_TaskView") == std::string::npos) {
580 // clang-format off
581 auto group = App::GetApplication().GetUserParameter()
582 .GetGroup("BaseApp")
583 ->GetGroup("Preferences")
584 ->GetGroup("DockWindows")
585 ->GetGroup("TaskView");
586 // clang-format on
587 auto taskView = new Gui::TaskView::TaskView(this);
588 bool restore = group->GetBool("RestoreWidth", taskView->shouldRestoreWidth());
589 taskView->setRestoreWidth(restore);
590 taskView->setObjectName(QStringLiteral("Tasks"));
591 taskView->setWindowTitle(QDockWidget::tr("Tasks"));
592 taskView->setMinimumWidth(210);
593
594 DockWindowManager* pDockMgr = DockWindowManager::instance();
595 pDockMgr->registerDockWindow("Std_TaskView", taskView);
596 return true;
597 }
598
599 return false;
600 }
601
602 bool MainWindow::setupSelectionView()
603 {
604 // Selection view
605 if (d->hiddenDockWindows.find("Std_SelectionView") == std::string::npos) {
606 auto pcSelectionView = new SelectionView(nullptr, this);
607 pcSelectionView->setObjectName(QStringLiteral("Selection view"));
608 pcSelectionView->setWindowTitle(QDockWidget::tr("Selection View"));
609 pcSelectionView->setMinimumWidth(210);
610
611 DockWindowManager* pDockMgr = DockWindowManager::instance();
612 pDockMgr->registerDockWindow("Std_SelectionView", pcSelectionView);
613 return true;
614 }
615
616 return false;
617 }
618
619 bool MainWindow::setupReportView()
620 {
621 // Report view
622 if (d->hiddenDockWindows.find("Std_ReportView") == std::string::npos) {
623 auto pcReport = new ReportOutput(this);
624 pcReport->setWindowIcon(BitmapFactory().pixmap("MacroEditor"));
625 pcReport->setObjectName(QStringLiteral("Report view"));
626 pcReport->setWindowTitle(QDockWidget::tr("Report View"));
627
628 DockWindowManager* pDockMgr = DockWindowManager::instance();
629 pDockMgr->registerDockWindow("Std_ReportView", pcReport);
630
631 auto rvObserver = new ReportOutputObserver(pcReport);
632 qApp->installEventFilter(rvObserver);
633 return true;
634 }
635
636 return false;
637 }
638
639 bool MainWindow::setupPythonConsole()
640 {
641 // Python console
642 if (d->hiddenDockWindows.find("Std_PythonView") == std::string::npos) {
643 auto pcPython = new PythonConsole(this);
644 pcPython->setWindowIcon(Gui::BitmapFactory().iconFromTheme("applications-python"));
645 pcPython->setObjectName(QStringLiteral("Python console"));
646 pcPython->setWindowTitle(QDockWidget::tr("Python Console"));
647
648 DockWindowManager* pDockMgr = DockWindowManager::instance();
649 pDockMgr->registerDockWindow("Std_PythonView", pcPython);
650 return true;
651 }
652
653 return false;
654 }
655
656 bool MainWindow::updateTreeView(bool show)
657 {
658 if (d->hiddenDockWindows.find("Std_TreeView") == std::string::npos) {
659 ParameterGrp::handle group = App::GetApplication()
660 .GetUserParameter()
661 .GetGroup("BaseApp")
662 ->GetGroup("Preferences")
663 ->GetGroup("DockWindows")
664 ->GetGroup("TreeView");
665 bool enabled = group->GetBool("Enabled", false);
666 _updateDockWidget("Std_TreeView", enabled, show, Qt::RightDockWidgetArea, [](QWidget* widget) {
667 if (widget) {
668 return widget;
669 }
670
671 auto tree = new TreeDockWidget(0, getMainWindow());
672 tree->setObjectName(QStringLiteral("Tree view"));
673 tree->setWindowTitle(QDockWidget::tr("Tree View"));
674 tree->setMinimumWidth(210);
675 widget = tree;
676 return widget;
677 });
678
679 return enabled;
680 }
681
682 return false;
683 }
684
685 bool MainWindow::updatePropertyView(bool show)
686 {
687 // Property view
688 if (d->hiddenDockWindows.find("Std_PropertyView") == std::string::npos) {
689 ParameterGrp::handle group = App::GetApplication()
690 .GetUserParameter()
691 .GetGroup("BaseApp")
692 ->GetGroup("Preferences")
693 ->GetGroup("DockWindows")
694 ->GetGroup("PropertyView");
695 bool enabled = group->GetBool("Enabled", false);
696 _updateDockWidget("Std_PropertyView", enabled, show, Qt::RightDockWidgetArea, [](QWidget* widget) {
697 if (widget) {
698 return widget;
699 }
700
701 auto pcPropView = new PropertyDockView(0, getMainWindow());
702 pcPropView->setObjectName(QStringLiteral("Property view"));
703 pcPropView->setWindowTitle(QDockWidget::tr("Property View"));
704 pcPropView->setMinimumWidth(210);
705 widget = pcPropView;
706 return widget;
707 });
708
709 return enabled;
710 }
711
712 return false;
713 }
714
715 bool MainWindow::updateTaskView(bool show)
716 {
717 // Task List (task watcher).
718 if (d->hiddenDockWindows.find("Std_TaskWatcher") == std::string::npos) {
719 // work through parameter.
720 ParameterGrp::handle group = App::GetApplication().GetUserParameter().GetGroup(
721 "BaseApp/Preferences/DockWindows/TaskWatcher"
722 );
723 bool enabled = group->GetBool("Enabled", false);
724 group->SetBool("Enabled", enabled); // ensure entry exists.
725 _updateDockWidget("Std_TaskWatcher", enabled, show, Qt::RightDockWidgetArea, [](QWidget* widget) {
726 if (widget) {
727 return widget;
728 }
729
730 widget = new TaskView::TaskView(getMainWindow());
731 widget->setObjectName(QStringLiteral("Task List"));
732 widget->setWindowTitle(QDockWidget::tr("Task List"));
733 return widget;
734 });
735
736 return enabled;
737 }
738
739 return false;
740 }
741
742 bool MainWindow::updateComboView(bool show)
743 {
744 // Combo view
745 if (d->hiddenDockWindows.find("Std_ComboView") == std::string::npos) {
746 ParameterGrp::handle group = App::GetApplication()
747 .GetUserParameter()
748 .GetGroup("BaseApp")
749 ->GetGroup("Preferences")
750 ->GetGroup("DockWindows")
751 ->GetGroup("ComboView");
752 bool enable = group->GetBool("Enabled", true);
753 _updateDockWidget("Std_ComboView", enable, show, Qt::LeftDockWidgetArea, [](QWidget* widget) {
754 auto pcComboView = qobject_cast<ComboView*>(widget);
755 if (widget) {
756 return widget;
757 }
758
759 pcComboView = new ComboView(nullptr, getMainWindow());
760 pcComboView->setObjectName(QStringLiteral("Model"));
761 pcComboView->setWindowTitle(QDockWidget::tr("Model"));
762 pcComboView->setMinimumWidth(150);
763 widget = pcComboView;
764 return widget;
765 });
766
767 return enable;
768 }
769
770 return false;
771 }
772
773 bool MainWindow::updateDAGView(bool show)
774 {
775 // Dag View.
776 if (d->hiddenDockWindows.find("Std_DAGView") == std::string::npos) {
777 ParameterGrp::handle group = App::GetApplication()
778 .GetUserParameter()
779 .GetGroup("BaseApp")
780 ->GetGroup("Preferences")
781 ->GetGroup("DockWindows")
782 ->GetGroup("DAGView");
783 bool enabled = group->GetBool("Enabled", false);
784 _updateDockWidget("Std_DAGView", enabled, show, Qt::RightDockWidgetArea, [](QWidget* widget) {
785 if (widget) {
786 return widget;
787 }
788
789 auto dagDockWindow = new DAG::DockWindow(nullptr, getMainWindow());
790 dagDockWindow->setObjectName(QStringLiteral("DAG View"));
791 dagDockWindow->setWindowTitle(QDockWidget::tr("DAG View"));
792 widget = dagDockWindow;
793 return widget;
794 });
795
796 return enabled;
797 }
798
799 return false;
800 }
801
802 QMenu* MainWindow::createPopupMenu()
803 {
804 QMenu* menu = new QMenu(this);
805 populateDockWindowMenu(menu);
806 menu->addSeparator();
807 populateToolBarMenu(menu);
808 menu->addSeparator();
809 Workbench* wb = WorkbenchManager::instance()->active();
810 if (wb) {
811 MenuItem item;
812 wb->createMainWindowPopupMenu(&item);
813 if (item.hasItems()) {
814 menu->addSeparator();
815 QList<MenuItem*> items = item.getItems();
816 for (const auto& item : items) {
817 if (item->command() == "Separator") {
818 menu->addSeparator();
819 }
820 else {
821 Command* cmd = Application::Instance->commandManager().getCommandByName(
822 item->command().c_str()
823 );
824 if (cmd) {
825 cmd->addTo(menu);
826 }
827 }
828 }
829 }
830 }
831
832 return menu;
833 }
834
835 void MainWindow::tile()
836 {
837 d->mdiArea->tileSubWindows();
838 }
839
840 void MainWindow::cascade()
841 {
842 d->mdiArea->cascadeSubWindows();
843 }
844
845 void MainWindow::closeActiveWindow()
846 {
847 d->mdiArea->closeActiveSubWindow();
848 }
849
850 int MainWindow::confirmSave(App::Document* doc, QWidget* parent, bool addCheckbox)
851 {
852 QMessageBox box(parent ? parent : this);
853 box.setObjectName(QStringLiteral("confirmSave"));
854 box.setIcon(QMessageBox::Question);
855 box.setWindowFlags(box.windowFlags() | Qt::WindowStaysOnTopHint);
856 box.setWindowTitle(QObject::tr("Unsaved Document"));
857 const QString docName = QString::fromStdString(doc->Label.getStrValue());
858 const QString text
859 = (!docName.isEmpty()
860 ? QObject::tr("Save all changes to document '%1' before closing?").arg(docName)
861 : QObject::tr("Save all changes to document before closing?"));
862 box.setText(text);
863
864
865 box.setInformativeText(QObject::tr("Otherwise, all changes will be lost."));
866 box.setStandardButtons(QMessageBox::Discard | QMessageBox::Cancel | QMessageBox::Save);
867 box.setDefaultButton(QMessageBox::Save);
868 box.setEscapeButton(QMessageBox::Cancel);
869
870 QCheckBox checkBox(QObject::tr("Apply to all"));
871 ParameterGrp::handle hGrp;
872 if (addCheckbox) {
873 hGrp = App::GetApplication()
874 .GetUserParameter()
875 .GetGroup("BaseApp")
876 ->GetGroup("Preferences")
877 ->GetGroup("General");
878 checkBox.setChecked(hGrp->GetBool("ConfirmAll", false));
879 checkBox.blockSignals(true);
880 box.addButton(&checkBox, QMessageBox::ResetRole);
881 }
882
883 // add shortcuts
884 QAbstractButton* saveBtn = box.button(QMessageBox::Save);
885 if (saveBtn->shortcut().isEmpty()) {
886 QString text = saveBtn->text();
887 text.prepend(QLatin1Char('&'));
888 saveBtn->setShortcut(QKeySequence::mnemonic(text));
889 }
890
891 QAbstractButton* discardBtn = box.button(QMessageBox::Discard);
892 if (discardBtn->shortcut().isEmpty()) {
893 QString text = discardBtn->text();
894 text.prepend(QLatin1Char('&'));
895 discardBtn->setShortcut(QKeySequence::mnemonic(text));
896 }
897
898 int res = ConfirmSaveResult::Cancel;
899 box.adjustSize(); // Silence warnings from Qt on Windows
900
901 // activates the last used MDI view of the closing document
902 MDIView* activeView = this->activeWindow();
903 App::Document* activeDoc = (activeView ? activeView->getAppDocument() : nullptr);
904 if (activeDoc != doc) {
905 const QList<QWidget*> listOfMDIs = this->windows();
906 for (QWidget* widget : listOfMDIs) {
907 auto mdiView = qobject_cast<MDIView*>(widget);
908 if (mdiView != nullptr && mdiView->getAppDocument() == doc) {
909 this->setActiveWindow(mdiView);
910 }
911 }
912 }
913
914 switch (box.exec()) {
915 case QMessageBox::Save:
916 res = checkBox.isChecked() ? ConfirmSaveResult::SaveAll : ConfirmSaveResult::Save;
917 break;
918 case QMessageBox::Discard:
919 res = checkBox.isChecked() ? ConfirmSaveResult::DiscardAll : ConfirmSaveResult::Discard;
920 break;
921 }
922 if (addCheckbox && res) {
923 hGrp->SetBool("ConfirmAll", checkBox.isChecked());
924 }
925 return res;
926 }
927
928 bool MainWindow::closeAllDocuments(bool close)
929 {
930 auto docs = App::GetApplication().getDocuments();
931 try {
932 docs = App::Document::getDependentDocuments(docs, true);
933 }
934 catch (Base::Exception& e) {
935 e.reportException();
936 }
937
938 bool checkModify = true;
939 bool saveAll = false;
940 int failedSaves = 0;
941
942 // moves the active document to the front
943 MDIView* activeView = this->activeWindow();
944 App::Document* activeDoc = (activeView ? activeView->getAppDocument() : nullptr);
945 if (activeDoc != nullptr) {
946 for (auto it = ++docs.begin(); it != docs.end(); it++) {
947 if (*it == activeDoc) {
948 docs.erase(it);
949 docs.insert(docs.begin(), activeDoc);
950 }
951 }
952 }
953
954 for (auto doc : docs) {
955 auto gdoc = Application::Instance->getDocument(doc);
956 if (!gdoc) {
957 continue;
958 }
959 if (!gdoc->canClose(false)) {
960 return false;
961 }
962 if (!gdoc->isModified() || doc->testStatus(App::Document::PartialDoc)
963 || doc->testStatus(App::Document::TempDoc)) {
964 continue;
965 }
966 bool save = saveAll;
967 if (!save && checkModify) {
968 int res = confirmSave(doc, this, docs.size() > 1);
969 switch (res) {
970 case ConfirmSaveResult::Cancel:
971 return false;
972 case ConfirmSaveResult::SaveAll:
973 saveAll = true;
974 /* FALLTHRU */
975 case ConfirmSaveResult::Save:
976 save = true;
977 break;
978 case ConfirmSaveResult::DiscardAll:
979 checkModify = false;
980 }
981 }
982
983 if (save && !gdoc->save()) {
984 failedSaves++;
985 }
986 }
987
988 if (failedSaves > 0) {
989 int ret = QMessageBox::question(
990 getMainWindow(),
991 QObject::tr("%1 Document(s) not saved").arg(QString::number(failedSaves)),
992 QObject::tr("Some documents could not be saved. Cancel closing?"),
993 QMessageBox::Discard | QMessageBox::Cancel,
994 QMessageBox::Discard
995 );
996 if (ret == QMessageBox::Cancel) {
997 return false;
998 }
999 }
1000
1001 if (close) {
1002 App::GetApplication().closeAllDocuments();
1003 }
1004
1005 return true;
1006 }
1007
1008 void MainWindow::activateNextWindow()
1009 {
1010 auto tab = d->mdiArea->findChild<QTabBar*>();
1011 if (tab && tab->count() > 0) {
1012 int index = (tab->currentIndex() + 1) % tab->count();
1013 tab->setCurrentIndex(index);
1014 }
1015 }
1016
1017 void MainWindow::activatePreviousWindow()
1018 {
1019 auto tab = d->mdiArea->findChild<QTabBar*>();
1020 if (tab && tab->count() > 0) {
1021 int index = (tab->currentIndex() + tab->count() - 1) % tab->count();
1022 tab->setCurrentIndex(index);
1023 }
1024 }
1025
1026 void MainWindow::activateWorkbench(const QString& name)
1027 {
1028 // remember workbench by tab (if enabled)
1029
1030 const ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
1031 "User parameter:BaseApp/Preferences/View"
1032 );
1033 const bool saveWB = hGrp->GetBool("SaveWBbyTab", false);
1034 MDIView* view = activeWindow();
1035 if (view && saveWB) {
1036 view->setProperty("ownWB", name);
1037 }
1038
1039 // emit this signal
1040 Q_EMIT workbenchActivated(name);
1041 updateActions(true);
1042 }
1043
1044 void MainWindow::whatsThis()
1045 {
1046 QWhatsThis::enterWhatsThisMode();
1047 }
1048
1049 void MainWindow::showDocumentation(const QString& help)
1050 {
1051 Base::PyGILStateLocker lock;
1052 try {
1053 PyObject* module = PyImport_ImportModule("Help");
1054 if (module) {
1055 Py_DECREF(module);
1056 Gui::Command::addModule(Gui::Command::Gui, "Help");
1057 Gui::Command::doCommand(Gui::Command::Gui, "Help.show(\"%s\")", help.toStdString().c_str());
1058 }
1059 }
1060 catch (const Base::Exception& e) {
1061 e.reportException();
1062 }
1063 }
1064
1065 bool MainWindow::event(QEvent* e)
1066 {
1067 if (e->type() == QEvent::EnterWhatsThisMode) {
1068 // Unfortunately, for top-level widgets such as menus or dialogs we
1069 // won't be notified when the user clicks the link in the hypertext of
1070 // the what's this text. Thus, we have to install the main window to
1071 // the application to observe what happens in eventFilter().
1072 d->whatstext.clear();
1073 if (!d->whatsthis) {
1074 d->whatsthis = true;
1075 qApp->installEventFilter(this);
1076 }
1077 }
1078 else if (e->type() == QEvent::LeaveWhatsThisMode) {
1079 // Here we can't do anything because this event is sent
1080 // before the WhatThisClicked event is sent. Thus, we handle
1081 // this in eventFilter().
1082 }
1083 else if (e->type() == QEvent::WhatsThisClicked) {
1084 auto wt = static_cast<QWhatsThisClickedEvent*>(e);
1085 showDocumentation(wt->href());
1086 }
1087 else if (e->type() == QEvent::ApplicationWindowIconChange) {
1088 // if application icon changes apply it to the main window and the "About..." dialog
1089 this->setWindowIcon(QApplication::windowIcon());
1090 Command* about = Application::Instance->commandManager().getCommandByName("Std_About");
1091 if (about) {
1092 Action* action = about->getAction();
1093 if (action) {
1094 action->setIcon(QApplication::windowIcon());
1095 }
1096 }
1097 }
1098 else if (e->type() == Spaceball::ButtonEvent::ButtonEventType) {
1099 auto buttonEvent = dynamic_cast<Spaceball::ButtonEvent*>(e);
1100 if (!buttonEvent) {
1101 return true;
1102 }
1103 buttonEvent->setHandled(true);
1104 // only going to respond to button press events.
1105 if (buttonEvent->buttonStatus() != Spaceball::BUTTON_PRESSED) {
1106 return true;
1107 }
1108 ParameterGrp::handle group = App::GetApplication()
1109 .GetUserParameter()
1110 .GetGroup("BaseApp")
1111 ->GetGroup("Spaceball")
1112 ->GetGroup("Buttons");
1113 QByteArray groupName(QVariant(buttonEvent->buttonNumber()).toByteArray());
1114 if (group->HasGroup(groupName.data())) {
1115 ParameterGrp::handle commandGroup = group->GetGroup(groupName.data());
1116 std::string commandName(commandGroup->GetASCII("Command"));
1117 if (commandName.empty()) {
1118 return true;
1119 }
1120 else {
1121 Application::Instance->commandManager().runCommandByName(commandName.c_str());
1122 }
1123 }
1124 else {
1125 return true;
1126 }
1127 }
1128 else if (e->type() == Spaceball::MotionEvent::MotionEventType) {
1129 auto motionEvent = dynamic_cast<Spaceball::MotionEvent*>(e);
1130 if (!motionEvent) {
1131 return true;
1132 }
1133 motionEvent->setHandled(true);
1134 Gui::Document* doc = Application::Instance->activeDocument();
1135 if (!doc) {
1136 return true;
1137 }
1138 auto temp = dynamic_cast<View3DInventor*>(doc->getActiveView());
1139 if (!temp) {
1140 return true;
1141 }
1142 View3DInventorViewer* view = temp->getViewer();
1143 if (view) {
1144 Spaceball::MotionEvent anotherEvent(*motionEvent);
1145 qApp->sendEvent(view, &anotherEvent);
1146 }
1147 return true;
1148 }
1149 else if (e->type() == QEvent::StatusTip) {
1150 // make sure warning and error message don't get blocked by tooltips
1151 if (std::abs(d->currentStatusType) <= MainWindow::Wrn) {
1152 return true;
1153 }
1154 }
1155 return QMainWindow::event(e);
1156 }
1157
1158 bool MainWindow::eventFilter(QObject* o, QEvent* e)
1159 {
1160 if (o != this) {
1161 if (e->type() == QEvent::WindowStateChange) {
1162 // notify all mdi views when the active view receives a show normal, show minimized
1163 // or show maximized event
1164 auto view = dynamic_cast<MDIView*>(o);
1165 if (view) { // emit this signal
1166 Qt::WindowStates oldstate = static_cast<QWindowStateChangeEvent*>(e)->oldState();
1167 Qt::WindowStates newstate = view->windowState();
1168 if (oldstate != newstate) {
1169 Q_EMIT windowStateChanged(view);
1170 }
1171 }
1172 }
1173
1174 // We don't want to show the bubble help for the what's this text but want to
1175 // start the help viewer with the according key word.
1176 // Thus, we have to observe WhatThis events if called for a widget, use its text and
1177 // must avoid to make the bubble widget visible.
1178 if (e->type() == QEvent::WhatsThis) {
1179 if (!o->isWidgetType()) {
1180 return false;
1181 }
1182 // clicked on a widget in what's this mode
1183 auto w = static_cast<QWidget*>(o);
1184 d->whatstext = w->whatsThis();
1185 }
1186 if (e->type() == QEvent::WhatsThisClicked) {
1187 // if the widget is a top-level window
1188 if (o->isWidgetType() && qobject_cast<QWidget*>(o)->isWindow()) {
1189 // re-direct to the widget
1190 QApplication::sendEvent(this, e);
1191 }
1192 }
1193 // special treatment for menus because they directly call QWhatsThis::showText()
1194 // whereby we must be informed for which action the help should be shown
1195 if (o->inherits("QMenu") && QWhatsThis::inWhatsThisMode()) {
1196 bool whatthis = false;
1197 if (e->type() == QEvent::KeyPress) {
1198 auto ke = static_cast<QKeyEvent*>(e);
1199 if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter
1200 || ke->key() == Qt::Key_F1) {
1201 whatthis = true;
1202 }
1203 }
1204 else if (e->type() == QEvent::MouseButtonRelease) {
1205 whatthis = true;
1206 }
1207 else if (e->type() == QEvent::EnterWhatsThisMode) {
1208 whatthis = true;
1209 }
1210 if (whatthis) {
1211 QAction* cur = static_cast<QMenu*>(o)->activeAction();
1212 if (cur) {
1213 // get the help text for later usage
1214 QString s = cur->whatsThis();
1215 if (s.isEmpty()) {
1216 s = static_cast<QMenu*>(o)->whatsThis();
1217 }
1218 d->whatstext = s;
1219 }
1220 }
1221 }
1222 if (o->inherits("QWhatsThat") && e->type() == QEvent::Show) {
1223 // the bubble help should become visible which we avoid by marking the widget
1224 // that it is out of range. Instead of, we show the help viewer
1225 if (!d->whatstext.isEmpty()) {
1226 QWhatsThisClickedEvent e(d->whatstext);
1227 QApplication::sendEvent(this, &e);
1228 }
1229 static_cast<QWidget*>(o)->setAttribute(Qt::WA_OutsideWSRange);
1230 o->deleteLater();
1231 return true;
1232 }
1233 if (o->inherits("QWhatsThat") && e->type() == QEvent::Hide) {
1234 // leave what's this mode
1235 if (d->whatsthis) {
1236 d->whatsthis = false;
1237 d->whatstext.clear();
1238 qApp->removeEventFilter(this);
1239 }
1240 }
1241 }
1242
1243 return QMainWindow::eventFilter(o, e);
1244 }
1245
1246 void MainWindow::addWindow(MDIView* view)
1247 {
1248 // make workspace parent of view
1249
1250 bool isempty = d->mdiArea->subWindowList().isEmpty();
1251 auto child = qobject_cast<QMdiSubWindow*>(view->parentWidget());
1252 if (!child) {
1253 child = new QMdiSubWindow(d->mdiArea->viewport());
1254 child->setAttribute(Qt::WA_DeleteOnClose);
1255 child->setWidget(view);
1256 child->setWindowIcon(view->windowIcon());
1257 QMenu* menu = child->systemMenu();
1258
1259 // See StdCmdCloseActiveWindow (#0002631)
1260 QList<QAction*> acts = menu->actions();
1261 for (auto& act : acts) {
1262 if (act->shortcut() == QKeySequence(QKeySequence::Close)) {
1263 act->setShortcuts(QList<QKeySequence>());
1264 break;
1265 }
1266 }
1267
1268 QAction* action = menu->addAction(tr("Close All"));
1269 connect(action, &QAction::triggered, d->mdiArea, &QMdiArea::closeAllSubWindows);
1270 d->mdiArea->addSubWindow(child);
1271 }
1272
1273 connect(view, &MDIView::message, this, &MainWindow::showMessage);
1274 connect(this, &MainWindow::windowStateChanged, view, &MDIView::windowStateChanged);
1275
1276 // listen to the incoming events of the view
1277 view->installEventFilter(this);
1278
1279 // Show the new window. This will also call onWindowActivated. The very first window is shown in
1280 // maximized mode.
1281
1282 if (isempty) {
1283 view->showMaximized();
1284 }
1285 else {
1286 view->show();
1287 }
1288 }
1289
1290 /**
1291 * Removes the instance of Gui::MDIView from the main window and sends n event
1292 * to the parent widget, a QMdiSubWindow to delete itself.
1293 * If you want to avoid that the Gui::MDIView instance gets destructed too you
1294 * must reparent it afterwards, e.g. set parent to NULL.
1295 */
1296 void MainWindow::removeWindow(Gui::MDIView* view, bool close)
1297 {
1298 if (view->currentViewMode() != MDIView::Child) {
1299 FC_WARN("tried to remove an MDIView that is not currently in child mode");
1300 return;
1301 }
1302
1303 // free all connections
1304 disconnect(view, &MDIView::message, this, &MainWindow::showMessage);
1305 disconnect(this, &MainWindow::windowStateChanged, view, &MDIView::windowStateChanged);
1306
1307 view->removeEventFilter(this);
1308
1309 // check if the focus widget is a child of the view
1310 QWidget* foc = this->focusWidget();
1311 if (foc) {
1312 QWidget* par = foc->parentWidget();
1313 while (par) {
1314 if (par == view) {
1315 foc->clearFocus();
1316 break;
1317 }
1318 par = par->parentWidget();
1319 }
1320 }
1321
1322 QWidget* parent = view->parentWidget();
1323
1324 // The call of 'd->mdiArea->removeSubWindow(parent)' causes the QMdiSubWindow
1325 // to lose its parent and thus the notification in QMdiSubWindow::closeEvent
1326 // of other mdi windows to get maximized if this window is maximized will fail.
1327 // However, we must let it here otherwise deleting MDI child views directly can
1328 // cause other problems.
1329 //
1330 // The above mentioned problem can be fixed by setParent(0) which triggers a
1331 // ChildRemoved event being handled properly inside QMidArea::viewportEvent()
1332 //
1333 auto subwindow = qobject_cast<QMdiSubWindow*>(parent);
1334 if (subwindow && d->mdiArea->subWindowList().contains(subwindow)) {
1335 subwindow->setParent(nullptr);
1336 subwindow->deleteLater();
1337
1338 assert(!d->mdiArea->subWindowList().contains(subwindow));
1339 }
1340
1341 if (close) {
1342 parent->deleteLater();
1343 }
1344 updateActions();
1345 }
1346
1347 void MainWindow::tabChanged(MDIView* view)
1348 {
1349 Q_UNUSED(view)
1350 updateActions();
1351 }
1352
1353 void MainWindow::tabCloseRequested(int index)
1354 {
1355 auto tab = d->mdiArea->findChild<QTabBar*>();
1356 if (index < 0 || index >= tab->count()) {
1357 return;
1358 }
1359
1360 const QList<QMdiSubWindow*> subWindows = d->mdiArea->subWindowList();
1361 Q_ASSERT(index < subWindows.size());
1362
1363 QMdiSubWindow* subWindow = d->mdiArea->subWindowList().at(index);
1364 Q_ASSERT(subWindow);
1365 subWindow->close();
1366 updateActions();
1367 }
1368
1369 void MainWindow::setActiveSubWindow(QWidget* window)
1370 {
1371 auto mdi = qobject_cast<QMdiSubWindow*>(window);
1372 if (!mdi) {
1373 return;
1374 }
1375
1376 auto view = qobject_cast<MDIView*>(mdi->widget());
1377 if (view) {
1378 setActiveWindow(view);
1379 }
1380 else {
1381 // check for non mdiview widgets ie. the plot widget
1382 d->mdiArea->setActiveSubWindow(mdi);
1383 if (mdi->widget()) {
1384 mdi->widget()->setFocus();
1385 }
1386 }
1387 }
1388
1389 void MainWindow::setActiveWindow(MDIView* view)
1390 {
1391 if (!view) {
1392 return;
1393 }
1394
1395 // always update the focus and active sub window
1396
1397 // We need the explicit call to setFocus because it seems the focus window and the
1398 // activeSubWindow in the QMdiView can diverge when calling setActiveWindow while the MainWindow
1399 // is not currently active. In this case Qt will later set the previous focus window as active,
1400 // which will call onWindowActivated and activate the wrong window. This e.g. happens when
1401 // switching from a 3d view to a spreadsheet using the "Windows..." dialog or when docking a
1402 // spreadsheet that was in top-level/fullscreen mode. Why this could only be reproduced with a
1403 // spreadsheet remains a mystery.
1404
1405 view->setFocus();
1406
1407 auto subwindow = qobject_cast<QMdiSubWindow*>(view->parentWidget());
1408 if (subwindow) {
1409 d->mdiArea->setActiveSubWindow(subwindow);
1410 }
1411
1412 // if active view changed, notify rest of the application
1413
1414 if (view == d->activeView) {
1415 return;
1416 }
1417
1418 d->activeView = view;
1419 Application::Instance->viewActivated(view);
1420
1421 // activate/remember workbench by tab (if enabled)
1422
1423 const ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
1424 "User parameter:BaseApp/Preferences/View"
1425 );
1426 const bool saveWB = hGrp->GetBool("SaveWBbyTab", false);
1427 if (saveWB) {
1428 const QString currWb = view->property("ownWB").toString();
1429 if (!currWb.isEmpty()) {
1430 this->activateWorkbench(currWb);
1431 }
1432 else {
1433 const std::string name = WorkbenchManager::instance()->active()->name();
1434 view->setProperty("ownWB", QString::fromStdString(name));
1435 }
1436 }
1437
1438 // update actions
1439
1440 updateActions();
1441 }
1442
1443 void MainWindow::onWindowActivated(QMdiSubWindow* mdi)
1444 {
1445 if (!mdi) {
1446 setWindowTitle(QString());
1447 setWindowModified(false);
1448 return;
1449 }
1450
1451 // set active the appropriate window (it needs not to be part of mdiIds, e.g. directly after
1452 // creation)
1453
1454 auto view = dynamic_cast<MDIView*>(mdi->widget());
1455 setActiveWindow(view);
1456 }
1457
1458 void MainWindow::onWindowsMenuAboutToShow()
1459 {
1460 QList<QMdiSubWindow*> windows = d->mdiArea->subWindowList(QMdiArea::CreationOrder);
1461 QWidget* active = d->mdiArea->activeSubWindow();
1462
1463 // We search for the 'Std_WindowsMenu' command that provides the list of actions
1464 CommandManager& cMgr = Application::Instance->commandManager();
1465 Command* cmd = cMgr.getCommandByName("Std_WindowsMenu");
1466 QList<QAction*> actions = qobject_cast<ActionGroup*>(cmd->getAction())->actions();
1467
1468 // do the connection only once
1469 static bool firstShow = true;
1470 if (firstShow) {
1471 firstShow = false;
1472 QAction* last = actions.isEmpty() ? 0 : actions.last();
1473 for (const auto& action : actions) {
1474 if (action == last) {
1475 break; // this is a separator
1476 }
1477 connect(action, &QAction::triggered, d->windowMapper, qOverload<>(&QSignalMapper::map));
1478 }
1479 }
1480
1481 int numWindows = std::min<int>(actions.count() - 1, windows.count());
1482 for (int index = 0; index < numWindows; index++) {
1483 QWidget* child = windows.at(index);
1484 QAction* action = actions.at(index);
1485 QString text;
1486 QString title = child->windowTitle();
1487 int lastIndex = title.lastIndexOf(QStringLiteral("[*]"));
1488 if (lastIndex > 0) {
1489 title = title.left(lastIndex);
1490 if (child->isWindowModified()) {
1491 title = QStringLiteral("%1*").arg(title);
1492 }
1493 }
1494 if (index < 9) {
1495 text = QStringLiteral("&%1 %2").arg(index + 1).arg(title);
1496 }
1497 else {
1498 text = QStringLiteral("%1 %2").arg(index + 1).arg(title);
1499 }
1500 action->setText(text);
1501 action->setVisible(true);
1502 action->setChecked(child == active);
1503 d->windowMapper->setMapping(action, child);
1504 }
1505
1506 // if less windows than actions
1507 for (int index = numWindows; index < actions.count(); index++) {
1508 actions[index]->setVisible(false);
1509 }
1510 // show the separator
1511 if (numWindows > 0) {
1512 actions.last()->setVisible(true);
1513 }
1514 }
1515
1516 void MainWindow::onToolBarMenuAboutToShow()
1517 {
1518 auto menu = static_cast<QMenu*>(sender());
1519 menu->clear();
1520 populateToolBarMenu(menu);
1521
1522 menu->addSeparator();
1523
1524 Application::Instance->commandManager().getCommandByName("Std_ToggleToolBarLock")->addTo(menu);
1525 }
1526
1527 void MainWindow::populateToolBarMenu(QMenu* menu)
1528 {
1529 QList<QToolBar*> toolbars = this->findChildren<QToolBar*>();
1530 for (const auto& toolbar : toolbars) {
1531 if (auto parent = toolbar->parentWidget()) {
1532 if (parent == this || parent == statusBar() || parent->parentWidget() == statusBar()
1533 || parent->parentWidget() == menuBar()) {
1534 QAction* action = toolbar->toggleViewAction();
1535 action->setToolTip(tr("Toggles this toolbar"));
1536 action->setStatusTip(tr("Toggles this toolbar"));
1537 action->setWhatsThis(tr("Toggles this toolbar"));
1538 menu->addAction(action);
1539 }
1540 }
1541 }
1542 }
1543
1544 void MainWindow::onDockWindowMenuAboutToShow()
1545 {
1546 auto menu = static_cast<QMenu*>(sender());
1547 menu->clear();
1548 populateDockWindowMenu(menu);
1549 }
1550
1551 void MainWindow::populateDockWindowMenu(QMenu* menu)
1552 {
1553 QList<QDockWidget*> dock = this->findChildren<QDockWidget*>();
1554 for (auto& it : dock) {
1555 QAction* action = it->toggleViewAction();
1556 action->setToolTip(tr("Toggles this dockable window"));
1557 action->setStatusTip(tr("Toggles this dockable window"));
1558 action->setWhatsThis(tr("Toggles this dockable window"));
1559 menu->addAction(action);
1560 }
1561 }
1562
1563 void MainWindow::setDockWindowMenu(QMenu* menu)
1564 {
1565 connect(menu, &QMenu::aboutToShow, this, &MainWindow::onDockWindowMenuAboutToShow);
1566 }
1567
1568 void MainWindow::setToolBarMenu(QMenu* menu)
1569 {
1570 connect(menu, &QMenu::aboutToShow, this, &MainWindow::onToolBarMenuAboutToShow);
1571 }
1572
1573 void MainWindow::setWindowsMenu(QMenu* menu)
1574 {
1575 connect(menu, &QMenu::aboutToShow, this, &MainWindow::onWindowsMenuAboutToShow);
1576 }
1577
1578 QList<QWidget*> MainWindow::windows(QMdiArea::WindowOrder order) const
1579 {
1580 QList<QWidget*> mdis;
1581 QList<QMdiSubWindow*> wnds = d->mdiArea->subWindowList(order);
1582 for (const auto& wnd : wnds) {
1583 mdis << wnd->widget();
1584 }
1585 return mdis;
1586 }
1587
1588 MDIView* MainWindow::activeWindow() const
1589 {
1590 // each activated window notifies this main window when it is activated
1591 return d->activeView;
1592 }
1593
1594 void MainWindow::closeEvent(QCloseEvent* e)
1595 {
1596 Application::Instance->tryClose(e);
1597 if (e->isAccepted()) {
1598 // Send close event to all non-modal dialogs
1599 QList<QDialog*> dialogs = this->findChildren<QDialog*>();
1600 // It is possible that closing a dialog internally closes further dialogs. Thus,
1601 // we have to check the pointer before.
1602 QVector<QPointer<QDialog>> dialogs_ptr;
1603 for (const auto& dialog : dialogs) {
1604 dialogs_ptr.append(dialog);
1605 }
1606 for (auto& it : dialogs_ptr) {
1607 if (!it.isNull()) {
1608 it->close();
1609 }
1610 }
1611 QList<MDIView*> mdis = this->findChildren<MDIView*>();
1612 // Force to close any remaining (passive) MDI child views
1613 for (auto& mdi : mdis) {
1614 mdi->hide();
1615 mdi->deleteLater();
1616 }
1617
1618 if (Workbench* wb = WorkbenchManager::instance()->active()) {
1619 wb->removeTaskWatcher();
1620 }
1621
1622 Q_EMIT mainWindowClosed();
1623 d->activityTimer->stop();
1624
1625 // https://forum.freecad.org/viewtopic.php?f=8&t=67748
1626 // When the session manager jumps in it can happen that the closeEvent()
1627 // function is triggered twice and for the second call the main window might be
1628 // invisible. In this case the window settings shouldn't be saved.
1629 if (isVisible()) {
1630 saveWindowSettings();
1631 }
1632
1633 delete d->assistant;
1634 d->assistant = nullptr;
1635
1636 // See createMimeDataFromSelection
1637 QVariant prop = this->property("x-documentobject-file");
1638 if (!prop.isNull()) {
1639 Base::FileInfo fi((const char*)prop.toByteArray());
1640 if (fi.exists()) {
1641 fi.deleteFile();
1642 }
1643 }
1644
1645 if (this->property("QuitOnClosed").isValid()) {
1646 QApplication::closeAllWindows();
1647 qApp->processEvents(); // flush all pending deferredDelete events
1648 qApp->quit(); // stop the event loop
1649 }
1650 }
1651 }
1652
1653 void MainWindow::showEvent(QShowEvent* e)
1654 {
1655 std::clog << "Show main window" << std::endl;
1656 QMainWindow::showEvent(e);
1657 }
1658
1659 void MainWindow::hideEvent(QHideEvent* e)
1660 {
1661 std::clog << "Hide main window" << std::endl;
1662 QMainWindow::hideEvent(e);
1663 }
1664
1665 void MainWindow::processMessages(const QList<QString>& msg)
1666 {
1667 // handle all the messages to open files
1668 try {
1669 WaitCursor wc;
1670 std::list<std::string> files;
1671 QString action = QStringLiteral("OpenFile:");
1672 for (const auto& it : msg) {
1673 if (it.startsWith(action)) {
1674 files.emplace_back(it.mid(action.size()).toStdString());
1675 }
1676 }
1677 files = App::Application::processFiles(files);
1678 for (const auto& file : files) {
1679 QString filename = QString::fromUtf8(file.c_str(), file.size());
1680 FileDialog::setWorkingDirectory(filename);
1681 }
1682 }
1683 catch (const Base::SystemExitException&) {
1684 }
1685 }
1686
1687 void MainWindow::delayedStartup()
1688 {
1689 // automatically run unit tests in Gui
1690 if (App::Application::Config()["RunMode"] == "Internal") {
1691 QTimer::singleShot(1000, this, [] {
1692 try {
1693 string command = "import sys\n"
1694 "import FreeCAD\n"
1695 "import QtUnitGui\n\n"
1696 "testCase = FreeCAD.ConfigGet(\"TestCase\")\n"
1697 "QtUnitGui.addTest(testCase)\n"
1698 "QtUnitGui.setTest(testCase)\n"
1699 "result = QtUnitGui.runTest()\n"
1700 "sys.stdout.flush()\n";
1701 if (App::Application::Config()["ExitTests"] == "yes") {
1702 command += "sys.exit(0 if result else 1)";
1703 }
1704 Base::Interpreter().runString(command.c_str());
1705 }
1706 catch (const Base::SystemExitException&) {
1707 throw;
1708 }
1709 catch (const Base::Exception& e) {
1710 e.reportException();
1711 }
1712 });
1713 return;
1714 }
1715
1716 // processing all command line files
1717 try {
1718 std::list<std::string> files = App::Application::getCmdLineFiles();
1719 files = App::Application::processFiles(files);
1720 for (const auto& file : files) {
1721 QString filename = QString::fromUtf8(file.c_str(), file.size());
1722 FileDialog::setWorkingDirectory(filename);
1723 }
1724 }
1725 catch (const Base::SystemExitException&) {
1726 throw;
1727 }
1728
1729 if (Application::hiddenMainWindow()) {
1730 QApplication::quit();
1731 return;
1732 }
1733
1734 // TODO: Check for deprecated settings
1735 Application::Instance->checkForDeprecatedSettings();
1736
1737 // Create new document?
1738 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("Document");
1739 if (hGrp->GetBool("CreateNewDoc", false)) {
1740 if (App::GetApplication().getDocuments().empty()) {
1741 Application::Instance->commandManager().runCommandByName("Std_New");
1742 // This document is autoCreated
1743 App::Document* newDoc = App::GetApplication().getActiveDocument();
1744 newDoc->setAutoCreated(true);
1745 }
1746 }
1747
1748 if (hGrp->GetBool("RecoveryEnabled", true)) {
1749 Application::Instance->checkForPreviousCrashes();
1750 }
1751
1752 if (SafeMode::SafeModeEnabled()) {
1753 auto safeModePopup = QMessageBox(
1754 QMessageBox::Information,
1755 tr("Safe mode enabled"),
1756 tr("FreeCAD is now running in safe mode."),
1757 QMessageBox::Ok
1758 );
1759 safeModePopup.setInformativeText(
1760 tr("Safe mode temporarily disables your configurations and addons."
1761 " Restart the application to exit safe mode.")
1762 );
1763 safeModePopup.exec();
1764 }
1765 }
1766
1767 void MainWindow::appendRecentFile(const QString& filename)
1768 {
1769 auto recent = this->findChild<RecentFilesAction*>(QStringLiteral("recentFiles"));
1770 if (recent) {
1771 recent->appendFile(filename);
1772 }
1773 }
1774
1775 void MainWindow::appendRecentMacro(const QString& filename)
1776 {
1777 auto recent = this->findChild<RecentMacrosAction*>(QStringLiteral("recentMacros"));
1778 if (recent) {
1779 recent->appendFile(filename);
1780 }
1781 }
1782
1783 void MainWindow::updateActions(bool delay)
1784 {
1785 // make it safe to call before the main window is actually created
1786 if (!instance) {
1787 return;
1788 }
1789
1790 if (!d->activityTimer->isActive()) {
1791 // If for some reason updateActions() is called from a worker thread
1792 // we must avoid to directly call QTimer::start() because this leaves
1793 // the whole application in a weird state
1794 if (d->activityTimer->thread() != QThread::currentThread()) {
1795 QMetaObject::invokeMethod(d->activityTimer, "start", Qt::QueuedConnection, Q_ARG(int, 150));
1796 }
1797 else {
1798 d->activityTimer->start(150);
1799 }
1800 }
1801 else if (delay) {
1802 if (!d->actionUpdateDelay) {
1803 d->actionUpdateDelay = 1;
1804 }
1805 }
1806 else {
1807 d->actionUpdateDelay = -1;
1808 }
1809 }
1810
1811 void MainWindow::_updateActions()
1812 {
1813 if (isVisible() && d->actionUpdateDelay <= 0) {
1814 FC_LOG("update actions");
1815 d->activityTimer->stop();
1816 Application::Instance->commandManager().testActive();
1817 }
1818
1819 d->actionUpdateDelay = 0;
1820
1821 if (auto view = activeWindow()) {
1822 setWindowTitle(view->buildWindowTitle());
1823 if (auto document = view->getGuiDocument()) {
1824 setWindowModified(document->isModified());
1825 }
1826 }
1827 }
1828
1829 void MainWindow::updateEditorActions()
1830 {
1831 Command* cmd = nullptr;
1832 CommandManager& mgr = Application::Instance->commandManager();
1833
1834 cmd = mgr.getCommandByName("Std_Cut");
1835 if (cmd) {
1836 cmd->testActive();
1837 }
1838
1839 cmd = mgr.getCommandByName("Std_Copy");
1840 if (cmd) {
1841 cmd->testActive();
1842 }
1843
1844 cmd = mgr.getCommandByName("Std_Paste");
1845 if (cmd) {
1846 cmd->testActive();
1847 }
1848
1849 cmd = mgr.getCommandByName("Std_Undo");
1850 if (cmd) {
1851 cmd->testActive();
1852 }
1853
1854 cmd = mgr.getCommandByName("Std_Redo");
1855 if (cmd) {
1856 cmd->testActive();
1857 }
1858 }
1859
1860 void MainWindow::switchToTopLevelMode()
1861 {
1862 QList<QDockWidget*> dw = this->findChildren<QDockWidget*>();
1863 for (auto& it : dw) {
1864 it->setParent(nullptr, Qt::Window);
1865 it->show();
1866 }
1867 QList<QWidget*> mdi = getMainWindow()->windows();
1868 for (auto& it : mdi) {
1869 it->setParent(nullptr, Qt::Window);
1870 it->show();
1871 }
1872 }
1873
1874 void MainWindow::switchToDockedMode()
1875 {
1876 // Search for all top-level MDI views
1877 QWidgetList toplevel = QApplication::topLevelWidgets();
1878 for (const auto& it : toplevel) {
1879 auto view = dynamic_cast<MDIView*>(it);
1880 if (view) {
1881 view->setCurrentViewMode(MDIView::Child);
1882 }
1883 }
1884 }
1885
1886 void MainWindow::loadWindowSettings()
1887 {
1888 QString vendor = QString::fromUtf8(App::Application::Config()["ExeVendor"].c_str());
1889 QString application = QString::fromUtf8(App::Application::Config()["ExeName"].c_str());
1890 int major = (QT_VERSION >> 0x10) & 0xff;
1891 int minor = (QT_VERSION >> 0x08) & 0xff;
1892 QString qtver = QStringLiteral("Qt%1.%2").arg(major).arg(minor);
1893 QSettings config(vendor, application);
1894
1895 // Put window in center of screen position by default (e.g. first run and safe-mode)
1896 // Note that pos refers to frameGeometry(), while size refers to geometry()
1897 QSize frameSizeDiff = frameSize() - size();
1898 QRect rect = QApplication::primaryScreen()->availableGeometry();
1899 QSize winSize
1900 = (QSize(1800, 1000).boundedTo(rect.size()) - frameSizeDiff).expandedTo(minimumSize());
1901 QPoint winPos = rect.center() - QRect({}, (winSize + frameSizeDiff) / 2).bottomRight();
1902
1903 // Read stored values from config (deprecated, not written since 1.0rc1)
1904 config.beginGroup(qtver);
1905 winPos = config.value(QStringLiteral("Position"), winPos).toPoint();
1906 winSize = config.value(QStringLiteral("Size"), winSize).toSize();
1907 bool max = config.value(QStringLiteral("Maximized"), false).toBool();
1908 bool showStatusBar = config.value(QStringLiteral("StatusBar"), true).toBool();
1909 QByteArray windowState = config.value(QStringLiteral("MainWindowState")).toByteArray();
1910 config.endGroup();
1911
1912 // Read stored values from user parameters
1913 std::istringstream iss(d->hGrp->GetASCII("Geometry"));
1914 if (int x, y, w, h; iss >> x >> y >> w >> h) {
1915 winPos = QPoint(x, y);
1916 winSize = QSize(w, h);
1917 }
1918 max = d->hGrp->GetBool("Maximized", max);
1919 showStatusBar = d->hGrp->GetBool("StatusBar", showStatusBar);
1920 if (auto wstate = d->hGrp->GetASCII("MainWindowState"); !wstate.empty()) {
1921 windowState = QByteArray::fromBase64(wstate.c_str());
1922 }
1923
1924 winSize = winSize.expandedTo(minimumSize());
1925
1926 // Check that no part of window outside all screens
1927 QRect winGeometry = QRect(winPos, winSize + frameSizeDiff);
1928 const auto screens = QApplication::screens();
1929 auto invisible = QPolygon(winGeometry);
1930 for (auto s : screens) {
1931 invisible = invisible.subtracted(s->geometry().adjusted(-10, -10, 10, 10));
1932 }
1933 if (!invisible.empty()) {
1934 // If not, move it inside the most overlapped or closest screen
1935 // Union of screens are not considered, as it e.g. may have holes in general case
1936 QRect screen {};
1937 for (int screenArea = 0; auto s : screens) {
1938 auto overlap = s->availableGeometry().intersected(winGeometry);
1939 int overlapArea = overlap.width() * overlap.height();
1940 if (overlapArea > screenArea) {
1941 screen = s->availableGeometry();
1942 screenArea = overlapArea;
1943 }
1944 }
1945 if (screen.isEmpty()) {
1946 for (int screenDist = -1; auto s : screens) {
1947 auto dist = (winGeometry.center() - s->availableGeometry().center()).manhattanLength();
1948 if (screenDist == -1 || dist < screenDist) {
1949 screen = s->availableGeometry();
1950 screenDist = dist;
1951 }
1952 }
1953 }
1954 winSize = winSize.boundedTo(screen.size() - frameSizeDiff).expandedTo(minimumSize());
1955 winGeometry = QRect(winPos, winSize + frameSizeDiff);
1956 winPos.setX(qMax(qMin(winPos.x(), screen.right() - winGeometry.width()), screen.x()));
1957 winPos.setY(qMax(qMin(winPos.y(), screen.bottom() - winGeometry.height()), screen.y()));
1958 }
1959
1960 // Scale before move reducing, or vice versa, so a dpi change wont make window to be moved
1961 resize(winSize.boundedTo(size()));
1962 move(winPos);
1963 resize(winSize);
1964
1965 Base::StateLocker guard(d->_restoring);
1966
1967 d->restoreWindowState(windowState);
1968 std::clog << "Main window restored" << std::endl;
1969
1970 max ? showMaximized() : show();
1971
1972 // make menus and tooltips usable in fullscreen under Windows, see issue #7563
1973 #if defined(Q_OS_WIN)
1974 # if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1975 if (QWindow* win = this->windowHandle()) {
1976 QWindowsWindowFunctions::setHasBorderInFullScreen(win, true);
1977 }
1978 # else
1979 using namespace QNativeInterface::Private;
1980 if (auto* windowsWindow = dynamic_cast<QWindowsWindow*>(this->windowHandle())) {
1981 windowsWindow->setHasBorderInFullScreen(true);
1982 }
1983 # endif
1984 #endif
1985
1986 statusBar()->setVisible(showStatusBar);
1987
1988 setAttribute(Qt::WA_AlwaysShowToolTips);
1989
1990 ToolBarManager::getInstance()->restoreState();
1991 std::clog << "Toolbars restored" << std::endl;
1992
1993 OverlayManager::instance()->restore();
1994 }
1995
1996 bool MainWindow::isRestoringWindowState() const
1997 {
1998 return d->_restoring;
1999 }
2000
2001 void MainWindowP::restoreWindowState(const QByteArray& windowState)
2002 {
2003 if (windowState.isEmpty()) {
2004 return;
2005 }
2006
2007 Base::StateLocker guard(_restoring);
2008
2009 // tmp. disable the report window to suppress some bothering warnings
2010 if (Base::Console().isMsgTypeEnabled("ReportOutput", Base::ConsoleSingleton::MsgType_Wrn)) {
2011 Base::Console().setEnabledMsgType("ReportOutput", Base::ConsoleSingleton::MsgType_Wrn, false);
2012 getMainWindow()->restoreState(windowState);
2013 Base::Console().setEnabledMsgType("ReportOutput", Base::ConsoleSingleton::MsgType_Wrn, true);
2014 }
2015 else {
2016 getMainWindow()->restoreState(windowState);
2017 }
2018
2019 Base::ConnectionBlocker block(connParam);
2020 // as a notification for user code on window state restore
2021 hGrp->SetBool("WindowStateRestored", !hGrp->GetBool("WindowStateRestored", false));
2022 }
2023
2024 void MainWindow::saveWindowSettings(bool canDelay)
2025 {
2026 if (isRestoringWindowState()) {
2027 return;
2028 }
2029
2030 if (canDelay) {
2031 d->saveStateTimer.start(100);
2032 return;
2033 }
2034
2035 Base::ConnectionBlocker block(d->connParam);
2036 d->hGrp->SetBool("Maximized", this->isMaximized());
2037 d->hGrp->SetBool("StatusBar", this->statusBar()->isVisible());
2038 d->hGrp->SetASCII("MainWindowState", this->saveState().toBase64().constData());
2039
2040 std::ostringstream ss;
2041 QRect rect(this->pos(), this->size());
2042 ss << rect.left() << " " << rect.top() << " " << rect.width() << " " << rect.height();
2043 d->hGrp->SetASCII("Geometry", ss.str().c_str());
2044
2045 DockWindowManager::instance()->saveState();
2046 OverlayManager::instance()->save();
2047 ToolBarManager::getInstance()->saveState();
2048 }
2049
2050 void MainWindow::startSplasher()
2051 {
2052 // startup splasher
2053 // when running in verbose mode no splasher
2054 if (!(App::Application::Config()["Verbose"] == "Strict")
2055 && (App::Application::Config()["RunMode"] == "Gui")) {
2056 ParameterGrp::handle hGrp = App::GetApplication()
2057 .GetUserParameter()
2058 .GetGroup("BaseApp")
2059 ->GetGroup("Preferences")
2060 ->GetGroup("General");
2061 // first search for an external image file
2062 if (hGrp->GetBool("ShowSplasher", true)) {
2063 d->splashscreen = new SplashScreen(SplashScreen::splashImage());
2064
2065 if (!hGrp->GetBool("ShowSplasherMessages", false)) {
2066 d->splashscreen->setShowMessages(false);
2067 }
2068
2069 d->splashscreen->show();
2070 }
2071 else {
2072 d->splashscreen = nullptr;
2073 }
2074 }
2075 }
2076
2077 void MainWindow::stopSplasher()
2078 {
2079 if (d->splashscreen) {
2080 d->splashscreen->finish(this);
2081 delete d->splashscreen;
2082 d->splashscreen = nullptr;
2083 }
2084 }
2085
2086 /**
2087 * Drops the event \a e and tries to open the files.
2088 */
2089 void MainWindow::dropEvent(QDropEvent* e)
2090 {
2091 const QMimeData* data = e->mimeData();
2092 if (data->hasUrls()) {
2093 // load the files into the active document if there is one, otherwise let create one
2094 loadUrls(App::GetApplication().getActiveDocument(), data->urls());
2095 }
2096 else {
2097 QMainWindow::dropEvent(e);
2098 }
2099 }
2100
2101 void MainWindow::dragEnterEvent(QDragEnterEvent* e)
2102 {
2103 // Here we must allow uri drafs and check them in dropEvent
2104 const QMimeData* data = e->mimeData();
2105 if (data->hasUrls()) {
2106 e->accept();
2107 }
2108 else {
2109 e->ignore();
2110 }
2111 }
2112
2113 static QLatin1String _MimeDocObj("application/x-documentobject");
2114 static QLatin1String _MimeDocObjX("application/x-documentobject-x");
2115 static QLatin1String _MimeDocObjFile("application/x-documentobject-file");
2116 static QLatin1String _MimeDocObjXFile("application/x-documentobject-x-file");
2117
2118 QMimeData* MainWindow::createMimeDataFromSelection() const
2119 {
2120 std::vector<App::DocumentObject*> sel;
2121 std::set<App::DocumentObject*> objSet;
2122 for (auto& s : Selection().getCompleteSelection()) {
2123 if (s.pObject && s.pObject->isAttachedToDocument() && objSet.insert(s.pObject).second) {
2124 sel.push_back(s.pObject);
2125 }
2126 }
2127 if (sel.empty()) {
2128 return nullptr;
2129 }
2130
2131 auto all = App::Document::getDependencyList(sel);
2132 if (all.size() > sel.size()) {
2133 DlgObjectSelection dlg(sel, getMainWindow());
2134 if (dlg.exec() != QDialog::Accepted) {
2135 return nullptr;
2136 }
2137 sel = dlg.getSelections();
2138 if (sel.empty()) {
2139 return nullptr;
2140 }
2141 }
2142
2143 std::vector<App::Document*> unsaved;
2144 bool hasXLink = App::PropertyXLink::hasXLink(sel, &unsaved);
2145 if (!unsaved.empty()) {
2146 QMessageBox::critical(
2147 getMainWindow(),
2148 tr("Unsaved document"),
2149 tr("The exported object contains external link. Save the document"
2150 "at least once before exporting.")
2151 );
2152 return nullptr;
2153 }
2154
2155 unsigned int memsize = 1000; // ~ for the meta-information
2156 for (const auto& it : sel) {
2157 memsize += it->getMemSize();
2158 }
2159
2160 // if less than ~10 MB
2161 bool use_buffer = (memsize < 0xA00000);
2162 QByteArray res;
2163 if (use_buffer) {
2164 try {
2165 res.reserve(memsize);
2166 }
2167 catch (const std::bad_alloc&) {
2168 use_buffer = false;
2169 }
2170 }
2171
2172 WaitCursor wc;
2173 QString mime;
2174 if (use_buffer) {
2175 mime = hasXLink ? _MimeDocObjX : _MimeDocObj;
2176 Base::ByteArrayOStreambuf buf(res);
2177 std::ostream str(&buf);
2178 // need this instance to call MergeDocuments::Save()
2179 App::Document* doc = sel.front()->getDocument();
2180 MergeDocuments mimeView(doc);
2181 doc->exportObjects(sel, str);
2182 }
2183 else {
2184 mime = hasXLink ? _MimeDocObjXFile : _MimeDocObjFile;
2185 static Base::FileInfo fi(App::Application::getTempFileName());
2186 Base::ofstream str(fi, std::ios::out | std::ios::binary);
2187 // need this instance to call MergeDocuments::Save()
2188 App::Document* doc = sel.front()->getDocument();
2189 MergeDocuments mimeView(doc);
2190 doc->exportObjects(sel, str);
2191 str.close();
2192 res = fi.filePath().c_str();
2193
2194 // store the path name as a custom property and
2195 // delete this file when closing the application
2196 const_cast<MainWindow*>(this)->setProperty("x-documentobject-file", res);
2197 }
2198
2199 auto mimeData = new QMimeData();
2200 mimeData->setData(mime, res);
2201 return mimeData;
2202 }
2203
2204 bool MainWindow::canInsertFromMimeData(const QMimeData* source) const
2205 {
2206 if (!source) {
2207 return false;
2208 }
2209 return source->hasUrls() || source->hasImage() || source->hasFormat(_MimeDocObj)
2210 || source->hasFormat(_MimeDocObjX) || source->hasFormat(_MimeDocObjFile)
2211 || source->hasFormat(_MimeDocObjXFile);
2212 }
2213
2214 void MainWindow::insertFromMimeData(const QMimeData* mimeData)
2215 {
2216 if (!mimeData) {
2217 return;
2218 }
2219
2220 if (mimeData->hasImage()) {
2221 App::Document* doc = App::GetApplication().getActiveDocument();
2222 if (!doc) {
2223 doc = App::GetApplication().newDocument();
2224 }
2225
2226 if (!doc) {
2227 return;
2228 }
2229
2230 QImage image = qvariant_cast<QImage>(mimeData->imageData());
2231 if (image.isNull()) {
2232 return;
2233 }
2234
2235 std::string tempPath = App::Application::getTempFileName("png");
2236 if (image.save(QString::fromStdString(tempPath), "PNG")) {
2237 WaitCursor wc;
2238 doc->openTransaction("Paste image");
2239
2240 try {
2241 std::string objName = doc->getUniqueObjectName("ImagePlane");
2242 App::DocumentObject* obj = doc->addObject("Image::ImagePlane", objName.c_str());
2243 if (obj) {
2244 obj->Label.setValue("PastedImage");
2245 static_cast<Image::ImagePlane*>(obj)->ImageFile.setValue(tempPath.c_str());
2246 doc->recompute();
2247 }
2248 }
2249 catch (const Base::Exception& e) {
2250 doc->abortTransaction();
2251 e.reportException();
2252 return;
2253 }
2254
2255 doc->commitTransaction();
2256 }
2257 else {
2258 Base::Console().error(
2259 "Failed to save pasted image to temporary file: %s\n",
2260 tempPath.c_str()
2261 );
2262 }
2263 return;
2264 }
2265
2266 bool fromDoc = false;
2267 bool hasXLink = false;
2268 QString format;
2269 if (mimeData->hasFormat(_MimeDocObj)) {
2270 format = _MimeDocObj;
2271 }
2272 else if (mimeData->hasFormat(_MimeDocObjX)) {
2273 format = _MimeDocObjX;
2274 hasXLink = true;
2275 }
2276 else if (mimeData->hasFormat(_MimeDocObjFile)) {
2277 format = _MimeDocObjFile;
2278 fromDoc = true;
2279 }
2280 else if (mimeData->hasFormat(_MimeDocObjXFile)) {
2281 format = _MimeDocObjXFile;
2282 fromDoc = true;
2283 hasXLink = true;
2284 }
2285 else {
2286 if (mimeData->hasUrls()) {
2287 loadUrls(App::GetApplication().getActiveDocument(), mimeData->urls());
2288 }
2289 return;
2290 }
2291
2292 App::Document* doc = App::GetApplication().getActiveDocument();
2293 if (!doc) {
2294 doc = App::GetApplication().newDocument();
2295 }
2296
2297 if (hasXLink && !doc->isSaved()) {
2298 int ret = QMessageBox::question(
2299 getMainWindow(),
2300 tr("Unsaved document"),
2301 tr("To link to external objects, the document must be saved at least once.\n"
2302 "Save the document now?"),
2303 QMessageBox::Yes,
2304 QMessageBox::No
2305 );
2306 if (ret != QMessageBox::Yes || !Application::Instance->getDocument(doc)->saveAs()) {
2307 return;
2308 }
2309 }
2310 if (!fromDoc) {
2311 QByteArray res = mimeData->data(format);
2312
2313 doc->openTransaction("Paste");
2314 Base::ByteArrayIStreambuf buf(res);
2315 std::istream in(nullptr);
2316 in.rdbuf(&buf);
2317 MergeDocuments mimeView(doc);
2318 std::vector<App::DocumentObject*> newObj = mimeView.importObjects(in);
2319 std::vector<App::DocumentObjectGroup*> grp
2320 = Gui::Selection().getObjectsOfType<App::DocumentObjectGroup>();
2321 if (grp.size() == 1) {
2322 Gui::Document* gui = Application::Instance->getDocument(doc);
2323 if (gui) {
2324 gui->addRootObjectsToGroup(newObj, grp.front());
2325 }
2326 }
2327 doc->commitTransaction();
2328 }
2329 else {
2330 QByteArray res = mimeData->data(format);
2331
2332 doc->openTransaction("Paste");
2333 Base::FileInfo fi((const char*)res);
2334 Base::ifstream str(fi, std::ios::in | std::ios::binary);
2335 MergeDocuments mimeView(doc);
2336 std::vector<App::DocumentObject*> newObj = mimeView.importObjects(str);
2337 str.close();
2338 std::vector<App::DocumentObjectGroup*> grp
2339 = Gui::Selection().getObjectsOfType<App::DocumentObjectGroup>();
2340 if (grp.size() == 1) {
2341 Gui::Document* gui = Application::Instance->getDocument(doc);
2342 if (gui) {
2343 gui->addRootObjectsToGroup(newObj, grp.front());
2344 }
2345 }
2346 doc->commitTransaction();
2347 }
2348 }
2349
2350 void MainWindow::setUrlHandler(const QString& scheme, Gui::UrlHandler* handler)
2351 {
2352 d->urlHandler[scheme] = handler;
2353 }
2354
2355 void MainWindow::unsetUrlHandler(const QString& scheme)
2356 {
2357 d->urlHandler.remove(scheme);
2358 }
2359
2360 void MainWindow::loadUrls(App::Document* doc, const QList<QUrl>& urls)
2361 {
2362 QStringList files;
2363 for (const auto& it : urls) {
2364 QMap<QString, QPointer<UrlHandler>>::iterator jt = d->urlHandler.find(it.scheme());
2365 if (jt != d->urlHandler.end() && !jt->isNull()) {
2366 // delegate the loading to the url handler
2367 (*jt)->openUrl(doc, it);
2368 continue;
2369 }
2370
2371 QFileInfo info(it.toLocalFile());
2372 if (info.exists() && info.isFile()) {
2373 if (info.isSymLink()) {
2374 info.setFile(info.symLinkTarget());
2375 }
2376 std::vector<std::string> module = App::GetApplication().getImportModules(
2377 info.completeSuffix().toStdString()
2378 );
2379 if (module.empty()) {
2380 module = App::GetApplication().getImportModules(info.suffix().toStdString());
2381 }
2382 if (!module.empty()) {
2383 // ok, we support files with this extension
2384 files << info.absoluteFilePath();
2385 }
2386 else {
2387 Base::Console().message(
2388 "No support to load file '%s'\n",
2389 (const char*)info.absoluteFilePath().toUtf8()
2390 );
2391 }
2392 }
2393 else if (it.scheme().toLower() == QLatin1String("http")) {
2394 Gui::Dialog::DownloadManager* dm = Gui::Dialog::DownloadManager::getInstance();
2395 dm->download(dm->redirectUrl(it));
2396 }
2397
2398 else if (it.scheme().toLower() == QLatin1String("https")) {
2399 QUrl url = it;
2400 QUrlQuery urlq(url);
2401 if (urlq.hasQueryItem(QLatin1String("sid"))) {
2402 urlq.removeAllQueryItems(QLatin1String("sid"));
2403 url.setQuery(urlq);
2404 url.setScheme(QLatin1String("http"));
2405 }
2406 Gui::Dialog::DownloadManager* dm = Gui::Dialog::DownloadManager::getInstance();
2407 dm->download(dm->redirectUrl(url));
2408 }
2409
2410 else if (it.scheme().toLower() == QLatin1String("ftp")) {
2411 Gui::Dialog::DownloadManager::getInstance()->download(it);
2412 }
2413 }
2414
2415 QByteArray docName = doc ? QByteArray(doc->getName())
2416 : qApp->translate("StdCmdNew", "Unnamed").toUtf8();
2417 ModuleIO::importFiles(files, docName);
2418 }
2419
2420 void MainWindow::changeEvent(QEvent* e)
2421 {
2422 if (e->type() == QEvent::LanguageChange) {
2423 d->sizeLabel->setText(tr("Dimension"));
2424
2425 CommandManager& rclMan = Application::Instance->commandManager();
2426 std::vector<Command*> cmd = rclMan.getAllCommands();
2427 for (auto& it : cmd) {
2428 it->languageChange();
2429 }
2430
2431 // reload current workbench to retranslate all actions and window titles
2432 Workbench* wb = WorkbenchManager::instance()->active();
2433 if (wb) {
2434 wb->retranslate();
2435 }
2436 }
2437 else if (e->type() == QEvent::ActivationChange) {
2438 if (isActiveWindow()) {
2439 QMdiSubWindow* mdi = d->mdiArea->currentSubWindow();
2440 setActiveSubWindow(mdi);
2441 }
2442 }
2443 else {
2444 QMainWindow::changeEvent(e);
2445 }
2446 }
2447
2448 void MainWindow::clearStatus()
2449 {
2450 d->currentStatusType = 100;
2451 statusBar()->setStyleSheet(QStringLiteral("#statusBar{}"));
2452 }
2453
2454 void MainWindow::statusMessageChanged()
2455 {
2456 if (d->currentStatusType < 0) {
2457 d->currentStatusType = -d->currentStatusType;
2458 }
2459 else {
2460 // here probably means the status bar message is changed by QMainWindow
2461 // internals, e.g. for displaying tooltip and stuff. Set reset what
2462 // we've changed.
2463 d->statusTimer->stop();
2464 clearStatus();
2465 }
2466 }
2467
2468 void MainWindow::showMessage(const QString& message, int timeout)
2469 {
2470 if (QApplication::instance()->thread() != QThread::currentThread()) {
2471 QApplication::postEvent(this, new CustomMessageEvent(MainWindow::Tmp, message, timeout));
2472 return;
2473 }
2474 d->actionLabel->setText(message.simplified());
2475 if (timeout) {
2476 d->actionTimer->setSingleShot(true);
2477 d->actionTimer->start(timeout);
2478 }
2479 else {
2480 d->actionTimer->stop();
2481 }
2482 }
2483
2484 void MainWindow::setRightSideMessage(const QString& message)
2485 {
2486 d->rightSideLabel->setText(message.simplified());
2487 }
2488
2489 bool MainWindow::isRightSideMessageVisible() const
2490 {
2491 return d->rightSideLabel->isVisible();
2492 }
2493
2494 void MainWindow::showStatus(int type, const QString& message)
2495 {
2496 if (QApplication::instance()->thread() != QThread::currentThread()) {
2497 QApplication::postEvent(this, new CustomMessageEvent(type, message));
2498 return;
2499 }
2500
2501 if (d->currentStatusType < type) {
2502 return;
2503 }
2504
2505 d->statusTimer->setSingleShot(true);
2506 // TODO: hardcode?
2507 int timeout = 5000;
2508 d->statusTimer->start(timeout);
2509
2510 QFontMetrics fm(statusBar()->font());
2511 QString msg = fm.elidedText(message, Qt::ElideMiddle, this->d->actionLabel->width());
2512 switch (type) {
2513 case MainWindow::Err:
2514 statusBar()->setStyleSheet(d->status->err);
2515 break;
2516 case MainWindow::Wrn:
2517 statusBar()->setStyleSheet(d->status->wrn);
2518 break;
2519 case MainWindow::Pane:
2520 statusBar()->setStyleSheet(QStringLiteral("#statusBar{}"));
2521 break;
2522 default:
2523 statusBar()->setStyleSheet(d->status->msg);
2524 break;
2525 }
2526 d->currentStatusType = -type;
2527 statusBar()->showMessage(msg.simplified(), timeout);
2528 }
2529
2530 void MainWindow::showHints(const std::list<InputHint>& hints)
2531 {
2532 d->hintLabel->showHints(hints);
2533 }
2534
2535 void MainWindow::hideHints()
2536 {
2537 d->hintLabel->clearHints();
2538 }
2539
2540 // set text to the pane
2541 void MainWindow::setPaneText(int i, QString text)
2542 {
2543 if (i == 1) {
2544 showStatus(MainWindow::Pane, text);
2545 }
2546 else if (i == 2) {
2547 d->sizeLabel->setText(text);
2548 }
2549 }
2550
2551
2552 void MainWindow::setUserSchema(int userSchema)
2553 {
2554 d->sizeLabel->setUserSchema(userSchema);
2555 }
2556
2557
2558 void MainWindow::customEvent(QEvent* e)
2559 {
2560 if (e->type() == QEvent::User) {
2561 auto ce = static_cast<Gui::CustomMessageEvent*>(e);
2562 QString msg = ce->message();
2563 switch (ce->type()) {
2564 case MainWindow::Log: {
2565 if (msg.startsWith(QLatin1String("#Inventor V2.1 ascii "))) {
2566 Gui::Document* d = Application::Instance->activeDocument();
2567 if (d) {
2568 auto view = new ViewProviderExtern();
2569 try {
2570 view->setModeByString("1", msg.toLatin1().constData());
2571 d->setAnnotationViewProvider("Vdbg", view);
2572 }
2573 catch (...) {
2574 delete view;
2575 }
2576 }
2577 }
2578 break;
2579 }
2580 case MainWindow::Tmp: {
2581 showMessage(msg, ce->timeout());
2582 break;
2583 }
2584 default:
2585 showStatus(ce->type(), msg);
2586 }
2587 }
2588 else if (e->type() == ActionStyleEvent::EventType) {
2589 QList<TaskView::TaskView*> tasks = findChildren<TaskView::TaskView*>();
2590 if (static_cast<ActionStyleEvent*>(e)->getType() == ActionStyleEvent::Clear) {
2591 for (auto& task : tasks) {
2592 task->clearActionStyle();
2593 }
2594 }
2595 else {
2596 for (auto& task : tasks) {
2597 task->restoreActionStyle();
2598 }
2599 }
2600 }
2601 }
2602
2603 QMdiArea* MainWindow::getMdiArea() const
2604 {
2605 return d->mdiArea;
2606 }
2607
2608 void MainWindow::setWindowTitle(const QString& string)
2609 {
2610 QString title;
2611 QString appname = QCoreApplication::applicationName();
2612 if (appname.isEmpty()) {
2613 appname = QString::fromLatin1(App::Application::Config()["ExeName"].c_str());
2614 }
2615
2616 // allow one to disable version number
2617 ParameterGrp::handle hGen = App::GetApplication().GetParameterGroupByPath(
2618 "User parameter:BaseApp/Preferences/General"
2619 );
2620 bool showVersion = hGen->GetBool("ShowVersionInTitle", true);
2621
2622 if (showVersion) {
2623 // set main window title with FreeCAD Version
2624 title = QString::fromStdString(App::Application::getNameWithVersion());
2625 }
2626 else {
2627 title = appname;
2628 }
2629
2630 if (SafeMode::SafeModeEnabled()) {
2631 title = QStringLiteral("%1 (%2)").arg(title, tr("Safe Mode"));
2632 }
2633
2634 if (!string.isEmpty()) {
2635 title = QStringLiteral("[*] %1 - %2").arg(string, title);
2636 }
2637
2638 QMainWindow::setWindowTitle(title);
2639 }
2640
2641 // ----------------------------------------------------------
2642
2643 StatusBarObserver::StatusBarObserver()
2644 : WindowParameter("OutputWindow")
2645 {
2646 msg = QStringLiteral("#statusBar{color: #000000}"); // black
2647 wrn = QStringLiteral("#statusBar{color: #ffaa00}"); // orange
2648 err = QStringLiteral("#statusBar{color: #ff0000}"); // red
2649 Base::Console().attachObserver(this);
2650 getWindowParameter()->Attach(this);
2651 getWindowParameter()->NotifyAll();
2652 }
2653
2654 StatusBarObserver::~StatusBarObserver()
2655 {
2656 getWindowParameter()->Detach(this);
2657 Base::Console().detachObserver(this);
2658 }
2659
2660 void StatusBarObserver::OnChange(Base::Subject<const char*>& rCaller, const char* sReason)
2661 {
2662 ParameterGrp& rclGrp = ((ParameterGrp&)rCaller);
2663 auto format = QStringLiteral("#statusBar{color: %1}");
2664 if (strcmp(sReason, "colorText") == 0) {
2665 unsigned long col = rclGrp.GetUnsigned(sReason);
2666 this->msg = format.arg(Base::Color::fromPackedRGB<QColor>(col).name());
2667 }
2668 else if (strcmp(sReason, "colorWarning") == 0) {
2669 unsigned long col = rclGrp.GetUnsigned(sReason);
2670 this->wrn = format.arg(Base::Color::fromPackedRGB<QColor>(col).name());
2671 }
2672 else if (strcmp(sReason, "colorError") == 0) {
2673 unsigned long col = rclGrp.GetUnsigned(sReason);
2674 this->err = format.arg(Base::Color::fromPackedRGB<QColor>(col).name());
2675 }
2676 else if (strcmp(sReason, "colorCritical") == 0) {
2677 unsigned long col = rclGrp.GetUnsigned(sReason);
2678 this->critical = format.arg(
2679 QColor((col >> 24) & 0xff, (col >> 16) & 0xff, (col >> 8) & 0xff).name()
2680 );
2681 }
2682 }
2683
2684 void StatusBarObserver::sendLog(
2685 const std::string& notifiername,
2686 const std::string& msg,
2687 Base::LogStyle level,
2688 Base::IntendedRecipient recipient,
2689 Base::ContentType content
2690 )
2691 {
2692 (void)notifiername;
2693
2694 // Do not log untranslated messages, or messages intended only to a developer to status bar
2695 if (recipient == Base::IntendedRecipient::Developer || content == Base::ContentType::Untranslated
2696 || content == Base::ContentType::Untranslatable) {
2697 return;
2698 }
2699
2700 int messageType = -1;
2701 switch (level) {
2702 case Base::LogStyle::Warning:
2703 messageType = MainWindow::Wrn;
2704 break;
2705 case Base::LogStyle::Message:
2706 messageType = MainWindow::Msg;
2707 break;
2708 case Base::LogStyle::Error:
2709 messageType = MainWindow::Err;
2710 break;
2711 case Base::LogStyle::Log:
2712 messageType = MainWindow::Log;
2713 break;
2714 case Base::LogStyle::Critical:
2715 messageType = MainWindow::Critical;
2716 break;
2717 default:
2718 break;
2719 }
2720
2721 // Send the event to the main window to allow thread-safety. Qt will delete it when done.
2722 auto ev = new CustomMessageEvent(messageType, QString::fromUtf8(msg.c_str()));
2723 QApplication::postEvent(getMainWindow(), ev);
2724 }
2725
2726 // -------------------------------------------------------------
2727
2728 int ActionStyleEvent::EventType = -1;
2729
2730 ActionStyleEvent::ActionStyleEvent(Style type)
2731 : QEvent(QEvent::Type(EventType))
2732 , type(type)
2733 {}
2734
2735 ActionStyleEvent::Style ActionStyleEvent::getType() const
2736 {
2737 return type;
2738 }
2739
2740
2741 #include "moc_MainWindow.cpp"
2742 #include "MainWindow.moc"