Debian Codegraph @

src/Gui/MDIView.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2007 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 #include <boost/signals2.hpp>
24 #include <boost/core/ignore_unused.hpp>
25 #include <QAction>
26 #include <QApplication>
27 #include <QEvent>
28 #include <QCloseEvent>
29 #include <QMdiSubWindow>
30 #include <QPrintDialog>
31 #include <QPrintPreviewDialog>
32 #include <QPrinter>
33 #include <QPrinterInfo>
34 #include <QRegularExpression>
35 #include <QRegularExpressionMatch>
36
37 #include <Base/Interpreter.h>
38 #include <App/Document.h>
39 #include <App/Application.h>
40 #include <Gui/PreferencePages/DlgSettingsPDF.h>
41
42 #include "MDIView.h"
43 #include "MDIViewPy.h"
44 #include "Application.h"
45 #include "Document.h"
46 #include "FileDialog.h"
47 #include "MainWindow.h"
48 #include "ViewProviderDocumentObject.h"
49
50
51 using namespace Gui;
52 namespace sp = std::placeholders;
53
54 TYPESYSTEM_SOURCE_ABSTRACT(Gui::MDIView, Gui::BaseView)
55
56
57 MDIView::MDIView(Gui::Document* pcDocument, QWidget* parent, Qt::WindowFlags wflags)
58 : QMainWindow(parent, wflags)
59 , BaseView(pcDocument)
60 , pythonObject(nullptr)
61 , currentMode(Child)
62 , wstate(Qt::WindowNoState)
63 , ActiveObjects(pcDocument)
64 {
65 setAttribute(Qt::WA_DeleteOnClose);
66
67 if (pcDocument) {
68 // NOLINTBEGIN
69 connectDelObject = pcDocument->signalDeletedObject.connect(
70 std::bind(&ActiveObjectList::objectDeleted, &ActiveObjects, sp::_1)
71 );
72 assert(connectDelObject.connected());
73 // NOLINTEND
74 }
75 }
76
77 MDIView::~MDIView()
78 {
79 // This view might be the focus widget of the main window. In this case we must
80 // clear the focus and e.g. set the focus directly to the main window, otherwise
81 // the application crashes when accessing this deleted view.
82 // This effect only occurs if this widget is not in Child mode, because otherwise
83 // the focus stuff is done correctly.
84 if (getMainWindow()) {
85 QWidget* foc = getMainWindow()->focusWidget();
86 if (foc) {
87 QWidget* par = foc;
88 while (par) {
89 if (par == this) {
90 getMainWindow()->setFocus();
91 break;
92 }
93 par = par->parentWidget();
94 }
95 }
96 }
97 if (connectDelObject.connected()) {
98 connectDelObject.disconnect();
99 }
100
101 if (pythonObject) {
102 Base::PyGILStateLocker lock;
103 Py_DECREF(pythonObject);
104 pythonObject = nullptr;
105 }
106 }
107
108 void MDIView::deleteSelf()
109 {
110 // When using QMdiArea make sure to remove the QMdiSubWindow
111 // this view is associated with.
112 //
113 // #0001023: Crash when quitting after using Windows > Tile
114 // Use deleteLater() instead of delete operator.
115 QWidget* parent = this->parentWidget();
116 if (qobject_cast<QMdiSubWindow*>(parent)) {
117 // https://forum.freecad.org/viewtopic.php?f=22&t=23070
118 parent->close();
119 }
120 else {
121 this->close();
122 }
123
124 // detach from document
125 if (_pcDocument) {
126 onClose();
127 }
128 _pcDocument = nullptr;
129 }
130
131 MDIView* MDIView::clone()
132 {
133 return nullptr;
134 }
135
136 void MDIView::cloneFrom(const MDIView& from)
137 {
138 setWindowTitle(from.windowTitle());
139 setWindowIcon(from.windowIcon());
140 resize(from.size());
141
142 // wstate is updated when changing from top-level mode to something else. This hasn't happened
143 // yet if the original widget is currently in top-level mode. In this case we want to use the
144 // actual windowState of the original widget instead of it's wstate.
145
146 if (from.currentViewMode() == TopLevel) {
147 wstate = from.windowState();
148 }
149 else {
150 wstate = from.wstate;
151 }
152 }
153
154 PyObject* MDIView::getPyObject()
155 {
156 if (!pythonObject) {
157 pythonObject = new MDIViewPy(this);
158 }
159
160 Py_INCREF(pythonObject);
161 return pythonObject;
162 }
163
164 void MDIView::setOverrideCursor(const QCursor& c)
165 {
166 Q_UNUSED(c);
167 }
168
169 void MDIView::restoreOverrideCursor()
170 {}
171
172 void MDIView::onRelabel(Gui::Document* pDoc)
173 {
174 if (!bIsPassive) {
175 // Try to separate document name and view number if there is one
176 QString cap = windowTitle();
177 // Either with dirty flag ...
178 QRegularExpression rx(QLatin1String(R"((\s\:\s\d+\[\*\])$)"));
179 QRegularExpressionMatch match;
180 // int pos =
181 boost::ignore_unused(cap.lastIndexOf(rx, -1, &match));
182 if (!match.hasMatch()) {
183 // ... or not
184 rx.setPattern(QLatin1String(R"((\s\:\s\d+)$)"));
185 // pos =
186 boost::ignore_unused(cap.lastIndexOf(rx, -1, &match));
187 }
188 if (match.hasMatch()) {
189 cap = QString::fromUtf8(pDoc->getDocument()->Label.getValue());
190 cap += match.captured();
191 setWindowTitle(cap);
192 }
193 else {
194 cap = QString::fromUtf8(pDoc->getDocument()->Label.getValue());
195 cap = QStringLiteral("%1[*]").arg(cap);
196 setWindowTitle(cap);
197 }
198 }
199 }
200
201 void MDIView::viewAll()
202 {}
203
204 /// receive a message
205 bool MDIView::onMsg(const char* pMsg, const char** ppReturn)
206 {
207 Q_UNUSED(pMsg);
208 Q_UNUSED(ppReturn);
209 return false;
210 }
211
212 bool MDIView::onHasMsg(const char* pMsg) const
213 {
214 Q_UNUSED(pMsg);
215 return false;
216 }
217
218 bool MDIView::canClose()
219 {
220 if (getAppDocument() && getAppDocument()->testStatus(App::Document::TempDoc)) {
221 return true;
222 }
223
224 if (!bIsPassive && getGuiDocument() && getGuiDocument()->isLastView()) {
225 this->setFocus(); // raises the view to front
226 return (getGuiDocument()->canClose(true, true));
227 }
228
229 return true;
230 }
231
232 void MDIView::closeEvent(QCloseEvent* e)
233 {
234 if (canClose()) {
235 e->accept();
236 Application::Instance->viewClosed(this);
237
238 if (!bIsPassive) {
239 // must be detached so that the last view can get asked
240 Document* doc = this->getGuiDocument();
241 if (doc && !doc->isLastView()) {
242 doc->detachView(this);
243 }
244 }
245
246 // Note: When using QMdiArea we must not use removeWindow()
247 // because otherwise the QMdiSubWindow will lose its parent
248 // and thus the notification in QMdiSubWindow::closeEvent of
249 // other mdi windows to get maximized if this window
250 // is maximized will fail.
251 // This odd behaviour is caused by the invocation of
252 // d->mdiArea->removeSubWindow(parent) which we must let there
253 // because otherwise other parts don't work as they should.
254 QMainWindow::closeEvent(e);
255 }
256 else {
257 e->ignore();
258 }
259 }
260
261 void MDIView::windowStateChanged(QWidget* view)
262 {
263 Q_UNUSED(view)
264 }
265
266 void MDIView::print(QPrinter* printer)
267 {
268 Q_UNUSED(printer);
269 std::cerr << "Printing not implemented for " << this->metaObject()->className() << std::endl;
270 }
271
272 void MDIView::print()
273 {
274 QPrinter printer(QPrinter::ScreenResolution);
275 printer.setFullPage(true);
276 QPrintDialog dlg(&printer, this);
277 if (dlg.exec() == QDialog::Accepted) {
278 print(&printer);
279 }
280 }
281
282 void MDIView::printPdf()
283 {
284 QString filename = FileDialog::getSaveFileName(
285 this,
286 tr("Export PDF"),
287 QString(),
288 QStringLiteral("%1 (*.pdf)").arg(tr("PDF file"))
289 );
290 if (!filename.isEmpty()) {
291 QPrinter printer(QPrinter::ScreenResolution);
292 // setPdfVersion sets the printed PDF Version to what is chosen in
293 // Preferences/Import-Export/PDF more details under:
294 // https://www.kdab.com/creating-pdfa-documents-qt/
295 printer.setPdfVersion(Gui::Dialog::DlgSettingsPDF::evaluatePDFVersion());
296 printer.setOutputFormat(QPrinter::PdfFormat);
297 printer.setOutputFileName(filename);
298 printer.setCreator(QString::fromStdString(App::Application::getNameWithVersion()));
299 print(&printer);
300 }
301 }
302
303 void MDIView::printPreview()
304 {
305 QPrinter printer(QPrinter::ScreenResolution);
306 QPrintPreviewDialog dlg(&printer, this);
307 connect(&dlg, &QPrintPreviewDialog::paintRequested, this, qOverload<QPrinter*>(&MDIView::print));
308 dlg.exec();
309 }
310
311 void MDIView::savePrinterSettings(QPrinter* printer)
312 {
313 auto hGrp = App::GetApplication().GetParameterGroupByPath(
314 "User parameter:BaseApp/Preferences/Printer"
315 );
316 QString printerName = printer->printerName();
317 if (printerName.isEmpty()) {
318 // no printer defined
319 return;
320 }
321
322 hGrp = hGrp->GetGroup(printerName.toUtf8());
323
324 hGrp->SetInt("DefaultPageSize", printer->pageLayout().pageSize().id());
325 hGrp->SetInt("DefaultPageOrientation", static_cast<int>(printer->pageLayout().orientation()));
326 hGrp->SetInt("DefaultColorMode", static_cast<int>(printer->colorMode()));
327 }
328
329 void MDIView::restorePrinterSettings(QPrinter* printer)
330 {
331 auto hGrp = App::GetApplication().GetParameterGroupByPath(
332 "User parameter:BaseApp/Preferences/Printer"
333 );
334 QString printerName = printer->printerName();
335 if (printerName.isEmpty()) {
336 // no printer defined
337 return;
338 }
339
340 hGrp = hGrp->GetGroup(printerName.toUtf8());
341
342 QPrinterInfo info = QPrinterInfo::defaultPrinter();
343 int initialDefaultPageSize = info.isNull() ? QPageSize::A4 : info.defaultPageSize().id();
344 int defaultPageSize = hGrp->GetInt("DefaultPageSize", initialDefaultPageSize);
345 int defaultPageOrientation = hGrp->GetInt("DefaultPageOrientation", QPageLayout::Portrait);
346 int defaultColorMode = hGrp->GetInt("DefaultColorMode", QPrinter::ColorMode::Color);
347
348 printer->setPageSize(QPageSize(static_cast<QPageSize::PageSizeId>(defaultPageSize)));
349 printer->setPageOrientation(static_cast<QPageLayout::Orientation>(defaultPageOrientation));
350 printer->setColorMode(static_cast<QPrinter::ColorMode>(defaultColorMode));
351 }
352
353 QStringList MDIView::undoActions() const
354 {
355 QStringList actions;
356 Gui::Document* doc = getGuiDocument();
357 if (doc) {
358 std::vector<std::string> vecUndos = doc->getUndoVector();
359 for (const auto& vecUndo : vecUndos) {
360 actions << QCoreApplication::translate("Command", vecUndo.c_str());
361 }
362 }
363
364 return actions;
365 }
366
367 QStringList MDIView::redoActions() const
368 {
369 QStringList actions;
370 Gui::Document* doc = getGuiDocument();
371 if (doc) {
372 std::vector<std::string> vecRedos = doc->getRedoVector();
373 for (const auto& vecRedo : vecRedos) {
374 actions << QCoreApplication::translate("Command", vecRedo.c_str());
375 }
376 }
377
378 return actions;
379 }
380
381 QSize MDIView::minimumSizeHint() const
382 {
383 return {400, 300};
384 }
385
386
387 void MDIView::changeEvent(QEvent* e)
388 {
389 switch (e->type()) {
390 case QEvent::ActivationChange: {
391 // Forces this top-level window to be the active view of the main window
392 if (isActiveWindow()) {
393 getMainWindow()->setActiveWindow(this);
394 }
395 } break;
396 case QEvent::WindowTitleChange:
397 case QEvent::ModifiedChange: {
398 // sets the appropriate tab of the tabbar
399 getMainWindow()->tabChanged(this);
400 } break;
401 default: {
402 QMainWindow::changeEvent(e);
403 } break;
404 }
405 }
406
407 bool MDIView::eventFilter(QObject* watched, QEvent* event)
408 {
409 // As long as this widget is a top-level window (either in 'TopLevel' or 'FullScreen' mode) we
410 // need to be notified when an action is added to a widget. This action must also be added to
411 // this window to allow one to make use of its shortcut (if defined).
412 // Note: We don't need to care about removing an action if its parent widget gets destroyed.
413 // This does the action itself for us.
414
415 if (watched != this && event->type() == QEvent::ActionAdded) {
416 auto actionEvent = static_cast<QActionEvent*>(event);
417 QAction* action = actionEvent->action();
418
419 if (!action->isSeparator()) {
420 QList<QAction*> acts = actions();
421 if (!acts.contains(action)) {
422 addAction(action);
423 }
424 }
425 }
426
427 return false;
428 }
429
430 #if defined(Q_WS_X11)
431 // To fix bug #0000345 move function declaration to here
432 extern void qt_x11_wait_for_window_manager(QWidget* w); // defined in qwidget_x11.cpp
433 #endif
434
435 void MDIView::setCurrentViewMode(ViewMode mode)
436 {
437 const ViewMode oldmode = MDIView::currentViewMode();
438 if (oldmode == mode) {
439 return;
440 }
441
442 if (oldmode == Child) {
443 // remove window from MDIArea
444 if (qobject_cast<QMdiSubWindow*>(parentWidget())) {
445 getMainWindow()->removeWindow(this, false);
446 setParent(nullptr);
447 }
448 }
449 else if (oldmode == TopLevel) {
450 // backup maximize state for top-level mode
451 wstate = windowState();
452 }
453
454 switch (mode) {
455 // go to normal mode
456 case Child:
457 getMainWindow()->addWindow(this);
458 break;
459
460 // go to top-level mode
461 case TopLevel:
462 if (wstate & Qt::WindowMaximized) {
463 // Only calling showMaximized doesn't work when the widget is currently in
464 // full-screen mode. We need to exit full-screen mode first or the widget will end
465 // up in normal mode. Same if the window is in child mode but maximized.
466 setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
467 showMaximized();
468 }
469 else {
470 showNormal();
471 }
472 break;
473
474 // go to full-screen mode
475 case FullScreen:
476 showFullScreen();
477 break;
478 }
479
480 currentMode = mode;
481
482 #if defined(Q_WS_X11)
483 if (mode == TopLevel && oldmode == Child) {
484 // extern void qt_x11_wait_for_window_manager( QWidget* w ); // defined in
485 // qwidget_x11.cpp
486 qt_x11_wait_for_window_manager(this);
487 }
488 #endif
489
490 activateWindow();
491
492 if (oldmode == Child) {
493 // To make a global shortcut working from this window we need to add
494 // all existing actions from the mainwindow and its sub-widgets
495
496 QList<QAction*> acts = getMainWindow()->findChildren<QAction*>();
497 addActions(acts);
498
499 // To be notfified for new actions
500 qApp->installEventFilter(this);
501 }
502 else if (mode == Child) {
503 qApp->removeEventFilter(this);
504 QList<QAction*> acts = actions();
505 for (QAction* it : acts) {
506 removeAction(it);
507 }
508
509 // When switching from undocked to docked mode, the widget position is somehow not updated
510 // correctly. In this case mapToGlobal(Point()) returns {0, 0} even though the widget is
511 // clearly not at the top-left corner of the screen. We fix this by briefly changing the
512 // maximum size of the widget.
513
514 const auto oldsize = maximumSize();
515 setMaximumSize({1, 1});
516 setMaximumSize(oldsize);
517 }
518 }
519
520 QString MDIView::buildWindowTitle() const
521 {
522 QString windowTitle;
523 if (auto document = getAppDocument()) {
524 windowTitle.append(QString::fromStdString(document->Label.getStrValue()));
525 }
526
527 return windowTitle;
528 }
529
530 void MDIView::setWindowTitle(const QString& title)
531 {
532 QString newerTitle {title};
533 newerTitle.replace(QLatin1Char('&'), QStringLiteral("&&"));
534 QMainWindow::setWindowTitle(newerTitle);
535 }
536
537 #include "moc_MDIView.cpp"