Debian Codegraph @

src/App/Document.h

raw
1 /***************************************************************************
2 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This 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 #ifndef SRC_APP_DOCUMENT_H_
24 #define SRC_APP_DOCUMENT_H_
25
26 #include <CXX/Objects.hxx>
27 #include <Base/Observer.h>
28 #include <Base/Persistence.h>
29 #include <Base/Type.h>
30 #include <Base/Handle.h>
31 #include <Base/Bitmask.h>
32
33 #include "PropertyContainer.h"
34 #include "PropertyLinks.h"
35 #include "PropertyStandard.h"
36 #include "ExportInfo.h"
37
38 #include <map>
39 #include <vector>
40 #include <utility>
41 #include <list>
42 #include <string>
43
44 namespace Base
45 {
46 class Writer;
47 }
48
49 namespace App
50 {
51 enum class AddObjectOption
52 {
53 None = 0,
54 SetNewStatus = 1,
55 SetPartialStatus = 2,
56 UnsetPartialStatus = 4,
57 DoSetup = 8,
58 ActivateObject = 16
59 };
60 using AddObjectOptions = Base::Flags<AddObjectOption>;
61
62 enum class RemoveObjectOption
63 {
64 None = 0,
65 MayRemoveWhileRecomputing = 1,
66 MayDestroyOutOfTransaction = 2,
67 DestroyOnRollback = 4,
68 PreserveChildrenVisibility = 8
69 };
70 using RemoveObjectOptions = Base::Flags<RemoveObjectOption>;
71
72 }
73 ENABLE_BITMASK_OPERATORS(App::AddObjectOption)
74 ENABLE_BITMASK_OPERATORS(App::RemoveObjectOption)
75
76 namespace App
77 {
78 class TransactionalObject;
79 class DocumentObject;
80 class DocumentObjectExecReturn;
81 class Document;
82 class DocumentPy;
83 class Application;
84 class Transaction;
85 class StringHasher;
86 using StringHasherRef = Base::Reference<StringHasher>;
87
88 /**
89 * @brief The document class
90 * @ingroup DocumentGroup
91 * @details For a more high-level discussion see the topic @ref DocumentGroup "Document".
92 */
93 class AppExport Document: public PropertyContainer
94 {
95 PROPERTY_HEADER_WITH_OVERRIDE(App::Document);
96
97 public:
98 // clang-format off
99 enum Status
100 {
101 SkipRecompute = 0,
102 KeepTrailingDigits = 1,
103 Closable = 2,
104 Restoring = 3,
105 Recomputing = 4,
106 PartialRestore = 5,
107 Importing = 6,
108 PartialDoc = 7,
109 AllowPartialRecompute = 8, // allow recomputing editing object if SkipRecompute is set
110 TempDoc = 9, // Mark as temporary document without prompt for save
111 RestoreError = 10,
112 LinkStampChanged = 11, // Indicates during restore time if any linked document's time stamp has changed
113 IgnoreErrorOnRecompute = 12, // Don't report errors if the recompute failed
114 RecomputeOnRestore = 13, // Mark pending recompute on restore for migration purposes
115 MigrateLCS = 14 // Migrate local coordinate system of older versions
116 };
117 // clang-format on
118
119 // NOLINTBEGIN
120 /** @name Properties */
121 //@{
122 /// holds the long name of the document (utf-8 coded)
123 PropertyString Label;
124 /// full qualified (with path) file name (utf-8 coded)
125 PropertyString FileName;
126 /// creators name (utf-8)
127 PropertyString CreatedBy;
128 PropertyString CreationDate;
129 /// user last modified the document
130 PropertyString LastModifiedBy;
131 PropertyString LastModifiedDate;
132 /// company name UTF8(optional)
133 PropertyString Company;
134 /// Unit System
135 PropertyEnumeration UnitSystem;
136 /// long comment or description (UTF8 with line breaks)
137 PropertyString Comment;
138 /// Id e.g. Part number
139 PropertyString Id;
140 /// unique identifier of the document
141 PropertyUUID Uid;
142 /// Full name of the licence e.g. "Creative Commons Attribution". See https://spdx.org/licenses/
143 PropertyString License;
144 /// License description/contract URL
145 PropertyString LicenseURL;
146 /// Meta descriptions
147 PropertyMap Meta;
148 /// Material descriptions, used and defined in the Material module.
149 PropertyMap Material;
150 /// read-only name of the temp dir created when the document is opened
151 PropertyString TransientDir;
152 /// Tip object of the document (if any)
153 PropertyLink Tip;
154 /// Tip object of the document (if any)
155 PropertyString TipName;
156 /// Whether to show hidden items in TreeView
157 PropertyBool ShowHidden;
158 /// Whether to use hasher on topological naming
159 PropertyBool UseHasher;
160 //@}
161
162 /** @name Signals of the document */
163 //@{
164 // clang-format off
165 /// signal before changing an doc property
166 boost::signals2::signal<void(const Document&, const Property&)> signalBeforeChange;
167 /// signal on changed doc property
168 boost::signals2::signal<void(const Document&, const Property&)> signalChanged;
169 /// signal on new Object
170 boost::signals2::signal<void(const DocumentObject&)> signalNewObject;
171 /// signal on deleted Object
172 boost::signals2::signal<void(const DocumentObject&)> signalDeletedObject;
173 /// signal before changing an Object
174 boost::signals2::signal<void(const DocumentObject&, const Property&)> signalBeforeChangeObject;
175 /// signal on changed Object
176 boost::signals2::signal<void(const DocumentObject&, const Property&)> signalChangedObject;
177 /// signal on manually called DocumentObject::touch()
178 boost::signals2::signal<void(const DocumentObject&)> signalTouchedObject;
179 /// signal on relabeled Object
180 boost::signals2::signal<void(const DocumentObject&)> signalRelabelObject;
181 /// signal on activated Object
182 boost::signals2::signal<void(const DocumentObject&)> signalActivatedObject;
183 /// signal on created object
184 boost::signals2::signal<void(const DocumentObject&, Transaction*)> signalTransactionAppend;
185 /// signal on removed object
186 boost::signals2::signal<void(const DocumentObject&, Transaction*)> signalTransactionRemove;
187 /// signal on undo
188 boost::signals2::signal<void(const Document&)> signalUndo;
189 /// signal on redo
190 boost::signals2::signal<void(const Document&)> signalRedo;
191 /** signal on load/save document
192 * this signal is given when the document gets streamed.
193 * you can use this hook to write additional information in
194 * the file (like the Gui::Document does).
195 */
196 boost::signals2::signal<void(Base::Writer&)> signalSaveDocument;
197 boost::signals2::signal<void(Base::XMLReader&)> signalRestoreDocument;
198 boost::signals2::signal<void(const std::vector<DocumentObject*>&, Base::Writer&)> signalExportObjects;
199 boost::signals2::signal<void(const std::vector<DocumentObject*>&, Base::Writer&)> signalExportViewObjects;
200 boost::signals2::signal<void(const std::vector<DocumentObject*>&, Base::XMLReader&)> signalImportObjects;
201 boost::signals2::signal<void(const std::vector<DocumentObject*>&, Base::Reader&,
202 const std::map<std::string, std::string>&)> signalImportViewObjects;
203 boost::signals2::signal<void(const std::vector<DocumentObject*>&)> signalFinishImportObjects;
204 // signal starting a save action to a file
205 boost::signals2::signal<void(const Document&, const std::string&)> signalStartSave;
206 // signal finishing a save action to a file
207 boost::signals2::signal<void(const Document&, const std::string&)> signalFinishSave;
208 boost::signals2::signal<void(const Document&)> signalBeforeRecompute;
209 boost::signals2::signal<void(const Document&, const std::vector<DocumentObject*>&)> signalRecomputed;
210 boost::signals2::signal<void(const DocumentObject&)> signalRecomputedObject;
211 // signal a new opened transaction
212 boost::signals2::signal<void(const Document&, std::string)> signalOpenTransaction;
213 // signal a committed transaction
214 boost::signals2::signal<void(const Document&)> signalCommitTransaction;
215 // signal an aborted transaction
216 boost::signals2::signal<void(const Document&)> signalAbortTransaction;
217 boost::signals2::signal<void(const Document&, const std::vector<DocumentObject*>&)> signalSkipRecompute;
218 boost::signals2::signal<void(const DocumentObject&)> signalFinishRestoreObject;
219 boost::signals2::signal<void(const Document&, const Property&)> signalChangePropertyEditor;
220 boost::signals2::signal<void(std::string)> signalLinkXsetValue;
221 // clang-format on
222 //@}
223 // NOLINTEND
224
225 using PreRecomputeHook = std::function<void()>;
226 void setPreRecomputeHook(const PreRecomputeHook& hook);
227
228 void clearDocument();
229
230 /** @name File handling of the document */
231 //@{
232 /// Save the Document under a new Name
233 // void saveAs (const char* Name);
234 /// Save the document to the file in Property Path
235 bool save();
236 bool saveAs(const char* file);
237 bool saveCopy(const char* file) const;
238 /// Restore the document from the file in Property Path
239 void restore(const char* filename = nullptr,
240 bool delaySignal = false,
241 const std::vector<std::string>& objNames = {});
242 bool afterRestore(bool checkPartial = false);
243 bool afterRestore(const std::vector<DocumentObject*>&, bool checkPartial = false);
244 enum ExportStatus
245 {
246 NotExporting,
247 Exporting,
248 };
249 ExportStatus isExporting(const DocumentObject* obj) const;
250 ExportInfo exportInfo() const;
251 void setExportInfo(const ExportInfo& info);
252 void exportObjects(const std::vector<DocumentObject*>&, std::ostream&);
253 void exportGraphviz(std::ostream&) const;
254 std::vector<DocumentObject*> importObjects(Base::XMLReader& reader);
255 /** Import any externally linked objects
256 *
257 * @param objs: input list of objects. Only objects belonging to this document will
258 * be checked for external links. And all found external linked object will be imported
259 * to this document. Link type properties of those input objects will be automatically
260 * reassigned to the imported objects. Note that the link properties of other objects
261 * in the document but not included in the input list, will not be affected even if they
262 * point to some object beining imported. To import all objects, simply pass in all objects
263 * of this document.
264 *
265 * @return the list of imported objects
266 */
267 std::vector<DocumentObject*>
268 importLinks(const std::vector<DocumentObject*>& objs = {});
269 /// Opens the document from its file name
270 // void open (void);
271 /// Is the document already saved to a file?
272 bool isSaved() const;
273 /// Get the document name
274 const char* getName() const;
275 /// Get program version the project file was created with
276 const char* getProgramVersion() const;
277 /** Returned filename
278 *
279 * For saved document, this will be the content stored in property
280 * 'Filename'. For unsaved temporary file, this will be the content of
281 * property 'TransientDir'.
282 */
283 const char* getFileName() const;
284 //@}
285
286 void Save(Base::Writer& writer) const override;
287 void Restore(Base::XMLReader& reader) override;
288
289 /// returns the complete document memory consumption, including all managed DocObjects and Undo
290 /// Redo.
291 unsigned int getMemSize() const override;
292
293 /** @name Object handling */
294 //@{
295 /** Add a feature of sType with sName (ASCII) to this document and set it active.
296 * Unicode names are set through the Label property.
297 * @param sType the type of created object
298 * @param pObjectName if nonNULL use that name otherwise generate a new unique name based on the
299 * \a sType
300 * @param isNew if false don't call the \c DocumentObject::setupObject() callback (default
301 * is true)
302 * @param viewType override object's view provider name
303 * @param isPartial indicate if this object is meant to be partially loaded
304 */
305 DocumentObject* addObject(const char* sType,
306 const char* pObjectName = nullptr,
307 bool isNew = true,
308 const char* viewType = nullptr,
309 bool isPartial = false);
310 //@{
311 /** Add a feature of T type with sName (ASCII) to this document and set it active.
312 * Unicode names are set through the Label property.
313 * @param pObjectName if nonNULL use that name otherwise generate a new unique name based on the
314 * \a sType
315 * @param isNew if false don't call the \c DocumentObject::setupObject() callback (default
316 * is true)
317 * @param viewType override object's view provider name
318 * @param isPartial indicate if this object is meant to be partially loaded
319 */
320 template<typename T>
321 T* addObject(const char* pObjectName = nullptr,
322 bool isNew = true,
323 const char* viewType = nullptr,
324 bool isPartial = false);
325 /** Add an array of features of the given types and names.
326 * Unicode names are set through the Label property.
327 * @param sType The type of created object
328 * @param objectNames A list of object names
329 * @param isNew If false don't call the \c DocumentObject::setupObject() callback (default
330 * is true)
331 */
332 std::vector<DocumentObject*>
333 addObjects(const char* sType, const std::vector<std::string>& objectNames, bool isNew = true);
334 /// Remove a feature out of the document
335 void removeObject(const char* sName);
336 /** Add an existing feature with sName (ASCII) to this document and set it active.
337 * Unicode names are set through the Label property.
338 * This is an overloaded function of the function above and can be used to create
339 * a feature outside and add it to the document afterwards.
340 * \note The passed feature must not yet be added to a document, otherwise an exception
341 * is raised.
342 */
343 void addObject(DocumentObject*, const char* pObjectName = nullptr);
344
345 /// returns whether this is actually contains the DocumentObject.
346 /// Testing the DocumentObject's pDoc pointer is not sufficient because the object
347 /// removeObject and _removeObject leave _pDoc unchanged
348 bool containsObject(const DocumentObject*) const;
349
350 /** Copy objects from another document to this document
351 *
352 * @param objs
353 * @param recursive: if true, then all objects this object depends on are
354 * copied as well. By default \a recursive is false.
355 *
356 * @param returnAll: if true, return all copied objects including those
357 * auto included by recursive searching. If false, then only return the
358 * copied object corresponding to the input objects.
359 *
360 * @return Returns the list of objects copied.
361 */
362 std::vector<DocumentObject*> copyObject(const std::vector<DocumentObject*>& objs,
363 bool recursive = false,
364 bool returnAll = false);
365 /** Move an object from another document to this document
366 * If \a recursive is true then all objects this object depends on
367 * are moved as well. By default \a recursive is false.
368 * Returns the moved object itself or 0 if the object is already part of this
369 * document..
370 */
371 DocumentObject* moveObject(DocumentObject* obj, bool recursive = false);
372 /// Returns the active Object of this document
373 DocumentObject* getActiveObject() const;
374 /// Returns a Object of this document
375 DocumentObject* getObject(const char* Name) const;
376 /// Returns a Object of this document by its id
377 DocumentObject* getObjectByID(long id) const;
378 /// Returns true if the DocumentObject is contained in this document
379 bool isIn(const DocumentObject* pFeat) const;
380 /// Returns a Name of an Object or 0
381 const char *getObjectName(const DocumentObject* pFeat) const;
382 /// Returns a Name for a new Object or empty if proposedName is null or empty.
383 std::string getUniqueObjectName(const char* proposedName) const;
384 /// Returns a name different from any of the Labels of any objects in this document, based on the given modelName.
385 std::string getStandardObjectLabel(const char* modelName, int d) const;
386 /// Determine if a given DocumentObject Name and a proposed Label are based on the same base name
387 bool haveSameBaseName(const std::string& name, const std::string& label);
388 /// Returns a list of document's objects including the dependencies
389 std::vector<DocumentObject*> getDependingObjects() const;
390 /// Returns a list of all Objects
391 const std::vector<DocumentObject*>& getObjects() const;
392 std::vector<DocumentObject*> getObjectsOfType(const Base::Type& typeId) const;
393 std::vector<DocumentObject*> getObjectsOfType(const std::vector<Base::Type>& types) const;
394 /// Returns all object with given extensions. If derived=true also all objects with extensions
395 /// derived from the given one
396 std::vector<DocumentObject*> getObjectsWithExtension(const Base::Type& typeId,
397 bool derived = true) const;
398 std::vector<DocumentObject*>
399 findObjects(const Base::Type& typeId, const char* objname, const char* label) const;
400 /// Returns an array with the correct types already.
401 template<typename T>
402 inline std::vector<T*> getObjectsOfType() const;
403 template<typename T>
404 inline int countObjectsOfType() const;
405 int countObjectsOfType(const char* typeName) const;
406 /// get the number of objects in the document
407 int countObjects() const;
408 //@}
409
410 /** @name methods for modification and state handling
411 */
412 //@{
413 /// Remove all modifications. After this call The document becomes Valid again.
414 void purgeTouched();
415 /// check if there is any touched object in this document
416 bool isTouched() const;
417 /// check if there is any object must execute in this document
418 bool mustExecute() const;
419 /// returns all touched objects
420 std::vector<DocumentObject*> getTouched() const;
421 /// set the document to be closable, this is on by default.
422 void setClosable(bool);
423 /// check whether the document can be closed
424 bool isClosable() const;
425 /// set the document to autoCreated, this is off by default.
426 void setAutoCreated(bool);
427 /// check whether the document is autoCreated.
428 bool isAutoCreated() const;
429 /** Recompute touched features and return the number of recalculated features
430 *
431 * @param objs: specify a sub set of objects to recompute. If empty, then
432 * all object in this document is checked for recompute
433 * @param force
434 * @param hasError
435 * @param options
436 */
437 int recompute(const std::vector<DocumentObject*>& objs = {},
438 bool force = false,
439 bool* hasError = nullptr,
440 int options = 0);
441 /// Recompute only one feature
442 bool recomputeFeature(DocumentObject* Feat, bool recursive = false);
443 /// get the text of the error of a specified object
444 const char* getErrorDescription(const DocumentObject*) const;
445 /// return the status bits
446 bool testStatus(Status pos) const;
447 /// set the status bits
448 void setStatus(Status pos, bool on);
449 //@}
450
451
452 /** @name methods for the UNDO REDO and Transaction handling
453 *
454 * Introduce a new concept of transaction ID. Each transaction must be
455 * unique inside the document. Multiple transactions from different
456 * documents can be grouped together with the same transaction ID.
457 *
458 * When undo, Gui component can query getAvailableUndo(id) to see if it is
459 * possible to undo with a given ID. If there more than one undo
460 * transactions, meaning that there are other transactions before the given
461 * ID. The Gui component shall ask user if they want to undo multiple steps.
462 * And if the user agrees, call undo(id) to unroll all transaction before
463 * and including the one with the given ID. Same applies for redo.
464 *
465 * The new transaction ID describe here is fully backward compatible.
466 * Calling the APIs with a default id=0 gives the original behavior.
467 */
468 //@{
469 /// switch the level of Undo/Redo
470 void setUndoMode(int iMode);
471 /// switch the level of Undo/Redo
472 int getUndoMode() const;
473 /// switch the transaction mode
474 void setTransactionMode(int iMode);
475 /** Open a new command Undo/Redo, an UTF-8 name can be specified
476 *
477 * @param name: transaction name
478 *
479 * This function calls Application::setActiveTransaction(name) instead
480 * to setup a potential transaction which will only be created if there is
481 * actual changes.
482 */
483 void openTransaction(const char* name = nullptr);
484 /// Rename the current transaction if the id matches
485 void renameTransaction(const char* name, int id) const;
486 /// Commit the Command transaction. Do nothing If there is no Command transaction open.
487 void commitTransaction();
488 /// Abort the actually running transaction.
489 void abortTransaction() const;
490 /// Check if a transaction is open
491 bool hasPendingTransaction() const;
492 /// Return the undo/redo transaction ID starting from the back
493 int getTransactionID(bool undo, unsigned pos = 0) const;
494 /// Check if a transaction is open and its list is empty.
495 /// If no transaction is open true is returned.
496 bool isTransactionEmpty() const;
497 /// Set the Undo limit in Byte!
498 void setUndoLimit(unsigned int UndoMemSize = 0);
499 /// Returns the actual memory consumption of the Undo redo stuff.
500 unsigned int getUndoMemSize() const;
501 /// Set the Undo limit as stack size
502 void setMaxUndoStackSize(unsigned int UndoMaxStackSize = 20); // NOLINT
503 /// Set the Undo limit as stack size
504 unsigned int getMaxUndoStackSize() const;
505 /// Remove all stored Undos and Redos
506 void clearUndos();
507 /// Returns the number of stored Undos. If greater than 0 Undo will be effective.
508 int getAvailableUndos(int id = 0) const;
509 /// Returns a list of the Undo names
510 std::vector<std::string> getAvailableUndoNames() const;
511 /// Will UNDO one step, returns False if no undo was done (Undos == 0).
512 bool undo(int id = 0);
513 /// Returns the number of stored Redos. If greater than 0 Redo will be effective.
514 int getAvailableRedos(int id = 0) const;
515 /// Returns a list of the Redo names.
516 std::vector<std::string> getAvailableRedoNames() const;
517 /// Will REDO one step, returns False if no redo was done (Redos == 0).
518 bool redo(int id = 0);
519 /// returns true if the document is in an Transaction phase, e.g. currently performing a
520 /// redo/undo or rollback
521 bool isPerformingTransaction() const;
522 /// \internal add or remove property from a transactional object
523 void addOrRemovePropertyOfObject(TransactionalObject*, const Property* prop, bool add);
524 void renamePropertyOfObject(TransactionalObject*, const Property* prop, const char* newName);
525 //@}
526
527 /** @name dependency stuff */
528 //@{
529 /// write GraphViz file
530 void writeDependencyGraphViz(std::ostream& out);
531 /// checks if the graph is directed and has no cycles
532 static bool checkOnCycle();
533 /// get a list of all objects linking to the given object
534 std::vector<DocumentObject*> getInList(const DocumentObject* me) const;
535
536 /// Option bit flags used by getDepenencyList()
537 enum DependencyOption
538 {
539 /// Return topological sorted list
540 DepSort = 1,
541 /// Do no include object linked by PropertyXLink, as it can handle external link
542 DepNoXLinked = 2,
543 /// Raise exception on cycles
544 DepNoCycle = 4,
545 };
546 /** Get a complete list of all objects the given objects depend on.
547 *
548 * This function is defined as static because it accepts objects from
549 * different documents, and the returned list will contain dependent
550 * objects from all relevant documents
551 *
552 * @param objs: input objects to query for dependency.
553 * @param options: See DependencyOption
554 */
555 static std::vector<DocumentObject*>
556 getDependencyList(const std::vector<DocumentObject*>& objs, int options = 0);
557
558 std::vector<Document*> getDependentDocuments(bool sort = true);
559 static std::vector<Document*> getDependentDocuments(std::vector<Document*> docs,
560 bool sort);
561
562 // set Changed
563 // void setChanged(DocumentObject* change);
564 /// get a list of topological sorted objects (https://en.wikipedia.org/wiki/Topological_sorting)
565 std::vector<DocumentObject*> topologicalSort() const;
566 /// get all root objects (objects no other one reference too)
567 std::vector<DocumentObject*> getRootObjects() const;
568 /// get all tree root objects (objects that are at the root of the object tree)
569 std::vector<DocumentObject*> getRootObjectsIgnoreLinks() const;
570 /// get all possible paths from one object to another following the OutList
571 std::vector<std::list<DocumentObject*>>
572 getPathsByOutList(const DocumentObject* from, const DocumentObject* to) const;
573 //@}
574
575 /** Called by a property during save to store its StringHasher
576 *
577 * @param hasher: the input hasher
578 * @return Returns a pair<bool,int>. The boolean indicates if the
579 * StringHasher has been added before. The integer is the hasher index.
580 *
581 * The StringHasher object is designed to be shared among multiple objects.
582 * We must not save duplicate copies of the same hasher, and must be
583 * able to restore with the same sharing relationship. This function returns
584 * whether the hasher has been added before by other objects, and the index
585 * of the hasher. If the hasher has not been added before, the object must
586 * save the hasher by calling StringHasher::Save
587 */
588 std::pair<bool, int> addStringHasher(const StringHasherRef& hasher) const;
589
590 /** Called by property to restore its StringHasher
591 *
592 * @param index: the index previously returned by calling addStringHasher()
593 * during save. Or if is negative, then return document's own string hasher.
594 *
595 * @return Return the resulting string hasher.
596 *
597 * The caller is responsible for restoring the hasher if the caller is the first
598 * owner of the hasher, i.e. if addStringHasher() returns true during save.
599 */
600 StringHasherRef getStringHasher(int index = -1) const;
601
602 /** Return the links to a given object
603 *
604 * @param links: holds the links found
605 * @param obj: the linked object. If NULL, then all links are returned.
606 * @param options: @sa GetLinkOption
607 * @param maxCount: limit the number of links returned, 0 means no limit
608 * @param objs: optional objects to search for, if empty, then all objects
609 * of this document are searched.
610 */
611 void getLinksTo(std::set<DocumentObject*>& links,
612 const DocumentObject* obj,
613 int options,
614 int maxCount = 0,
615 const std::vector<DocumentObject*>& objs = {}) const;
616
617 /// Check if there is any link to the given object
618 bool hasLinksTo(const DocumentObject* obj) const;
619
620 /// Called by objects during restore to ask for recompute
621 void addRecomputeObject(DocumentObject* obj);
622
623 const std::string& getOldLabel() const
624 {
625 return oldLabel;
626 }
627
628 /// Function called to signal that an object identifier has been renamed
629 void renameObjectIdentifiers(
630 const std::map<ObjectIdentifier, ObjectIdentifier>& paths,
631 const std::function<bool(const DocumentObject*)>& selector =
632 [](const DocumentObject*) {
633 return true;
634 });
635
636 PyObject* getPyObject() override;
637
638 std::string getFullName() const override;
639
640 /// Indicate if there is any document restoring/importing
641 static bool isAnyRestoring();
642
643 void registerLabel(const std ::string& newLabel);
644 void unregisterLabel(const std::string& oldLabel);
645 bool containsLabel(const std::string& label);
646 std::string makeUniqueLabel(const std::string& modelLabel);
647
648 friend class Application;
649 /// because of transaction handling
650 friend class TransactionalObject;
651 friend class DocumentObject;
652 friend class Transaction;
653 friend class TransactionDocumentObject;
654
655 /// Destruction
656 ~Document() override;
657
658 protected:
659 /// Construction
660 explicit Document(const char* documentName = "");
661
662 void _removeObject(DocumentObject* pcObject, RemoveObjectOptions options = RemoveObjectOption::DestroyOnRollback | RemoveObjectOption::PreserveChildrenVisibility);
663 void _addObject(DocumentObject* pcObject, const char* pObjectName, AddObjectOptions options = AddObjectOption::ActivateObject, const char* viewType = nullptr);
664 /// checks if a valid transaction is open
665 void _checkTransaction(DocumentObject* pcDelObj, const Property* What, int line);
666 void breakDependency(DocumentObject* pcObject, bool clear);
667 std::vector<DocumentObject*> readObjects(Base::XMLReader& reader);
668 void writeObjects(const std::vector<DocumentObject*>&, Base::Writer& writer) const;
669 bool saveToFile(const char* filename) const;
670 int countObjectsOfType(const Base::Type& typeId) const;
671
672 void onBeforeChange(const Property* prop) override;
673 void onChanged(const Property* prop) override;
674 /// callback from the Document objects before property will be changed
675 void onBeforeChangeProperty(const TransactionalObject* Who, const Property* What);
676 /// callback from the Document objects after property was changed
677 void onChangedProperty(const DocumentObject* Who, const Property* What);
678 /// helper which Recompute only this feature
679 /// @return 0 if succeeded, 1 if failed, -1 if aborted by user.
680 int _recomputeFeature(DocumentObject* Feat);
681 void _clearRedos();
682
683 /// refresh the internal dependency graph
684 void _rebuildDependencyList(
685 const std::vector<DocumentObject*>& objs = std::vector<DocumentObject*>());
686
687 std::string getTransientDirectoryName(const std::string& uuid,
688 const std::string& filename) const;
689
690 /** Open a new command Undo/Redo, an UTF-8 name can be specified
691 *
692 * @param name: transaction name
693 * @param id: transaction ID, if 0 then the ID is auto generated.
694 *
695 * @return: Return the ID of the new transaction.
696 *
697 * This function creates an actual transaction regardless of Application
698 * AutoTransaction setting.
699 */
700 int _openTransaction(const char* name = nullptr, int id = 0);
701 /// Internally called by Application to commit the Command transaction.
702 void _commitTransaction(bool notify = false);
703 /// Internally called by Application to abort the running transaction.
704 void _abortTransaction();
705
706 private:
707 void changePropertyOfObject(TransactionalObject* obj, const Property* prop,
708 const std::function<void()>& changeFunc);
709
710 private:
711 // # Data Member of the document
712 // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
713 std::list<Transaction*> mUndoTransactions;
714 std::map<int, Transaction*> mUndoMap;
715 std::list<Transaction*> mRedoTransactions;
716 std::map<int, Transaction*> mRedoMap;
717
718 struct DocumentP* d;
719
720 std::string oldLabel;
721 std::string myName;
722 bool autoCreated; // Flag to know if the document was automatically created at startup
723 };
724
725 template<typename T>
726 inline std::vector<T*> Document::getObjectsOfType() const
727 {
728 std::vector<T*> type;
729 const std::vector<DocumentObject*> obj = this->getObjectsOfType(T::getClassTypeId());
730 type.reserve(obj.size());
731 for (auto it : obj) {
732 type.push_back(static_cast<T*>(it));
733 }
734 return type;
735 }
736
737 template<typename T>
738 inline int Document::countObjectsOfType() const
739 {
740 static_assert(std::is_base_of_v<DocumentObject, T>,
741 "T must be derived from App::DocumentObject");
742 return this->countObjectsOfType(T::getClassTypeId());
743 }
744
745 template<typename T>
746 T* Document::addObject(const char* pObjectName, bool isNew, const char* viewType, bool isPartial)
747 {
748 static_assert(std::is_base_of<DocumentObject, T>::value, "T must be derived from DocumentObject");
749 return static_cast<T*>(addObject(T::getClassName(), pObjectName, isNew, viewType, isPartial));
750 }
751
752 } // namespace App
753
754 #endif // SRC_APP_DOCUMENT_H_