Debian Codegraph @

src/Gui/Document.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2004 Jürgen Riegel <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23 #include <tuple>
24 #include <memory>
25 #include <list>
26 #include <string>
27 #include <map>
28 #include <set>
29 #include <unordered_map>
30 #include <vector>
31 #include <cctype>
32 #include <mutex>
33 #include <QApplication>
34 #include <QCheckBox>
35 #include <QFileInfo>
36 #include <QMessageBox>
37 #include <QOpenGLWidget>
38 #include <QTextStream>
39 #include <QTimer>
40 #include <QThread>
41 #include <QStatusBar>
42 #include <Inventor/actions/SoSearchAction.h>
43 #include <Inventor/nodes/SoSeparator.h>
44
45 #include <App/AutoTransaction.h>
46 #include <App/Document.h>
47 #include <App/DocumentObject.h>
48 #include <App/DocumentObjectGroup.h>
49 #include <App/Transactions.h>
50 #include <App/ElementNamingUtils.h>
51 #include <Base/Console.h>
52 #include <Base/Exception.h>
53 #include <Base/Matrix.h>
54 #include <Base/Reader.h>
55 #include <Base/Writer.h>
56 #include <Base/Tools.h>
57
58 #include "Document.h"
59 #include "DocumentPy.h"
60 #include "Application.h"
61 #include "Command.h"
62 #include "Control.h"
63 #include "FileDialog.h"
64 #include "MainWindow.h"
65 #include "MDIView.h"
66 #include "NotificationArea.h"
67 #include "Selection.h"
68 #include "Thumbnail.h"
69 #include "Tree.h"
70 #include "View3DInventor.h"
71 #include "View3DInventorViewer.h"
72 #include "ViewProviderDocumentObject.h"
73 #include "ViewProviderDocumentObjectGroup.h"
74 #include "WaitCursor.h"
75
76
77 FC_LOG_LEVEL_INIT("Gui", true, true)
78
79 using namespace Gui;
80 namespace sp = std::placeholders;
81
82 namespace Gui
83 {
84
85 // Pimpl class
86 struct DocumentP
87 {
88 Thumbnail thumb;
89 int _iWinCount;
90 int _iDocId;
91 bool _isClosing;
92 bool _isModified;
93 bool _isTransacting;
94 bool _changeViewTouchDocument;
95 bool _editWantsRestore;
96 bool _editWantsRestorePrevious;
97 int _editMode;
98 int _editModePrevious;
99 ViewProvider* _editViewProvider;
100 ViewProvider* _editViewProviderPrevious;
101 App::DocumentObject* _editingObject;
102 ViewProviderDocumentObject* _editViewProviderParent;
103 std::string _editSubname;
104 std::string _editSubElement;
105 Base::Matrix4D _editingTransform;
106 View3DInventorViewer* _editingViewer;
107 std::set<const App::DocumentObject*> _editObjs;
108
109 Application* _pcAppWnd;
110 // the doc/Document
111 App::Document* _pcDocument;
112 /// List of all registered views
113 std::list<Gui::BaseView*> baseViews;
114 /// List of all registered views
115 std::list<Gui::BaseView*> passiveViews;
116 std::map<const App::DocumentObject*, ViewProviderDocumentObject*> _ViewProviderMap;
117 std::map<SoSeparator*, ViewProviderDocumentObject*> _CoinMap;
118 std::map<std::string, ViewProvider*> _ViewProviderMapAnnotation;
119 std::list<ViewProviderDocumentObject*> _redoViewProviders;
120
121 using Connection = boost::signals2::connection;
122 Connection connectNewObject;
123 Connection connectDelObject;
124 Connection connectCngObject;
125 Connection connectRenObject;
126 Connection connectActObject;
127 Connection connectSaveDocument;
128 Connection connectRestDocument;
129 Connection connectStartLoadDocument;
130 Connection connectFinishLoadDocument;
131 Connection connectShowHidden;
132 Connection connectFinishRestoreDocument;
133 Connection connectFinishRestoreObject;
134 Connection connectExportObjects;
135 Connection connectImportObjects;
136 Connection connectFinishImportObjects;
137 Connection connectUndoDocument;
138 Connection connectRedoDocument;
139 Connection connectRecomputed;
140 Connection connectSkipRecompute;
141 Connection connectTransactionAppend;
142 Connection connectTransactionRemove;
143 Connection connectTouchedObject;
144 Connection connectChangePropertyEditor;
145 Connection connectChangeDocument;
146
147 using ConnectionBlock = boost::signals2::shared_connection_block;
148 ConnectionBlock connectActObjectBlocker;
149 ConnectionBlock connectChangeDocumentBlocker;
150
151 static ViewProviderDocumentObject* throwIfCastFails(ViewProvider* p)
152 {
153 if (auto vp = freecad_cast<ViewProviderDocumentObject*>(p)) {
154 return vp;
155 }
156
157 throw Base::RuntimeError("cannot edit non ViewProviderDocumentObject");
158 }
159
160 static App::DocumentObject* tryGetObject(ViewProviderDocumentObject* vp)
161 {
162 auto obj = vp->getObject();
163 if (!obj->isAttachedToDocument()) {
164 throw Base::RuntimeError("cannot edit detached object");
165 }
166
167 return obj;
168 }
169
170 void throwIfNotInMap(App::DocumentObject* obj, App::Document* doc) const
171 {
172 if (_ViewProviderMap.find(obj) == _ViewProviderMap.end()) {
173 // We can actually support editing external object, by calling
174 // View3DInventViewer::setupEditingRoot() before exiting from
175 // ViewProvider::setEditViewer(), which transfer all child node of the view
176 // provider into an editing node inside the viewer of this document. And
177 // that's may actually be the case, as the subname referenced sub object
178 // is allowed to be in other documents.
179 //
180 // We just disabling editing external parent object here, for bug
181 // tracking purpose. Because, bringing an unrelated external object to
182 // the current view for editing will confuse user, and is certainly a
183 // bug. By right, the top parent object should always belong to the
184 // editing document, and the actually editing sub object can be
185 // external.
186 //
187 // So, you can either call setEdit() with subname set to 0, which cause
188 // the code above to auto detect selection context, and dispatch the
189 // editing call to the correct document. Or, supply subname yourself,
190 // and make sure you get the document right.
191 //
192 std::stringstream str;
193 str << "cannot edit object '" << obj->getNameInDocument() << "': not found in document "
194 << "'" << doc->getName() << "'";
195 throw Base::RuntimeError(str.str());
196 }
197 }
198
199 App::DocumentObject* tryGetSubObject(App::DocumentObject* obj, const char* subname)
200 {
201 _editingTransform = Base::Matrix4D();
202 auto sobj = obj->getSubObject(subname, nullptr, &_editingTransform);
203 if (!sobj || !sobj->isAttachedToDocument()) {
204 std::stringstream str;
205 str << "Invalid sub object '" << obj->getFullName() << '.' << (subname ? subname : "")
206 << "'";
207 throw Base::RuntimeError(str.str());
208 }
209
210 return sobj;
211 }
212
213 ViewProviderDocumentObject* tryGetSubViewProvider(
214 ViewProviderDocumentObject* vp,
215 App::DocumentObject* obj,
216 App::DocumentObject* sobj
217 ) const
218 {
219 auto svp = vp;
220 if (sobj != obj) {
221 svp = freecad_cast<ViewProviderDocumentObject*>(
222 Application::Instance->getViewProvider(sobj)
223 );
224 if (!svp) {
225 std::stringstream str;
226 str << "Cannot edit '" << sobj->getFullName() << "' without view provider";
227 throw Base::RuntimeError(str.str());
228 }
229 }
230
231 return svp;
232 }
233
234 void setParentViewProvider(ViewProviderDocumentObject* vp)
235 {
236 _editViewProviderParent = vp;
237 }
238
239 void clearSubElement()
240 {
241 _editSubElement.clear();
242 _editSubname.clear();
243 }
244
245 void findElementName(const char* subname)
246 {
247 if (subname) {
248 const char* element = Data::findElementName(subname);
249 if (element) {
250 _editSubname = std::string(subname, element - subname);
251 _editSubElement = element;
252 }
253 else {
254 _editSubname = subname;
255 }
256 }
257 }
258
259 void findSubObjectList(App::DocumentObject* obj, const char* subname)
260 {
261 auto sobjs = obj->getSubObjectList(subname);
262 _editObjs.clear();
263 _editObjs.insert(sobjs.begin(), sobjs.end());
264 }
265
266 bool tryStartEditing(
267 ViewProviderDocumentObject* vp,
268 App::DocumentObject* obj,
269 const char* subname,
270 int ModNum
271 )
272 {
273 auto sobj = tryGetSubObject(obj, subname);
274 auto svp = tryGetSubViewProvider(vp, obj, sobj);
275
276 setParentViewProvider(vp);
277 clearSubElement();
278 findElementName(subname);
279 findSubObjectList(obj, subname);
280 return tryStartEditing(svp, sobj, ModNum);
281 }
282
283 bool tryStartEditing(ViewProviderDocumentObject* svp, App::DocumentObject* sobj, int ModNum)
284 {
285 _editingObject = sobj;
286 _editMode = ModNum;
287 _editViewProvider = svp->startEditing(ModNum);
288 if (!_editViewProvider) {
289 _editViewProviderParent = nullptr;
290 _editObjs.clear();
291 _editingObject = nullptr;
292 FC_LOG("object '" << sobj->getFullName() << "' refuse to edit");
293 return false;
294 }
295
296 return true;
297 }
298
299 void setEditingViewerIfPossible(View3DInventor* view3d, int ModNum)
300 {
301 if (view3d) {
302 view3d->getViewer()->setEditingViewProvider(_editViewProvider, ModNum);
303 _editingViewer = view3d->getViewer();
304 }
305 }
306
307 void signalEditMode()
308 {
309 if (auto vpd = freecad_cast<ViewProviderDocumentObject*>(_editViewProvider)) {
310 vpd->getDocument()->signalInEdit(*vpd);
311 }
312 }
313
314 void setDocumentNameOfTaskDialog(App::Document* doc)
315 {
316 Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog();
317 if (dlg) {
318 dlg->setDocumentName(doc->getName());
319 }
320 }
321 };
322
323 class ParentFinder
324 {
325 public:
326 ParentFinder(App::DocumentObject* obj, ViewProviderDocumentObject* vp, const std::string& subname)
327 : obj {obj}
328 , vp {vp}
329 , subname {subname}
330 {}
331
332 App::DocumentObject* getObject() const
333 {
334 return obj;
335 }
336
337 ViewProviderDocumentObject* getViewProvider() const
338 {
339 return vp;
340 }
341
342 std::string getSubname() const
343 {
344 return subname;
345 }
346
347 bool findParent()
348 {
349 auto result = findParentAndSubName(obj);
350 App::DocumentObject* parentObj = std::get<0>(result);
351
352 if (parentObj) {
353 subname = std::get<1>(result);
354 obj = parentObj;
355 vp = findParentObject(parentObj, subname.c_str());
356 return true;
357 }
358
359 return false;
360 }
361
362 private:
363 static std::tuple<App::DocumentObject*, std::string> findParentAndSubName(App::DocumentObject* obj)
364 {
365 // No subname reference is given, we try to extract one from the current
366 // selection in order to obtain the correct transformation matrix below
367 auto sels = Gui::Selection().getCompleteSelection(ResolveMode::NoResolve);
368 App::DocumentObject* parentObj = nullptr;
369 std::string _subname;
370 for (auto& sel : sels) {
371 if (!sel.pObject || !sel.pObject->isAttachedToDocument()) {
372 continue;
373 }
374 if (!parentObj) {
375 parentObj = sel.pObject;
376 }
377 else if (parentObj != sel.pObject) {
378 FC_LOG("Cannot deduce subname for editing, more than one parent?");
379 parentObj = nullptr;
380 break;
381 }
382
383 auto sobj = parentObj->getSubObject(sel.SubName);
384 if (!sobj || (sobj != obj && sobj->getLinkedObject(true) != obj)) {
385 FC_LOG("Cannot deduce subname for editing, subname mismatch");
386 parentObj = nullptr;
387 break;
388 }
389
390 _subname = sel.SubName;
391 }
392
393 return std::make_tuple(parentObj, _subname);
394 }
395
396 static Gui::ViewProviderDocumentObject* findParentObject(
397 App::DocumentObject* parentObj,
398 const char* subname
399 )
400 {
401 FC_LOG("deduced editing reference " << parentObj->getFullName() << '.' << subname);
402 auto vp = freecad_cast<ViewProviderDocumentObject*>(
403 Application::Instance->getViewProvider(parentObj)
404 );
405 if (!vp || !vp->getDocument()) {
406 throw Base::RuntimeError("invalid view provider for parent object");
407 }
408
409 return vp;
410 }
411
412 private:
413 App::DocumentObject* obj;
414 ViewProviderDocumentObject* vp;
415 std::string subname;
416 };
417
418 } // namespace Gui
419
420 /* TRANSLATOR Gui::Document */
421
422 /// @namespace Gui @class Document
423
424 int Document::_iDocCount = 0;
425
426 Document::Document(App::Document* pcDocument, Application* app)
427 {
428 d = new DocumentP;
429 d->_iWinCount = 1;
430 // new instance
431 d->_iDocId = (++_iDocCount);
432 d->_isClosing = false;
433 d->_isModified = false;
434 d->_isTransacting = false;
435 d->_pcAppWnd = app;
436 d->_pcDocument = pcDocument;
437 d->_editViewProvider = nullptr;
438 d->_editViewProviderPrevious = nullptr;
439 d->_editingObject = nullptr;
440 d->_editViewProviderParent = nullptr;
441 d->_editingViewer = nullptr;
442 d->_editMode = 0;
443 d->_editModePrevious = 0;
444 d->_editWantsRestore = false;
445 d->_editWantsRestorePrevious = false;
446
447 // NOLINTBEGIN
448 // Setup the connections
449 d->connectNewObject = pcDocument->signalNewObject.connect(
450 std::bind(&Gui::Document::slotNewObject, this, sp::_1)
451 );
452 d->connectDelObject = pcDocument->signalDeletedObject.connect(
453 std::bind(&Gui::Document::slotDeletedObject, this, sp::_1)
454 );
455 d->connectCngObject = pcDocument->signalChangedObject.connect(
456 std::bind(&Gui::Document::slotChangedObject, this, sp::_1, sp::_2)
457 );
458 d->connectRenObject = pcDocument->signalRelabelObject.connect(
459 std::bind(&Gui::Document::slotRelabelObject, this, sp::_1)
460 );
461 d->connectActObject = pcDocument->signalActivatedObject.connect(
462 std::bind(&Gui::Document::slotActivatedObject, this, sp::_1)
463 );
464 d->connectActObjectBlocker = boost::signals2::shared_connection_block(d->connectActObject, false);
465 d->connectSaveDocument = pcDocument->signalSaveDocument.connect(
466 std::bind(&Gui::Document::Save, this, sp::_1)
467 );
468 d->connectRestDocument = pcDocument->signalRestoreDocument.connect(
469 std::bind(&Gui::Document::Restore, this, sp::_1)
470 );
471 d->connectStartLoadDocument = App::GetApplication().signalStartRestoreDocument.connect(
472 std::bind(&Gui::Document::slotStartRestoreDocument, this, sp::_1)
473 );
474 d->connectFinishLoadDocument = App::GetApplication().signalFinishRestoreDocument.connect(
475 std::bind(&Gui::Document::slotFinishRestoreDocument, this, sp::_1)
476 );
477 d->connectShowHidden = App::GetApplication().signalShowHidden.connect(
478 std::bind(&Gui::Document::slotShowHidden, this, sp::_1)
479 );
480
481 d->connectChangePropertyEditor = pcDocument->signalChangePropertyEditor.connect(
482 std::bind(&Gui::Document::slotChangePropertyEditor, this, sp::_1, sp::_2)
483 );
484 d->connectChangeDocument
485 = d->_pcDocument->signalChanged.connect // use the same slot function
486 (std::bind(&Gui::Document::slotChangePropertyEditor, this, sp::_1, sp::_2));
487 d->connectChangeDocumentBlocker
488 = boost::signals2::shared_connection_block(d->connectChangeDocument, true);
489 d->connectFinishRestoreObject = pcDocument->signalFinishRestoreObject.connect(
490 std::bind(&Gui::Document::slotFinishRestoreObject, this, sp::_1)
491 );
492 d->connectExportObjects = pcDocument->signalExportViewObjects.connect(
493 std::bind(&Gui::Document::exportObjects, this, sp::_1, sp::_2)
494 );
495 d->connectImportObjects = pcDocument->signalImportViewObjects.connect(
496 std::bind(&Gui::Document::importObjects, this, sp::_1, sp::_2, sp::_3)
497 );
498 d->connectFinishImportObjects = pcDocument->signalFinishImportObjects.connect(
499 std::bind(&Gui::Document::slotFinishImportObjects, this, sp::_1)
500 );
501
502 d->connectUndoDocument = pcDocument->signalUndo.connect(
503 std::bind(&Gui::Document::slotUndoDocument, this, sp::_1)
504 );
505 d->connectRedoDocument = pcDocument->signalRedo.connect(
506 std::bind(&Gui::Document::slotRedoDocument, this, sp::_1)
507 );
508 d->connectRecomputed = pcDocument->signalRecomputed.connect(
509 std::bind(&Gui::Document::slotRecomputed, this, sp::_1)
510 );
511 d->connectSkipRecompute = pcDocument->signalSkipRecompute.connect(
512 std::bind(&Gui::Document::slotSkipRecompute, this, sp::_1, sp::_2)
513 );
514 d->connectTouchedObject = pcDocument->signalTouchedObject.connect(
515 std::bind(&Gui::Document::slotTouchedObject, this, sp::_1)
516 );
517
518 d->connectTransactionAppend = pcDocument->signalTransactionAppend.connect(
519 std::bind(&Gui::Document::slotTransactionAppend, this, sp::_1, sp::_2)
520 );
521 d->connectTransactionRemove = pcDocument->signalTransactionRemove.connect(
522 std::bind(&Gui::Document::slotTransactionRemove, this, sp::_1, sp::_2)
523 );
524 // NOLINTEND
525
526 pcDocument->setPreRecomputeHook([this] { callSignalBeforeRecompute(); });
527
528 // pointer to the python class
529 // NOTE: As this Python object doesn't get returned to the interpreter we
530 // mustn't increment it (Werner Jan-12-2006)
531 Base::PyGILStateLocker lock;
532 _pcDocPy = new Gui::DocumentPy(this);
533
534 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
535 "User parameter:BaseApp/Preferences/Document"
536 );
537 if (hGrp->GetBool("UsingUndo", true)) {
538 d->_pcDocument->setUndoMode(1);
539 // set the maximum stack size
540 d->_pcDocument->setMaxUndoStackSize(hGrp->GetInt("MaxUndoSize", 20));
541 }
542
543 d->_changeViewTouchDocument = hGrp->GetBool("ChangeViewProviderTouchDocument", true);
544 }
545
546 Document::~Document()
547 {
548 // disconnect everything to avoid to be double-deleted
549 // in case an exception is raised somewhere
550 d->connectNewObject.disconnect();
551 d->connectDelObject.disconnect();
552 d->connectCngObject.disconnect();
553 d->connectRenObject.disconnect();
554 d->connectActObject.disconnect();
555 d->connectSaveDocument.disconnect();
556 d->connectRestDocument.disconnect();
557 d->connectStartLoadDocument.disconnect();
558 d->connectFinishLoadDocument.disconnect();
559 d->connectShowHidden.disconnect();
560 d->connectFinishRestoreObject.disconnect();
561 d->connectExportObjects.disconnect();
562 d->connectImportObjects.disconnect();
563 d->connectFinishImportObjects.disconnect();
564 d->connectUndoDocument.disconnect();
565 d->connectRedoDocument.disconnect();
566 d->connectRecomputed.disconnect();
567 d->connectSkipRecompute.disconnect();
568 d->connectTransactionAppend.disconnect();
569 d->connectTransactionRemove.disconnect();
570 d->connectTouchedObject.disconnect();
571 d->connectChangePropertyEditor.disconnect();
572 d->connectChangeDocument.disconnect();
573
574 // e.g. if document gets closed from within a Python command
575 d->_isClosing = true;
576 // calls Document::detachView() and alter the view list
577 std::list<Gui::BaseView*> temp = d->baseViews;
578 for (auto& it : temp) {
579 it->deleteSelf();
580 }
581
582 std::map<const App::DocumentObject*, ViewProviderDocumentObject*>::iterator jt;
583 for (jt = d->_ViewProviderMap.begin(); jt != d->_ViewProviderMap.end(); ++jt) {
584 delete jt->second;
585 }
586 std::map<std::string, ViewProvider*>::iterator it2;
587 for (it2 = d->_ViewProviderMapAnnotation.begin(); it2 != d->_ViewProviderMapAnnotation.end();
588 ++it2) {
589 delete it2->second;
590 }
591
592 // remove the reference from the object
593 Base::PyGILStateLocker lock;
594 _pcDocPy->setInvalid();
595 _pcDocPy->DecRef();
596 delete d;
597 }
598
599 //*****************************************************************************************************
600 // 3D viewer handling
601 //*****************************************************************************************************
602
603 bool Document::setEdit(Gui::ViewProvider* p, int ModNum, const char* subname)
604 {
605 try {
606 return trySetEdit(p, ModNum, subname);
607 }
608 catch (const Base::Exception& e) {
609 FC_ERR("" << e.what());
610 return false;
611 }
612 }
613
614 void Document::resetIfEditing()
615 {
616 // Fix regression: https://forum.freecad.org/viewtopic.php?f=19&t=43629&p=371972#p371972
617 // When an object is already in edit mode a subsequent call for editing is only possible
618 // when resetting the currently edited object.
619 if (d->_editViewProvider) {
620 _resetEdit();
621 }
622 }
623
624 View3DInventor* Document::openEditingView3D(const ViewProviderDocumentObject* vp)
625 {
626 auto view3d = dynamic_cast<View3DInventor*>(getActiveView());
627 // if the currently active view is not the 3d view search for it and activate it
628 if (view3d) {
629 getMainWindow()->setActiveWindow(view3d);
630 }
631 else {
632 view3d = dynamic_cast<View3DInventor*>(setActiveView(vp));
633 }
634
635 return view3d;
636 }
637
638 View3DInventor* Document::openEditingView3D(const App::DocumentObject* obj)
639 {
640 if (auto vp
641 = freecad_cast<ViewProviderDocumentObject*>(Application::Instance->getViewProvider(obj))) {
642 return openEditingView3D(vp);
643 }
644
645 return nullptr;
646 }
647
648 bool Document::trySetEdit(Gui::ViewProvider* p, int ModNum, const char* subname)
649 {
650 auto vp = DocumentP::throwIfCastFails(p);
651
652 auto obj = DocumentP::tryGetObject(vp);
653
654 std::string _subname = subname ? subname : "";
655 if (_subname.empty()) {
656 ParentFinder finder(obj, vp, _subname);
657 if (finder.findParent()) {
658 _subname = finder.getSubname();
659 obj = finder.getObject();
660 vp = finder.getViewProvider();
661 if (vp->getDocument() != this) {
662 resetIfEditing();
663
664 return vp->getDocument()->setEdit(vp, ModNum, _subname.c_str());
665 }
666 }
667 }
668
669 // Fix for #13852: When switching edit directly between sketches, resetIfEditing()
670 // triggers unsetEdit() on the previous sketch which restores its selection.
671 // This clobbers the selection of the new sketch that ParentFinder relies on.
672 // Moving resetIfEditing() after ParentFinder ensures we resolve the parent context correctly
673 // using the current selection before closing the previous edit.
674 resetIfEditing();
675
676 d->throwIfNotInMap(obj, getDocument());
677
678 Application::Instance->setEditDocument(this);
679
680 if (!d->tryStartEditing(vp, obj, _subname.c_str(), ModNum)) {
681 d->setDocumentNameOfTaskDialog(getDocument());
682 return false;
683 }
684
685 d->setDocumentNameOfTaskDialog(getDocument());
686
687 auto view3d = openEditingView3D(vp);
688 d->setEditingViewerIfPossible(view3d, ModNum);
689 d->signalEditMode();
690
691 App::AutoTransaction::setEnable(false);
692 return true;
693 }
694
695 const Base::Matrix4D& Document::getEditingTransform() const
696 {
697 return d->_editingTransform;
698 }
699
700 void Document::setEditingTransform(const Base::Matrix4D& mat)
701 {
702 d->_editObjs.clear();
703 d->_editingTransform = mat;
704 auto activeView = dynamic_cast<View3DInventor*>(getActiveView());
705 if (activeView) {
706 activeView->getViewer()->setEditingTransform(mat);
707 }
708 }
709
710 void Document::resetEdit()
711 {
712 bool vpIsNotNull = d->_editViewProvider != nullptr;
713 bool vpHasChanged = d->_editViewProvider != d->_editViewProviderPrevious;
714 int modeToRestore = d->_editModePrevious;
715 Gui::ViewProvider* vpToRestore = d->_editViewProviderPrevious;
716 bool shouldRestorePrevious = d->_editWantsRestorePrevious;
717
718 Application::Instance->setEditDocument(nullptr);
719
720 if (vpIsNotNull && vpHasChanged && shouldRestorePrevious) {
721 setEdit(vpToRestore, modeToRestore);
722 }
723 }
724
725 void Document::_resetEdit()
726 {
727 std::list<Gui::BaseView*>::iterator it;
728 if (d->_editViewProvider) {
729 for (it = d->baseViews.begin(); it != d->baseViews.end(); ++it) {
730 auto activeView = dynamic_cast<View3DInventor*>(*it);
731 if (activeView) {
732 activeView->getViewer()->resetEditingViewProvider();
733 }
734 }
735
736 d->_editViewProvider->finishEditing();
737
738 d->_editViewProviderPrevious = d->_editViewProvider;
739 d->_editModePrevious = d->_editMode;
740 d->_editWantsRestorePrevious = d->_editWantsRestore;
741 d->_editWantsRestore = false;
742
743 // Have to check d->_editViewProvider below, because there is a chance
744 // the editing object gets deleted inside the above call to
745 // 'finishEditing()', which will trigger our slotDeletedObject(), which
746 // nullifies _editViewProvider.
747 if (d->_editViewProvider
748 && d->_editViewProvider->isDerivedFrom<ViewProviderDocumentObject>()) {
749 auto vpd = static_cast<ViewProviderDocumentObject*>(d->_editViewProvider);
750 vpd->getDocument()->signalResetEdit(*vpd);
751 }
752 d->_editViewProvider = nullptr;
753
754 // The logic below is not necessary anymore, because this method is
755 // changed into a private one, _resetEdit(). And the exposed
756 // resetEdit() above calls into Application->setEditDocument(0) which
757 // will prevent recursive calling.
758
759 App::GetApplication().closeActiveTransaction();
760 }
761 d->_editViewProviderParent = nullptr;
762 d->_editingViewer = nullptr;
763 d->_editObjs.clear();
764 d->_editingObject = nullptr;
765 if (Application::Instance->editDocument() == this) {
766 Application::Instance->setEditDocument(nullptr);
767 }
768 }
769
770 ViewProvider* Document::getInEdit(
771 ViewProviderDocumentObject** parentVp,
772 std::string* subname,
773 int* mode,
774 std::string* subelement
775 ) const
776 {
777 if (parentVp) {
778 *parentVp = d->_editViewProviderParent;
779 }
780 if (subname) {
781 *subname = d->_editSubname;
782 }
783 if (subelement) {
784 *subelement = d->_editSubElement;
785 }
786 if (mode) {
787 *mode = d->_editMode;
788 }
789
790 if (d->_editViewProvider) {
791 // there is only one 3d view which is in edit mode
792 auto activeView = dynamic_cast<View3DInventor*>(getActiveView());
793 if (activeView && activeView->getViewer()->isEditingViewProvider()) {
794 return d->_editViewProvider;
795 }
796 }
797
798 return nullptr;
799 }
800
801 void Document::setInEdit(ViewProviderDocumentObject* parentVp, const char* subname)
802 {
803 if (d->_editViewProvider) {
804 d->_editViewProviderParent = parentVp;
805 d->_editSubname = subname ? subname : "";
806 }
807 }
808
809 void Document::setAnnotationViewProvider(const char* name, ViewProvider* pcProvider)
810 {
811 std::list<Gui::BaseView*>::iterator vIt;
812
813 // already in ?
814 std::map<std::string, ViewProvider*>::iterator it = d->_ViewProviderMapAnnotation.find(name);
815 if (it != d->_ViewProviderMapAnnotation.end()) {
816 removeAnnotationViewProvider(name);
817 }
818
819 // add
820 d->_ViewProviderMapAnnotation[name] = pcProvider;
821
822 // cycling to all views of the document
823 for (vIt = d->baseViews.begin(); vIt != d->baseViews.end(); ++vIt) {
824 auto activeView = dynamic_cast<View3DInventor*>(*vIt);
825 if (activeView) {
826 activeView->getViewer()->addViewProvider(pcProvider);
827 }
828 }
829 }
830
831 void Document::setEditRestore(bool askRestore)
832 {
833 d->_editWantsRestore = askRestore;
834 }
835
836 ViewProvider* Document::getAnnotationViewProvider(const char* name) const
837 {
838 std::map<std::string, ViewProvider*>::const_iterator it = d->_ViewProviderMapAnnotation.find(name);
839 return ((it != d->_ViewProviderMapAnnotation.end()) ? it->second : 0);
840 }
841
842 bool Document::isAnnotationViewProvider(const ViewProvider* vp) const
843 {
844 std::map<std::string, ViewProvider*>::const_iterator it;
845 for (it = d->_ViewProviderMapAnnotation.begin(); it != d->_ViewProviderMapAnnotation.end(); ++it) {
846 if (it->second == vp) {
847 return true;
848 }
849 }
850 return false;
851 }
852
853
854 ViewProvider* Document::takeAnnotationViewProvider(const char* name)
855 {
856 auto it = d->_ViewProviderMapAnnotation.find(name);
857 if (it == d->_ViewProviderMapAnnotation.end()) {
858 return nullptr;
859 }
860
861 ViewProvider* vp = it->second;
862 d->_ViewProviderMapAnnotation.erase(it);
863
864 // cycling to all views of the document
865 for (auto vIt : d->baseViews) {
866 if (auto activeView = dynamic_cast<View3DInventor*>(vIt)) {
867 activeView->getViewer()->removeViewProvider(vp);
868 }
869 }
870
871 return vp;
872 }
873
874
875 void Document::removeAnnotationViewProvider(const char* name)
876 {
877 delete takeAnnotationViewProvider(name);
878 }
879
880
881 ViewProvider* Document::getViewProvider(const App::DocumentObject* Feat) const
882 {
883 std::map<const App::DocumentObject*, ViewProviderDocumentObject*>::const_iterator it
884 = d->_ViewProviderMap.find(Feat);
885 return ((it != d->_ViewProviderMap.end()) ? it->second : 0);
886 }
887
888 std::vector<ViewProvider*> Document::getViewProvidersOfType(const Base::Type& typeId) const
889 {
890 std::vector<ViewProvider*> Objects;
891 for (std::map<const App::DocumentObject*, ViewProviderDocumentObject*>::const_iterator it
892 = d->_ViewProviderMap.begin();
893 it != d->_ViewProviderMap.end();
894 ++it) {
895 if (it->second->isDerivedFrom(typeId)) {
896 Objects.push_back(it->second);
897 }
898 }
899 return Objects;
900 }
901
902 ViewProvider* Document::getViewProviderByName(const char* name) const
903 {
904 // first check on feature name
905 App::DocumentObject* pcFeat = getDocument()->getObject(name);
906
907 if (pcFeat) {
908 std::map<const App::DocumentObject*, ViewProviderDocumentObject*>::const_iterator it
909 = d->_ViewProviderMap.find(pcFeat);
910
911 if (it != d->_ViewProviderMap.end()) {
912 return it->second;
913 }
914 }
915 else {
916 // then try annotation name
917 std::map<std::string, ViewProvider*>::const_iterator it2
918 = d->_ViewProviderMapAnnotation.find(name);
919
920 if (it2 != d->_ViewProviderMapAnnotation.end()) {
921 return it2->second;
922 }
923 }
924
925 return nullptr;
926 }
927
928 bool Document::isShow(const char* name)
929 {
930 ViewProvider* pcProv = getViewProviderByName(name);
931 return pcProv ? pcProv->isShow() : false;
932 }
933
934 /// put the feature in show
935 void Document::setShow(const char* name)
936 {
937 ViewProvider* pcProv = getViewProviderByName(name);
938
939 if (pcProv && pcProv->isDerivedFrom<ViewProviderDocumentObject>()) {
940 static_cast<ViewProviderDocumentObject*>(pcProv)->Visibility.setValue(true);
941 }
942 }
943
944 /// set the feature in Noshow
945 void Document::setHide(const char* name)
946 {
947 ViewProvider* pcProv = getViewProviderByName(name);
948
949 if (pcProv && pcProv->isDerivedFrom<ViewProviderDocumentObject>()) {
950 static_cast<ViewProviderDocumentObject*>(pcProv)->Visibility.setValue(false);
951 }
952 }
953
954 /// set the feature in Noshow
955 void Document::setPos(const char* name, const Base::Matrix4D& rclMtrx)
956 {
957 ViewProvider* pcProv = getViewProviderByName(name);
958 if (pcProv) {
959 pcProv->setTransformation(rclMtrx);
960 }
961 }
962
963 //*****************************************************************************************************
964 // Document
965 //*****************************************************************************************************
966 void Document::slotNewObject(const App::DocumentObject& Obj)
967 {
968 auto pcProvider = static_cast<ViewProviderDocumentObject*>(getViewProvider(&Obj));
969 if (!pcProvider) {
970 std::string cName = Obj.getViewProviderNameStored();
971 for (;;) {
972 if (cName.empty()) {
973 // handle document object with no view provider specified
974 FC_LOG(Obj.getFullName() << " has no view provider specified");
975 return;
976 }
977 Base::Type type = Base::Type::getTypeIfDerivedFrom(
978 cName.c_str(),
979 ViewProviderDocumentObject::getClassTypeId(),
980 true
981 );
982 pcProvider = static_cast<ViewProviderDocumentObject*>(type.createInstance());
983 // createInstance could return a null pointer
984 if (!pcProvider) {
985 // type not derived from ViewProviderDocumentObject!!!
986 FC_ERR("Invalid view provider type '" << cName << "' for " << Obj.getFullName());
987 return;
988 }
989 else if (cName != Obj.getViewProviderName() && !pcProvider->allowOverride(Obj)) {
990 FC_WARN("View provider type '" << cName << "' does not support " << Obj.getFullName());
991 delete pcProvider;
992 pcProvider = nullptr;
993 cName = Obj.getViewProviderName();
994 }
995 else {
996 break;
997 }
998 }
999
1000 setModified(true);
1001 d->_ViewProviderMap[&Obj] = pcProvider;
1002 d->_CoinMap[pcProvider->getRoot()] = pcProvider;
1003 pcProvider->setStatus(Gui::ViewStatus::TouchDocument, d->_changeViewTouchDocument);
1004
1005 try {
1006 // if successfully created set the right name and calculate the view
1007 // FIXME: Consider to change argument of attach() to const pointer
1008 pcProvider->attach(const_cast<App::DocumentObject*>(&Obj));
1009 pcProvider->updateView();
1010 pcProvider->setActiveMode();
1011 }
1012 catch (const Base::MemoryException& e) {
1013 FC_ERR("Memory exception in " << Obj.getFullName() << " thrown: " << e.what());
1014 }
1015 catch (Base::Exception& e) {
1016 e.reportException();
1017 }
1018 #ifndef FC_DEBUG
1019 catch (...) {
1020 FC_ERR("Unknown exception in Feature " << Obj.getFullName() << " thrown");
1021 }
1022 #endif
1023 }
1024 else {
1025 try {
1026 pcProvider->reattach(const_cast<App::DocumentObject*>(&Obj));
1027 }
1028 catch (Base::Exception& e) {
1029 e.reportException();
1030 }
1031 }
1032
1033 if (pcProvider) {
1034 std::list<Gui::BaseView*>::iterator vIt;
1035 // cycling to all views of the document
1036 for (vIt = d->baseViews.begin(); vIt != d->baseViews.end(); ++vIt) {
1037 auto activeView = dynamic_cast<View3DInventor*>(*vIt);
1038 if (activeView) {
1039 activeView->getViewer()->addViewProvider(pcProvider);
1040 }
1041 }
1042
1043 // adding to the tree
1044 signalNewObject(*pcProvider);
1045 pcProvider->pcDocument = this;
1046
1047 // it is possible that a new viewprovider already claims children
1048 handleChildren3D(pcProvider);
1049 if (d->_isTransacting) {
1050 d->_redoViewProviders.push_back(pcProvider);
1051 }
1052 }
1053 }
1054
1055 void Document::slotDeletedObject(const App::DocumentObject& Obj)
1056 {
1057 std::list<Gui::BaseView*>::iterator vIt;
1058 setModified(true);
1059
1060 // cycling to all views of the document
1061 ViewProvider* viewProvider = getViewProvider(&Obj);
1062 if (!viewProvider) {
1063 return;
1064 }
1065
1066 if (d->_editViewProvider == viewProvider || d->_editViewProviderParent == viewProvider) {
1067 _resetEdit();
1068 }
1069 else if (Application::Instance->editDocument()) {
1070 auto editDoc = Application::Instance->editDocument();
1071 if (editDoc->d->_editViewProvider == viewProvider
1072 || editDoc->d->_editViewProviderParent == viewProvider) {
1073 Application::Instance->setEditDocument(nullptr);
1074 }
1075 }
1076
1077 handleChildren3D(viewProvider, true);
1078
1079 if (viewProvider && viewProvider->isDerivedFrom(ViewProviderDocumentObject::getClassTypeId())) {
1080 // go through the views
1081 for (vIt = d->baseViews.begin(); vIt != d->baseViews.end(); ++vIt) {
1082 auto activeView = dynamic_cast<View3DInventor*>(*vIt);
1083 if (activeView) {
1084 activeView->getViewer()->removeViewProvider(viewProvider);
1085 }
1086 }
1087
1088 // removing from tree
1089 signalDeletedObject(*(static_cast<ViewProviderDocumentObject*>(viewProvider)));
1090 }
1091
1092 viewProvider->beforeDelete();
1093 }
1094
1095 void Document::beforeDelete()
1096 {
1097 auto editDoc = Application::Instance->editDocument();
1098 if (editDoc) {
1099 auto vp = freecad_cast<ViewProviderDocumentObject*>(editDoc->d->_editViewProvider);
1100 auto vpp = freecad_cast<ViewProviderDocumentObject*>(editDoc->d->_editViewProviderParent);
1101 if (editDoc == this || (vp && vp->getDocument() == this)
1102 || (vpp && vpp->getDocument() == this)) {
1103 Application::Instance->setEditDocument(nullptr);
1104 }
1105 }
1106 for (auto& v : d->_ViewProviderMap) {
1107 v.second->beforeDelete();
1108 }
1109 }
1110
1111 void Document::slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop)
1112 {
1113 ViewProvider* viewProvider = getViewProvider(&Obj);
1114 if (viewProvider) {
1115 try {
1116 viewProvider->update(&Prop);
1117 if (d->_editingViewer && d->_editingObject && d->_editViewProviderParent
1118 && (Prop.isDerivedFrom<App::PropertyPlacement>()
1119 // Issue ID 0004230 : getName() can return null in which case strstr() crashes
1120 || (Prop.getName() && strstr(Prop.getName(), "Scale")))
1121 && d->_editObjs.contains(&Obj)) {
1122 Base::Matrix4D mat;
1123 auto sobj = d->_editViewProviderParent->getObject()
1124 ->getSubObject(d->_editSubname.c_str(), nullptr, &mat);
1125 if (sobj == d->_editingObject && d->_editingTransform != mat) {
1126 d->_editingTransform = mat;
1127 d->_editingViewer->setEditingTransform(d->_editingTransform);
1128 }
1129 }
1130 }
1131 catch (const Base::MemoryException& e) {
1132 FC_ERR("Memory exception in " << Obj.getFullName() << " thrown: " << e.what());
1133 }
1134 catch (Base::Exception& e) {
1135 e.reportException();
1136 }
1137 catch (const std::exception& e) {
1138 FC_ERR("C++ exception in " << Obj.getFullName() << " thrown " << e.what());
1139 }
1140 catch (...) {
1141 FC_ERR("Cannot update representation for " << Obj.getFullName());
1142 }
1143
1144 handleChildren3D(viewProvider);
1145
1146 if (viewProvider->isDerivedFrom<ViewProviderDocumentObject>()) {
1147 signalChangedObject(static_cast<ViewProviderDocumentObject&>(*viewProvider), Prop);
1148 }
1149 }
1150
1151 // a property of an object has changed
1152 if (!Prop.testStatus(App::Property::NoModify) && !isModified()) {
1153 FC_LOG(Prop.getFullName() << " modified");
1154 setModified(true);
1155 }
1156
1157 getMainWindow()->updateActions(true);
1158 }
1159
1160 void Document::slotRelabelObject(const App::DocumentObject& Obj)
1161 {
1162 ViewProvider* viewProvider = getViewProvider(&Obj);
1163 if (viewProvider && viewProvider->isDerivedFrom<ViewProviderDocumentObject>()) {
1164 signalRelabelObject(*(static_cast<ViewProviderDocumentObject*>(viewProvider)));
1165 }
1166 }
1167
1168 void Document::slotTransactionAppend(const App::DocumentObject& obj, App::Transaction* transaction)
1169 {
1170 ViewProvider* viewProvider = getViewProvider(&obj);
1171 if (viewProvider && viewProvider->isDerivedFrom<ViewProviderDocumentObject>()) {
1172 transaction->addObjectDel(viewProvider);
1173 }
1174 }
1175
1176 void Document::slotTransactionRemove(const App::DocumentObject& obj, App::Transaction* transaction)
1177 {
1178 std::map<const App::DocumentObject*, ViewProviderDocumentObject*>::const_iterator it
1179 = d->_ViewProviderMap.find(&obj);
1180 if (it != d->_ViewProviderMap.end()) {
1181 ViewProvider* viewProvider = it->second;
1182
1183 auto itC = d->_CoinMap.find(viewProvider->getRoot());
1184 if (itC != d->_CoinMap.end()) {
1185 d->_CoinMap.erase(itC);
1186 }
1187
1188 d->_ViewProviderMap.erase(&obj);
1189 // transaction being a nullptr indicates that undo/redo is off and the object
1190 // can be safely deleted
1191 if (transaction) {
1192 transaction->addObjectNew(viewProvider);
1193 }
1194 else {
1195 delete viewProvider;
1196 }
1197 }
1198 }
1199
1200 void Document::slotActivatedObject(const App::DocumentObject& Obj)
1201 {
1202 ViewProvider* viewProvider = getViewProvider(&Obj);
1203 if (viewProvider && viewProvider->isDerivedFrom<ViewProviderDocumentObject>()) {
1204 signalActivatedObject(*(static_cast<ViewProviderDocumentObject*>(viewProvider)));
1205 }
1206 }
1207
1208 void Document::slotUndoDocument(const App::Document& doc)
1209 {
1210 if (d->_pcDocument != &doc) {
1211 return;
1212 }
1213
1214 signalUndoDocument(*this);
1215 getMainWindow()->updateActions();
1216 }
1217
1218 void Document::slotRedoDocument(const App::Document& doc)
1219 {
1220 if (d->_pcDocument != &doc) {
1221 return;
1222 }
1223
1224 signalRedoDocument(*this);
1225 getMainWindow()->updateActions();
1226 }
1227
1228 void Document::slotRecomputed(const App::Document& doc)
1229 {
1230 if (d->_pcDocument != &doc) {
1231 return;
1232 }
1233 getMainWindow()->updateActions();
1234 TreeWidget::updateStatus();
1235 }
1236
1237 // This function is called when some asks to recompute a document that is marked
1238 // as 'SkipRecompute'. We'll check if we are the current document, and if either
1239 // not given an explicit recomputing object list, or the given single object is
1240 // the eidting object or the active object. If the conditions are met, we'll
1241 // force recompute only that object and all its dependent objects.
1242 void Document::slotSkipRecompute(const App::Document& doc, const std::vector<App::DocumentObject*>& objs)
1243 {
1244 if (d->_pcDocument != &doc) {
1245 return;
1246 }
1247 if (objs.size() > 1 || App::GetApplication().getActiveDocument() != &doc
1248 || !doc.testStatus(App::Document::AllowPartialRecompute)) {
1249 return;
1250 }
1251 App::DocumentObject* obj = nullptr;
1252 auto editDoc = Application::Instance->editDocument();
1253 if (editDoc) {
1254 auto vp = freecad_cast<ViewProviderDocumentObject*>(editDoc->getInEdit());
1255 if (vp) {
1256 obj = vp->getObject();
1257 }
1258 }
1259 if (!obj) {
1260 obj = doc.getActiveObject();
1261 }
1262 if (!obj || !obj->isAttachedToDocument() || (!objs.empty() && objs.front() != obj)) {
1263 return;
1264 }
1265 obj->recomputeFeature(true);
1266 }
1267
1268 void Document::slotTouchedObject(const App::DocumentObject& Obj)
1269 {
1270 getMainWindow()->updateActions(true);
1271 if (!isModified()) {
1272 FC_LOG(Obj.getFullName() << " touched");
1273 setModified(true);
1274 }
1275 }
1276
1277 // helper that guarantees signalBeforeRecompute call is executed in the GUI thread and
1278 // that the worker waits until it finishes
1279 void Document::callSignalBeforeRecompute()
1280 {
1281 auto invokeSignalBeforeRecompute = [this] {
1282 // this runs in the GUI thread
1283 this->getDocument()->signalBeforeRecompute(*this->getDocument());
1284 };
1285
1286 if (QThread::currentThread() == qApp->thread()) {
1287 // already on GUI thread – no hop, just call it
1288 invokeSignalBeforeRecompute();
1289 }
1290 else {
1291 // hop to GUI and *block* until it returns
1292 QMetaObject::invokeMethod(
1293 qApp,
1294 std::move(invokeSignalBeforeRecompute),
1295 Qt::BlockingQueuedConnection
1296 );
1297 }
1298 }
1299
1300 void Document::addViewProvider(Gui::ViewProviderDocumentObject* vp)
1301 {
1302 // Hint: The undo/redo first adds the view provider to the Gui
1303 // document before adding the objects to the App document.
1304
1305 // the view provider is added by TransactionViewProvider and an
1306 // object can be there only once
1307 assert(d->_ViewProviderMap.find(vp->getObject()) == d->_ViewProviderMap.end());
1308 vp->setStatus(Detach, false);
1309 d->_ViewProviderMap[vp->getObject()] = vp;
1310 d->_CoinMap[vp->getRoot()] = vp;
1311 }
1312
1313 void Document::setModified(bool b)
1314 {
1315 if (d->_isModified == b) {
1316 return;
1317 }
1318 d->_isModified = b;
1319
1320 std::list<MDIView*> mdis = getMDIViews();
1321 for (auto& mdi : mdis) {
1322 mdi->setWindowModified(b);
1323 }
1324 }
1325
1326 bool Document::isModified() const
1327 {
1328 return d->_isModified;
1329 }
1330
1331 bool Document::isAboutToClose() const
1332 {
1333 return d->_isClosing;
1334 }
1335
1336 ViewProviderDocumentObject* Document::getViewProviderByPathFromTail(SoPath* path) const
1337 {
1338 // Get the lowest root node in the pick path!
1339 for (int i = 0; i < path->getLength(); i++) {
1340 SoNode* node = path->getNodeFromTail(i);
1341 if (node->isOfType(SoSeparator::getClassTypeId())) {
1342 auto it = d->_CoinMap.find(static_cast<SoSeparator*>(node));
1343 if (it != d->_CoinMap.end()) {
1344 return it->second;
1345 }
1346 }
1347 }
1348
1349 return nullptr;
1350 }
1351
1352 ViewProviderDocumentObject* Document::getViewProviderByPathFromHead(SoPath* path) const
1353 {
1354 for (int i = 0; i < path->getLength(); i++) {
1355 SoNode* node = path->getNode(i);
1356 if (node->isOfType(SoSeparator::getClassTypeId())) {
1357 auto it = d->_CoinMap.find(static_cast<SoSeparator*>(node));
1358 if (it != d->_CoinMap.end()) {
1359 return it->second;
1360 }
1361 }
1362 }
1363
1364 return nullptr;
1365 }
1366
1367 ViewProviderDocumentObject* Document::getViewProvider(SoNode* node) const
1368 {
1369 if (!node || !node->isOfType(SoSeparator::getClassTypeId())) {
1370 return nullptr;
1371 }
1372 auto it = d->_CoinMap.find(static_cast<SoSeparator*>(node));
1373 if (it != d->_CoinMap.end()) {
1374 return it->second;
1375 }
1376 return nullptr;
1377 }
1378
1379 std::vector<std::pair<ViewProviderDocumentObject*, int>> Document::getViewProvidersByPath(
1380 SoPath* path
1381 ) const
1382 {
1383 std::vector<std::pair<ViewProviderDocumentObject*, int>> ret;
1384 for (int i = 0; i < path->getLength(); i++) {
1385 SoNode* node = path->getNodeFromTail(i);
1386 if (node->isOfType(SoSeparator::getClassTypeId())) {
1387 auto it = d->_CoinMap.find(static_cast<SoSeparator*>(node));
1388 if (it != d->_CoinMap.end()) {
1389 ret.emplace_back(it->second, i);
1390 }
1391 }
1392 }
1393 return ret;
1394 }
1395
1396 App::Document* Document::getDocument() const
1397 {
1398 return d->_pcDocument;
1399 }
1400
1401 static bool checkCanonicalPath(const std::map<App::Document*, bool>& docs)
1402 {
1403 std::map<QString, std::vector<App::Document*>> paths;
1404 bool warn = false;
1405 for (auto doc : App::GetApplication().getDocuments()) {
1406 QFileInfo info(QString::fromUtf8(doc->FileName.getValue()));
1407 auto& d = paths[info.canonicalFilePath()];
1408 d.push_back(doc);
1409 if (!warn && d.size() > 1) {
1410 if (docs.contains(d.front()) || docs.contains(d.back())) {
1411 warn = true;
1412 }
1413 }
1414 }
1415 if (!warn) {
1416 return true;
1417 }
1418 QString msg;
1419 QTextStream ts(&msg);
1420 ts << QObject::tr("Identical physical path detected. It may cause unwanted overwrite of existing document!\n\n")
1421 << QObject::tr("Are you sure you want to continue?");
1422
1423 auto docName = [](App::Document* doc) -> QString {
1424 if (doc->Label.getStrValue() == doc->getName()) {
1425 return QString::fromUtf8(doc->getName());
1426 }
1427 return QStringLiteral("%1 (%2)").arg(
1428 QString::fromUtf8(doc->Label.getValue()),
1429 QString::fromUtf8(doc->getName())
1430 );
1431 };
1432 int count = 0;
1433 for (auto& v : paths) {
1434 if (v.second.size() <= 1) {
1435 continue;
1436 }
1437 for (auto doc : v.second) {
1438 if (docs.contains(doc)) {
1439 FC_WARN("Physical path: " << v.first.toUtf8().constData());
1440 for (auto d : v.second) {
1441 FC_WARN(
1442 " Document: " << docName(d).toUtf8().constData() << ": "
1443 << d->FileName.getValue()
1444 );
1445 }
1446 if (count == 3) {
1447 ts << "\n\n" << QObject::tr("Check report view for more…");
1448 }
1449 else if (count < 3) {
1450 ts << "\n\n"
1451 << QObject::tr("Physical path:") << ' ' << v.first << "\n"
1452 << QObject::tr("Document:") << ' ' << docName(doc) << "\n "
1453 << QObject::tr("Path:") << ' ' << QString::fromUtf8(doc->FileName.getValue());
1454 for (auto d : v.second) {
1455 if (d == doc) {
1456 continue;
1457 }
1458 ts << "\n"
1459 << QObject::tr("Document:") << ' ' << docName(d) << "\n "
1460 << QObject::tr("Path:") << ' '
1461 << QString::fromUtf8(d->FileName.getValue());
1462 }
1463 }
1464 ++count;
1465 break;
1466 }
1467 }
1468 }
1469 int ret = QMessageBox::warning(
1470 getMainWindow(),
1471 QObject::tr("Identical physical path"),
1472 msg,
1473 QMessageBox::Yes,
1474 QMessageBox::No
1475 );
1476 return ret == QMessageBox::Yes;
1477 }
1478
1479 bool Document::askIfSavingFailed(const QString& error)
1480 {
1481 int ret = QMessageBox::question(
1482 getMainWindow(),
1483 QObject::tr("Could not save document"),
1484 QObject::tr(
1485 "There was an issue trying to save the file. "
1486 "This may be because some of the parent folders do not exist, "
1487 "or you do not have sufficient permissions, "
1488 "or for other reasons. Error details:\n\n\"%1\"\n\n"
1489 "Would you like to save the file with a different name?"
1490 )
1491 .arg(error),
1492 QMessageBox::Yes,
1493 QMessageBox::No
1494 );
1495
1496 if (ret == QMessageBox::No) {
1497 // TODO: Understand what exactly is supposed to be returned here
1498 getMainWindow()->showMessage(QObject::tr("Saving aborted"), 2000);
1499 return false;
1500 }
1501 else if (ret == QMessageBox::Yes) {
1502 return saveAs();
1503 }
1504
1505 return false;
1506 }
1507
1508 bool Document::warnIfOlderVersion()
1509 {
1510 // Skip warning if no GUI (headless/scripted mode)
1511 if (!getMainWindow()) {
1512 return true;
1513 }
1514
1515 // Check if version checking is disabled in preferences
1516 if (App::GetApplication()
1517 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")
1518 ->GetBool("DisableVersionCheckOnSave", false)) {
1519 return true;
1520 }
1521
1522 // Get document version info
1523 const char* docVersion = d->_pcDocument->getProgramVersion();
1524 const bool hasVersionString = !Base::Tools::isNullOrEmpty(docVersion);
1525
1526 // Parse document version string like "1.0R39319 (Git)" or "0.21R33694 (Git)"
1527 // hasVersion is true only if the string is present AND parses as major.minor.
1528 // Unrecognised strings like "pre-0.14" still display in the dialog but cannot
1529 // be compared numerically, so they are treated as older versions.
1530 int docMajor = 0, docMinor = 0;
1531 const bool hasVersion = hasVersionString
1532 && std::sscanf(docVersion, "%d.%d", &docMajor, &docMinor) == 2;
1533
1534 // Get current FreeCAD version
1535 auto config = App::Application::Config();
1536 int currentMajor = 0, currentMinor = 0;
1537 if (config.count("BuildVersionMajor") && config.count("BuildVersionMinor")) {
1538 currentMajor = std::stoi(config["BuildVersionMajor"]);
1539 currentMinor = std::stoi(config["BuildVersionMinor"]);
1540 }
1541 else {
1542 return true;
1543 }
1544
1545 // Warn if the document was created with an older version or has no version info
1546 if (!hasVersion || (docMajor < currentMajor)
1547 || (docMajor == currentMajor && docMinor < currentMinor)) {
1548 QMessageBox msgBox(getMainWindow());
1549 msgBox.setWindowTitle(QObject::tr("File Created with Older FreeCAD Version"));
1550 msgBox.setIcon(QMessageBox::Warning);
1551 msgBox.setText(
1552 QObject::tr(
1553 "This file was created with %1, but you are using v%2.%3.\n\n"
1554 "Saving will upgrade the file format. The file may not be readable "
1555 "by older versions of FreeCAD after saving.\n\n"
1556 "Use 'Save As…' to preserve the original file."
1557 "\n"
1558 )
1559 .arg(
1560 !hasVersionString
1561 ? QObject::tr("an unknown older version of FreeCAD")
1562 : QObject::tr("FreeCAD version %1").arg(QString::fromUtf8(docVersion))
1563 )
1564 .arg(currentMajor)
1565 .arg(currentMinor)
1566 );
1567 QPushButton* saveButton = msgBox.addButton(QObject::tr("Save"), QMessageBox::AcceptRole);
1568 QPushButton* saveAsButton = msgBox.addButton(QObject::tr("Save As…"), QMessageBox::ActionRole);
1569 msgBox.addButton(QMessageBox::Cancel);
1570 msgBox.setDefaultButton(QMessageBox::Cancel);
1571
1572 QCheckBox dontShowCheckBox(QObject::tr("Do not show this warning again"), &msgBox);
1573 msgBox.setCheckBox(&dontShowCheckBox);
1574
1575 int ret = msgBox.exec();
1576
1577 if (msgBox.clickedButton() == saveButton) {
1578 if (dontShowCheckBox.isChecked()) {
1579 App::GetApplication()
1580 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")
1581 ->SetBool("DisableVersionCheckOnSave", true);
1582 }
1583 }
1584 else if (msgBox.clickedButton() == saveAsButton) {
1585 saveAs();
1586 return false;
1587 }
1588
1589 if (ret == QMessageBox::Cancel) {
1590 return false;
1591 }
1592 }
1593 return true;
1594 }
1595
1596 /// Save the document
1597 bool Document::save()
1598 {
1599 if (d->_pcDocument->isSaved()) {
1600 // Warn if this document was created with an older FreeCAD version
1601 if (!warnIfOlderVersion()) {
1602 return false;
1603 }
1604
1605 try {
1606 std::vector<App::Document*> docs;
1607 std::map<App::Document*, bool> dmap;
1608 try {
1609 docs = getDocument()->getDependentDocuments();
1610 for (auto it = docs.begin(); it != docs.end();) {
1611 App::Document* doc = *it;
1612 if (doc == getDocument()) {
1613 dmap[doc] = doc->mustExecute();
1614 ++it;
1615 continue;
1616 }
1617 auto gdoc = Application::Instance->getDocument(doc);
1618 if ((gdoc && !gdoc->isModified()) || doc->testStatus(App::Document::PartialDoc)
1619 || doc->testStatus(App::Document::TempDoc)) {
1620 it = docs.erase(it);
1621 continue;
1622 }
1623 dmap[doc] = doc->mustExecute();
1624 ++it;
1625 }
1626 }
1627 catch (const Base::RuntimeError& e) {
1628 FC_ERR(e.what());
1629 docs = {getDocument()};
1630 dmap.clear();
1631 dmap[getDocument()] = getDocument()->mustExecute();
1632 }
1633
1634 if (docs.size() > 1) {
1635 int ret = QMessageBox::question(
1636 getMainWindow(),
1637 QObject::tr("Save dependent files"),
1638 QObject::tr(
1639 "The file contains external dependencies. "
1640 "Do you want to save the dependent files, too?"
1641 ),
1642 QMessageBox::Yes,
1643 QMessageBox::No
1644 );
1645
1646 if (ret != QMessageBox::Yes) {
1647 docs = {getDocument()};
1648 dmap.clear();
1649 dmap[getDocument()] = getDocument()->mustExecute();
1650 }
1651 }
1652
1653 if (!checkCanonicalPath(dmap)) {
1654 return false;
1655 }
1656
1657 Gui::WaitCursor wc;
1658 // save all documents
1659 for (auto doc : docs) {
1660 // Changed 'mustExecute' status may be triggered by saving external document
1661 if (!dmap[doc] && doc->mustExecute()) {
1662 App::AutoTransaction trans("Recompute");
1663 Command::doCommand(
1664 Command::Doc,
1665 "App.getDocument(\"%s\").recompute()",
1666 doc->getName()
1667 );
1668 }
1669
1670 Command::doCommand(Command::Doc, "App.getDocument(\"%s\").save()", doc->getName());
1671 auto gdoc = Application::Instance->getDocument(doc);
1672 if (gdoc) {
1673 gdoc->setModified(false);
1674 }
1675 }
1676 }
1677 catch (const Base::FileException& e) {
1678 e.reportException();
1679 return askIfSavingFailed(QString::fromUtf8(e.what()));
1680 }
1681 catch (const Base::Exception& e) {
1682 QMessageBox::critical(
1683 getMainWindow(),
1684 QObject::tr("Saving document failed"),
1685 QString::fromLatin1(e.what())
1686 );
1687 return false;
1688 }
1689 return true;
1690 }
1691 else {
1692 return saveAs();
1693 }
1694 }
1695
1696 /// Save the document under a new file name
1697 bool Document::saveAs()
1698 {
1699 getMainWindow()->showMessage(QObject::tr("Save document under new filename…"));
1700
1701 QString exe = qApp->applicationName();
1702 QString name = QString::fromUtf8(getDocument()->FileName.getValue());
1703 if (name.isEmpty()) {
1704 name = QString::fromUtf8(getDocument()->Label.getValue());
1705 }
1706 QString fn = FileDialog::getSaveFileName(
1707 getMainWindow(),
1708 QObject::tr("Save %1 Document").arg(exe),
1709 name,
1710 QStringLiteral("%1 %2 (*.FCStd)").arg(exe, QObject::tr("Document"))
1711 );
1712
1713 if (!fn.isEmpty()) {
1714 QFileInfo fi;
1715 fi.setFile(fn);
1716
1717 const char* DocName = App::GetApplication().getDocumentName(getDocument());
1718
1719 // save as new file name
1720 try {
1721 Gui::WaitCursor wc;
1722 std::string escapedstr = Base::Tools::escapedUnicodeFromUtf8(fn.toUtf8());
1723 escapedstr = Base::Tools::escapeEncodeFilename(escapedstr);
1724 Command::doCommand(
1725 Command::Doc,
1726 "App.getDocument(\"%s\").saveAs(u\"%s\")",
1727 DocName,
1728 escapedstr.c_str()
1729 );
1730 // App::Document::saveAs() may modify the passed file name
1731 fi.setFile(QString::fromUtf8(d->_pcDocument->FileName.getValue()));
1732 setModified(false);
1733 getMainWindow()->appendRecentFile(fi.filePath());
1734 }
1735 catch (const Base::FileException& e) {
1736 e.reportException();
1737 return askIfSavingFailed(QString::fromUtf8(e.what()));
1738 }
1739 catch (const Base::Exception& e) {
1740 QMessageBox::critical(
1741 getMainWindow(),
1742 QObject::tr("Saving document failed"),
1743 QString::fromLatin1(e.what())
1744 );
1745 }
1746 return true;
1747 }
1748 else {
1749 getMainWindow()->showMessage(QObject::tr("Saving aborted"), 2000);
1750 return false;
1751 }
1752 }
1753
1754 void Document::saveAll()
1755 {
1756 std::vector<App::Document*> docs;
1757 try {
1758 docs = App::Document::getDependentDocuments(App::GetApplication().getDocuments(), true);
1759 }
1760 catch (Base::Exception& e) {
1761 e.reportException();
1762 int ret = QMessageBox::critical(
1763 getMainWindow(),
1764 QObject::tr("Failed to save document"),
1765 QObject::tr("Documents contains cyclic dependencies. Do you still want to save them?"),
1766 QMessageBox::Yes,
1767 QMessageBox::No
1768 );
1769 if (ret != QMessageBox::Yes) {
1770 return;
1771 }
1772 docs = App::GetApplication().getDocuments();
1773 }
1774
1775 std::map<App::Document*, bool> dmap;
1776 for (auto doc : docs) {
1777 if (doc->testStatus(App::Document::PartialDoc) || doc->testStatus(App::Document::TempDoc)) {
1778 continue;
1779 }
1780 dmap[doc] = doc->mustExecute();
1781 }
1782
1783 if (!checkCanonicalPath(dmap)) {
1784 return;
1785 }
1786
1787 for (auto doc : docs) {
1788 if (doc->testStatus(App::Document::PartialDoc) || doc->testStatus(App::Document::TempDoc)) {
1789 continue;
1790 }
1791 auto gdoc = Application::Instance->getDocument(doc);
1792 if (!gdoc) {
1793 continue;
1794 }
1795 if (!doc->isSaved()) {
1796 if (!gdoc->saveAs()) {
1797 break;
1798 }
1799 }
1800 Gui::WaitCursor wc;
1801
1802 try {
1803 // Changed 'mustExecute' status may be triggered by saving external document
1804 if (!dmap[doc] && doc->mustExecute()) {
1805 App::AutoTransaction trans("Recompute");
1806 Command::doCommand(Command::Doc, "App.getDocument('%s').recompute()", doc->getName());
1807 }
1808 Command::doCommand(Command::Doc, "App.getDocument('%s').save()", doc->getName());
1809 gdoc->setModified(false);
1810 }
1811 catch (const Base::Exception& e) {
1812 QMessageBox::critical(
1813 getMainWindow(),
1814 QObject::tr("Failed to save document")
1815 + QStringLiteral(": %1").arg(QString::fromUtf8(doc->getName())),
1816 QString::fromLatin1(e.what())
1817 );
1818 break;
1819 }
1820 }
1821 }
1822
1823 /// Save a copy of the document under a new file name
1824 bool Document::saveCopy()
1825 {
1826 getMainWindow()->showMessage(QObject::tr("Save a copy of the document under new filename…"));
1827
1828 QString exe = qApp->applicationName();
1829 QString fn = FileDialog::getSaveFileName(
1830 getMainWindow(),
1831 QObject::tr("Save %1 Document").arg(exe),
1832 QString::fromUtf8(getDocument()->FileName.getValue()),
1833 QObject::tr("%1 document (*.FCStd)").arg(exe)
1834 );
1835 if (!fn.isEmpty()) {
1836 const char* DocName = App::GetApplication().getDocumentName(getDocument());
1837
1838 // save as new file name
1839 Gui::WaitCursor wc;
1840 QString pyfn = Base::Tools::escapeEncodeFilename(fn);
1841 Command::doCommand(
1842 Command::Doc,
1843 "App.getDocument(\"%s\").saveCopy(\"%s\")",
1844 DocName,
1845 (const char*)pyfn.toUtf8()
1846 );
1847
1848 return true;
1849 }
1850 else {
1851 getMainWindow()->showMessage(QObject::tr("Saving aborted"), 2000);
1852 return false;
1853 }
1854 }
1855
1856 unsigned int Document::getMemSize() const
1857 {
1858 unsigned int size = 0;
1859
1860 // size of the view providers in the document
1861 std::map<const App::DocumentObject*, ViewProviderDocumentObject*>::const_iterator it;
1862 for (it = d->_ViewProviderMap.begin(); it != d->_ViewProviderMap.end(); ++it) {
1863 size += it->second->getMemSize();
1864 }
1865 return size;
1866 }
1867
1868 /**
1869 * Adds a separate XML file to the projects file that contains information about the view providers.
1870 */
1871 void Document::Save(Base::Writer& writer) const
1872 {
1873 // It's only possible to add extra information if force of XML is disabled
1874 if (!writer.isForceXML()) {
1875 writer.addFile("GuiDocument.xml", this);
1876
1877 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
1878 "User parameter:BaseApp/Preferences/Document"
1879 );
1880 if (hGrp->GetBool("SaveThumbnail", true)) {
1881 int size = hGrp->GetInt("ThumbnailSize", 256);
1882 size = Base::clamp<int>(size, 64, 512);
1883 std::list<MDIView*> mdi = getMDIViews();
1884
1885 View3DInventorViewer* view = nullptr;
1886 for (const auto& it : mdi) {
1887 if (it->isDerivedFrom<View3DInventor>()) {
1888 view = static_cast<View3DInventor*>(it)->getViewer();
1889 break;
1890 }
1891 }
1892
1893 d->thumb.setFileName(d->_pcDocument->FileName.getValue());
1894 d->thumb.setSize(size);
1895 d->thumb.setViewer(view);
1896 d->thumb.Save(writer);
1897 }
1898 }
1899 }
1900
1901 /**
1902 * Loads a separate XML file from the projects file with information about the view providers.
1903 */
1904 void Document::Restore(Base::XMLReader& reader)
1905 {
1906 reader.addFile("GuiDocument.xml", this);
1907
1908 // hide all elements to avoid to update the 3d view when loading data files
1909 // RestoreDocFile then restores the visibility status again
1910 std::map<const App::DocumentObject*, ViewProviderDocumentObject*>::iterator it;
1911 for (it = d->_ViewProviderMap.begin(); it != d->_ViewProviderMap.end(); ++it) {
1912 it->second->startRestoring();
1913 it->second->setStatus(Gui::isRestoring, true);
1914 }
1915 }
1916
1917 /**
1918 * Restores the properties of the view providers.
1919 */
1920 void Document::RestoreDocFile(Base::Reader& reader)
1921 {
1922 // We must create an XML parser to read from the input stream
1923 std::shared_ptr<Base::XMLReader> localreader
1924 = std::make_shared<Base::XMLReader>("GuiDocument.xml", reader);
1925 localreader->FileVersion = reader.getFileVersion();
1926
1927 localreader->readElement("Document");
1928 long scheme = localreader->getAttribute<long>("SchemaVersion");
1929 localreader->DocumentSchema = scheme;
1930 localreader->ProgramVersion = d->_pcDocument->getProgramVersion();
1931
1932 bool hasExpansion = localreader->hasAttribute("HasExpansion");
1933 if (hasExpansion) {
1934 auto tree = TreeWidget::instance();
1935 if (tree) {
1936 auto docItem = tree->getDocumentItem(this);
1937 if (docItem) {
1938 docItem->Restore(*localreader);
1939 }
1940 }
1941 }
1942
1943 // At this stage all the document objects and their associated view providers exist.
1944 // Now we must restore the properties of the view providers only.
1945 //
1946 // SchemeVersion "1"
1947 if (scheme == 1) {
1948 // read the viewproviders itself
1949 localreader->readElement("ViewProviderData");
1950 int Cnt = localreader->getAttribute<long>("Count");
1951 for (int i = 0; i < Cnt; i++) {
1952 localreader->readElement("ViewProvider");
1953 std::string name = localreader->getAttribute<const char*>("name");
1954
1955 bool expanded = false;
1956 if (!hasExpansion && localreader->hasAttribute("expanded")) {
1957 const char* attr = localreader->getAttribute<const char*>("expanded");
1958 if (strcmp(attr, "1") == 0) {
1959 expanded = true;
1960 }
1961 }
1962
1963 int treeRank = -1;
1964 if (localreader->hasAttribute("treeRank")) {
1965 treeRank = localreader->getAttribute<int>("treeRank");
1966 }
1967
1968 auto pObj = freecad_cast<ViewProviderDocumentObject*>(getViewProviderByName(name.c_str()));
1969 // check if this feature has been registered
1970 if (pObj) {
1971 pObj->Restore(*localreader);
1972 }
1973
1974 if (pObj && treeRank >= 0) {
1975 pObj->setTreeRank(treeRank);
1976 }
1977
1978 if (pObj && expanded) {
1979 this->signalExpandObject(*pObj, TreeItemMode::ExpandItem, 0, 0);
1980 }
1981 localreader->readEndElement("ViewProvider");
1982 }
1983 localreader->readEndElement("ViewProviderData");
1984
1985 // read camera settings
1986 localreader->readElement("Camera");
1987 const char* ppReturn = localreader->getAttribute<const char*>("settings");
1988 cameraSettings.clear();
1989 if (!Base::Tools::isNullOrEmpty(ppReturn)) {
1990 saveCameraSettings(ppReturn);
1991 try {
1992 const char** pReturnIgnore = nullptr;
1993 std::list<MDIView*> mdi = getMDIViews();
1994 for (const auto& it : mdi) {
1995 if (it->onHasMsg("SetCamera")) {
1996 it->onMsg(cameraSettings.c_str(), pReturnIgnore);
1997 }
1998 }
1999 }
2000 catch (const Base::Exception& e) {
2001 Base::Console().error("%s\n", e.what());
2002 }
2003 }
2004 }
2005
2006 reader.initLocalReader(localreader);
2007
2008 // reset modified flag
2009 setModified(false);
2010 }
2011
2012 void Document::slotStartRestoreDocument(const App::Document& doc)
2013 {
2014 if (d->_pcDocument != &doc) {
2015 return;
2016 }
2017 // disable this signal while loading a document
2018 d->connectActObjectBlocker.block();
2019 }
2020
2021 void Document::slotFinishRestoreObject(const App::DocumentObject& obj)
2022 {
2023 auto vpd = freecad_cast<ViewProviderDocumentObject*>(getViewProvider(&obj));
2024 if (vpd) {
2025 vpd->setStatus(Gui::isRestoring, false);
2026 vpd->finishRestoring();
2027 if (!vpd->canAddToSceneGraph()) {
2028 toggleInSceneGraph(vpd);
2029 }
2030 }
2031 }
2032
2033 void Document::slotFinishRestoreDocument(const App::Document& doc)
2034 {
2035 if (d->_pcDocument != &doc) {
2036 return;
2037 }
2038 d->connectActObjectBlocker.unblock();
2039 App::DocumentObject* act = doc.getActiveObject();
2040 if (act) {
2041 ViewProvider* viewProvider = getViewProvider(act);
2042 if (viewProvider && viewProvider->isDerivedFrom<ViewProviderDocumentObject>()) {
2043 signalActivatedObject(*(static_cast<ViewProviderDocumentObject*>(viewProvider)));
2044 }
2045 }
2046
2047 // reset modified flag
2048 setModified(doc.testStatus(App::Document::LinkStampChanged));
2049 }
2050
2051 void Document::slotShowHidden(const App::Document& doc)
2052 {
2053 if (d->_pcDocument != &doc) {
2054 return;
2055 }
2056
2057 Application::Instance->signalShowHidden(*this);
2058 }
2059
2060 /**
2061 * Saves the properties of the view providers.
2062 */
2063 void Document::SaveDocFile(Base::Writer& writer) const
2064 {
2065 writer.Stream() << "<?xml version='1.0' encoding='utf-8'?>" << std::endl
2066 << "<!--" << std::endl
2067 << " FreeCAD Document, see https://www.freecad.org for more information…"
2068 << std::endl
2069 << "-->" << std::endl;
2070
2071 writer.Stream() << "<Document SchemaVersion=\"1\"";
2072
2073 writer.incInd();
2074
2075 auto tree = TreeWidget::instance();
2076 bool hasExpansion = false;
2077 if (tree) {
2078 auto docItem = tree->getDocumentItem(this);
2079 if (docItem) {
2080 hasExpansion = true;
2081 writer.Stream() << " HasExpansion=\"1\">" << std::endl;
2082 docItem->Save(writer);
2083 }
2084 }
2085 if (!hasExpansion) {
2086 writer.Stream() << ">" << std::endl;
2087 }
2088
2089 // writing the view provider names itself
2090 writer.Stream() << writer.ind() << "<ViewProviderData Count=\"" << d->_ViewProviderMap.size()
2091 << "\">" << std::endl;
2092
2093 bool xml = writer.isForceXML();
2094 // writer.setForceXML(true);
2095 writer.incInd(); // indentation for 'ViewProvider name'
2096 for (const auto& it : d->_ViewProviderMap) {
2097 const App::DocumentObject* doc = it.first;
2098 ViewProviderDocumentObject* obj = it.second;
2099 writer.Stream() << writer.ind() << "<ViewProvider name=\"" << doc->getNameInDocument() << "\""
2100 << " expanded=\"" << (doc->testStatus(App::Expand) ? 1 : 0) << "\""
2101 << " treeRank=\"" << obj->getTreeRank() << "\"";
2102 if (obj->hasExtensions()) {
2103 writer.Stream() << " Extensions=\"True\"";
2104 }
2105
2106 writer.Stream() << ">" << std::endl;
2107 obj->Save(writer);
2108 writer.Stream() << writer.ind() << "</ViewProvider>" << std::endl;
2109 }
2110 writer.setForceXML(xml);
2111
2112 writer.decInd(); // indentation for 'ViewProvider name'
2113 writer.Stream() << writer.ind() << "</ViewProviderData>" << std::endl;
2114 writer.decInd(); // indentation for 'ViewProviderData Count'
2115
2116 // save camera settings
2117 std::list<MDIView*> mdi = getMDIViews();
2118 for (const auto& it : mdi) {
2119 if (it->onHasMsg("GetCamera")) {
2120 const char* ppReturn = nullptr;
2121 it->onMsg("GetCamera", &ppReturn);
2122 if (saveCameraSettings(ppReturn)) {
2123 break;
2124 }
2125 }
2126 }
2127
2128 writer.incInd(); // indentation for camera settings
2129 writer.Stream() << writer.ind() << "<Camera settings=\"" << encodeAttribute(getCameraSettings())
2130 << "\"/>\n";
2131 writer.decInd(); // indentation for camera settings
2132
2133 writer.Stream() << "</Document>" << std::endl;
2134 }
2135
2136 void Document::exportObjects(const std::vector<App::DocumentObject*>& obj, Base::Writer& writer)
2137 {
2138 writer.Stream() << "<?xml version='1.0' encoding='utf-8'?>" << std::endl;
2139 writer.Stream() << "<Document SchemaVersion=\"1\">" << std::endl;
2140
2141 std::map<const App::DocumentObject*, ViewProvider*> views;
2142 for (const auto& it : obj) {
2143 Document* doc = Application::Instance->getDocument(it->getDocument());
2144 if (doc) {
2145 ViewProvider* vp = doc->getViewProvider(it);
2146 if (vp) {
2147 views[it] = vp;
2148 }
2149 }
2150 }
2151
2152 // writing the view provider names itself
2153 writer.incInd(); // indentation for 'ViewProviderData Count'
2154 writer.Stream() << writer.ind() << "<ViewProviderData Count=\"" << views.size() << "\">"
2155 << std::endl;
2156
2157 bool xml = writer.isForceXML();
2158 // writer.setForceXML(true);
2159 writer.incInd(); // indentation for 'ViewProvider name'
2160 std::map<const App::DocumentObject*, ViewProvider*>::const_iterator jt;
2161 for (jt = views.begin(); jt != views.end(); ++jt) {
2162 const App::DocumentObject* doc = jt->first;
2163 ViewProvider* vp = jt->second;
2164 writer.Stream() << writer.ind() << "<ViewProvider name=\"" << doc->getExportName() << "\" "
2165 << "expanded=\"" << (doc->testStatus(App::Expand) ? 1 : 0) << "\"";
2166 if (vp->hasExtensions()) {
2167 writer.Stream() << " Extensions=\"True\"";
2168 }
2169
2170 writer.Stream() << ">" << std::endl;
2171 vp->Save(writer);
2172 writer.Stream() << writer.ind() << "</ViewProvider>" << std::endl;
2173 }
2174 writer.setForceXML(xml);
2175
2176 writer.decInd(); // indentation for 'ViewProvider name'
2177 writer.Stream() << writer.ind() << "</ViewProviderData>" << std::endl;
2178 writer.decInd(); // indentation for 'ViewProviderData Count'
2179 writer.incInd(); // indentation for camera settings
2180 writer.Stream() << writer.ind() << "<Camera settings=\"\"/>" << std::endl;
2181 writer.decInd(); // indentation for camera settings
2182 writer.Stream() << "</Document>" << std::endl;
2183 }
2184
2185 void Document::importObjects(
2186 const std::vector<App::DocumentObject*>& obj,
2187 Base::Reader& reader,
2188 const std::map<std::string, std::string>& nameMapping
2189 )
2190 {
2191 // We must create an XML parser to read from the input stream
2192 std::shared_ptr<Base::XMLReader> localreader
2193 = std::make_shared<Base::XMLReader>("GuiDocument.xml", reader);
2194 localreader->readElement("Document");
2195 long scheme = localreader->getAttribute<long>("SchemaVersion");
2196
2197 // At this stage all the document objects and their associated view providers exist.
2198 // Now we must restore the properties of the view providers only.
2199 //
2200 // SchemeVersion "1"
2201 if (scheme == 1) {
2202 // read the viewproviders itself
2203 localreader->readElement("ViewProviderData");
2204 int Cnt = localreader->getAttribute<long>("Count");
2205 auto it = obj.begin();
2206 for (int i = 0; i < Cnt && it != obj.end(); ++i, ++it) {
2207 // The stored name usually doesn't match with the current name anymore
2208 // thus we try to match by type. This should work because the order of
2209 // objects should not have changed
2210 localreader->readElement("ViewProvider");
2211 std::string name = localreader->getAttribute<const char*>("name");
2212 auto jt = nameMapping.find(name);
2213 if (jt != nameMapping.end()) {
2214 name = jt->second;
2215 }
2216 bool expanded = false;
2217 if (localreader->hasAttribute("expanded")) {
2218 const char* attr = localreader->getAttribute<const char*>("expanded");
2219 if (strcmp(attr, "1") == 0) {
2220 expanded = true;
2221 }
2222 }
2223 Gui::ViewProvider* pObj = this->getViewProviderByName(name.c_str());
2224 if (pObj) {
2225 pObj->setStatus(Gui::isRestoring, true);
2226 auto vpd = freecad_cast<ViewProviderDocumentObject*>(pObj);
2227 if (vpd) {
2228 vpd->startRestoring();
2229 }
2230 pObj->Restore(*localreader);
2231 if (expanded && vpd) {
2232 this->signalExpandObject(*vpd, TreeItemMode::ExpandItem, 0, 0);
2233 }
2234 }
2235 localreader->readEndElement("ViewProvider");
2236 if (it == obj.end()) {
2237 break;
2238 }
2239 }
2240 localreader->readEndElement("ViewProviderData");
2241 }
2242
2243 localreader->readEndElement("Document");
2244
2245 // In the file GuiDocument.xml new data files might be added
2246 if (localreader->hasFilenames()) {
2247 reader.initLocalReader(localreader);
2248 }
2249 }
2250
2251 void Document::slotFinishImportObjects(const std::vector<App::DocumentObject*>& objs)
2252 {
2253 (void)objs;
2254 // finishRestoring() is now triggered by signalFinishRestoreObject
2255 //
2256 // for(auto obj : objs) {
2257 // auto vp = getViewProvider(obj);
2258 // if(!vp) continue;
2259 // vp->setStatus(Gui::isRestoring,false);
2260 // auto vpd = freecad_cast<ViewProviderDocumentObject*>(vp);
2261 // if(vpd) vpd->finishRestoring();
2262 // }
2263 }
2264
2265 void Document::addRootObjectsToGroup(
2266 const std::vector<App::DocumentObject*>& obj,
2267 App::DocumentObjectGroup* grp
2268 )
2269 {
2270 std::map<App::DocumentObject*, bool> rootMap;
2271 for (const auto it : obj) {
2272 rootMap[it] = true;
2273 }
2274 // get the view providers and check which objects are children
2275 for (const auto it : obj) {
2276 Gui::ViewProvider* vp = getViewProvider(it);
2277 if (vp) {
2278 std::vector<App::DocumentObject*> child = vp->claimChildren();
2279 for (const auto& jt : child) {
2280 auto kt = rootMap.find(jt);
2281 if (kt != rootMap.end()) {
2282 kt->second = false;
2283 }
2284 }
2285 }
2286 }
2287
2288 // all objects that are not children of other objects can be added to the group
2289 for (const auto& it : rootMap) {
2290 if (it.second) {
2291 grp->addObject(it.first);
2292 }
2293 }
2294 }
2295
2296 MDIView* Document::createView(const Base::Type& typeId, CreateViewMode mode)
2297 {
2298 if (!typeId.isDerivedFrom(MDIView::getClassTypeId())) {
2299 return nullptr;
2300 }
2301
2302 std::list<MDIView*> theViews = this->getMDIViewsOfType(typeId);
2303 if (typeId == View3DInventor::getClassTypeId()) {
2304
2305 QOpenGLWidget* shareWidget = nullptr;
2306 // VBO rendering doesn't work correctly when we don't share the OpenGL widgets
2307 if (!theViews.empty()) {
2308 auto firstView = static_cast<View3DInventor*>(theViews.front());
2309 shareWidget = qobject_cast<QOpenGLWidget*>(firstView->getViewer()->getGLWidget());
2310
2311 const char* ppReturn = nullptr;
2312 firstView->onMsg("GetCamera", &ppReturn);
2313 saveCameraSettings(ppReturn);
2314 }
2315
2316 auto view3D = new View3DInventor(this, getMainWindow(), shareWidget);
2317 if (!theViews.empty()) {
2318 auto firstView = static_cast<View3DInventor*>(theViews.front());
2319 std::string overrideMode = firstView->getViewer()->getOverrideMode();
2320 view3D->getViewer()->setOverrideMode(overrideMode);
2321 }
2322
2323 // attach the viewproviders. we need to make sure that we only attach the toplevel ones
2324 // and not viewproviders which are claimed by other providers. To ensure this we first
2325 // add all providers and then remove the ones already claimed
2326 std::map<const App::DocumentObject*, ViewProviderDocumentObject*>::const_iterator It1;
2327 std::vector<App::DocumentObject*> child_vps;
2328 for (It1 = d->_ViewProviderMap.begin(); It1 != d->_ViewProviderMap.end(); ++It1) {
2329 view3D->getViewer()->addViewProvider(It1->second);
2330 std::vector<App::DocumentObject*> children = It1->second->claimChildren3D();
2331 child_vps.insert(child_vps.end(), children.begin(), children.end());
2332 }
2333 std::map<std::string, ViewProvider*>::const_iterator It2;
2334 for (It2 = d->_ViewProviderMapAnnotation.begin(); It2 != d->_ViewProviderMapAnnotation.end();
2335 ++It2) {
2336 view3D->getViewer()->addViewProvider(It2->second);
2337 std::vector<App::DocumentObject*> children = It2->second->claimChildren3D();
2338 child_vps.insert(child_vps.end(), children.begin(), children.end());
2339 }
2340
2341 for (App::DocumentObject* obj : child_vps) {
2342 view3D->getViewer()->removeViewProvider(getViewProvider(obj));
2343 }
2344
2345 // When cloning the view, don't increment the window counter as the old view will be deleted
2346 // shortly after.
2347 if (mode != CreateViewMode::Clone) {
2348 const char* name = getDocument()->Label.getValue();
2349 QString title
2350 = QStringLiteral("%1 : %2[*]").arg(QString::fromUtf8(name)).arg(d->_iWinCount++);
2351
2352 view3D->setWindowTitle(title);
2353 }
2354
2355 view3D->setWindowModified(this->isModified());
2356 view3D->resize(400, 300);
2357
2358 if (!cameraSettings.empty()) {
2359 const char* ppReturn = nullptr;
2360 view3D->onMsg(cameraSettings.c_str(), &ppReturn);
2361 }
2362
2363 // When cloning the view, don't add the view to the main window. The whole purpose of the
2364 // workaround using cloned views is that the view can be shown in undocked/fullscreen mode
2365 // without having been docked before.
2366 if (mode != CreateViewMode::Clone) {
2367 getMainWindow()->addWindow(view3D);
2368 }
2369
2370 view3D->getViewer()->redraw();
2371 return view3D;
2372 }
2373 return nullptr;
2374 }
2375
2376 const char* Document::getCameraSettings() const
2377 {
2378 return cameraSettings.size() > 10 ? cameraSettings.c_str() + 10 : cameraSettings.c_str();
2379 }
2380
2381 bool Document::saveCameraSettings(const char* settings) const
2382 {
2383 if (!settings) {
2384 return false;
2385 }
2386
2387 // skip starting comment lines
2388 bool skipping = false;
2389 char c = *settings;
2390 for (; c; c = *(++settings)) {
2391 if (skipping) {
2392 if (c == '\n') {
2393 skipping = false;
2394 }
2395 }
2396 else if (c == '#') {
2397 skipping = true;
2398 }
2399 else if (!std::isspace(c)) {
2400 break;
2401 }
2402 }
2403
2404 if (!c) {
2405 return false;
2406 }
2407
2408 cameraSettings = std::string("SetCamera ") + settings;
2409 return true;
2410 }
2411
2412 void Document::attachView(Gui::BaseView* pcView, bool bPassiv)
2413 {
2414 if (!bPassiv) {
2415 d->baseViews.push_back(pcView);
2416 }
2417 else {
2418 d->passiveViews.push_back(pcView);
2419 }
2420 }
2421
2422 void Document::detachView(Gui::BaseView* pcView, bool bPassiv)
2423 {
2424 if (bPassiv) {
2425 if (find(d->passiveViews.begin(), d->passiveViews.end(), pcView) != d->passiveViews.end()) {
2426 d->passiveViews.remove(pcView);
2427 }
2428 }
2429 else {
2430 if (find(d->baseViews.begin(), d->baseViews.end(), pcView) != d->baseViews.end()) {
2431 d->baseViews.remove(pcView);
2432 }
2433
2434 // last view?
2435 if (d->baseViews.empty()) {
2436 // decouple a passive view
2437 std::list<Gui::BaseView*>::iterator it = d->passiveViews.begin();
2438 while (it != d->passiveViews.end()) {
2439 (*it)->setDocument(nullptr);
2440 it = d->passiveViews.begin();
2441 }
2442
2443 // is already closing the document, and is not linked by other documents
2444 if (!d->_isClosing && App::PropertyXLink::getDocumentInList(getDocument()).empty()) {
2445 d->_pcAppWnd->onLastWindowClosed(this);
2446 }
2447 }
2448 }
2449 }
2450
2451 void Document::onUpdate()
2452 {
2453 #ifdef FC_LOGUPDATECHAIN
2454 Base::Console().log("Acti: Gui::Document::onUpdate()");
2455 #endif
2456
2457 std::list<Gui::BaseView*>::iterator it;
2458
2459 for (it = d->baseViews.begin(); it != d->baseViews.end(); ++it) {
2460 (*it)->onUpdate();
2461 }
2462
2463 for (it = d->passiveViews.begin(); it != d->passiveViews.end(); ++it) {
2464 (*it)->onUpdate();
2465 }
2466 }
2467
2468 void Document::onRelabel()
2469 {
2470 #ifdef FC_LOGUPDATECHAIN
2471 Base::Console().log("Acti: Gui::Document::onRelabel()");
2472 #endif
2473
2474 std::list<Gui::BaseView*>::iterator it;
2475
2476 for (it = d->baseViews.begin(); it != d->baseViews.end(); ++it) {
2477 (*it)->onRelabel(this);
2478 }
2479
2480 for (it = d->passiveViews.begin(); it != d->passiveViews.end(); ++it) {
2481 (*it)->onRelabel(this);
2482 }
2483
2484 d->connectChangeDocumentBlocker.unblock();
2485 }
2486
2487 bool Document::isLastView()
2488 {
2489 if (d->baseViews.size() <= 1) {
2490 return true;
2491 }
2492 return false;
2493 }
2494
2495 /**
2496 * This method checks if the document can be closed. It checks on
2497 * the save state of the document and is able to abort the closing.
2498 */
2499 bool Document::canClose(bool checkModify, bool checkLink)
2500 {
2501 if (d->_isClosing) {
2502 return true;
2503 }
2504 if (!getDocument()->isClosable()) {
2505 QMessageBox::warning(
2506 getActiveView(),
2507 QObject::tr("Document not closable"),
2508 QObject::tr("The document is not closable for the moment.")
2509 );
2510 return false;
2511 }
2512 // else if (!Gui::Control().isAllowedAlterDocument()) {
2513 // std::string name = Gui::Control().activeDialog()->getDocumentName();
2514 // if (name == this->getDocument()->getName()) {
2515 // QMessageBox::warning(getActiveView(),
2516 // QObject::tr("Document not closable"),
2517 // QObject::tr("The document is in editing mode and thus cannot be closed for the
2518 // moment.\n"
2519 // "You either have to finish or cancel the editing in the task panel."));
2520 // Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog();
2521 // if (dlg) Gui::Control().showDialog(dlg);
2522 // return false;
2523 // }
2524 // }
2525
2526 if (checkLink && !App::PropertyXLink::getDocumentInList(getDocument()).empty()) {
2527 return true;
2528 }
2529
2530 if (getDocument()->testStatus(App::Document::TempDoc)) {
2531 return true;
2532 }
2533
2534 bool ok = true;
2535 if (checkModify && isModified() && !getDocument()->testStatus(App::Document::PartialDoc)) {
2536 int res = getMainWindow()->confirmSave(getDocument(), getActiveView());
2537 switch (res) {
2538 case MainWindow::ConfirmSaveResult::Cancel:
2539 ok = false;
2540 break;
2541 case MainWindow::ConfirmSaveResult::SaveAll:
2542 case MainWindow::ConfirmSaveResult::Save:
2543 ok = save();
2544 if (!ok) {
2545 const QString docName = QString::fromStdString(getDocument()->Label.getStrValue());
2546 const QString text
2547 = (!docName.isEmpty()
2548 ? QObject::tr("Failed to save document '%1'. Would you like to cancel the closure?")
2549 .arg(docName)
2550 : QObject::tr(
2551 "Document saving failed. Would you like to cancel the closure?"
2552 ));
2553 int ret = QMessageBox::question(
2554 getActiveView(),
2555 QObject::tr("Unable to save document"),
2556 text,
2557 QMessageBox::Discard | QMessageBox::Cancel,
2558 QMessageBox::Discard
2559 );
2560 if (ret == QMessageBox::Discard) {
2561 ok = true;
2562 }
2563 }
2564 break;
2565 case MainWindow::ConfirmSaveResult::DiscardAll:
2566 case MainWindow::ConfirmSaveResult::Discard:
2567 ok = true;
2568 break;
2569 }
2570 }
2571
2572 if (ok) {
2573 // If a task dialog is open that doesn't allow other commands to modify
2574 // the document it must be closed by resetting the edit mode of the
2575 // corresponding view provider.
2576 if (!Gui::Control().isAllowedAlterDocument()) {
2577 std::string name = Gui::Control().activeDialog()->getDocumentName();
2578 if (name == this->getDocument()->getName()) {
2579 // getInEdit() only checks if the currently active MDI view is
2580 // a 3D view and that it is in edit mode. However, when closing a
2581 // document then the edit mode must be reset independent of the
2582 // active view.
2583 if (d->_editViewProvider) {
2584 this->_resetEdit();
2585 }
2586 }
2587 }
2588 }
2589
2590 return ok;
2591 }
2592
2593 std::list<MDIView*> Document::getMDIViews() const
2594 {
2595 std::list<MDIView*> views;
2596 for (std::list<BaseView*>::const_iterator it = d->baseViews.begin(); it != d->baseViews.end();
2597 ++it) {
2598 auto view = dynamic_cast<MDIView*>(*it);
2599 if (view) {
2600 views.push_back(view);
2601 }
2602 }
2603
2604 return views;
2605 }
2606
2607 std::list<MDIView*> Document::getMDIViewsOfType(const Base::Type& typeId) const
2608 {
2609 std::list<MDIView*> views;
2610 for (std::list<BaseView*>::const_iterator it = d->baseViews.begin(); it != d->baseViews.end();
2611 ++it) {
2612 auto view = dynamic_cast<MDIView*>(*it);
2613 if (view && view->isDerivedFrom(typeId)) {
2614 views.push_back(view);
2615 }
2616 }
2617
2618 return views;
2619 }
2620
2621 /// send messages to the active view
2622 bool Document::sendMsgToViews(const char* pMsg)
2623 {
2624 std::list<Gui::BaseView*>::iterator it;
2625 const char** pReturnIgnore = nullptr;
2626
2627 for (it = d->baseViews.begin(); it != d->baseViews.end(); ++it) {
2628 if ((*it)->onMsg(pMsg, pReturnIgnore)) {
2629 return true;
2630 }
2631 }
2632
2633 for (it = d->passiveViews.begin(); it != d->passiveViews.end(); ++it) {
2634 if ((*it)->onMsg(pMsg, pReturnIgnore)) {
2635 return true;
2636 }
2637 }
2638
2639 return false;
2640 }
2641
2642 bool Document::sendMsgToFirstView(const Base::Type& typeId, const char* pMsg, const char** ppReturn)
2643 {
2644 // first try the active view
2645 Gui::MDIView* view = getActiveView();
2646 if (view && view->isDerivedFrom(typeId)) {
2647 if (view->onMsg(pMsg, ppReturn)) {
2648 return true;
2649 }
2650 }
2651
2652 // now try the other views
2653 std::list<Gui::MDIView*> views = getMDIViewsOfType(typeId);
2654 for (const auto& it : views) {
2655 if ((it != view) && it->onMsg(pMsg, ppReturn)) {
2656 return true;
2657 }
2658 }
2659
2660 return false;
2661 }
2662
2663 /// Getter for the active view
2664 MDIView* Document::getActiveView() const
2665 {
2666 // get the main window's active view
2667 MDIView* active = getMainWindow()->activeWindow();
2668
2669 // get all MDI views of the document
2670 std::list<MDIView*> mdis = getMDIViews();
2671
2672 // check whether the active view is part of this document
2673 bool ok = false;
2674 for (const auto& mdi : mdis) {
2675 if (mdi == active) {
2676 ok = true;
2677 break;
2678 }
2679 }
2680
2681 if (ok) {
2682 return active;
2683 }
2684
2685 // the active view is not part of this document, just use the last view
2686 const auto& windows = Gui::getMainWindow()->windows();
2687 for (auto rit = mdis.rbegin(); rit != mdis.rend(); ++rit) {
2688 // Some view is removed from window list for some reason, e.g. TechDraw
2689 // hidden page has view but not in the list. By right, the view will
2690 // self delete, but not the case for TechDraw, especially during
2691 // document restore.
2692 if (windows.contains(*rit) || (*rit)->isDerivedFrom<View3DInventor>()) {
2693 return *rit;
2694 }
2695 }
2696 return nullptr;
2697 }
2698
2699 MDIView* Document::setActiveView(const ViewProviderDocumentObject* vp, Base::Type typeId)
2700 {
2701 MDIView* view = nullptr;
2702 if (!vp) {
2703 view = getActiveView();
2704 }
2705 else {
2706 view = vp->getMDIView();
2707 if (!view) {
2708 auto obj = vp->getObject();
2709 if (!obj) {
2710 view = getActiveView();
2711 }
2712 else {
2713 auto linked = obj->getLinkedObject(true);
2714 if (linked != obj) {
2715 auto vpLinked = freecad_cast<ViewProviderDocumentObject*>(
2716 Application::Instance->getViewProvider(linked)
2717 );
2718 if (vpLinked) {
2719 view = vpLinked->getMDIView();
2720 }
2721 }
2722
2723 if (!view && typeId.isBad()) {
2724 MDIView* active = getActiveView();
2725 if (active && active->containsViewProvider(vp)) {
2726 view = active;
2727 }
2728 else {
2729 typeId = View3DInventor::getClassTypeId();
2730 }
2731 }
2732 }
2733 }
2734 }
2735
2736 if (!view || (!typeId.isBad() && !view->isDerivedFrom(typeId))) {
2737 view = nullptr;
2738 for (auto* v : d->baseViews) {
2739 if (v->isDerivedFrom<MDIView>() && (typeId.isBad() || v->isDerivedFrom(typeId))) {
2740 view = static_cast<MDIView*>(v);
2741 break;
2742 }
2743 }
2744 }
2745
2746 if (!view && !typeId.isBad()) {
2747 view = createView(typeId);
2748 }
2749
2750 if (view) {
2751 getMainWindow()->setActiveWindow(view);
2752 }
2753
2754 return view;
2755 }
2756
2757 /**
2758 * @brief Document::setActiveWindow
2759 * If this document is active and the view is part of it then it will be
2760 * activated. If the document is not active or if the view is already active
2761 * nothing is done.
2762 * @param view
2763 */
2764 void Document::setActiveWindow(Gui::MDIView* view)
2765 {
2766 // get the main window's active view
2767 MDIView* active = getMainWindow()->activeWindow();
2768
2769 // view is already active
2770 if (active == view) {
2771 return;
2772 }
2773
2774 // get all MDI views of the document
2775 std::list<MDIView*> mdis = getMDIViews();
2776
2777 // this document is not active
2778 if (std::ranges::find(mdis, active) == mdis.end()) {
2779 return;
2780 }
2781
2782 // the view is not part of the document
2783 if (std::ranges::find(mdis, view) == mdis.end()) {
2784 return;
2785 }
2786
2787 getMainWindow()->setActiveWindow(view);
2788 }
2789
2790 Gui::MDIView* Document::getViewOfNode(SoNode* node) const
2791 {
2792 std::list<MDIView*> mdis = getMDIViewsOfType(View3DInventor::getClassTypeId());
2793 for (const auto& mdi : mdis) {
2794 auto view = static_cast<View3DInventor*>(mdi);
2795 if (view->getViewer()->searchNode(node)) {
2796 return mdi;
2797 }
2798 }
2799
2800 return nullptr;
2801 }
2802
2803 Gui::MDIView* Document::getViewOfViewProvider(const Gui::ViewProvider* vp) const
2804 {
2805 return getViewOfNode(vp->getRoot());
2806 }
2807
2808 Gui::MDIView* Document::getEditingViewOfViewProvider(Gui::ViewProvider* vp) const
2809 {
2810 std::list<MDIView*> mdis = getMDIViewsOfType(View3DInventor::getClassTypeId());
2811 for (const auto& mdi : mdis) {
2812 auto view = static_cast<View3DInventor*>(mdi);
2813 View3DInventorViewer* viewer = view->getViewer();
2814 // there is only one 3d view which is in edit mode
2815 if (viewer->hasViewProvider(vp) && viewer->isEditingViewProvider()) {
2816 return mdi;
2817 }
2818 }
2819
2820 return nullptr;
2821 }
2822
2823 //--------------------------------------------------------------------------
2824 // UNDO REDO transaction handling
2825 //--------------------------------------------------------------------------
2826 /** Open a new Undo transaction on the active document
2827 * This method opens a new UNDO transaction on the active document. This transaction
2828 * will later appear in the UNDO/REDO dialog with the name of the command. If the user
2829 * recall the transaction everything changed on the document between OpenCommand() and
2830 * CommitCommand will be undone (or redone). You can use an alternative name for the
2831 * operation default is the command name.
2832 * @see CommitCommand(),AbortCommand()
2833 */
2834 void Document::openCommand(const char* sName)
2835 {
2836 getDocument()->openTransaction(sName);
2837 }
2838
2839 void Document::commitCommand()
2840 {
2841 getDocument()->commitTransaction();
2842 }
2843
2844 void Document::abortCommand()
2845 {
2846 getDocument()->abortTransaction();
2847 }
2848
2849 bool Document::hasPendingCommand() const
2850 {
2851 return getDocument()->hasPendingTransaction();
2852 }
2853
2854 /// Get a string vector with the 'Undo' actions
2855 std::vector<std::string> Document::getUndoVector() const
2856 {
2857 return getDocument()->getAvailableUndoNames();
2858 }
2859
2860 /// Get a string vector with the 'Redo' actions
2861 std::vector<std::string> Document::getRedoVector() const
2862 {
2863 return getDocument()->getAvailableRedoNames();
2864 }
2865
2866 bool Document::checkTransactionID(bool undo, int iSteps)
2867 {
2868 if (!iSteps) {
2869 return false;
2870 }
2871
2872 std::vector<int> ids;
2873 for (int i = 0; i < iSteps; i++) {
2874 int id = getDocument()->getTransactionID(undo, i);
2875 if (!id) {
2876 break;
2877 }
2878 ids.push_back(id);
2879 }
2880 std::set<App::Document*> prompts;
2881 std::map<App::Document*, int> dmap;
2882 for (auto doc : App::GetApplication().getDocuments()) {
2883 if (doc == getDocument()) {
2884 continue;
2885 }
2886 for (auto id : ids) {
2887 int steps = undo ? doc->getAvailableUndos(id) : doc->getAvailableRedos(id);
2888 if (!steps) {
2889 continue;
2890 }
2891 int& currentSteps = dmap[doc];
2892 if (currentSteps + 1 != steps) {
2893 prompts.insert(doc);
2894 }
2895 if (currentSteps < steps) {
2896 currentSteps = steps;
2897 }
2898 }
2899 }
2900 if (!prompts.empty()) {
2901 std::ostringstream str;
2902 int i = 0;
2903 for (auto doc : prompts) {
2904 if (i++ == 5) {
2905 str << "...\n";
2906 break;
2907 }
2908 str << " " << doc->getName() << "\n";
2909 }
2910 int ret = QMessageBox::warning(
2911 getMainWindow(),
2912 undo ? QObject::tr("Undo") : QObject::tr("Redo"),
2913 QStringLiteral("%1,\n%2%3")
2914 .arg(
2915 QObject::tr(
2916 "There are grouped transactions in the following documents with "
2917 "other preceding transactions"
2918 ),
2919 QString::fromStdString(str.str()),
2920 QObject::tr(
2921 "Choose 'Yes' to roll back all preceding transactions.\n"
2922 "Choose 'No' to roll back in the active document only.\n"
2923 "Choose 'Abort' to abort"
2924 )
2925 ),
2926 QMessageBox::Yes | QMessageBox::No | QMessageBox::Abort,
2927 QMessageBox::Yes
2928 );
2929 if (ret == QMessageBox::Abort) {
2930 return false;
2931 }
2932 if (ret == QMessageBox::No) {
2933 return true;
2934 }
2935 }
2936 for (auto& v : dmap) {
2937 for (int i = 0; i < v.second; ++i) {
2938 if (undo) {
2939 v.first->undo();
2940 }
2941 else {
2942 v.first->redo();
2943 }
2944 }
2945 }
2946 return true;
2947 }
2948
2949 bool Document::isPerformingTransaction() const
2950 {
2951 return d->_isTransacting;
2952 }
2953
2954 /// Will UNDO one or more steps
2955 void Document::undo(int iSteps)
2956 {
2957 Base::FlagToggler<> flag(d->_isTransacting);
2958
2959 if (!checkTransactionID(true, iSteps)) {
2960 return;
2961 }
2962
2963 for (int i = 0; i < iSteps; i++) {
2964 getDocument()->undo();
2965 }
2966 App::GetApplication().signalUndo();
2967 }
2968
2969 /// Will REDO one or more steps
2970 void Document::redo(int iSteps)
2971 {
2972 Base::FlagToggler<> flag(d->_isTransacting);
2973
2974 if (!checkTransactionID(false, iSteps)) {
2975 return;
2976 }
2977
2978 for (int i = 0; i < iSteps; i++) {
2979 getDocument()->redo();
2980 }
2981 App::GetApplication().signalRedo();
2982
2983 for (auto it : d->_redoViewProviders) {
2984 handleChildren3D(it);
2985 }
2986 d->_redoViewProviders.clear();
2987 }
2988
2989 PyObject* Document::getPyObject()
2990 {
2991 _pcDocPy->IncRef();
2992 return _pcDocPy;
2993 }
2994
2995 void Document::handleChildren3D(ViewProvider* viewProvider, bool deleting)
2996 {
2997 // check for children
2998 if (viewProvider && viewProvider->getChildRoot()) {
2999 std::vector<App::DocumentObject*> children = viewProvider->claimChildren3D();
3000 SoGroup* childGroup = viewProvider->getChildRoot();
3001 SoGroup* frontGroup = viewProvider->getFrontRoot();
3002 SoGroup* backGroup = viewProvider->getFrontRoot();
3003
3004 // size not the same -> build up the list new
3005 if (deleting || childGroup->getNumChildren() != static_cast<int>(children.size())) {
3006
3007 std::set<ViewProviderDocumentObject*> oldChildren;
3008 for (int i = 0, count = childGroup->getNumChildren(); i < count; ++i) {
3009 auto it = d->_CoinMap.find(static_cast<SoSeparator*>(childGroup->getChild(i)));
3010 if (it == d->_CoinMap.end()) {
3011 continue;
3012 }
3013 oldChildren.insert(it->second);
3014 }
3015
3016 Gui::coinRemoveAllChildren(childGroup);
3017 Gui::coinRemoveAllChildren(frontGroup);
3018 Gui::coinRemoveAllChildren(backGroup);
3019
3020 if (!deleting) {
3021 for (const auto& it : children) {
3022 if (auto ChildViewProvider
3023 = dynamic_cast<ViewProviderDocumentObject*>(getViewProvider(it))) {
3024 auto itOld = oldChildren.find(ChildViewProvider);
3025 if (itOld != oldChildren.end()) {
3026 oldChildren.erase(itOld);
3027 }
3028
3029 if (SoSeparator* childRootNode = ChildViewProvider->getRoot()) {
3030 if (childRootNode == childGroup) {
3031 Base::Console().warning(
3032 "Document::handleChildren3D: Do not add "
3033 "group of '%s' to itself\n",
3034 it->getNameInDocument()
3035 );
3036 }
3037 else if (childGroup) {
3038 childGroup->addChild(childRootNode);
3039 }
3040 }
3041
3042 if (SoSeparator* childFrontNode = ChildViewProvider->getFrontRoot()) {
3043 if (childFrontNode == frontGroup) {
3044 Base::Console().warning(
3045 "Document::handleChildren3D: Do not add "
3046 "foreground group of '%s' to itself\n",
3047 it->getNameInDocument()
3048 );
3049 }
3050 else if (frontGroup) {
3051 frontGroup->addChild(childFrontNode);
3052 }
3053 }
3054
3055 if (SoSeparator* childBackNode = ChildViewProvider->getBackRoot()) {
3056 if (childBackNode == backGroup) {
3057 Base::Console().warning(
3058 "Document::handleChildren3D: Do not add "
3059 "background group of '%s' to itself\n",
3060 it->getNameInDocument()
3061 );
3062 }
3063 else if (backGroup) {
3064 backGroup->addChild(childBackNode);
3065 }
3066 }
3067
3068 // cycling to all views of the document to remove the viewprovider from the
3069 // viewer itself
3070 for (Gui::BaseView* vIt : d->baseViews) {
3071 auto activeView = dynamic_cast<View3DInventor*>(vIt);
3072 if (activeView
3073 && activeView->getViewer()->hasViewProvider(ChildViewProvider)) {
3074 // @Note hasViewProvider()
3075 // remove the viewprovider serves the purpose of detaching the
3076 // inventor nodes from the top level root in the viewer. However, if
3077 // some of the children were grouped beneath the object earlier they
3078 // are not anymore part of the toplevel inventor node. we need to
3079 // check for that.
3080 activeView->getViewer()->removeViewProvider(ChildViewProvider);
3081 }
3082 }
3083 }
3084 }
3085 }
3086
3087 // add the remaining old children back to toplevel invertor node
3088 for (auto vpd : oldChildren) {
3089 auto obj = vpd->getObject();
3090 if (!obj || !obj->isAttachedToDocument()) {
3091 continue;
3092 }
3093
3094 for (BaseView* view : d->baseViews) {
3095 auto activeView = dynamic_cast<View3DInventor*>(view);
3096 if (activeView && !activeView->getViewer()->hasViewProvider(vpd)) {
3097 activeView->getViewer()->addViewProvider(vpd);
3098 }
3099 }
3100 }
3101 }
3102 }
3103 }
3104
3105 void Document::toggleInSceneGraph(ViewProvider* vp)
3106 {
3107 // FIXME: What's the point of having this function?
3108 //
3109 for (auto view : d->baseViews) {
3110 auto activeView = dynamic_cast<View3DInventor*>(view);
3111 if (!activeView) {
3112 continue;
3113 }
3114
3115 auto root = vp->getRoot();
3116 if (!root) {
3117 continue;
3118 }
3119
3120 auto scenegraph = dynamic_cast<SoGroup*>(activeView->getViewer()->getSceneGraph());
3121 if (!scenegraph) {
3122 continue;
3123 }
3124
3125 // If it cannot be added then only check the top-level nodes
3126 if (!vp->canAddToSceneGraph()) {
3127 int idx = scenegraph->findChild(root);
3128 if (idx >= 0) {
3129 scenegraph->removeChild(idx);
3130 }
3131 }
3132 else {
3133 // Do a deep search of the scene because the root node
3134 // isn't necessarily a top-level node when claimed by
3135 // another view provider.
3136 // This is to avoid to add a node twice to the scene.
3137 SoSearchAction sa;
3138 sa.setNode(root);
3139 sa.setSearchingAll(false);
3140 sa.apply(scenegraph);
3141
3142 SoPath* path = sa.getPath();
3143 if (!path) {
3144 scenegraph->addChild(root);
3145 }
3146 }
3147 }
3148 }
3149
3150 void Document::slotChangePropertyEditor(const App::Document& doc, const App::Property& Prop)
3151 {
3152 if (getDocument() == &doc) {
3153 FC_LOG(Prop.getFullName() << " editor changed");
3154 setModified(true);
3155 getMainWindow()->setUserSchema(doc.UnitSystem.getValue());
3156 }
3157 }
3158
3159 std::vector<App::DocumentObject*> Document::getTreeRootObjects() const
3160 {
3161 std::vector<App::DocumentObject*> docObjects = d->_pcDocument->getObjects();
3162 std::unordered_map<App::DocumentObject*, bool> rootMap;
3163 for (auto it : docObjects) {
3164 rootMap[it] = true;
3165 }
3166
3167 for (auto obj : docObjects) {
3168 ViewProvider* vp = Application::Instance->getViewProvider(obj);
3169 if (!vp) {
3170 continue;
3171 }
3172
3173 std::vector<App::DocumentObject*> children = vp->claimChildren();
3174 for (auto child : children) {
3175 rootMap[child] = false;
3176 }
3177 }
3178
3179 std::vector<App::DocumentObject*> rootObjs;
3180 for (const auto& it : rootMap) {
3181 if (it.second) {
3182 rootObjs.push_back(it.first);
3183 }
3184 }
3185 return rootObjs;
3186 }