Debian Codegraph @

src/App/Transactions.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2011 Jürgen Riegel <[email protected]> *
3 * Copyright (c) 2011 Werner Mayer <wmayer[at]users.sourceforge.net> *
4 * *
5 * This file is part of the FreeCAD CAx development system. *
6 * *
7 * This library is free software; you can redistribute it and/or *
8 * modify it under the terms of the GNU Library General Public *
9 * License as published by the Free Software Foundation; either *
10 * version 2 of the License, or (at your option) any later version. *
11 * *
12 * This library is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU Library General Public License for more details. *
16 * *
17 * You should have received a copy of the GNU Library General Public *
18 * License along with this library; see the file COPYING.LIB. If not, *
19 * write to the Free Software Foundation, Inc., 59 Temple Place, *
20 * Suite 330, Boston, MA 02111-1307, USA *
21 * *
22 ***************************************************************************/
23
24 #include <cassert>
25
26 #include <atomic>
27 #include <Base/Console.h>
28 #include <Base/Reader.h>
29 #include <Base/Writer.h>
30
31 #include "Transactions.h"
32 #include "Document.h"
33 #include "DocumentObject.h"
34 #include "Property.h"
35
36
37 FC_LOG_LEVEL_INIT("App", true, true)
38
39 using namespace App;
40 using namespace std;
41
42 TYPESYSTEM_SOURCE(App::Transaction, Base::Persistence)
43
44 //**************************************************************************
45 // Construction/Destruction
46
47 Transaction::Transaction(int id)
48 {
49 if (!id) {
50 id = getNewID();
51 }
52 transID = id;
53 }
54
55 Transaction::~Transaction()
56 {
57 auto& index = _Objects.get<0>();
58 for (const auto& It : index) {
59 if (It.second->status == TransactionObject::New) {
60 // If an object has been removed from the document the transaction
61 // status is 'New'. The 'pcNameInDocument' member serves as criterion
62 // to check whether the object is part of the document or not.
63 // Note, it's possible that the transaction status is 'New' while the
64 // object is (again) part of the document. This usually happens when
65 // a previous removal is undone.
66 // Thus, if the object has been removed, i.e. the status is 'New' and
67 // is still not part of the document the object must be destroyed not
68 // to cause a memory leak. This usually is the case when the removal
69 // of an object is not undone or when an addition is undone.
70
71 if (!It.first->isAttachedToDocument()) {
72 if (It.first->isDerivedFrom<DocumentObject>()) {
73 // #0003323: Crash when clearing transaction list
74 // It can happen that when clearing the transaction list several objects
75 // are destroyed with dependencies which can lead to dangling pointers.
76 // When setting the 'Destroy' flag of an object the destructors of link
77 // properties don't ry to remove backlinks, i.e. they don't try to access
78 // possible dangling pointers.
79 // An alternative solution is to call breakDependency inside
80 // Document::_removeObject. Make this change in v0.18.
81 const DocumentObject* obj = static_cast<const DocumentObject*>(It.first);
82 const_cast<DocumentObject*>(obj)->setStatus(ObjectStatus::Destroy, true);
83 }
84 delete It.first;
85 }
86 }
87 delete It.second;
88 }
89 }
90
91 static std::atomic<int> _TransactionID;
92
93 int Transaction::getNewID()
94 {
95 int id = ++_TransactionID;
96 if (id) {
97 return id;
98 }
99 // wrap around? really?
100 return ++_TransactionID;
101 }
102
103 int Transaction::getLastID()
104 {
105 return _TransactionID;
106 }
107
108 unsigned int Transaction::getMemSize() const
109 {
110 return 0;
111 }
112
113 void Transaction::Save(Base::Writer& /*writer*/) const
114 {
115 assert(0);
116 }
117
118 void Transaction::Restore(Base::XMLReader& /*reader*/)
119 {
120 assert(0);
121 }
122
123 int Transaction::getID() const
124 {
125 return transID;
126 }
127
128 bool Transaction::isEmpty() const
129 {
130 return _Objects.empty();
131 }
132
133 bool Transaction::hasObject(const TransactionalObject* Obj) const
134 {
135 #if BOOST_VERSION < 107500
136 return !!_Objects.get<1>().count(Obj);
137 #else
138 return !!_Objects.get<1>().contains(Obj);
139 #endif
140 }
141
142 void Transaction::changeProperty(TransactionalObject* Obj,
143 std::function<void(TransactionObject* to)> changeFunc)
144 {
145 auto& index = _Objects.get<1>();
146 auto pos = index.find(Obj);
147
148 if (pos != index.end()) {
149 auto To = pos->second;
150 changeFunc(To);
151 }
152 else if (auto To = TransactionFactory::instance().createTransaction(Obj->getTypeId())) {
153 To->status = TransactionObject::Chn;
154 index.emplace(Obj, To);
155 changeFunc(To);
156 }
157 }
158
159 void Transaction::renameProperty(TransactionalObject* Obj, const Property* pcProp, const char* oldName)
160 {
161 changeProperty(Obj, [pcProp, oldName](TransactionObject* to) {
162 to->renameProperty(pcProp, oldName);
163 });
164 }
165
166 void Transaction::addOrRemoveProperty(TransactionalObject* Obj, const Property* pcProp, bool add)
167 {
168 changeProperty(Obj, [pcProp, add](TransactionObject* to) {
169 to->addOrRemoveProperty(pcProp, add);
170 });
171 }
172
173 //**************************************************************************
174 // separator for other implementation aspects
175
176
177 void Transaction::apply(Document& Doc, bool forward)
178 {
179 std::string errMsg;
180 try {
181 auto& index = _Objects.get<0>();
182 for (auto& info : index) {
183 info.second->applyDel(Doc, const_cast<TransactionalObject*>(info.first));
184 }
185 for (auto& info : index) {
186 info.second->applyNew(Doc, const_cast<TransactionalObject*>(info.first));
187 }
188 for (auto& info : index) {
189 info.second->applyChn(Doc, const_cast<TransactionalObject*>(info.first), forward);
190 }
191 }
192 catch (Base::Exception& e) {
193 e.reportException();
194 errMsg = e.what();
195 }
196 catch (std::exception& e) {
197 errMsg = e.what();
198 }
199 catch (...) {
200 errMsg = "Unknown exception";
201 }
202 if (!errMsg.empty()) {
203 FC_ERR("Exception on " << (forward ? "redo" : "undo") << " '" << Name << "':" << errMsg);
204 }
205 }
206
207 void Transaction::addObjectNew(TransactionalObject* Obj)
208 {
209 auto& index = _Objects.get<1>();
210 auto pos = index.find(Obj);
211 if (pos != index.end()) {
212 if (pos->second->status == TransactionObject::Del) {
213 // first remove the item from the container before deleting it
214 auto second = pos->second;
215 auto first = pos->first;
216 index.erase(pos);
217 delete second;
218 delete first;
219 }
220 else {
221 pos->second->status = TransactionObject::New;
222 pos->second->_NameInDocument = Obj->detachFromDocument();
223 // move item at the end to make sure the order of removal is kept
224 auto& seq = _Objects.get<0>();
225 seq.relocate(seq.end(), _Objects.project<0>(pos));
226 }
227 }
228 else if (auto To = TransactionFactory::instance().createTransaction(Obj->getTypeId())) {
229 To->status = TransactionObject::New;
230 To->_NameInDocument = Obj->detachFromDocument();
231 index.emplace(Obj, To);
232 }
233 }
234
235 void Transaction::addObjectDel(const TransactionalObject* Obj)
236 {
237 auto& index = _Objects.get<1>();
238 auto pos = index.find(Obj);
239
240 // is it created in this transaction ?
241 if (pos != index.end() && pos->second->status == TransactionObject::New) {
242 // remove completely from transaction
243 delete pos->second;
244 index.erase(pos);
245 }
246 else if (pos != index.end() && pos->second->status == TransactionObject::Chn) {
247 pos->second->status = TransactionObject::Del;
248 }
249 else if (auto To = TransactionFactory::instance().createTransaction(Obj->getTypeId())) {
250 To->status = TransactionObject::Del;
251 index.emplace(Obj, To);
252 }
253 }
254
255 void Transaction::addObjectChange(const TransactionalObject* Obj, const Property* Prop)
256 {
257 auto& index = _Objects.get<1>();
258 auto pos = index.find(Obj);
259
260 if (pos != index.end()) {
261 auto To = pos->second;
262 To->setProperty(Prop);
263 }
264 else if (auto To = TransactionFactory::instance().createTransaction(Obj->getTypeId())) {
265 To->status = TransactionObject::Chn;
266 index.emplace(Obj, To);
267 To->setProperty(Prop);
268 }
269 }
270
271
272 //**************************************************************************
273 //**************************************************************************
274 // TransactionObject
275 //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
276
277 TYPESYSTEM_SOURCE_ABSTRACT(App::TransactionObject, Base::Persistence)
278
279 //**************************************************************************
280 // Construction/Destruction
281
282 TransactionObject::TransactionObject() = default;
283
284 TransactionObject::~TransactionObject()
285 {
286 for (auto& v : _PropChangeMap) {
287 auto& data = v.second;
288 // If nameOrig is used, it means it is a transaction of a rename
289 // operation. This operation does not interact with v.second.property,
290 // so it should not be deleted in that case.
291 if (data.nameOrig.empty()) {
292 delete v.second.property;
293 }
294 }
295 }
296
297 void TransactionObject::applyDel(Document& /*Doc*/, TransactionalObject* /*pcObj*/)
298 {}
299
300 void TransactionObject::applyNew(Document& /*Doc*/, TransactionalObject* /*pcObj*/)
301 {}
302
303 void TransactionObject::applyChn(Document& /*Doc*/, TransactionalObject* pcObj, bool /* Forward */)
304 {
305 if (status == New || status == Chn) {
306 // Property change order is not preserved, as it is recursive in nature
307 for (auto& v : _PropChangeMap) {
308 auto& data = v.second;
309 auto prop = const_cast<Property*>(data.propertyOrig);
310
311 if (!data.nameOrig.empty()) {
312 // This means we are undoing/redoing a rename operation
313 Property* currentProp = pcObj->getDynamicPropertyByName(data.name.c_str());
314 if (currentProp) {
315 pcObj->renameDynamicProperty(currentProp, data.nameOrig.c_str());
316 }
317 continue;
318 }
319
320 if (!data.property) {
321 // here means we are undoing/redoing and property add operation
322 pcObj->removeDynamicProperty(v.second.name.c_str());
323 continue;
324 }
325
326 // getPropertyName() is specially coded to be safe even if prop has
327 // been destroyed. We must prepare for the case where user removed
328 // a dynamic property but does not recordered as transaction.
329 auto name = pcObj->getPropertyName(prop);
330 if (!name || (!data.name.empty() && data.name != name)
331 || data.propertyType != prop->getTypeId()) {
332 // Here means the original property is not found, probably removed
333 if (data.name.empty()) {
334 // not a dynamic property, nothing to do
335 continue;
336 }
337
338 // It is possible for the dynamic property to be removed and
339 // restored. But since restoring property is actually creating
340 // a new property, the property key inside redo stack will not
341 // match. So we search by name first.
342 prop = pcObj->getDynamicPropertyByName(data.name.c_str());
343 if (!prop) {
344 // Still not found, re-create the property
345 prop = pcObj->addDynamicProperty(data.propertyType.getName(),
346 data.name.c_str(),
347 data.group.c_str(),
348 data.doc.c_str(),
349 data.attr,
350 data.readonly,
351 data.hidden);
352 if (!prop) {
353 continue;
354 }
355 prop->setStatusValue(data.property->getStatus());
356 }
357 }
358
359 // Many properties do not bother implement Copy() and accepts
360 // derived types just fine in Paste(). So we do not enforce type
361 // matching here. But instead, strengthen type checking in all
362 // Paste() implementation.
363 //
364 // if(data.propertyType != prop->getTypeId()) {
365 // FC_WARN("Cannot " << (Forward?"redo":"undo")
366 // << " change of property " << prop->getName()
367 // << " because of type change: "
368 // << data.propertyType.getName()
369 // << " -> " << prop->getTypeId().getName());
370 // continue;
371 // }
372 try {
373 prop->Paste(*data.property);
374 }
375 catch (Base::Exception& e) {
376 e.reportException();
377 FC_ERR("exception while restoring " << prop->getFullName() << ": " << e.what());
378 }
379 catch (std::exception& e) {
380 FC_ERR("exception while restoring " << prop->getFullName() << ": " << e.what());
381 }
382 catch (...) {
383 }
384 }
385 }
386 }
387
388 void TransactionObject::setProperty(const Property* pcProp)
389 {
390 auto& data = _PropChangeMap[pcProp->getID()];
391 if (!data.property && data.name.empty()) {
392 static_cast<DynamicProperty::PropData&>(data) =
393 pcProp->getContainer()->getDynamicPropertyData(pcProp);
394 data.propertyOrig = pcProp;
395 data.property = pcProp->Copy();
396 data.propertyType = pcProp->getTypeId();
397 data.property->setStatusValue(pcProp->getStatus());
398 }
399 }
400
401 void TransactionObject::renameProperty(const Property* pcProp, const char* oldName)
402 {
403 if (!pcProp || !pcProp->getContainer()) {
404 return;
405 }
406
407 auto& data = _PropChangeMap[pcProp->getID()];
408
409 if (data.name.empty()) {
410 static_cast<DynamicProperty::PropData&>(data) =
411 pcProp->getContainer()->getDynamicPropertyData(pcProp);
412 }
413 data.nameOrig = oldName;
414 }
415
416 void TransactionObject::addOrRemoveProperty(const Property* pcProp, bool add)
417 {
418 (void)add;
419 if (!pcProp || !pcProp->getContainer()) {
420 return;
421 }
422
423 auto& data = _PropChangeMap[pcProp->getID()];
424 if (!data.name.empty()) {
425 if (!add && !data.property) {
426 // this means add and remove the same property inside a single
427 // transaction, so they cancel each other out.
428 _PropChangeMap.erase(pcProp->getID());
429 }
430 return;
431 }
432 if (data.property) {
433 delete data.property;
434 data.property = nullptr;
435 }
436 data.propertyOrig = pcProp;
437 static_cast<DynamicProperty::PropData&>(data) =
438 pcProp->getContainer()->getDynamicPropertyData(pcProp);
439 if (add) {
440 data.property = nullptr;
441 }
442 else {
443 data.property = pcProp->Copy();
444 data.propertyType = pcProp->getTypeId();
445 data.property->setStatusValue(pcProp->getStatus());
446 }
447 }
448
449 unsigned int TransactionObject::getMemSize() const
450 {
451 return 0;
452 }
453
454 void TransactionObject::Save(Base::Writer& /*writer*/) const
455 {
456 assert(0);
457 }
458
459 void TransactionObject::Restore(Base::XMLReader& /*reader*/)
460 {
461 assert(0);
462 }
463
464 //**************************************************************************
465 //**************************************************************************
466 // TransactionDocumentObject
467 //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
468
469 TYPESYSTEM_SOURCE_ABSTRACT(App::TransactionDocumentObject, App::TransactionObject)
470
471 //**************************************************************************
472 // Construction/Destruction
473
474 /**
475 * A constructor.
476 * A more elaborate description of the constructor.
477 */
478 TransactionDocumentObject::TransactionDocumentObject() = default;
479
480 /**
481 * A destructor.
482 * A more elaborate description of the destructor.
483 */
484 TransactionDocumentObject::~TransactionDocumentObject() = default;
485
486 void TransactionDocumentObject::applyDel(Document& Doc, TransactionalObject* pcObj)
487 {
488 if (status == Del) {
489 DocumentObject* obj = static_cast<DocumentObject*>(pcObj);
490
491 // Make sure the backlinks of all linked objects are updated. As the links of the removed
492 // object are never set to [] they also do not remove the backlink. But as they are
493 // not in the document anymore we need to remove them anyway to ensure a correct graph
494 auto list = obj->getOutList();
495 for (auto link : list) {
496 link->_removeBackLink(obj);
497 }
498
499 // simply filling in the saved object
500 Doc._removeObject(obj);
501 }
502 }
503
504 void TransactionDocumentObject::applyNew(Document& Doc, TransactionalObject* pcObj)
505 {
506 if (status == New) {
507 DocumentObject* obj = static_cast<DocumentObject*>(pcObj);
508 Doc._addObject(obj, _NameInDocument.c_str());
509
510 // make sure the backlinks of all linked objects are updated
511 auto list = obj->getOutList();
512 for (auto link : list) {
513 link->_addBackLink(obj);
514 }
515 }
516 }
517
518 //**************************************************************************
519 //**************************************************************************
520 // TransactionFactory
521 //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
522
523 App::TransactionFactory* App::TransactionFactory::self = nullptr;
524
525 TransactionFactory& TransactionFactory::instance()
526 {
527 if (!self) {
528 self = new TransactionFactory;
529 }
530 return *self;
531 }
532
533 void TransactionFactory::destruct()
534 {
535 delete self;
536 self = nullptr;
537 }
538
539 void TransactionFactory::addProducer(const Base::Type& type, Base::AbstractProducer* producer)
540 {
541 producers[type] = producer;
542 }
543
544 /**
545 * Creates a transaction object for the given type id.
546 */
547 TransactionObject* TransactionFactory::createTransaction(const Base::Type& type) const
548 {
549 for (const auto& it : producers) {
550 if (type.isDerivedFrom(it.first)) {
551 return static_cast<TransactionObject*>(it.second->Produce());
552 }
553 }
554
555 Base::Console().log("Cannot create transaction object from %s\n", type.getName());
556 return nullptr;
557 }