| 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 |
#include <bitset> |
| 24 |
#include <stack> |
| 25 |
#include <deque> |
| 26 |
#include <iostream> |
| 27 |
#include <utility> |
| 28 |
#include <set> |
| 29 |
#include <memory> |
| 30 |
#include <string> |
| 31 |
#include <map> |
| 32 |
#include <vector> |
| 33 |
#include <list> |
| 34 |
#include <algorithm> |
| 35 |
#include <filesystem> |
| 36 |
|
| 37 |
#include <boost/algorithm/string.hpp> |
| 38 |
#include <boost/bimap.hpp> |
| 39 |
#include <boost/graph/strong_components.hpp> |
| 40 |
|
| 41 |
#include <boost/regex.hpp> |
| 42 |
#include <random> |
| 43 |
#include <unordered_map> |
| 44 |
#include <unordered_set> |
| 45 |
|
| 46 |
#include <QCryptographicHash> |
| 47 |
#include <QCoreApplication> |
| 48 |
|
| 49 |
#include <FCConfig.h> |
| 50 |
|
| 51 |
#include <App/DocumentPy.h> |
| 52 |
#include <Base/Interpreter.h> |
| 53 |
#include <Base/Console.h> |
| 54 |
#include <Base/Exception.h> |
| 55 |
#include <Base/FileInfo.h> |
| 56 |
#include <Base/TimeInfo.h> |
| 57 |
#include <Base/Reader.h> |
| 58 |
#include <Base/Writer.h> |
| 59 |
#include <Base/Profiler.h> |
| 60 |
#include <Base/Tools.h> |
| 61 |
#include <Base/Uuid.h> |
| 62 |
#include <Base/Sequencer.h> |
| 63 |
#include <Base/Stream.h> |
| 64 |
#include <Base/UnitsApi.h> |
| 65 |
|
| 66 |
#include "Document.h" |
| 67 |
#include "private/DocumentP.h" |
| 68 |
#include "Application.h" |
| 69 |
#include "AutoTransaction.h" |
| 70 |
#include "BackupPolicy.h" |
| 71 |
#include "ExpressionParser.h" |
| 72 |
#include "GeoFeature.h" |
| 73 |
#include "License.h" |
| 74 |
#include "Link.h" |
| 75 |
#include "MergeDocuments.h" |
| 76 |
#include "StringHasher.h" |
| 77 |
#include "Transactions.h" |
| 78 |
|
| 79 |
#ifdef _MSC_VER |
| 80 |
#include <zipios++/zipios-config.h> |
| 81 |
#endif |
| 82 |
#include <zipios++/zipfile.h> |
| 83 |
#include <zipios++/zipinputstream.h> |
| 84 |
#include <zipios++/zipoutputstream.h> |
| 85 |
#include <zipios++/meta-iostreams.h> |
| 86 |
|
| 87 |
|
| 88 |
FC_LOG_LEVEL_INIT("App", true, true, true) |
| 89 |
|
| 90 |
using Base::Console; |
| 91 |
using Base::streq; |
| 92 |
using Base::Writer; |
| 93 |
using namespace App; |
| 94 |
using namespace std; |
| 95 |
using namespace boost; |
| 96 |
using namespace zipios; |
| 97 |
|
| 98 |
#if FC_DEBUG |
| 99 |
#define FC_LOGFEATUREUPDATE |
| 100 |
#endif |
| 101 |
|
| 102 |
namespace fs = std::filesystem; |
| 103 |
|
| 104 |
namespace App |
| 105 |
{ |
| 106 |
|
| 107 |
static bool globalIsRestoring; |
| 108 |
static bool globalIsRelabeling; |
| 109 |
|
| 110 |
DocumentP::DocumentP() |
| 111 |
{ |
| 112 |
static std::random_device rd; |
| 113 |
static std::mt19937 rgen(rd()); |
| 114 |
static std::uniform_int_distribution<> rdist(0, 5000); |
| 115 |
// Set some random offset to reduce likelihood of ID collision when |
| 116 |
// copying shape from other document. It is probably better to randomize |
| 117 |
// on each object ID. |
| 118 |
lastObjectId = rdist(rgen); |
| 119 |
StatusBits.set((size_t)Document::Closable, true); |
| 120 |
StatusBits.set((size_t)Document::KeepTrailingDigits, true); |
| 121 |
StatusBits.set((size_t)Document::Restoring, false); |
| 122 |
} |
| 123 |
|
| 124 |
} // namespace App |
| 125 |
|
| 126 |
PROPERTY_SOURCE(App::Document, App::PropertyContainer) |
| 127 |
|
| 128 |
bool Document::testStatus(const Status pos) const |
| 129 |
{ |
| 130 |
return d->StatusBits.test(static_cast<size_t>(pos)); |
| 131 |
} |
| 132 |
|
| 133 |
void Document::setStatus(const Status pos, const bool on) // NOLINT |
| 134 |
{ |
| 135 |
d->StatusBits.set(static_cast<size_t>(pos), on); |
| 136 |
} |
| 137 |
|
| 138 |
// bool _has_cycle_dfs(const DependencyList & g, vertex_t u, default_color_type * color) |
| 139 |
//{ |
| 140 |
// color[u] = gray_color; |
| 141 |
// graph_traits < DependencyList >::adjacency_iterator vi, vi_end; |
| 142 |
// for (tie(vi, vi_end) = adjacent_vertices(u, g); vi != vi_end; ++vi) |
| 143 |
// if (color[*vi] == white_color) |
| 144 |
// if (has_cycle_dfs(g, *vi, color)) |
| 145 |
// return true; // cycle detected, return immediately |
| 146 |
// else if (color[*vi] == gray_color) // *vi is an ancestor! |
| 147 |
// return true; |
| 148 |
// color[u] = black_color; |
| 149 |
// return false; |
| 150 |
// } |
| 151 |
|
| 152 |
bool Document::checkOnCycle() |
| 153 |
{ |
| 154 |
return false; |
| 155 |
} |
| 156 |
|
| 157 |
bool Document::undo(const int id) |
| 158 |
{ |
| 159 |
if (d->iUndoMode != 0) { |
| 160 |
if (id != 0) { |
| 161 |
const auto it = mUndoMap.find(id); |
| 162 |
if (it == mUndoMap.end()) { |
| 163 |
return false; |
| 164 |
} |
| 165 |
if (it->second != d->activeUndoTransaction) { |
| 166 |
while (!mUndoTransactions.empty() && mUndoTransactions.back() != it->second) { |
| 167 |
undo(0); |
| 168 |
} |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
if (d->activeUndoTransaction) { |
| 173 |
_commitTransaction(true); |
| 174 |
} |
| 175 |
if (mUndoTransactions.empty()) { |
| 176 |
return false; |
| 177 |
} |
| 178 |
// redo |
| 179 |
d->activeUndoTransaction = new Transaction(mUndoTransactions.back()->getID()); |
| 180 |
d->activeUndoTransaction->Name = mUndoTransactions.back()->Name; |
| 181 |
|
| 182 |
{ |
| 183 |
Base::FlagToggler<bool> flag(d->undoing); |
| 184 |
// applying the undo |
| 185 |
mUndoTransactions.back()->apply(*this, false); |
| 186 |
|
| 187 |
// save the redo |
| 188 |
mRedoMap[d->activeUndoTransaction->getID()] = d->activeUndoTransaction; |
| 189 |
mRedoTransactions.push_back(d->activeUndoTransaction); |
| 190 |
d->activeUndoTransaction = nullptr; |
| 191 |
|
| 192 |
mUndoMap.erase(mUndoTransactions.back()->getID()); |
| 193 |
delete mUndoTransactions.back(); |
| 194 |
mUndoTransactions.pop_back(); |
| 195 |
} |
| 196 |
|
| 197 |
for (const auto& obj : d->objectArray) { |
| 198 |
if (obj->testStatus(ObjectStatus::PendingTransactionUpdate)) { |
| 199 |
obj->onUndoRedoFinished(); |
| 200 |
obj->setStatus(ObjectStatus::PendingTransactionUpdate, false); |
| 201 |
} |
| 202 |
} |
| 203 |
|
| 204 |
signalUndo(*this); // now signal the undo |
| 205 |
|
| 206 |
return true; |
| 207 |
} |
| 208 |
|
| 209 |
return false; |
| 210 |
} |
| 211 |
|
| 212 |
bool Document::redo(const int id) |
| 213 |
{ |
| 214 |
if (d->iUndoMode != 0) { |
| 215 |
if (id != 0) { |
| 216 |
const auto it = mRedoMap.find(id); |
| 217 |
if (it == mRedoMap.end()) { |
| 218 |
return false; |
| 219 |
} |
| 220 |
while (!mRedoTransactions.empty() && mRedoTransactions.back() != it->second) { |
| 221 |
redo(0); |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
if (d->activeUndoTransaction) { |
| 226 |
_commitTransaction(true); |
| 227 |
} |
| 228 |
|
| 229 |
assert(mRedoTransactions.size() != 0); |
| 230 |
|
| 231 |
// undo |
| 232 |
d->activeUndoTransaction = new Transaction(mRedoTransactions.back()->getID()); |
| 233 |
d->activeUndoTransaction->Name = mRedoTransactions.back()->Name; |
| 234 |
|
| 235 |
// do the redo |
| 236 |
{ |
| 237 |
Base::FlagToggler<bool> flag(d->undoing); |
| 238 |
mRedoTransactions.back()->apply(*this, true); |
| 239 |
|
| 240 |
mUndoMap[d->activeUndoTransaction->getID()] = d->activeUndoTransaction; |
| 241 |
mUndoTransactions.push_back(d->activeUndoTransaction); |
| 242 |
d->activeUndoTransaction = nullptr; |
| 243 |
|
| 244 |
mRedoMap.erase(mRedoTransactions.back()->getID()); |
| 245 |
delete mRedoTransactions.back(); |
| 246 |
mRedoTransactions.pop_back(); |
| 247 |
} |
| 248 |
|
| 249 |
for (const auto& obj : d->objectArray) { |
| 250 |
if (obj->testStatus(ObjectStatus::PendingTransactionUpdate)) { |
| 251 |
obj->onUndoRedoFinished(); |
| 252 |
obj->setStatus(ObjectStatus::PendingTransactionUpdate, false); |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
signalRedo(*this); |
| 257 |
return true; |
| 258 |
} |
| 259 |
|
| 260 |
return false; |
| 261 |
} |
| 262 |
|
| 263 |
void Document::changePropertyOfObject(TransactionalObject* obj, |
| 264 |
const Property* prop, |
| 265 |
const std::function<void()>& changeFunc) |
| 266 |
{ |
| 267 |
if (!prop || !obj || !obj->isAttachedToDocument()) { |
| 268 |
return; |
| 269 |
} |
| 270 |
if ((d->iUndoMode != 0) && !isPerformingTransaction() && !d->activeUndoTransaction) { |
| 271 |
if (!testStatus(Restoring) || testStatus(Importing)) { |
| 272 |
int tid = 0; |
| 273 |
const char* name = GetApplication().getActiveTransaction(&tid); |
| 274 |
if (name && tid > 0) { |
| 275 |
_openTransaction(name, tid); |
| 276 |
} |
| 277 |
} |
| 278 |
} |
| 279 |
if (d->activeUndoTransaction && !d->rollback) { |
| 280 |
changeFunc(); |
| 281 |
} |
| 282 |
} |
| 283 |
|
| 284 |
void Document::renamePropertyOfObject(TransactionalObject* obj, |
| 285 |
const Property* prop, const char* oldName) |
| 286 |
{ |
| 287 |
changePropertyOfObject(obj, prop, [this, obj, prop, oldName]() { |
| 288 |
d->activeUndoTransaction->renameProperty(obj, prop, oldName); |
| 289 |
}); |
| 290 |
} |
| 291 |
|
| 292 |
void Document::addOrRemovePropertyOfObject(TransactionalObject* obj, |
| 293 |
const Property* prop, const bool add) |
| 294 |
{ |
| 295 |
changePropertyOfObject(obj, prop, [this, obj, prop, add]() { |
| 296 |
d->activeUndoTransaction->addOrRemoveProperty(obj, prop, add); |
| 297 |
}); |
| 298 |
} |
| 299 |
|
| 300 |
bool Document::isPerformingTransaction() const |
| 301 |
{ |
| 302 |
return d->undoing || d->rollback; |
| 303 |
} |
| 304 |
|
| 305 |
std::vector<std::string> Document::getAvailableUndoNames() const |
| 306 |
{ |
| 307 |
std::vector<std::string> vList; |
| 308 |
if (d->activeUndoTransaction) { |
| 309 |
vList.push_back(d->activeUndoTransaction->Name); |
| 310 |
} |
| 311 |
for (auto It = mUndoTransactions.rbegin(); |
| 312 |
It != mUndoTransactions.rend(); |
| 313 |
++It) { |
| 314 |
vList.push_back((*It)->Name); |
| 315 |
} |
| 316 |
return vList; |
| 317 |
} |
| 318 |
|
| 319 |
std::vector<std::string> Document::getAvailableRedoNames() const |
| 320 |
{ |
| 321 |
std::vector<std::string> vList; |
| 322 |
for (auto It = mRedoTransactions.rbegin(); |
| 323 |
It != mRedoTransactions.rend(); |
| 324 |
++It) { |
| 325 |
vList.push_back((*It)->Name); |
| 326 |
} |
| 327 |
return vList; |
| 328 |
} |
| 329 |
|
| 330 |
void Document::openTransaction(const char* name) // NOLINT |
| 331 |
{ |
| 332 |
if (isPerformingTransaction() || d->committing) { |
| 333 |
if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { |
| 334 |
FC_WARN("Cannot open transaction while transacting"); |
| 335 |
} |
| 336 |
return; |
| 337 |
} |
| 338 |
|
| 339 |
GetApplication().setActiveTransaction(name ? name : "<empty>"); |
| 340 |
} |
| 341 |
|
| 342 |
int Document::_openTransaction(const char* name, int id) |
| 343 |
{ |
| 344 |
if (isPerformingTransaction() || d->committing) { |
| 345 |
if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { |
| 346 |
FC_WARN("Cannot open transaction while transacting"); |
| 347 |
} |
| 348 |
return 0; |
| 349 |
} |
| 350 |
|
| 351 |
if (d->iUndoMode != 0) { |
| 352 |
// Avoid recursive calls that is possible while |
| 353 |
// clearing the redo transactions and will cause |
| 354 |
// a double deletion of some transaction and thus |
| 355 |
// a segmentation fault |
| 356 |
if (d->opentransaction) { |
| 357 |
return 0; |
| 358 |
} |
| 359 |
Base::FlagToggler<> flag(d->opentransaction); |
| 360 |
|
| 361 |
if ((id != 0) && mUndoMap.find(id) != mUndoMap.end()) { |
| 362 |
throw Base::RuntimeError("invalid transaction id"); |
| 363 |
} |
| 364 |
if (d->activeUndoTransaction) { |
| 365 |
_commitTransaction(true); |
| 366 |
} |
| 367 |
_clearRedos(); |
| 368 |
|
| 369 |
d->activeUndoTransaction = new Transaction(id); |
| 370 |
if (!name) { |
| 371 |
name = "<empty>"; |
| 372 |
} |
| 373 |
d->activeUndoTransaction->Name = name; |
| 374 |
mUndoMap[d->activeUndoTransaction->getID()] = d->activeUndoTransaction; |
| 375 |
id = d->activeUndoTransaction->getID(); |
| 376 |
|
| 377 |
signalOpenTransaction(*this, name); |
| 378 |
|
| 379 |
auto& app = GetApplication(); |
| 380 |
auto activeDoc = app.getActiveDocument(); |
| 381 |
if (activeDoc && activeDoc != this && !activeDoc->hasPendingTransaction()) { |
| 382 |
std::string aname("-> "); |
| 383 |
aname += d->activeUndoTransaction->Name; |
| 384 |
FC_LOG("auto transaction " << getName() << " -> " << activeDoc->getName()); |
| 385 |
activeDoc->_openTransaction(aname.c_str(), id); |
| 386 |
} |
| 387 |
return id; |
| 388 |
} |
| 389 |
return 0; |
| 390 |
} |
| 391 |
|
| 392 |
void Document::renameTransaction(const char* name, const int id) const |
| 393 |
{ |
| 394 |
if (name && d->activeUndoTransaction && d->activeUndoTransaction->getID() == id) { |
| 395 |
if (boost::starts_with(d->activeUndoTransaction->Name, "-> ")) { |
| 396 |
d->activeUndoTransaction->Name.resize(3); |
| 397 |
} |
| 398 |
else { |
| 399 |
d->activeUndoTransaction->Name.clear(); |
| 400 |
} |
| 401 |
d->activeUndoTransaction->Name += name; |
| 402 |
} |
| 403 |
} |
| 404 |
|
| 405 |
void Document::_checkTransaction(DocumentObject* pcDelObj, const Property* What, int line) |
| 406 |
{ |
| 407 |
// if the undo is active but no transaction open, open one! |
| 408 |
if ((d->iUndoMode != 0) && !isPerformingTransaction()) { |
| 409 |
if (!d->activeUndoTransaction) { |
| 410 |
if (!testStatus(Restoring) || testStatus(Importing)) { |
| 411 |
int tid = 0; |
| 412 |
const char* name = GetApplication().getActiveTransaction(&tid); |
| 413 |
if (name && tid > 0) { |
| 414 |
bool ignore = false; |
| 415 |
if (What && What->testStatus(Property::NoModify)) { |
| 416 |
ignore = true; |
| 417 |
} |
| 418 |
if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { |
| 419 |
if (What) { |
| 420 |
FC_LOG((ignore ? "ignore" : "auto") |
| 421 |
<< " transaction (" << line << ") '" << What->getFullName()); |
| 422 |
} |
| 423 |
else { |
| 424 |
FC_LOG((ignore ? "ignore" : "auto") << " transaction (" << line << ") '" |
| 425 |
<< name << "' in " << getName()); |
| 426 |
} |
| 427 |
} |
| 428 |
if (!ignore) { |
| 429 |
_openTransaction(name, tid); |
| 430 |
} |
| 431 |
return; |
| 432 |
} |
| 433 |
} |
| 434 |
if (!pcDelObj) { |
| 435 |
return; |
| 436 |
} |
| 437 |
// When the object is going to be deleted we have to check if it has already been added |
| 438 |
// to the undo transactions |
| 439 |
std::list<Transaction*>::iterator it; |
| 440 |
for (it = mUndoTransactions.begin(); it != mUndoTransactions.end(); ++it) { |
| 441 |
if ((*it)->hasObject(pcDelObj)) { |
| 442 |
_openTransaction("Delete"); |
| 443 |
break; |
| 444 |
} |
| 445 |
} |
| 446 |
} |
| 447 |
} |
| 448 |
} |
| 449 |
|
| 450 |
void Document::_clearRedos() |
| 451 |
{ |
| 452 |
if (isPerformingTransaction() || d->committing) { |
| 453 |
FC_ERR("Cannot clear redo while transacting"); |
| 454 |
return; |
| 455 |
} |
| 456 |
|
| 457 |
mRedoMap.clear(); |
| 458 |
while (!mRedoTransactions.empty()) { |
| 459 |
delete mRedoTransactions.back(); |
| 460 |
mRedoTransactions.pop_back(); |
| 461 |
} |
| 462 |
} |
| 463 |
|
| 464 |
void Document::commitTransaction() // NOLINT |
| 465 |
{ |
| 466 |
if (isPerformingTransaction() || d->committing) { |
| 467 |
if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { |
| 468 |
FC_WARN("Cannot commit transaction while transacting"); |
| 469 |
} |
| 470 |
return; |
| 471 |
} |
| 472 |
|
| 473 |
if (d->activeUndoTransaction) { |
| 474 |
GetApplication().closeActiveTransaction(false, d->activeUndoTransaction->getID()); |
| 475 |
} |
| 476 |
} |
| 477 |
|
| 478 |
void Document::_commitTransaction(const bool notify) |
| 479 |
{ |
| 480 |
if (isPerformingTransaction()) { |
| 481 |
if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { |
| 482 |
FC_WARN("Cannot commit transaction while transacting"); |
| 483 |
} |
| 484 |
return; |
| 485 |
} |
| 486 |
if (d->committing) { |
| 487 |
// for a recursive call return without printing a warning |
| 488 |
return; |
| 489 |
} |
| 490 |
|
| 491 |
if (d->activeUndoTransaction) { |
| 492 |
Base::FlagToggler<> flag(d->committing); |
| 493 |
Application::TransactionSignaller signaller(false, true); |
| 494 |
const int id = d->activeUndoTransaction->getID(); |
| 495 |
mUndoTransactions.push_back(d->activeUndoTransaction); |
| 496 |
d->activeUndoTransaction = nullptr; |
| 497 |
// check the stack for the limits |
| 498 |
if (mUndoTransactions.size() > d->UndoMaxStackSize) { |
| 499 |
mUndoMap.erase(mUndoTransactions.front()->getID()); |
| 500 |
delete mUndoTransactions.front(); |
| 501 |
mUndoTransactions.pop_front(); |
| 502 |
} |
| 503 |
signalCommitTransaction(*this); |
| 504 |
|
| 505 |
// closeActiveTransaction() may call again _commitTransaction() |
| 506 |
if (notify) { |
| 507 |
GetApplication().closeActiveTransaction(false, id); |
| 508 |
} |
| 509 |
} |
| 510 |
} |
| 511 |
|
| 512 |
void Document::abortTransaction() const |
| 513 |
{ |
| 514 |
if (isPerformingTransaction() || d->committing) { |
| 515 |
if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { |
| 516 |
FC_WARN("Cannot abort transaction while transacting"); |
| 517 |
} |
| 518 |
return; |
| 519 |
} |
| 520 |
if (d->activeUndoTransaction) { |
| 521 |
GetApplication().closeActiveTransaction(true, d->activeUndoTransaction->getID()); |
| 522 |
} |
| 523 |
} |
| 524 |
|
| 525 |
void Document::_abortTransaction() |
| 526 |
{ |
| 527 |
if (isPerformingTransaction() || d->committing) { |
| 528 |
if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { |
| 529 |
FC_WARN("Cannot abort transaction while transacting"); |
| 530 |
} |
| 531 |
} |
| 532 |
|
| 533 |
if (d->activeUndoTransaction) { |
| 534 |
Base::FlagToggler<bool> flag(d->rollback); |
| 535 |
Application::TransactionSignaller signaller(true, true); |
| 536 |
|
| 537 |
// applying the so far made changes |
| 538 |
d->activeUndoTransaction->apply(*this, false); |
| 539 |
|
| 540 |
// destroy the undo |
| 541 |
mUndoMap.erase(d->activeUndoTransaction->getID()); |
| 542 |
delete d->activeUndoTransaction; |
| 543 |
d->activeUndoTransaction = nullptr; |
| 544 |
signalAbortTransaction(*this); |
| 545 |
} |
| 546 |
} |
| 547 |
|
| 548 |
bool Document::hasPendingTransaction() const |
| 549 |
{ |
| 550 |
return d->activeUndoTransaction != nullptr; |
| 551 |
} |
| 552 |
|
| 553 |
int Document::getTransactionID(const bool undo, unsigned pos) const |
| 554 |
{ |
| 555 |
if (undo) { |
| 556 |
if (d->activeUndoTransaction) { |
| 557 |
if (pos == 0) { |
| 558 |
return d->activeUndoTransaction->getID(); |
| 559 |
} |
| 560 |
--pos; |
| 561 |
} |
| 562 |
if (pos >= mUndoTransactions.size()) { |
| 563 |
return 0; |
| 564 |
} |
| 565 |
auto rit = mUndoTransactions.rbegin(); |
| 566 |
for (; pos != 0U; ++rit, --pos) {} |
| 567 |
return (*rit)->getID(); |
| 568 |
} |
| 569 |
if (pos >= mRedoTransactions.size()) { |
| 570 |
return 0; |
| 571 |
} |
| 572 |
auto rit = mRedoTransactions.rbegin(); |
| 573 |
for (; pos != 0U; ++rit, --pos) {} |
| 574 |
return (*rit)->getID(); |
| 575 |
} |
| 576 |
|
| 577 |
bool Document::isTransactionEmpty() const |
| 578 |
{ |
| 579 |
return !d->activeUndoTransaction; |
| 580 |
// Transactions are now only created when there are actual changes. |
| 581 |
// Empty transaction is now significant for marking external changes. It |
| 582 |
// is used to match ID with transactions in external documents and |
| 583 |
// trigger undo/redo there. |
| 584 |
|
| 585 |
// return d->activeUndoTransaction->isEmpty(); |
| 586 |
|
| 587 |
} |
| 588 |
|
| 589 |
void Document::clearDocument() // NOLINT |
| 590 |
{ |
| 591 |
d->activeObject = nullptr; |
| 592 |
|
| 593 |
if (!d->objectArray.empty()) { |
| 594 |
GetApplication().signalDeleteDocument(*this); |
| 595 |
d->clearDocument(); |
| 596 |
GetApplication().signalNewDocument(*this, false); |
| 597 |
} |
| 598 |
|
| 599 |
Base::FlagToggler<> flag(globalIsRestoring, false); |
| 600 |
|
| 601 |
setStatus(Document::PartialDoc, false); |
| 602 |
|
| 603 |
d->clearRecomputeLog(); |
| 604 |
d->objectLabelManager.clear(); |
| 605 |
d->objectArray.clear(); |
| 606 |
d->objectMap.clear(); |
| 607 |
d->objectNameManager.clear(); |
| 608 |
d->objectIdMap.clear(); |
| 609 |
d->lastObjectId = 0; |
| 610 |
} |
| 611 |
|
| 612 |
|
| 613 |
void Document::clearUndos() |
| 614 |
{ |
| 615 |
if (isPerformingTransaction() || d->committing) { |
| 616 |
FC_ERR("Cannot clear undos while transacting"); |
| 617 |
return; |
| 618 |
} |
| 619 |
|
| 620 |
if (d->activeUndoTransaction) { |
| 621 |
_commitTransaction(true); |
| 622 |
} |
| 623 |
|
| 624 |
mUndoMap.clear(); |
| 625 |
|
| 626 |
// When cleaning up the undo stack we must delete the transactions from front |
| 627 |
// to back because a document object can appear in several transactions but |
| 628 |
// once removed from the document the object can never ever appear in any later |
| 629 |
// transaction. Since the document object may be also deleted when the transaction |
| 630 |
// is deleted we must make sure not access an object once it's destroyed. Thus, we |
| 631 |
// go from front to back and not the other way round. |
| 632 |
while (!mUndoTransactions.empty()) { |
| 633 |
delete mUndoTransactions.front(); |
| 634 |
mUndoTransactions.pop_front(); |
| 635 |
} |
| 636 |
// while (!mUndoTransactions.empty()) { |
| 637 |
// delete mUndoTransactions.back(); |
| 638 |
// mUndoTransactions.pop_back(); |
| 639 |
// } |
| 640 |
|
| 641 |
_clearRedos(); |
| 642 |
} |
| 643 |
|
| 644 |
int Document::getAvailableUndos(const int id) const |
| 645 |
{ |
| 646 |
if (id != 0) { |
| 647 |
const auto it = mUndoMap.find(id); |
| 648 |
if (it == mUndoMap.end()) { |
| 649 |
return 0; |
| 650 |
} |
| 651 |
int i = 0; |
| 652 |
if (d->activeUndoTransaction) { |
| 653 |
++i; |
| 654 |
if (d->activeUndoTransaction->getID() == id) { |
| 655 |
return i; |
| 656 |
} |
| 657 |
} |
| 658 |
auto rit = mUndoTransactions.rbegin(); |
| 659 |
for (; rit != mUndoTransactions.rend() && *rit != it->second; ++rit) { |
| 660 |
++i; |
| 661 |
} |
| 662 |
assert(rit != mUndoTransactions.rend()); |
| 663 |
return i + 1; |
| 664 |
} |
| 665 |
if (d->activeUndoTransaction) { |
| 666 |
return static_cast<int>(mUndoTransactions.size() + 1); |
| 667 |
} |
| 668 |
return static_cast<int>(mUndoTransactions.size()); |
| 669 |
} |
| 670 |
|
| 671 |
int Document::getAvailableRedos(const int id) const |
| 672 |
{ |
| 673 |
if (id != 0) { |
| 674 |
const auto it = mRedoMap.find(id); |
| 675 |
if (it == mRedoMap.end()) { |
| 676 |
return 0; |
| 677 |
} |
| 678 |
int i = 0; |
| 679 |
for (auto rit = mRedoTransactions.rbegin(); *rit != it->second; ++rit) { |
| 680 |
++i; |
| 681 |
} |
| 682 |
assert(i < static_cast<int>(mRedoTransactions.size())); |
| 683 |
return i + 1; |
| 684 |
} |
| 685 |
return static_cast<int>(mRedoTransactions.size()); |
| 686 |
} |
| 687 |
|
| 688 |
void Document::setUndoMode(const int iMode) |
| 689 |
{ |
| 690 |
if ((d->iUndoMode != 0) && (iMode == 0)) { |
| 691 |
clearUndos(); |
| 692 |
} |
| 693 |
|
| 694 |
d->iUndoMode = iMode; |
| 695 |
} |
| 696 |
|
| 697 |
int Document::getUndoMode() const |
| 698 |
{ |
| 699 |
return d->iUndoMode; |
| 700 |
} |
| 701 |
|
| 702 |
unsigned int Document::getUndoMemSize() const |
| 703 |
{ |
| 704 |
return d->UndoMemSize; |
| 705 |
} |
| 706 |
|
| 707 |
void Document::setUndoLimit(const unsigned int UndoMemSize) // NOLINT |
| 708 |
{ |
| 709 |
d->UndoMemSize = UndoMemSize; |
| 710 |
} |
| 711 |
|
| 712 |
void Document::setMaxUndoStackSize(const unsigned int UndoMaxStackSize) // NOLINT |
| 713 |
{ |
| 714 |
d->UndoMaxStackSize = UndoMaxStackSize; |
| 715 |
} |
| 716 |
|
| 717 |
unsigned int Document::getMaxUndoStackSize() const |
| 718 |
{ |
| 719 |
return d->UndoMaxStackSize; |
| 720 |
} |
| 721 |
|
| 722 |
void Document::onBeforeChange(const Property* prop) |
| 723 |
{ |
| 724 |
if (prop == &Label) { |
| 725 |
oldLabel = Label.getValue(); |
| 726 |
} |
| 727 |
signalBeforeChange(*this, *prop); |
| 728 |
} |
| 729 |
|
| 730 |
void Document::onChanged(const Property* prop) |
| 731 |
{ |
| 732 |
signalChanged(*this, *prop); |
| 733 |
|
| 734 |
// the Name property is a label for display purposes |
| 735 |
if (prop == &Label) { |
| 736 |
Base::FlagToggler<> flag(globalIsRelabeling); |
| 737 |
GetApplication().signalRelabelDocument(*this); |
| 738 |
} |
| 739 |
else if (prop == &ShowHidden) { |
| 740 |
GetApplication().signalShowHidden(*this); |
| 741 |
} |
| 742 |
else if (prop == &Uid) { |
| 743 |
std::string new_dir = |
| 744 |
getTransientDirectoryName(this->Uid.getValueStr(), this->FileName.getStrValue()); |
| 745 |
std::string old_dir = this->TransientDir.getStrValue(); |
| 746 |
Base::FileInfo TransDirNew(new_dir); |
| 747 |
Base::FileInfo TransDirOld(old_dir); |
| 748 |
// this directory should not exist |
| 749 |
if (!TransDirNew.exists()) { |
| 750 |
if (TransDirOld.exists()) { |
| 751 |
if (!TransDirOld.renameFile(new_dir.c_str())) { |
| 752 |
Base::Console().warning("Failed to rename '%s' to '%s'\n", |
| 753 |
old_dir.c_str(), |
| 754 |
new_dir.c_str()); |
| 755 |
} |
| 756 |
else { |
| 757 |
this->TransientDir.setValue(new_dir); |
| 758 |
} |
| 759 |
} |
| 760 |
else { |
| 761 |
if (!TransDirNew.createDirectories()) { |
| 762 |
Base::Console().warning("Failed to create '%s'\n", new_dir.c_str()); |
| 763 |
} |
| 764 |
else { |
| 765 |
this->TransientDir.setValue(new_dir); |
| 766 |
} |
| 767 |
} |
| 768 |
} |
| 769 |
// when reloading an existing document the transient directory doesn't change |
| 770 |
// so we must avoid to generate a new uuid |
| 771 |
else if (TransDirNew.filePath() != TransDirOld.filePath()) { |
| 772 |
// make sure that the uuid is unique |
| 773 |
std::string uuid = this->Uid.getValueStr(); |
| 774 |
Base::Uuid id; |
| 775 |
Base::Console().warning("Document with the UUID '%s' already exists, change to '%s'\n", |
| 776 |
uuid.c_str(), |
| 777 |
id.getValue().c_str()); |
| 778 |
// recursive call of onChanged() |
| 779 |
this->Uid.setValue(id); |
| 780 |
} |
| 781 |
} |
| 782 |
else if (prop == &UseHasher) { |
| 783 |
for (auto obj : d->objectArray) { |
| 784 |
auto geofeature = freecad_cast<GeoFeature*>(obj); |
| 785 |
if (geofeature && geofeature->getPropertyOfGeometry()) { |
| 786 |
geofeature->enforceRecompute(); |
| 787 |
} |
| 788 |
} |
| 789 |
} |
| 790 |
} |
| 791 |
|
| 792 |
void Document::onBeforeChangeProperty(const TransactionalObject* Who, const Property* What) |
| 793 |
{ |
| 794 |
if (Who->isDerivedFrom<DocumentObject>()) { |
| 795 |
signalBeforeChangeObject(*static_cast<const DocumentObject*>(Who), *What); |
| 796 |
} |
| 797 |
if (!d->rollback && !globalIsRelabeling) { |
| 798 |
_checkTransaction(nullptr, What, __LINE__); |
| 799 |
if (d->activeUndoTransaction) { |
| 800 |
d->activeUndoTransaction->addObjectChange(Who, What); |
| 801 |
} |
| 802 |
} |
| 803 |
} |
| 804 |
|
| 805 |
void Document::onChangedProperty(const DocumentObject* Who, const Property* What) |
| 806 |
{ |
| 807 |
signalChangedObject(*Who, *What); |
| 808 |
} |
| 809 |
|
| 810 |
void Document::setTransactionMode(const int iMode) // NOLINT |
| 811 |
{ |
| 812 |
d->iTransactionMode = iMode; |
| 813 |
} |
| 814 |
|
| 815 |
//-------------------------------------------------------------------------- |
| 816 |
// constructor |
| 817 |
//-------------------------------------------------------------------------- |
| 818 |
Document::Document(const char* documentName) |
| 819 |
: d(new DocumentP), myName(documentName) |
| 820 |
{ |
| 821 |
// Remark: In a constructor we should never increment a Python object as we cannot be sure |
| 822 |
// if the Python interpreter gets a reference of it. E.g. if we increment but Python don't |
| 823 |
// get a reference then the object wouldn't get deleted in the destructor. |
| 824 |
// So, we must increment only if the interpreter gets a reference. |
| 825 |
// Remark: We force the document Python object to own the DocumentPy instance, thus we don't |
| 826 |
// have to care about ref counting any more. |
| 827 |
setAutoCreated(false); |
| 828 |
Base::PyGILStateLocker lock; |
| 829 |
d->DocumentPythonObject = Py::Object(new DocumentPy(this), true); |
| 830 |
|
| 831 |
#ifdef FC_LOGUPDATECHAIN |
| 832 |
Console().log("+App::Document: %p\n", this); |
| 833 |
#endif |
| 834 |
std::string CreationDateString = Base::Tools::currentDateTimeString(); |
| 835 |
std::string Author = GetApplication() |
| 836 |
.GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") |
| 837 |
->GetASCII("prefAuthor", ""); |
| 838 |
std::string AuthorComp = |
| 839 |
GetApplication() |
| 840 |
.GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") |
| 841 |
->GetASCII("prefCompany", ""); |
| 842 |
ADD_PROPERTY_TYPE(Label, ("Unnamed"), 0, Prop_ReadOnly, "The name of the document"); |
| 843 |
ADD_PROPERTY_TYPE(FileName, |
| 844 |
(""), |
| 845 |
0, |
| 846 |
PropertyType(Prop_Transient | Prop_ReadOnly), |
| 847 |
"The path to the file where the document is saved to"); |
| 848 |
ADD_PROPERTY_TYPE(CreatedBy, (Author.c_str()), 0, Prop_None, "The creator of the document"); |
| 849 |
ADD_PROPERTY_TYPE(CreationDate, |
| 850 |
(CreationDateString.c_str()), |
| 851 |
0, |
| 852 |
Prop_ReadOnly, |
| 853 |
"Date of creation"); |
| 854 |
ADD_PROPERTY_TYPE(LastModifiedBy, (""), 0, Prop_None, 0); |
| 855 |
ADD_PROPERTY_TYPE(LastModifiedDate, ("Unknown"), 0, Prop_ReadOnly, "Date of last modification"); |
| 856 |
ADD_PROPERTY_TYPE(Company, |
| 857 |
(AuthorComp.c_str()), |
| 858 |
0, |
| 859 |
Prop_None, |
| 860 |
"Additional tag to save the name of the company"); |
| 861 |
ADD_PROPERTY_TYPE(UnitSystem, (""), 0, Prop_None, "Unit system to use in this project"); |
| 862 |
// Set up the possible enum values for the unit system |
| 863 |
|
| 864 |
UnitSystem.setEnums(Base::UnitsApi::getDescriptions()); |
| 865 |
// Get the preferences/General unit system as the default for a new document |
| 866 |
ParameterGrp::handle hGrpu = |
| 867 |
GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Units"); |
| 868 |
UnitSystem.setValue(hGrpu->GetInt("UserSchema", 0)); |
| 869 |
ADD_PROPERTY_TYPE(Comment, (""), 0, Prop_None, "Additional tag to save a comment"); |
| 870 |
ADD_PROPERTY_TYPE(Meta, (), 0, Prop_None, "Map with additional meta information"); |
| 871 |
ADD_PROPERTY_TYPE(Material, (), 0, Prop_None, "Map with material properties"); |
| 872 |
// create the uuid for the document |
| 873 |
Base::Uuid id; |
| 874 |
ADD_PROPERTY_TYPE(Id, (""), 0, Prop_None, "ID of the document"); |
| 875 |
ADD_PROPERTY_TYPE(Uid, (id), 0, Prop_ReadOnly, "UUID of the document"); |
| 876 |
|
| 877 |
// license stuff |
| 878 |
auto paramGrp {GetApplication().GetParameterGroupByPath( |
| 879 |
"User parameter:BaseApp/Preferences/Document")}; |
| 880 |
auto index = static_cast<int>(paramGrp->GetInt("prefLicenseType", 0)); |
| 881 |
auto name = ""; |
| 882 |
std::string licenseUrl = ""; |
| 883 |
if (index >= 0 && index < countOfLicenses) { |
| 884 |
name = licenseItems.at(index).at(posnOfFullName); |
| 885 |
auto url = licenseItems.at(index).at(posnOfUrl); |
| 886 |
licenseUrl = (paramGrp->GetASCII("prefLicenseUrl", url)); |
| 887 |
} |
| 888 |
ADD_PROPERTY_TYPE(License, (name), 0, Prop_None, "License string of the Item"); |
| 889 |
ADD_PROPERTY_TYPE(LicenseURL, |
| 890 |
(licenseUrl.c_str()), |
| 891 |
0, |
| 892 |
Prop_None, |
| 893 |
"URL to the license text/contract"); |
| 894 |
ADD_PROPERTY_TYPE(ShowHidden, |
| 895 |
(false), |
| 896 |
0, |
| 897 |
PropertyType(Prop_None), |
| 898 |
"Whether to show hidden object items in the tree view"); |
| 899 |
ADD_PROPERTY_TYPE(UseHasher, |
| 900 |
(true), |
| 901 |
0, |
| 902 |
PropertyType(Prop_Hidden), |
| 903 |
"Whether to use hasher on topological naming"); |
| 904 |
|
| 905 |
// this creates and sets 'TransientDir' in onChanged() |
| 906 |
ADD_PROPERTY_TYPE(TransientDir, |
| 907 |
(""), |
| 908 |
0, |
| 909 |
PropertyType(Prop_Transient | Prop_ReadOnly), |
| 910 |
"Transient directory, where the files live while the document is open"); |
| 911 |
ADD_PROPERTY_TYPE(Tip, |
| 912 |
(nullptr), |
| 913 |
0, |
| 914 |
PropertyType(Prop_Transient), |
| 915 |
"Link of the tip object of the document"); |
| 916 |
ADD_PROPERTY_TYPE(TipName, |
| 917 |
(""), |
| 918 |
0, |
| 919 |
PropertyType(Prop_Hidden | Prop_ReadOnly), |
| 920 |
"Link of the tip object of the document"); |
| 921 |
Uid.touch(); |
| 922 |
} |
| 923 |
|
| 924 |
Document::~Document() |
| 925 |
{ |
| 926 |
#ifdef FC_LOGUPDATECHAIN |
| 927 |
Console().log("-App::Document: %s %p\n", getName(), this); |
| 928 |
#endif |
| 929 |
|
| 930 |
try { |
| 931 |
clearUndos(); |
| 932 |
} |
| 933 |
catch (const boost::exception&) { |
| 934 |
} |
| 935 |
|
| 936 |
#ifdef FC_LOGUPDATECHAIN |
| 937 |
Console().log("-Delete Features of %s \n", getName()); |
| 938 |
#endif |
| 939 |
|
| 940 |
d->clearDocument(); |
| 941 |
|
| 942 |
// Remark: The API of Py::Object has been changed to set whether the wrapper owns the passed |
| 943 |
// Python object or not. In the constructor we forced the wrapper to own the object so we need |
| 944 |
// not to dec'ref the Python object any more. |
| 945 |
// But we must still invalidate the Python object because it doesn't need to be |
| 946 |
// destructed right now because the interpreter can own several references to it. |
| 947 |
Base::PyGILStateLocker lock; |
| 948 |
auto* doc = static_cast<Base::PyObjectBase*>(d->DocumentPythonObject.ptr()); |
| 949 |
// Call before decrementing the reference counter, otherwise a heap error can occur |
| 950 |
doc->setInvalid(); |
| 951 |
|
| 952 |
// remove Transient directory |
| 953 |
try { |
| 954 |
const Base::FileInfo TransDir(TransientDir.getValue()); |
| 955 |
TransDir.deleteDirectoryRecursive(); |
| 956 |
} |
| 957 |
catch (const Base::Exception& e) { |
| 958 |
std::cerr << "Removing transient directory failed: " << e.what() << '\n'; |
| 959 |
} |
| 960 |
delete d; |
| 961 |
} |
| 962 |
|
| 963 |
std::string Document::getTransientDirectoryName(const std::string& uuid, |
| 964 |
const std::string& filename) const |
| 965 |
{ |
| 966 |
// Create a directory name of the form: {ExeName}_Doc_{UUID}_{HASH}_{PID} |
| 967 |
std::stringstream out; |
| 968 |
QCryptographicHash hash(QCryptographicHash::Sha1); |
| 969 |
#if QT_VERSION < QT_VERSION_CHECK(6, 3, 0) |
| 970 |
hash.addData(filename.c_str(), filename.size()); |
| 971 |
#else |
| 972 |
hash.addData(QByteArrayView(filename.c_str(), filename.size())); |
| 973 |
#endif |
| 974 |
out << Application::getUserCachePath() << Application::getExecutableName() << "_Doc_" |
| 975 |
<< uuid << "_" << hash.result().toHex().left(6).constData() << "_" |
| 976 |
<< Application::applicationPid(); |
| 977 |
return out.str(); |
| 978 |
} |
| 979 |
|
| 980 |
//-------------------------------------------------------------------------- |
| 981 |
// Exported functions |
| 982 |
//-------------------------------------------------------------------------- |
| 983 |
|
| 984 |
void Document::Save(Base::Writer& writer) const |
| 985 |
{ |
| 986 |
d->hashers.clear(); |
| 987 |
addStringHasher(d->Hasher); |
| 988 |
|
| 989 |
writer.Stream() << R"(<Document SchemaVersion="4" ProgramVersion=")" |
| 990 |
<< Application::Config()["BuildVersionMajor"] << "." |
| 991 |
<< Application::Config()["BuildVersionMinor"] << "R" |
| 992 |
<< Application::Config()["BuildRevision"] << "\" FileVersion=\"" |
| 993 |
<< writer.getFileVersion() << "\" StringHasher=\"1\">\n"; |
| 994 |
|
| 995 |
writer.incInd(); |
| 996 |
|
| 997 |
// NOTE: This differs from LS3 Code. Persisting this table |
| 998 |
// forces the assertion in Writer.addFile(...): assert(!isForceXML()); to be removed |
| 999 |
// see: https://github.com/FreeCAD/FreeCAD/issues/27489 |
| 1000 |
// |
| 1001 |
// Original code in LS3: |
| 1002 |
// d->Hasher->setPersistenceFileName(0); |
| 1003 |
d->Hasher->setPersistenceFileName("StringHasher.Table"); |
| 1004 |
|
| 1005 |
for (const auto o : d->objectArray) { |
| 1006 |
o->beforeSave(); |
| 1007 |
} |
| 1008 |
beforeSave(); |
| 1009 |
|
| 1010 |
d->Hasher->Save(writer); |
| 1011 |
|
| 1012 |
writer.decInd(); |
| 1013 |
|
| 1014 |
PropertyContainer::Save(writer); |
| 1015 |
|
| 1016 |
// writing the features types |
| 1017 |
writeObjects(d->objectArray, writer); |
| 1018 |
writer.Stream() << "</Document>" << '\n'; |
| 1019 |
} |
| 1020 |
|
| 1021 |
void Document::Restore(Base::XMLReader& reader) |
| 1022 |
{ |
| 1023 |
d->hashers.clear(); |
| 1024 |
d->touchedObjs.clear(); |
| 1025 |
addStringHasher(d->Hasher); |
| 1026 |
setStatus(Document::PartialDoc, false); |
| 1027 |
|
| 1028 |
reader.readElement("Document"); |
| 1029 |
const long scheme = reader.getAttribute<long>("SchemaVersion"); |
| 1030 |
reader.DocumentSchema = static_cast<int>(scheme); |
| 1031 |
if (reader.hasAttribute("ProgramVersion")) { |
| 1032 |
reader.ProgramVersion = reader.getAttribute<const char*>("ProgramVersion"); |
| 1033 |
} |
| 1034 |
else { |
| 1035 |
reader.ProgramVersion = "pre-0.14"; |
| 1036 |
} |
| 1037 |
if (reader.hasAttribute("FileVersion")) { |
| 1038 |
reader.FileVersion = static_cast<int>(reader.getAttribute<unsigned long>("FileVersion")); |
| 1039 |
} |
| 1040 |
else { |
| 1041 |
reader.FileVersion = 0; |
| 1042 |
} |
| 1043 |
|
| 1044 |
if (reader.hasAttribute("StringHasher")) { |
| 1045 |
d->Hasher->Restore(reader); |
| 1046 |
} |
| 1047 |
else { |
| 1048 |
d->Hasher->clear(); |
| 1049 |
} |
| 1050 |
|
| 1051 |
// When this document was created the FileName and Label properties |
| 1052 |
// were set to the absolute path or file name, respectively. To save |
| 1053 |
// the document to the file it was loaded from or to show the file name |
| 1054 |
// in the tree view we must restore them after loading the file because |
| 1055 |
// they will be overridden. |
| 1056 |
// Note: This does not affect the internal name of the document in any way |
| 1057 |
// that is kept in Application. |
| 1058 |
const std::string FilePath = FileName.getValue(); |
| 1059 |
const std::string DocLabel = Label.getValue(); |
| 1060 |
|
| 1061 |
// read the Document Properties, when reading in Uid the transient directory gets renamed |
| 1062 |
// automatically |
| 1063 |
PropertyContainer::Restore(reader); |
| 1064 |
|
| 1065 |
// We must restore the correct 'FileName' property again because the stored |
| 1066 |
// value could be invalid. |
| 1067 |
FileName.setValue(FilePath.c_str()); |
| 1068 |
Label.setValue(DocLabel.c_str()); |
| 1069 |
|
| 1070 |
// SchemeVersion "2" |
| 1071 |
if (scheme == 2) { |
| 1072 |
// read the feature types |
| 1073 |
reader.readElement("Features"); |
| 1074 |
for (auto i = 0; i < reader.getAttribute<long>("Count"); i++) { |
| 1075 |
reader.readElement("Feature"); |
| 1076 |
string type = reader.getAttribute<const char*>("type"); |
| 1077 |
string name = reader.getAttribute<const char*>("name"); |
| 1078 |
try { |
| 1079 |
addObject(type.c_str(), name.c_str(), /*isNew=*/false); |
| 1080 |
} |
| 1081 |
catch (Base::Exception&) { |
| 1082 |
Base::Console().message("Cannot create object '%s'\n", name.c_str()); |
| 1083 |
} |
| 1084 |
} |
| 1085 |
reader.readEndElement("Features"); |
| 1086 |
|
| 1087 |
// read the features itself |
| 1088 |
reader.readElement("FeatureData"); |
| 1089 |
for (auto i = 0; i < reader.getAttribute<long>("Count"); i++) { |
| 1090 |
reader.readElement("Feature"); |
| 1091 |
string name = reader.getAttribute<const char*>("name"); |
| 1092 |
DocumentObject* pObj = getObject(name.c_str()); |
| 1093 |
if (pObj) { // check if this feature has been registered |
| 1094 |
pObj->setStatus(ObjectStatus::Restore, true); |
| 1095 |
pObj->Restore(reader); |
| 1096 |
pObj->setStatus(ObjectStatus::Restore, false); |
| 1097 |
} |
| 1098 |
reader.readEndElement("Feature"); |
| 1099 |
} |
| 1100 |
reader.readEndElement("FeatureData"); |
| 1101 |
} // SchemeVersion "3" or higher |
| 1102 |
else if (scheme >= 3) { |
| 1103 |
// read the feature types |
| 1104 |
readObjects(reader); |
| 1105 |
|
| 1106 |
// tip object handling. First the whole document has to be read, then we |
| 1107 |
// can restore the Tip link out of the TipName Property: |
| 1108 |
Tip.setValue(getObject(TipName.getValue())); |
| 1109 |
} |
| 1110 |
|
| 1111 |
reader.readEndElement("Document"); |
| 1112 |
} |
| 1113 |
|
| 1114 |
void DocumentP::checkStringHasher(const Base::XMLReader& reader) |
| 1115 |
{ |
| 1116 |
if (reader.hasReadFailed("StringHasher.Table.txt")) { |
| 1117 |
Base::Console().error(QT_TRANSLATE_NOOP( |
| 1118 |
"Notifications", |
| 1119 |
"\nIt is recommended that the user right-click the root of " |
| 1120 |
"the document and select Mark to recompute.\n" |
| 1121 |
"The user should then click the Refresh button in the main toolbar.\n")); |
| 1122 |
} |
| 1123 |
} |
| 1124 |
|
| 1125 |
std::pair<bool, int> Document::addStringHasher(const StringHasherRef& hasher) const |
| 1126 |
{ |
| 1127 |
if (!hasher) { |
| 1128 |
return std::make_pair(false, 0); |
| 1129 |
} |
| 1130 |
auto ret = |
| 1131 |
d->hashers.left.insert(HasherMap::left_map::value_type(hasher, static_cast<int>(d->hashers.size()))); |
| 1132 |
if (ret.second) { |
| 1133 |
hasher->clearMarks(); |
| 1134 |
} |
| 1135 |
return std::make_pair(ret.second, ret.first->second); |
| 1136 |
} |
| 1137 |
|
| 1138 |
StringHasherRef Document::getStringHasher(const int idx) const |
| 1139 |
{ |
| 1140 |
StringHasherRef hasher; |
| 1141 |
if (idx < 0) { |
| 1142 |
if (UseHasher.getValue()) { |
| 1143 |
return d->Hasher; |
| 1144 |
} |
| 1145 |
return hasher; |
| 1146 |
} |
| 1147 |
const auto it = d->hashers.right.find(idx); |
| 1148 |
if (it == d->hashers.right.end()) { |
| 1149 |
hasher = new StringHasher; |
| 1150 |
d->hashers.right.insert(HasherMap::right_map::value_type(idx, hasher)); |
| 1151 |
} |
| 1152 |
else { |
| 1153 |
hasher = it->second; |
| 1154 |
} |
| 1155 |
return hasher; |
| 1156 |
} |
| 1157 |
|
| 1158 |
struct DocExportStatus |
| 1159 |
{ |
| 1160 |
Document::ExportStatus status; |
| 1161 |
std::set<const DocumentObject*> objs; |
| 1162 |
}; |
| 1163 |
|
| 1164 |
static DocExportStatus exportStatus; |
| 1165 |
|
| 1166 |
// Exception-safe exporting status setter |
| 1167 |
class DocumentExporting |
| 1168 |
{ |
| 1169 |
public: |
| 1170 |
explicit DocumentExporting(const std::vector<DocumentObject*>& objs) |
| 1171 |
{ |
| 1172 |
exportStatus.status = Document::Exporting; |
| 1173 |
exportStatus.objs.insert(objs.begin(), objs.end()); |
| 1174 |
} |
| 1175 |
|
| 1176 |
~DocumentExporting() |
| 1177 |
{ |
| 1178 |
exportStatus.status = Document::NotExporting; |
| 1179 |
exportStatus.objs.clear(); |
| 1180 |
} |
| 1181 |
}; |
| 1182 |
|
| 1183 |
// The current implementation choose to use a static variable for exporting |
| 1184 |
// status because we can be exporting multiple objects from multiple documents |
| 1185 |
// at the same time. I see no benefits in distinguish which documents are |
| 1186 |
// exporting, so just use a static variable for global status. But the |
| 1187 |
// implementation can easily be changed here if necessary. |
| 1188 |
Document::ExportStatus Document::isExporting(const DocumentObject* obj) const |
| 1189 |
{ |
| 1190 |
if (exportStatus.status != Document::NotExporting |
| 1191 |
&& ((obj == nullptr) || exportStatus.objs.find(obj) != exportStatus.objs.end())) { |
| 1192 |
return exportStatus.status; |
| 1193 |
} |
| 1194 |
return Document::NotExporting; |
| 1195 |
} |
| 1196 |
ExportInfo Document::exportInfo() const |
| 1197 |
{ |
| 1198 |
return d->exportInfo; |
| 1199 |
} |
| 1200 |
void Document::setExportInfo(const ExportInfo& info) |
| 1201 |
{ |
| 1202 |
d->exportInfo = info; |
| 1203 |
} |
| 1204 |
|
| 1205 |
void Document::exportObjects(const std::vector<DocumentObject*>& obj, std::ostream& out) |
| 1206 |
{ |
| 1207 |
|
| 1208 |
DocumentExporting exporting(obj); |
| 1209 |
d->hashers.clear(); |
| 1210 |
|
| 1211 |
if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { |
| 1212 |
for (auto o : obj) { |
| 1213 |
if (o && o->isAttachedToDocument()) { |
| 1214 |
FC_LOG("exporting " << o->getFullName()); |
| 1215 |
if (!o->getPropertyByName("_ObjectUUID")) { |
| 1216 |
auto prop = static_cast<PropertyUUID*>( |
| 1217 |
o->addDynamicProperty("App::PropertyUUID", |
| 1218 |
"_ObjectUUID", |
| 1219 |
nullptr, |
| 1220 |
nullptr, |
| 1221 |
Prop_Output | Prop_Hidden)); |
| 1222 |
prop->setValue(Base::Uuid::createUuid()); |
| 1223 |
} |
| 1224 |
} |
| 1225 |
} |
| 1226 |
} |
| 1227 |
|
| 1228 |
Base::ZipWriter writer(out); |
| 1229 |
writer.putNextEntry("Document.xml"); |
| 1230 |
writer.Stream() << "<?xml version='1.0' encoding='utf-8'?>" << '\n'; |
| 1231 |
writer.Stream() << R"(<Document SchemaVersion="4" ProgramVersion=")" |
| 1232 |
<< Application::Config()["BuildVersionMajor"] << "." |
| 1233 |
<< Application::Config()["BuildVersionMinor"] << "R" |
| 1234 |
<< Application::Config()["BuildRevision"] << R"(" FileVersion="1">)" |
| 1235 |
<< '\n'; |
| 1236 |
// Add this block to have the same layout as for normal documents |
| 1237 |
writer.Stream() << "<Properties Count=\"0\">" << '\n'; |
| 1238 |
writer.Stream() << "</Properties>" << '\n'; |
| 1239 |
|
| 1240 |
// writing the object types |
| 1241 |
writeObjects(obj, writer); |
| 1242 |
writer.Stream() << "</Document>" << '\n'; |
| 1243 |
|
| 1244 |
// Hook for others to add further data. |
| 1245 |
signalExportObjects(obj, writer); |
| 1246 |
|
| 1247 |
// write additional files |
| 1248 |
writer.writeFiles(); |
| 1249 |
d->hashers.clear(); |
| 1250 |
} |
| 1251 |
|
| 1252 |
constexpr auto fcAttrDependencies {"Dependencies"}; |
| 1253 |
constexpr auto fcElementObjectDeps {"ObjectDeps"}; |
| 1254 |
constexpr auto fcAttrDepCount {"Count"}; |
| 1255 |
constexpr auto fcAttrDepObjName {"Name"}; |
| 1256 |
constexpr auto fcAttrDepAllowPartial {"AllowPartial"}; |
| 1257 |
constexpr auto fcElementObjectDep {"Dep"}; |
| 1258 |
|
| 1259 |
void Document::writeObjects(const std::vector<DocumentObject*>& obj, |
| 1260 |
Base::Writer& writer) const |
| 1261 |
{ |
| 1262 |
// writing the features types |
| 1263 |
writer.incInd(); // indentation for 'Objects count' |
| 1264 |
writer.Stream() << writer.ind() << "<Objects Count=\"" << obj.size(); |
| 1265 |
if (isExporting(nullptr) == 0U) { |
| 1266 |
writer.Stream() << "\" " << fcAttrDependencies << "=\"1"; |
| 1267 |
} |
| 1268 |
writer.Stream() << "\">" << '\n'; |
| 1269 |
|
| 1270 |
writer.incInd(); // indentation for 'Object type' |
| 1271 |
|
| 1272 |
if (isExporting(nullptr) == 0U) { |
| 1273 |
for (const auto o : obj) { |
| 1274 |
const auto& outList = |
| 1275 |
o->getOutList(DocumentObject::OutListNoHidden | DocumentObject::OutListNoXLinked); |
| 1276 |
writer.Stream() << writer.ind() |
| 1277 |
<< "<" << fcElementObjectDeps << " " << fcAttrDepObjName << "=\"" |
| 1278 |
<< o->getNameInDocument() << "\" " << fcAttrDepCount << "=\"" |
| 1279 |
<< outList.size(); |
| 1280 |
if (outList.empty()) { |
| 1281 |
writer.Stream() << "\"/>" << '\n'; |
| 1282 |
continue; |
| 1283 |
} |
| 1284 |
const int partial = o->canLoadPartial(); |
| 1285 |
if (partial > 0) { |
| 1286 |
writer.Stream() << "\" " << fcAttrDepAllowPartial << "=\"" << partial; |
| 1287 |
} |
| 1288 |
writer.Stream() << "\">" << '\n'; |
| 1289 |
writer.incInd(); |
| 1290 |
for (const auto dep : outList) { |
| 1291 |
const auto name = dep ? dep->getNameInDocument() : ""; |
| 1292 |
writer.Stream() << writer.ind() |
| 1293 |
<< "<" << fcElementObjectDep << " " << fcAttrDepObjName << "=\"" |
| 1294 |
<< (name ? name : "") << "\"/>" << '\n'; |
| 1295 |
} |
| 1296 |
writer.decInd(); |
| 1297 |
writer.Stream() << writer.ind() << "</" << fcElementObjectDeps << ">" << '\n'; |
| 1298 |
} |
| 1299 |
} |
| 1300 |
|
| 1301 |
std::vector<DocumentObject*>::const_iterator it; |
| 1302 |
for (it = obj.begin(); it != obj.end(); ++it) { |
| 1303 |
writer.Stream() << writer.ind() << "<Object " |
| 1304 |
<< "type=\"" << (*it)->getTypeId().getName() << "\" " |
| 1305 |
<< "name=\"" << (*it)->getExportName() << "\" " |
| 1306 |
<< "id=\"" << (*it)->getID() << "\" "; |
| 1307 |
|
| 1308 |
// Only write out custom view provider types |
| 1309 |
std::string viewType = (*it)->getViewProviderNameStored(); |
| 1310 |
if (viewType != (*it)->getViewProviderName()) { |
| 1311 |
writer.Stream() << "ViewType=\"" << viewType << "\" "; |
| 1312 |
} |
| 1313 |
|
| 1314 |
// See DocumentObjectPy::getState |
| 1315 |
if ((*it)->testStatus(ObjectStatus::Touch)) { |
| 1316 |
writer.Stream() << "Touched=\"1\" "; |
| 1317 |
} |
| 1318 |
if ((*it)->testStatus(ObjectStatus::Error)) { |
| 1319 |
writer.Stream() << "Invalid=\"1\" "; |
| 1320 |
const auto desc = getErrorDescription(*it); |
| 1321 |
if (desc) { |
| 1322 |
writer.Stream() << "Error=\"" << Property::encodeAttribute(desc) << "\" "; |
| 1323 |
} |
| 1324 |
} |
| 1325 |
writer.Stream() << "/>" << '\n'; |
| 1326 |
} |
| 1327 |
|
| 1328 |
writer.decInd(); // indentation for 'Object type' |
| 1329 |
writer.Stream() << writer.ind() << "</Objects>" << '\n'; |
| 1330 |
|
| 1331 |
// writing the features itself |
| 1332 |
writer.Stream() << writer.ind() << "<ObjectData Count=\"" << obj.size() << "\">" << '\n'; |
| 1333 |
|
| 1334 |
writer.incInd(); // indentation for 'Object name' |
| 1335 |
for (it = obj.begin(); it != obj.end(); ++it) { |
| 1336 |
writer.Stream() << writer.ind() << "<Object name=\"" << (*it)->getExportName() << "\""; |
| 1337 |
if ((*it)->hasExtensions()) { |
| 1338 |
writer.Stream() << " Extensions=\"True\""; |
| 1339 |
} |
| 1340 |
|
| 1341 |
writer.Stream() << ">" << '\n'; |
| 1342 |
(*it)->Save(writer); |
| 1343 |
writer.Stream() << writer.ind() << "</Object>" << '\n'; |
| 1344 |
} |
| 1345 |
|
| 1346 |
writer.decInd(); // indentation for 'Object name' |
| 1347 |
writer.Stream() << writer.ind() << "</ObjectData>" << '\n'; |
| 1348 |
writer.decInd(); // indentation for 'Objects count' |
| 1349 |
} |
| 1350 |
|
| 1351 |
struct DepInfo |
| 1352 |
{ |
| 1353 |
std::unordered_set<std::string> deps; |
| 1354 |
int canLoadPartial = 0; |
| 1355 |
}; |
| 1356 |
|
| 1357 |
static void loadDeps(const std::string& name, |
| 1358 |
std::unordered_map<std::string, bool>& objs, |
| 1359 |
const std::unordered_map<std::string, DepInfo>& deps) |
| 1360 |
{ |
| 1361 |
const auto it = deps.find(name); |
| 1362 |
if (it == deps.end()) { |
| 1363 |
objs.emplace(name, true); |
| 1364 |
return; |
| 1365 |
} |
| 1366 |
if (it->second.canLoadPartial != 0) { |
| 1367 |
if (it->second.canLoadPartial == 1) { |
| 1368 |
// canLoadPartial==1 means all its children will be created but not |
| 1369 |
// restored, i.e. exists as if newly created object, and therefore no |
| 1370 |
// need to load dependency of the children |
| 1371 |
for (auto& dep : it->second.deps) { |
| 1372 |
objs.emplace(dep, false); |
| 1373 |
} |
| 1374 |
objs.emplace(name, true); |
| 1375 |
} |
| 1376 |
else { |
| 1377 |
objs.emplace(name, false); |
| 1378 |
} |
| 1379 |
return; |
| 1380 |
} |
| 1381 |
objs[name] = true; |
| 1382 |
// If cannot load partial, then recurse to load all children dependency |
| 1383 |
for (auto& dep : it->second.deps) { |
| 1384 |
if (auto found = objs.find(dep); found != objs.end() && found->second) { |
| 1385 |
continue; |
| 1386 |
} |
| 1387 |
loadDeps(dep, objs, deps); |
| 1388 |
} |
| 1389 |
} |
| 1390 |
|
| 1391 |
std::vector<DocumentObject*> Document::readObjects(Base::XMLReader& reader) |
| 1392 |
{ |
| 1393 |
d->touchedObjs.clear(); |
| 1394 |
bool keepDigits = testStatus(Document::KeepTrailingDigits); |
| 1395 |
setStatus(Document::KeepTrailingDigits, !reader.doNameMapping()); |
| 1396 |
std::vector<DocumentObject*> objs; |
| 1397 |
|
| 1398 |
|
| 1399 |
// read the object types |
| 1400 |
reader.readElement("Objects"); |
| 1401 |
int Cnt = static_cast<int>(reader.getAttribute<long>("Count")); |
| 1402 |
|
| 1403 |
if (!reader.hasAttribute(fcAttrDependencies)) { |
| 1404 |
d->partialLoadObjects.clear(); |
| 1405 |
} |
| 1406 |
else if (!d->partialLoadObjects.empty()) { |
| 1407 |
std::unordered_map<std::string, DepInfo> deps; |
| 1408 |
for (int i = 0; i < Cnt; i++) { |
| 1409 |
reader.readElement(fcElementObjectDeps); |
| 1410 |
int dcount = static_cast<int>(reader.getAttribute<long>(fcAttrDepCount)); |
| 1411 |
if (dcount == 0) { |
| 1412 |
continue; |
| 1413 |
} |
| 1414 |
auto& info = deps[reader.getAttribute<const char*>(fcAttrDepObjName)]; |
| 1415 |
if (reader.hasAttribute(fcAttrDepAllowPartial)) { |
| 1416 |
info.canLoadPartial = |
| 1417 |
static_cast<int>(reader.getAttribute<long>(fcAttrDepAllowPartial)); |
| 1418 |
} |
| 1419 |
for (int j = 0; j < dcount; ++j) { |
| 1420 |
reader.readElement(fcElementObjectDep); |
| 1421 |
const char* name = reader.getAttribute<const char*>(fcAttrDepObjName); |
| 1422 |
if (!Base::Tools::isNullOrEmpty(name)) { |
| 1423 |
info.deps.insert(name); |
| 1424 |
} |
| 1425 |
} |
| 1426 |
reader.readEndElement(fcElementObjectDeps); |
| 1427 |
} |
| 1428 |
std::vector<std::string> strings; |
| 1429 |
strings.reserve(d->partialLoadObjects.size()); |
| 1430 |
for (auto& v : d->partialLoadObjects) { |
| 1431 |
strings.emplace_back(v.first.c_str()); |
| 1432 |
} |
| 1433 |
for (auto& name : strings) { |
| 1434 |
loadDeps(name, d->partialLoadObjects, deps); |
| 1435 |
} |
| 1436 |
if (Cnt > static_cast<int>(d->partialLoadObjects.size())) { |
| 1437 |
setStatus(Document::PartialDoc, true); |
| 1438 |
} |
| 1439 |
else { |
| 1440 |
for (auto& v : d->partialLoadObjects) { |
| 1441 |
if (!v.second) { |
| 1442 |
setStatus(Document::PartialDoc, true); |
| 1443 |
break; |
| 1444 |
} |
| 1445 |
} |
| 1446 |
if (!testStatus(Document::PartialDoc)) { |
| 1447 |
d->partialLoadObjects.clear(); |
| 1448 |
} |
| 1449 |
} |
| 1450 |
} |
| 1451 |
|
| 1452 |
long lastId = 0; |
| 1453 |
for (int i = 0; i < Cnt; i++) { |
| 1454 |
reader.readElement("Object"); |
| 1455 |
std::string type = reader.getAttribute<const char*>("type"); |
| 1456 |
std::string name = reader.getAttribute<const char*>("name"); |
| 1457 |
std::string viewType = |
| 1458 |
reader.hasAttribute("ViewType") ? reader.getAttribute<const char*>("ViewType") : ""; |
| 1459 |
|
| 1460 |
bool partial = false; |
| 1461 |
if (!d->partialLoadObjects.empty()) { |
| 1462 |
auto it = d->partialLoadObjects.find(name); |
| 1463 |
if (it == d->partialLoadObjects.end()) { |
| 1464 |
continue; |
| 1465 |
} |
| 1466 |
partial = !it->second; |
| 1467 |
} |
| 1468 |
|
| 1469 |
if (!testStatus(Status::Importing) && reader.hasAttribute("id")) { |
| 1470 |
// if not importing, then temporary reset lastObjectId and make the |
| 1471 |
// following addObject() generate the correct id for this object. |
| 1472 |
d->lastObjectId = reader.getAttribute<long>("id") - 1; |
| 1473 |
} |
| 1474 |
|
| 1475 |
// To prevent duplicate name when export/import of objects from |
| 1476 |
// external documents, we append those external object name with |
| 1477 |
// @<document name>. Before importing (here means we are called by |
| 1478 |
// importObjects), we shall strip the postfix. What the caller |
| 1479 |
// (MergeDocument) sees is still the unstripped name mapped to a new |
| 1480 |
// internal name, and the rest of the link properties will be able to |
| 1481 |
// correctly unmap the names. |
| 1482 |
auto pos = name.find('@'); |
| 1483 |
std::string _obj_name; |
| 1484 |
const char* obj_name {nullptr}; |
| 1485 |
if (pos != std::string::npos) { |
| 1486 |
_obj_name = name.substr(0, pos); |
| 1487 |
obj_name = _obj_name.c_str(); |
| 1488 |
} |
| 1489 |
else { |
| 1490 |
obj_name = name.c_str(); |
| 1491 |
} |
| 1492 |
|
| 1493 |
try { |
| 1494 |
// Use name from XML as is and do NOT remove trailing digits because |
| 1495 |
// otherwise we may cause a dependency to itself |
| 1496 |
// Example: Object 'Cut001' references object 'Cut' and removing the |
| 1497 |
// digits we make an object 'Cut' referencing itself. |
| 1498 |
DocumentObject* obj = |
| 1499 |
addObject(type.c_str(), obj_name, /*isNew=*/false, viewType.c_str(), partial); |
| 1500 |
if (obj) { |
| 1501 |
if (lastId < obj->_Id) { |
| 1502 |
lastId = obj->_Id; |
| 1503 |
} |
| 1504 |
objs.push_back(obj); |
| 1505 |
// use this name for the later access because an object with |
| 1506 |
// the given name may already exist |
| 1507 |
reader.addName(name.c_str(), obj->getNameInDocument()); |
| 1508 |
|
| 1509 |
// restore touch/error status flags |
| 1510 |
if (reader.hasAttribute("Touched")) { |
| 1511 |
if (reader.getAttribute<long>("Touched") != 0) { |
| 1512 |
d->touchedObjs.insert(obj); |
| 1513 |
} |
| 1514 |
} |
| 1515 |
if (reader.hasAttribute("Invalid")) { |
| 1516 |
obj->setStatus(ObjectStatus::Error, |
| 1517 |
reader.getAttribute<bool>("Invalid")); |
| 1518 |
if (obj->isError() && reader.hasAttribute("Error")) { |
| 1519 |
d->addRecomputeLog(reader.getAttribute<const char*>("Error"), obj); |
| 1520 |
} |
| 1521 |
} |
| 1522 |
} |
| 1523 |
} |
| 1524 |
catch (const Base::Exception& e) { |
| 1525 |
Base::Console().error("Cannot create object '%s': (%s)\n", name.c_str(), e.what()); |
| 1526 |
} |
| 1527 |
} |
| 1528 |
if (!testStatus(Status::Importing)) { |
| 1529 |
d->lastObjectId = lastId; |
| 1530 |
} |
| 1531 |
|
| 1532 |
reader.readEndElement("Objects"); |
| 1533 |
setStatus(Document::KeepTrailingDigits, keepDigits); |
| 1534 |
|
| 1535 |
// read the features itself |
| 1536 |
reader.clearPartialRestoreDocumentObject(); |
| 1537 |
reader.readElement("ObjectData"); |
| 1538 |
Cnt = static_cast<int>(reader.getAttribute<long>("Count")); |
| 1539 |
for (int i = 0; i < Cnt; i++) { |
| 1540 |
reader.readElement("Object"); |
| 1541 |
std::string name = reader.getName(reader.getAttribute<const char*>("name")); |
| 1542 |
if (DocumentObject* pObj = getObject(name.c_str()); pObj |
| 1543 |
&& !pObj->testStatus( |
| 1544 |
PartialObject)) { // check if this feature has been registered |
| 1545 |
pObj->setStatus(ObjectStatus::Restore, true); |
| 1546 |
try { |
| 1547 |
FC_TRACE("restoring " << pObj->getFullName()); |
| 1548 |
pObj->Restore(reader); |
| 1549 |
} |
| 1550 |
// Try to continue only for certain exception types if not handled |
| 1551 |
// by the feature type. For all other exception types abort the process. |
| 1552 |
catch (const Base::UnicodeError& e) { |
| 1553 |
e.reportException(); |
| 1554 |
} |
| 1555 |
catch (const Base::ValueError& e) { |
| 1556 |
e.reportException(); |
| 1557 |
} |
| 1558 |
catch (const Base::IndexError& e) { |
| 1559 |
e.reportException(); |
| 1560 |
} |
| 1561 |
catch (const Base::RuntimeError& e) { |
| 1562 |
e.reportException(); |
| 1563 |
} |
| 1564 |
catch (const Base::XMLAttributeError& e) { |
| 1565 |
e.reportException(); |
| 1566 |
} |
| 1567 |
|
| 1568 |
pObj->setStatus(ObjectStatus::Restore, false); |
| 1569 |
|
| 1570 |
if (reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestoreInDocumentObject)) { |
| 1571 |
Base::Console().error("Object \"%s\" was subject to a partial restore. As a result " |
| 1572 |
"geometry may have changed or be incomplete.\n", |
| 1573 |
name.c_str()); |
| 1574 |
reader.clearPartialRestoreDocumentObject(); |
| 1575 |
} |
| 1576 |
} |
| 1577 |
reader.readEndElement("Object"); |
| 1578 |
} |
| 1579 |
reader.readEndElement("ObjectData"); |
| 1580 |
|
| 1581 |
return objs; |
| 1582 |
} |
| 1583 |
|
| 1584 |
void Document::addRecomputeObject(DocumentObject* obj) // NOLINT |
| 1585 |
{ |
| 1586 |
if (testStatus(Status::Restoring) && obj) { |
| 1587 |
setStatus(Status::RecomputeOnRestore, true); |
| 1588 |
d->touchedObjs.insert(obj); |
| 1589 |
obj->touch(); |
| 1590 |
} |
| 1591 |
} |
| 1592 |
|
| 1593 |
std::vector<DocumentObject*> Document::importObjects(Base::XMLReader& reader) |
| 1594 |
{ |
| 1595 |
d->hashers.clear(); |
| 1596 |
Base::FlagToggler<> flag(globalIsRestoring, false); |
| 1597 |
Base::ObjectStatusLocker<Status, Document> restoreBit(Status::Restoring, this); |
| 1598 |
Base::ObjectStatusLocker<Status, Document> restoreBit2(Status::Importing, this); |
| 1599 |
ExpressionParser::ExpressionImporter expImporter(reader); |
| 1600 |
reader.readElement("Document"); |
| 1601 |
const long scheme = reader.getAttribute<long>("SchemaVersion"); |
| 1602 |
reader.DocumentSchema = static_cast<int>(scheme); |
| 1603 |
if (reader.hasAttribute("ProgramVersion")) { |
| 1604 |
reader.ProgramVersion = reader.getAttribute<const char*>("ProgramVersion"); |
| 1605 |
} |
| 1606 |
else { |
| 1607 |
reader.ProgramVersion = "pre-0.14"; |
| 1608 |
} |
| 1609 |
if (reader.hasAttribute("FileVersion")) { |
| 1610 |
reader.FileVersion = static_cast<int>(reader.getAttribute<unsigned long>("FileVersion")); |
| 1611 |
} |
| 1612 |
else { |
| 1613 |
reader.FileVersion = 0; |
| 1614 |
} |
| 1615 |
|
| 1616 |
std::vector<DocumentObject*> objs = readObjects(reader); |
| 1617 |
for (const auto o : objs) { |
| 1618 |
if (o && o->isAttachedToDocument()) { |
| 1619 |
o->setStatus(ObjImporting, true); |
| 1620 |
FC_LOG("importing " << o->getFullName()); |
| 1621 |
if (const auto propUUID = |
| 1622 |
freecad_cast<PropertyUUID*>(o->getPropertyByName("_ObjectUUID"))) { |
| 1623 |
auto propSource = |
| 1624 |
freecad_cast<PropertyUUID*>(o->getPropertyByName("_SourceUUID")); |
| 1625 |
if (!propSource) { |
| 1626 |
propSource = static_cast<PropertyUUID*>( |
| 1627 |
o->addDynamicProperty("App::PropertyUUID", |
| 1628 |
"_SourceUUID", |
| 1629 |
nullptr, |
| 1630 |
nullptr, |
| 1631 |
Prop_Output | Prop_Hidden)); |
| 1632 |
} |
| 1633 |
if (propSource) { |
| 1634 |
propSource->setValue(propUUID->getValue()); |
| 1635 |
} |
| 1636 |
propUUID->setValue(Base::Uuid::createUuid()); |
| 1637 |
} |
| 1638 |
} |
| 1639 |
} |
| 1640 |
|
| 1641 |
reader.readEndElement("Document"); |
| 1642 |
|
| 1643 |
signalImportObjects(objs, reader); |
| 1644 |
afterRestore(objs, true); |
| 1645 |
|
| 1646 |
signalFinishImportObjects(objs); |
| 1647 |
|
| 1648 |
for (const auto o : objs) { |
| 1649 |
if (o && o->isAttachedToDocument()) { |
| 1650 |
o->setStatus(ObjImporting, false); |
| 1651 |
} |
| 1652 |
} |
| 1653 |
|
| 1654 |
d->hashers.clear(); |
| 1655 |
return objs; |
| 1656 |
} |
| 1657 |
|
| 1658 |
unsigned int Document::getMemSize() const |
| 1659 |
{ |
| 1660 |
unsigned int size = 0; |
| 1661 |
|
| 1662 |
// size of the DocObjects in the document |
| 1663 |
for (const auto & it : d->objectArray) { |
| 1664 |
size += it->getMemSize(); |
| 1665 |
} |
| 1666 |
|
| 1667 |
size += d->Hasher->getMemSize(); |
| 1668 |
|
| 1669 |
// size of the document properties... |
| 1670 |
size += PropertyContainer::getMemSize(); |
| 1671 |
|
| 1672 |
// Undo Redo size |
| 1673 |
size += getUndoMemSize(); |
| 1674 |
|
| 1675 |
return size; |
| 1676 |
} |
| 1677 |
|
| 1678 |
static std::string checkFileName(const char* file) |
| 1679 |
{ |
| 1680 |
std::string fn(file); |
| 1681 |
|
| 1682 |
// Append extension if missing. This option is added for security reason, so |
| 1683 |
// that the user won't accidentally overwrite other file that may be critical. |
| 1684 |
if (GetApplication() |
| 1685 |
.GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") |
| 1686 |
->GetBool("CheckExtension", true)) { |
| 1687 |
const char* ext = strrchr(file, '.'); |
| 1688 |
if ((ext == nullptr) || !boost::iequals(ext + 1, "fcstd")) { |
| 1689 |
if (ext && ext[1] == 0) { |
| 1690 |
fn += "FCStd"; |
| 1691 |
} |
| 1692 |
else { |
| 1693 |
fn += ".FCStd"; |
| 1694 |
} |
| 1695 |
} |
| 1696 |
} |
| 1697 |
return fn; |
| 1698 |
} |
| 1699 |
|
| 1700 |
bool Document::saveAs(const char* _file) |
| 1701 |
{ |
| 1702 |
const std::string file = checkFileName(_file); |
| 1703 |
const Base::FileInfo fi(file.c_str()); |
| 1704 |
if (this->FileName.getStrValue() != file) { |
| 1705 |
this->FileName.setValue(file); |
| 1706 |
this->Label.setValue(fi.fileNamePure()); |
| 1707 |
this->Uid.touch(); // this forces a rename of the transient directory |
| 1708 |
} |
| 1709 |
|
| 1710 |
return save(); |
| 1711 |
} |
| 1712 |
|
| 1713 |
bool Document::saveCopy(const char* file) const |
| 1714 |
{ |
| 1715 |
const std::string checked = checkFileName(file); |
| 1716 |
return this->FileName.getStrValue() != checked ? saveToFile(checked.c_str()) : false; |
| 1717 |
} |
| 1718 |
|
| 1719 |
// Save the document under the name it has been opened |
| 1720 |
bool Document::save() |
| 1721 |
{ |
| 1722 |
if (testStatus(Document::PartialDoc)) { |
| 1723 |
FC_ERR("Partial loaded document '" << Label.getValue() << "' cannot be saved"); |
| 1724 |
// TODO We don't make this a fatal error and return 'true' to make it possible to |
| 1725 |
// save other documents that depends on this partial opened document. We need better |
| 1726 |
// handling to avoid touching partial documents. |
| 1727 |
return true; |
| 1728 |
} |
| 1729 |
|
| 1730 |
if (*(FileName.getValue()) != '\0') { |
| 1731 |
// Save the name of the tip object in order to handle in Restore() |
| 1732 |
if (Tip.getValue()) { |
| 1733 |
TipName.setValue(Tip.getValue()->getNameInDocument()); |
| 1734 |
} |
| 1735 |
|
| 1736 |
const std::string LastModifiedDateString = Base::Tools::currentDateTimeString(); |
| 1737 |
LastModifiedDate.setValue(LastModifiedDateString.c_str()); |
| 1738 |
// set author if needed |
| 1739 |
const bool saveAuthor = |
| 1740 |
GetApplication() |
| 1741 |
.GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") |
| 1742 |
->GetBool("prefSetAuthorOnSave", false); |
| 1743 |
if (saveAuthor) { |
| 1744 |
const std::string Author = |
| 1745 |
GetApplication() |
| 1746 |
.GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") |
| 1747 |
->GetASCII("prefAuthor", ""); |
| 1748 |
LastModifiedBy.setValue(Author.c_str()); |
| 1749 |
} |
| 1750 |
|
| 1751 |
bool result = saveToFile(FileName.getValue()); |
| 1752 |
if (result) { |
| 1753 |
d->programVersion = Application::Config()["BuildVersionMajor"] + "." |
| 1754 |
+ Application::Config()["BuildVersionMinor"] + "R" |
| 1755 |
+ Application::Config()["BuildRevision"]; |
| 1756 |
} |
| 1757 |
return result; |
| 1758 |
} |
| 1759 |
|
| 1760 |
return false; |
| 1761 |
} |
| 1762 |
|
| 1763 |
bool Document::saveToFile(const char* filename) const |
| 1764 |
{ |
| 1765 |
signalStartSave(*this, filename); |
| 1766 |
|
| 1767 |
auto hGrp = GetApplication().GetParameterGroupByPath( |
| 1768 |
"User parameter:BaseApp/Preferences/Document"); |
| 1769 |
int compression = static_cast<int>(hGrp->GetInt("CompressionLevel", 7)); |
| 1770 |
compression = Base::clamp<int>(compression, Z_NO_COMPRESSION, Z_BEST_COMPRESSION); |
| 1771 |
|
| 1772 |
bool policy = GetApplication() |
| 1773 |
.GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") |
| 1774 |
->GetBool("BackupPolicy", true); |
| 1775 |
|
| 1776 |
auto canonical_path = [](const char* filename) { |
| 1777 |
try { |
| 1778 |
#ifdef FC_OS_WIN32 |
| 1779 |
QString utf8Name = QString::fromUtf8(filename); |
| 1780 |
auto realpath = fs::weakly_canonical(fs::absolute(fs::path(utf8Name.toStdWString()))); |
| 1781 |
std::string nativePath = QString::fromStdWString(realpath.native()).toStdString(); |
| 1782 |
#else |
| 1783 |
auto realpath = fs::weakly_canonical(fs::absolute(fs::path(filename))); |
| 1784 |
std::string nativePath = realpath.native(); |
| 1785 |
#endif |
| 1786 |
// In case some folders in the path do not exist |
| 1787 |
auto parentPath = realpath.parent_path(); |
| 1788 |
fs::create_directories(parentPath); |
| 1789 |
|
| 1790 |
return nativePath; |
| 1791 |
} |
| 1792 |
catch (const std::exception&) { |
| 1793 |
#ifdef FC_OS_WIN32 |
| 1794 |
QString utf8Name = QString::fromUtf8(filename); |
| 1795 |
auto parentPath = fs::absolute(fs::path(utf8Name.toStdWString())).parent_path(); |
| 1796 |
#else |
| 1797 |
auto parentPath = fs::absolute(fs::path(filename)).parent_path(); |
| 1798 |
#endif |
| 1799 |
fs::create_directories(parentPath); |
| 1800 |
|
| 1801 |
return std::string(filename); |
| 1802 |
} |
| 1803 |
}; |
| 1804 |
|
| 1805 |
// realpath is canonical filename i.e. without symlink |
| 1806 |
std::string nativePath = canonical_path(filename); |
| 1807 |
|
| 1808 |
// check if file is writeable, then block the save if it is not. |
| 1809 |
Base::FileInfo originalFileInfo(nativePath); |
| 1810 |
if (originalFileInfo.exists() && !originalFileInfo.isWritable()) { |
| 1811 |
throw Base::FileException("Unable to save document because file is marked as read-only or write permission is not available.", originalFileInfo); |
| 1812 |
} |
| 1813 |
|
| 1814 |
// make a tmp. file where to save the project data first and then rename to |
| 1815 |
// the actual file name. This may be useful if overwriting an existing file |
| 1816 |
// fails so that the data of the work up to now isn't lost. |
| 1817 |
std::string uuid = Base::Uuid::createUuid(); |
| 1818 |
std::string fn = nativePath; |
| 1819 |
if (policy) { |
| 1820 |
fn += "."; |
| 1821 |
fn += uuid; |
| 1822 |
} |
| 1823 |
|
| 1824 |
|
| 1825 |
// open extra scope to close ZipWriter properly |
| 1826 |
{ |
| 1827 |
Base::FileInfo tmp(fn); |
| 1828 |
Base::ofstream file(tmp, std::ios::out | std::ios::binary); |
| 1829 |
|
| 1830 |
Base::ZipWriter writer(file); |
| 1831 |
if (!file.is_open()) { |
| 1832 |
throw Base::FileException("Failed to open file", tmp); |
| 1833 |
} |
| 1834 |
|
| 1835 |
writer.setComment("FreeCAD Document"); |
| 1836 |
writer.setLevel(compression); |
| 1837 |
writer.putNextEntry("Document.xml"); |
| 1838 |
|
| 1839 |
if (hGrp->GetBool("SaveBinaryBrep", false)) { |
| 1840 |
writer.setMode("BinaryBrep"); |
| 1841 |
} |
| 1842 |
|
| 1843 |
writer.Stream() << "<?xml version='1.0' encoding='utf-8'?>" << '\n' |
| 1844 |
<< "<!--" << '\n' |
| 1845 |
<< " FreeCAD Document, see https://www.freecad.org for more information..." |
| 1846 |
<< '\n' |
| 1847 |
<< "-->" << '\n'; |
| 1848 |
Document::Save(writer); |
| 1849 |
|
| 1850 |
// Special handling for Gui document. |
| 1851 |
signalSaveDocument(writer); |
| 1852 |
|
| 1853 |
// write additional files |
| 1854 |
writer.writeFiles(); |
| 1855 |
if (writer.hasErrors()) { |
| 1856 |
// retrieve Writer error strings |
| 1857 |
std::stringstream message; |
| 1858 |
message << "Failed to write all data to file "; |
| 1859 |
message << writer.getErrors().front(); |
| 1860 |
throw Base::FileException(message.str().c_str(), tmp); |
| 1861 |
} |
| 1862 |
|
| 1863 |
GetApplication().signalSaveDocument(*this); |
| 1864 |
} |
| 1865 |
|
| 1866 |
if (policy) { |
| 1867 |
// if saving the project data succeeded rename to the actual file name |
| 1868 |
int count_bak = static_cast<int>(GetApplication() |
| 1869 |
.GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") |
| 1870 |
->GetInt("CountBackupFiles", 1)); |
| 1871 |
bool backup = GetApplication() |
| 1872 |
.GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") |
| 1873 |
->GetBool("CreateBackupFiles", true); |
| 1874 |
if (!backup) { |
| 1875 |
count_bak = -1; |
| 1876 |
} |
| 1877 |
bool useFCBakExtension = |
| 1878 |
GetApplication() |
| 1879 |
.GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") |
| 1880 |
->GetBool("UseFCBakExtension", true); |
| 1881 |
std::string saveBackupDateFormat = |
| 1882 |
GetApplication() |
| 1883 |
.GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") |
| 1884 |
->GetASCII("SaveBackupDateFormat", "%Y%m%d-%H%M%S"); |
| 1885 |
|
| 1886 |
BackupPolicy backupPolicy; |
| 1887 |
if (useFCBakExtension) { |
| 1888 |
backupPolicy.setPolicy(BackupPolicy::TimeStamp); |
| 1889 |
backupPolicy.useBackupExtension(useFCBakExtension); |
| 1890 |
backupPolicy.setDateFormat(saveBackupDateFormat); |
| 1891 |
} |
| 1892 |
else { |
| 1893 |
backupPolicy.setPolicy(BackupPolicy::Standard); |
| 1894 |
} |
| 1895 |
backupPolicy.setNumberOfFiles(count_bak); |
| 1896 |
backupPolicy.apply(fn, nativePath); |
| 1897 |
} |
| 1898 |
|
| 1899 |
signalFinishSave(*this, filename); |
| 1900 |
|
| 1901 |
return true; |
| 1902 |
} |
| 1903 |
|
| 1904 |
void Document::registerLabel(const std::string& newLabel) |
| 1905 |
{ |
| 1906 |
if (!newLabel.empty()) { |
| 1907 |
d->objectLabelManager.addExactName(newLabel); |
| 1908 |
} |
| 1909 |
} |
| 1910 |
|
| 1911 |
void Document::unregisterLabel(const std::string& oldLabel) |
| 1912 |
{ |
| 1913 |
if (!oldLabel.empty()) { |
| 1914 |
d->objectLabelManager.removeExactName(oldLabel); |
| 1915 |
} |
| 1916 |
} |
| 1917 |
|
| 1918 |
bool Document::containsLabel(const std::string& label) |
| 1919 |
{ |
| 1920 |
return d->objectLabelManager.containsName(label); |
| 1921 |
} |
| 1922 |
|
| 1923 |
std::string Document::makeUniqueLabel(const std::string& modelLabel) |
| 1924 |
{ |
| 1925 |
if (modelLabel.empty()) { |
| 1926 |
return {}; |
| 1927 |
} |
| 1928 |
|
| 1929 |
return d->objectLabelManager.makeUniqueName(modelLabel, 3); |
| 1930 |
} |
| 1931 |
|
| 1932 |
bool Document::isAnyRestoring() |
| 1933 |
{ |
| 1934 |
return globalIsRestoring; |
| 1935 |
} |
| 1936 |
|
| 1937 |
// Open the document |
| 1938 |
void Document::restore(const char* filename, |
| 1939 |
bool delaySignal, |
| 1940 |
const std::vector<std::string>& objNames) |
| 1941 |
{ |
| 1942 |
clearUndos(); |
| 1943 |
d->activeObject = nullptr; |
| 1944 |
|
| 1945 |
bool signal = false; |
| 1946 |
Document* activeDoc = GetApplication().getActiveDocument(); |
| 1947 |
if (!d->objectArray.empty()) { |
| 1948 |
signal = true; |
| 1949 |
GetApplication().signalDeleteDocument(*this); |
| 1950 |
d->clearDocument(); |
| 1951 |
} |
| 1952 |
|
| 1953 |
Base::FlagToggler<> flag(globalIsRestoring, false); |
| 1954 |
|
| 1955 |
setStatus(Document::PartialDoc, false); |
| 1956 |
|
| 1957 |
d->clearRecomputeLog(); |
| 1958 |
d->objectLabelManager.clear(); |
| 1959 |
d->objectArray.clear(); |
| 1960 |
d->objectNameManager.clear(); |
| 1961 |
d->objectMap.clear(); |
| 1962 |
d->objectIdMap.clear(); |
| 1963 |
d->lastObjectId = 0; |
| 1964 |
|
| 1965 |
if (signal) { |
| 1966 |
GetApplication().signalNewDocument(*this, true); |
| 1967 |
if (activeDoc == this) { |
| 1968 |
GetApplication().setActiveDocument(this); |
| 1969 |
} |
| 1970 |
} |
| 1971 |
|
| 1972 |
if (!filename) { |
| 1973 |
filename = FileName.getValue(); |
| 1974 |
} |
| 1975 |
Base::FileInfo fi(filename); |
| 1976 |
Base::ifstream file(fi, std::ios::in | std::ios::binary); |
| 1977 |
std::streambuf* buf = file.rdbuf(); |
| 1978 |
std::streamoff size = buf->pubseekoff(0, std::ios::end, std::ios::in); |
| 1979 |
buf->pubseekoff(0, std::ios::beg, std::ios::in); |
| 1980 |
if (size < 22) { // an empty zip archive has 22 bytes |
| 1981 |
throw Base::FileException("Invalid project file", filename); |
| 1982 |
} |
| 1983 |
|
| 1984 |
zipios::ZipInputStream zipstream(file); |
| 1985 |
Base::XMLReader reader(filename, zipstream); |
| 1986 |
|
| 1987 |
if (!reader.isValid()) { |
| 1988 |
throw Base::FileException("Error reading compression file", filename); |
| 1989 |
} |
| 1990 |
|
| 1991 |
GetApplication().signalStartRestoreDocument(*this); |
| 1992 |
setStatus(Document::Restoring, true); |
| 1993 |
|
| 1994 |
d->partialLoadObjects.clear(); |
| 1995 |
for (auto& name : objNames) { |
| 1996 |
d->partialLoadObjects.emplace(name, true); |
| 1997 |
} |
| 1998 |
try { |
| 1999 |
Document::Restore(reader); |
| 2000 |
} |
| 2001 |
catch (const Base::Exception& e) { |
| 2002 |
Base::Console().error("Invalid Document.xml: %s\n", e.what()); |
| 2003 |
setStatus(Document::RestoreError, true); |
| 2004 |
} |
| 2005 |
|
| 2006 |
d->partialLoadObjects.clear(); |
| 2007 |
d->programVersion = reader.ProgramVersion; |
| 2008 |
|
| 2009 |
// Special handling for Gui document, the view representations must already |
| 2010 |
// exist, what is done in Restore(). |
| 2011 |
// Note: This file doesn't need to be available if the document has been created |
| 2012 |
// without GUI. But if available then follow after all data files of the App document. |
| 2013 |
signalRestoreDocument(reader); |
| 2014 |
reader.readFiles(zipstream); |
| 2015 |
|
| 2016 |
DocumentP::checkStringHasher(reader); |
| 2017 |
|
| 2018 |
if (reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestore)) { |
| 2019 |
setStatus(Document::PartialRestore, true); |
| 2020 |
Base::Console().error("There were errors while loading the file. Some data might have been " |
| 2021 |
"modified or not recovered at all. Look above for more specific " |
| 2022 |
"information about the objects involved.\n"); |
| 2023 |
} |
| 2024 |
|
| 2025 |
if (!delaySignal) { |
| 2026 |
afterRestore(true); |
| 2027 |
} |
| 2028 |
} |
| 2029 |
|
| 2030 |
bool Document::afterRestore(const bool checkPartial) |
| 2031 |
{ |
| 2032 |
Base::FlagToggler<> flag(globalIsRestoring, false); |
| 2033 |
if (!afterRestore(d->objectArray, checkPartial)) { |
| 2034 |
FC_WARN("Reload partial document " << getName()); |
| 2035 |
GetApplication().signalPendingReloadDocument(*this); |
| 2036 |
return false; |
| 2037 |
} |
| 2038 |
GetApplication().signalFinishRestoreDocument(*this); |
| 2039 |
setStatus(Document::Restoring, false); |
| 2040 |
return true; |
| 2041 |
} |
| 2042 |
|
| 2043 |
bool Document::afterRestore(const std::vector<DocumentObject*>& objArray, bool checkPartial) |
| 2044 |
{ |
| 2045 |
checkPartial = checkPartial && testStatus(Document::PartialDoc); |
| 2046 |
if (checkPartial && !d->touchedObjs.empty()) { |
| 2047 |
return false; |
| 2048 |
} |
| 2049 |
|
| 2050 |
// some link type property cannot restore link information until other |
| 2051 |
// objects has been restored. For example, PropertyExpressionEngine and |
| 2052 |
// PropertySheet with expression containing label reference. So we add the |
| 2053 |
// Property::afterRestore() interface to let them sort it out. Note, this |
| 2054 |
// API is not called in object dedpenency order, because the order |
| 2055 |
// information is not ready yet. |
| 2056 |
std::map<DocumentObject*, std::vector<Property*>> propMap; |
| 2057 |
for (auto obj : objArray) { |
| 2058 |
auto& props = propMap[obj]; |
| 2059 |
obj->getPropertyList(props); |
| 2060 |
for (auto prop : props) { |
| 2061 |
try { |
| 2062 |
prop->afterRestore(); |
| 2063 |
} |
| 2064 |
catch (const Base::Exception& e) { |
| 2065 |
FC_ERR("Failed to restore " << obj->getFullName() << '.' << prop->getName() << ": " |
| 2066 |
<< e.what()); |
| 2067 |
} |
| 2068 |
} |
| 2069 |
} |
| 2070 |
|
| 2071 |
if (checkPartial && !d->touchedObjs.empty()) { |
| 2072 |
// partial document touched, signal full reload |
| 2073 |
return false; |
| 2074 |
} |
| 2075 |
|
| 2076 |
std::set<DocumentObject*> objSet(objArray.begin(), objArray.end()); |
| 2077 |
auto objs = getDependencyList(objArray.empty() ? d->objectArray : objArray, DepSort); |
| 2078 |
for (auto obj : objs) { |
| 2079 |
if (objSet.find(obj) == objSet.end()) { |
| 2080 |
continue; |
| 2081 |
} |
| 2082 |
try { |
| 2083 |
for (auto prop : propMap[obj]) { |
| 2084 |
prop->onContainerRestored(); |
| 2085 |
} |
| 2086 |
bool touched = false; |
| 2087 |
auto returnCode = |
| 2088 |
obj->ExpressionEngine.execute(PropertyExpressionEngine::ExecuteOnRestore, &touched); |
| 2089 |
if (returnCode != DocumentObject::StdReturn) { |
| 2090 |
FC_ERR("Expression engine failed to restore " << obj->getFullName() << ": " |
| 2091 |
<< returnCode->Why); |
| 2092 |
d->addRecomputeLog(returnCode); |
| 2093 |
} |
| 2094 |
obj->onDocumentRestored(); |
| 2095 |
if (touched) { |
| 2096 |
d->touchedObjs.insert(obj); |
| 2097 |
} |
| 2098 |
} |
| 2099 |
catch (const Base::Exception& e) { |
| 2100 |
d->addRecomputeLog(e.what(), obj); |
| 2101 |
FC_ERR("Failed to restore " << obj->getFullName() << ": " << e.what()); |
| 2102 |
} |
| 2103 |
catch (std::exception& e) { |
| 2104 |
d->addRecomputeLog(e.what(), obj); |
| 2105 |
FC_ERR("Failed to restore " << obj->getFullName() << ": " << e.what()); |
| 2106 |
} |
| 2107 |
catch (...) { |
| 2108 |
|
| 2109 |
// If a Python exception occurred, it must be cleared immediately. |
| 2110 |
// Otherwise, the interpreter remains in a dirty state, causing |
| 2111 |
// Segfaults later when FreeCAD interacts with Python. |
| 2112 |
if (PyErr_Occurred()) { |
| 2113 |
Base::Console().error("Python error during object restore:\n"); |
| 2114 |
PyErr_Print(); // Print the traceback to stderr/Console |
| 2115 |
PyErr_Clear(); // Reset the interpreter state |
| 2116 |
} |
| 2117 |
|
| 2118 |
d->addRecomputeLog("Unknown exception on restore", obj); |
| 2119 |
FC_ERR("Failed to restore " << obj->getFullName() << ": " << "unknown exception"); |
| 2120 |
} |
| 2121 |
if (obj->isValid()) { |
| 2122 |
auto& props = propMap[obj]; |
| 2123 |
props.clear(); |
| 2124 |
// refresh properties in case the object changes its property list |
| 2125 |
obj->getPropertyList(props); |
| 2126 |
for (auto prop : props) { |
| 2127 |
auto link = freecad_cast<PropertyLinkBase*>(prop); |
| 2128 |
int res {0}; |
| 2129 |
std::string errMsg; |
| 2130 |
if (link && ((res = link->checkRestore(&errMsg)) != 0)) { |
| 2131 |
d->touchedObjs.insert(obj); |
| 2132 |
if (res == 1 || checkPartial) { |
| 2133 |
FC_WARN(obj->getFullName() << '.' << prop->getName() << ": " << errMsg); |
| 2134 |
setStatus(Document::LinkStampChanged, true); |
| 2135 |
if (checkPartial) { |
| 2136 |
return false; |
| 2137 |
} |
| 2138 |
} |
| 2139 |
else { |
| 2140 |
FC_ERR(obj->getFullName() << '.' << prop->getName() << ": " << errMsg); |
| 2141 |
d->addRecomputeLog(errMsg, obj); |
| 2142 |
setStatus(Document::PartialRestore, true); |
| 2143 |
} |
| 2144 |
} |
| 2145 |
} |
| 2146 |
} |
| 2147 |
|
| 2148 |
if (checkPartial && !d->touchedObjs.empty()) { |
| 2149 |
// partial document touched, signal full reload |
| 2150 |
return false; |
| 2151 |
} |
| 2152 |
if (!d->touchedObjs.contains(obj)) { |
| 2153 |
obj->purgeTouched(); |
| 2154 |
} |
| 2155 |
|
| 2156 |
signalFinishRestoreObject(*obj); |
| 2157 |
} |
| 2158 |
|
| 2159 |
d->touchedObjs.clear(); |
| 2160 |
return true; |
| 2161 |
} |
| 2162 |
|
| 2163 |
bool Document::isSaved() const |
| 2164 |
{ |
| 2165 |
const std::string name = FileName.getValue(); |
| 2166 |
return !name.empty(); |
| 2167 |
} |
| 2168 |
|
| 2169 |
/** Label is the visible name of a document shown e.g. in the windows title |
| 2170 |
* or in the tree view. The label almost (but not always e.g. if you manually change it) |
| 2171 |
* matches with the file name where the document is stored to. |
| 2172 |
* In contrast to Label the method getName() returns the internal name of the document that only |
| 2173 |
* matches with Label when loading or creating a document because then both are set to the same |
| 2174 |
* value. Since the internal name cannot be changed during runtime it must differ from the Label |
| 2175 |
* after saving the document the first time or saving it under a new file name. |
| 2176 |
* @ note More than one document can have the same label name. |
| 2177 |
* @ note The internal is always guaranteed to be unique because @ref Application::newDocument() |
| 2178 |
* checks for a document with the same name and makes it unique if needed. Hence you cannot rely on |
| 2179 |
* that the internal name matches with the name you passed to Application::newDoument(). You should |
| 2180 |
* use the method getName() instead. |
| 2181 |
*/ |
| 2182 |
const char* Document::getName() const |
| 2183 |
{ |
| 2184 |
// return GetApplication().getDocumentName(this); |
| 2185 |
return myName.c_str(); |
| 2186 |
} |
| 2187 |
|
| 2188 |
std::string Document::getFullName() const |
| 2189 |
{ |
| 2190 |
return myName; |
| 2191 |
} |
| 2192 |
|
| 2193 |
void Document::setAutoCreated(bool value) { |
| 2194 |
autoCreated = value; |
| 2195 |
} |
| 2196 |
|
| 2197 |
bool Document::isAutoCreated() const { |
| 2198 |
return autoCreated; |
| 2199 |
} |
| 2200 |
|
| 2201 |
const char* Document::getProgramVersion() const |
| 2202 |
{ |
| 2203 |
return d->programVersion.c_str(); |
| 2204 |
} |
| 2205 |
|
| 2206 |
const char* Document::getFileName() const |
| 2207 |
{ |
| 2208 |
return testStatus(TempDoc) ? TransientDir.getValue() : FileName.getValue(); |
| 2209 |
} |
| 2210 |
|
| 2211 |
/// Remove all modifications. After this call The document becomes valid again. |
| 2212 |
void Document::purgeTouched() // NOLINT |
| 2213 |
{ |
| 2214 |
for (const auto It : d->objectArray) { |
| 2215 |
It->purgeTouched(); |
| 2216 |
} |
| 2217 |
} |
| 2218 |
|
| 2219 |
bool Document::isTouched() const |
| 2220 |
{ |
| 2221 |
for (const auto It : d->objectArray) { |
| 2222 |
if (It->isTouched()) { |
| 2223 |
return true; |
| 2224 |
} |
| 2225 |
} |
| 2226 |
return false; |
| 2227 |
} |
| 2228 |
|
| 2229 |
vector<DocumentObject*> Document::getTouched() const |
| 2230 |
{ |
| 2231 |
vector<DocumentObject*> result; |
| 2232 |
|
| 2233 |
for (auto It : d->objectArray) { |
| 2234 |
if (It->isTouched()) { |
| 2235 |
result.push_back(It); |
| 2236 |
} |
| 2237 |
} |
| 2238 |
|
| 2239 |
return result; |
| 2240 |
} |
| 2241 |
|
| 2242 |
void Document::setClosable(const bool c) // NOLINT |
| 2243 |
{ |
| 2244 |
setStatus(Document::Closable, c); |
| 2245 |
} |
| 2246 |
|
| 2247 |
bool Document::isClosable() const |
| 2248 |
{ |
| 2249 |
return testStatus(Document::Closable); |
| 2250 |
} |
| 2251 |
|
| 2252 |
int Document::countObjects() const |
| 2253 |
{ |
| 2254 |
return static_cast<int>(d->objectArray.size()); |
| 2255 |
} |
| 2256 |
|
| 2257 |
void Document::getLinksTo(std::set<DocumentObject*>& links, |
| 2258 |
const DocumentObject* obj, |
| 2259 |
const int options, |
| 2260 |
const int maxCount, |
| 2261 |
const std::vector<DocumentObject*>& objs) const |
| 2262 |
{ |
| 2263 |
std::map<const DocumentObject*, std::vector<DocumentObject*>> linkMap; |
| 2264 |
|
| 2265 |
for (auto o : !objs.empty() ? objs : d->objectArray) { |
| 2266 |
if (o == obj) { |
| 2267 |
continue; |
| 2268 |
} |
| 2269 |
auto linked = o; |
| 2270 |
if ((options & GetLinkArrayElement) != 0) { |
| 2271 |
linked = o->getLinkedObject(false); |
| 2272 |
} |
| 2273 |
else { |
| 2274 |
const auto ext = o->getExtensionByType<LinkBaseExtension>(true); |
| 2275 |
linked = |
| 2276 |
ext ? ext->getTrueLinkedObject(false, nullptr, 0, true) : o->getLinkedObject(false); |
| 2277 |
} |
| 2278 |
|
| 2279 |
if (linked && linked != o) { |
| 2280 |
if ((options & GetLinkRecursive) != 0) { |
| 2281 |
linkMap[linked].push_back(o); |
| 2282 |
} |
| 2283 |
else if (linked == obj || !obj) { |
| 2284 |
if (((options & GetLinkExternal) != 0) && linked->getDocument() == o->getDocument()) { |
| 2285 |
continue; |
| 2286 |
} |
| 2287 |
if ((options & GetLinkedObject) != 0) { |
| 2288 |
links.insert(linked); |
| 2289 |
} |
| 2290 |
else { |
| 2291 |
links.insert(o); |
| 2292 |
} |
| 2293 |
if ((maxCount != 0) && maxCount <= static_cast<int>(links.size())) { |
| 2294 |
return; |
| 2295 |
} |
| 2296 |
} |
| 2297 |
} |
| 2298 |
} |
| 2299 |
|
| 2300 |
if ((options & GetLinkRecursive) == 0) { |
| 2301 |
return; |
| 2302 |
} |
| 2303 |
|
| 2304 |
std::vector<const DocumentObject*> current(1, obj); |
| 2305 |
for (int depth = 0; !current.empty(); ++depth) { |
| 2306 |
if (GetApplication().checkLinkDepth(depth, MessageOption::Error) == 0) { |
| 2307 |
break; |
| 2308 |
} |
| 2309 |
std::vector<const DocumentObject*> next; |
| 2310 |
for (const DocumentObject* o : current) { |
| 2311 |
auto iter = linkMap.find(o); |
| 2312 |
if (iter == linkMap.end()) { |
| 2313 |
continue; |
| 2314 |
} |
| 2315 |
for (DocumentObject* link : iter->second) { |
| 2316 |
if (links.insert(link).second) { |
| 2317 |
if ((maxCount != 0) && maxCount <= static_cast<int>(links.size())) { |
| 2318 |
return; |
| 2319 |
} |
| 2320 |
next.push_back(link); |
| 2321 |
} |
| 2322 |
} |
| 2323 |
} |
| 2324 |
current = std::move(next); |
| 2325 |
} |
| 2326 |
} |
| 2327 |
|
| 2328 |
bool Document::hasLinksTo(const DocumentObject* obj) const |
| 2329 |
{ |
| 2330 |
std::set<DocumentObject*> links; |
| 2331 |
getLinksTo(links, obj, 0, 1); |
| 2332 |
return !links.empty(); |
| 2333 |
} |
| 2334 |
|
| 2335 |
std::vector<DocumentObject*> Document::getInList(const DocumentObject* me) const |
| 2336 |
{ |
| 2337 |
// result list |
| 2338 |
std::vector<DocumentObject*> result; |
| 2339 |
// go through all objects |
| 2340 |
for (const auto& [name, object] : d->objectMap) { |
| 2341 |
// get the outList and search if me is in that list |
| 2342 |
std::vector<DocumentObject*> OutList = object->getOutList(); |
| 2343 |
for (const auto obj : OutList) { |
| 2344 |
if (obj && obj == me) { |
| 2345 |
// add the parent object |
| 2346 |
result.push_back(object); |
| 2347 |
} |
| 2348 |
} |
| 2349 |
} |
| 2350 |
return result; |
| 2351 |
} |
| 2352 |
|
| 2353 |
// This function unifies the old _rebuildDependencyList() and |
| 2354 |
// getDependencyList(). The algorithm basically obtains the object dependency |
| 2355 |
// by recrusivly visiting the OutList of each object in the given object array. |
| 2356 |
// It makes sure to call getOutList() of each object once and only once, which |
| 2357 |
// makes it much more efficient than calling getRecursiveOutList() on each |
| 2358 |
// individual object. |
| 2359 |
// |
| 2360 |
// The problem with the original algorithm is that, it assumes the objects |
| 2361 |
// inside any OutList are all within the given object array, so it does not |
| 2362 |
// recursively call getOutList() on those dependent objects inside. This |
| 2363 |
// assumption is broken by the introduction of PropertyXLink which can link to |
| 2364 |
// external object. |
| 2365 |
// |
| 2366 |
static void buildDependencyList(const std::vector<DocumentObject*>& objectArray, |
| 2367 |
const int options, |
| 2368 |
std::vector<DocumentObject*>* depObjs, |
| 2369 |
DependencyList* depList, |
| 2370 |
std::map<DocumentObject*, Vertex>* objectMap, |
| 2371 |
bool* touchCheck = nullptr) |
| 2372 |
{ |
| 2373 |
std::map<DocumentObject*, std::vector<DocumentObject*>> outLists; |
| 2374 |
std::deque<DocumentObject*> objs; |
| 2375 |
|
| 2376 |
if (objectMap) { |
| 2377 |
objectMap->clear(); |
| 2378 |
} |
| 2379 |
if (depList) { |
| 2380 |
depList->clear(); |
| 2381 |
} |
| 2382 |
|
| 2383 |
const int op = ((options & Document::DepNoXLinked) != 0) ? DocumentObject::OutListNoXLinked : 0; |
| 2384 |
for (auto obj : objectArray) { |
| 2385 |
objs.push_back(obj); |
| 2386 |
while (!objs.empty()) { |
| 2387 |
auto objF = objs.front(); |
| 2388 |
objs.pop_front(); |
| 2389 |
if (!objF || !objF->isAttachedToDocument()) { |
| 2390 |
continue; |
| 2391 |
} |
| 2392 |
|
| 2393 |
auto it = outLists.find(objF); |
| 2394 |
if (it != outLists.end()) { |
| 2395 |
continue; |
| 2396 |
} |
| 2397 |
|
| 2398 |
if (touchCheck) { |
| 2399 |
if (objF->isTouched() || (objF->mustExecute() != 0)) { |
| 2400 |
// early termination on touch check |
| 2401 |
*touchCheck = true; |
| 2402 |
return; |
| 2403 |
} |
| 2404 |
} |
| 2405 |
if (depObjs) { |
| 2406 |
depObjs->push_back(objF); |
| 2407 |
} |
| 2408 |
if (objectMap && depList) { |
| 2409 |
(*objectMap)[objF] = add_vertex(*depList); |
| 2410 |
} |
| 2411 |
|
| 2412 |
auto& outList = outLists[objF]; |
| 2413 |
outList = objF->getOutList(op); |
| 2414 |
objs.insert(objs.end(), outList.begin(), outList.end()); |
| 2415 |
} |
| 2416 |
} |
| 2417 |
|
| 2418 |
if (objectMap && depList) { |
| 2419 |
for (const auto& [key, objects] : outLists) { |
| 2420 |
for (auto obj : objects) { |
| 2421 |
if (obj && obj->isAttachedToDocument()) { |
| 2422 |
add_edge((*objectMap)[key], (*objectMap)[obj], *depList); |
| 2423 |
} |
| 2424 |
} |
| 2425 |
} |
| 2426 |
} |
| 2427 |
} |
| 2428 |
|
| 2429 |
std::vector<DocumentObject*> |
| 2430 |
Document::getDependencyList(const std::vector<DocumentObject*>& objs, int options) |
| 2431 |
{ |
| 2432 |
std::vector<DocumentObject*> ret; |
| 2433 |
if ((options & DepSort) == 0) { |
| 2434 |
buildDependencyList(objs, options, &ret, nullptr, nullptr); |
| 2435 |
return ret; |
| 2436 |
} |
| 2437 |
|
| 2438 |
DependencyList depList; |
| 2439 |
std::map<DocumentObject*, Vertex> objectMap; |
| 2440 |
std::map<Vertex, DocumentObject*> vertexMap; |
| 2441 |
|
| 2442 |
buildDependencyList(objs, options, nullptr, &depList, &objectMap); |
| 2443 |
|
| 2444 |
for (auto& v : objectMap) { |
| 2445 |
vertexMap[v.second] = v.first; |
| 2446 |
} |
| 2447 |
|
| 2448 |
std::list<Vertex> make_order; |
| 2449 |
try { |
| 2450 |
boost::topological_sort(depList, std::front_inserter(make_order)); |
| 2451 |
} |
| 2452 |
catch (const std::exception& e) { |
| 2453 |
if ((options & DepNoCycle) != 0) { |
| 2454 |
// Use boost::strong_components to find cycles. It groups strongly |
| 2455 |
// connected vertices as components, and therefore each component |
| 2456 |
// forms a cycle. |
| 2457 |
std::vector<int> c(vertexMap.size()); |
| 2458 |
std::map<int, std::vector<Vertex>> components; |
| 2459 |
boost::strong_components( |
| 2460 |
depList, |
| 2461 |
boost::make_iterator_property_map(c.begin(), |
| 2462 |
boost::get(boost::vertex_index, depList), |
| 2463 |
c[0])); |
| 2464 |
for (size_t i = 0; i < c.size(); ++i) { |
| 2465 |
components[c[i]].push_back(i); |
| 2466 |
} |
| 2467 |
|
| 2468 |
FC_ERR("Dependency cycles: "); |
| 2469 |
std::ostringstream ss; |
| 2470 |
ss << '\n'; |
| 2471 |
for (auto& [key, vertexes] : components) { |
| 2472 |
if (vertexes.size() == 1) { |
| 2473 |
// For components with only one member, we still need to |
| 2474 |
// check if there it is self looping. |
| 2475 |
auto it = vertexMap.find(vertexes[0]); |
| 2476 |
if (it == vertexMap.end()) { |
| 2477 |
continue; |
| 2478 |
} |
| 2479 |
// Try search the object in its own out list |
| 2480 |
for (auto obj : it->second->getOutList()) { |
| 2481 |
if (obj == it->second) { |
| 2482 |
ss << '\n' << it->second->getFullName() << '\n'; |
| 2483 |
break; |
| 2484 |
} |
| 2485 |
} |
| 2486 |
continue; |
| 2487 |
} |
| 2488 |
// For components with more than one member, they form a loop together |
| 2489 |
for (size_t i = 0; i < vertexes.size(); ++i) { |
| 2490 |
auto it = vertexMap.find(vertexes[i]); |
| 2491 |
if (it == vertexMap.end()) { |
| 2492 |
continue; |
| 2493 |
} |
| 2494 |
if (i % 6 == 0) { |
| 2495 |
ss << '\n'; |
| 2496 |
} |
| 2497 |
ss << it->second->getFullName() << ", "; |
| 2498 |
} |
| 2499 |
ss << '\n'; |
| 2500 |
} |
| 2501 |
FC_ERR(ss.str()); |
| 2502 |
FC_THROWM(Base::RuntimeError, e.what()); |
| 2503 |
} |
| 2504 |
FC_ERR(e.what()); |
| 2505 |
ret = DocumentP::partialTopologicalSort(objs); |
| 2506 |
std::reverse(ret.begin(), ret.end()); |
| 2507 |
return ret; |
| 2508 |
} |
| 2509 |
|
| 2510 |
for (auto i = make_order.rbegin(); i != make_order.rend(); ++i) { |
| 2511 |
ret.push_back(vertexMap[*i]); |
| 2512 |
} |
| 2513 |
return ret; |
| 2514 |
} |
| 2515 |
|
| 2516 |
std::vector<Document*> Document::getDependentDocuments(const bool sort) |
| 2517 |
{ |
| 2518 |
return getDependentDocuments({this}, sort); |
| 2519 |
} |
| 2520 |
|
| 2521 |
std::vector<Document*> Document::getDependentDocuments(std::vector<Document*> docs, |
| 2522 |
const bool sort) |
| 2523 |
{ |
| 2524 |
DependencyList depList; |
| 2525 |
std::map<Document*, Vertex> docMap; |
| 2526 |
std::map<Vertex, Document*> vertexMap; |
| 2527 |
|
| 2528 |
std::vector<Document*> ret; |
| 2529 |
if (docs.empty()) { |
| 2530 |
return ret; |
| 2531 |
} |
| 2532 |
|
| 2533 |
auto outLists = PropertyXLink::getDocumentOutList(); |
| 2534 |
std::set<Document*> docSet; |
| 2535 |
docSet.insert(docs.begin(), docs.end()); |
| 2536 |
if (sort) { |
| 2537 |
for (auto doc : docs) { |
| 2538 |
docMap[doc] = add_vertex(depList); |
| 2539 |
} |
| 2540 |
} |
| 2541 |
while (!docs.empty()) { |
| 2542 |
auto doc = docs.back(); |
| 2543 |
docs.pop_back(); |
| 2544 |
|
| 2545 |
auto it = outLists.find(doc); |
| 2546 |
if (it == outLists.end()) { |
| 2547 |
continue; |
| 2548 |
} |
| 2549 |
|
| 2550 |
const auto& vertex = docMap[doc]; |
| 2551 |
for (auto depDoc : it->second) { |
| 2552 |
if (docSet.insert(depDoc).second) { |
| 2553 |
docs.push_back(depDoc); |
| 2554 |
if (sort) { |
| 2555 |
docMap[depDoc] = add_vertex(depList); |
| 2556 |
} |
| 2557 |
} |
| 2558 |
add_edge(vertex, docMap[depDoc], depList); |
| 2559 |
} |
| 2560 |
} |
| 2561 |
|
| 2562 |
if (!sort) { |
| 2563 |
ret.insert(ret.end(), docSet.begin(), docSet.end()); |
| 2564 |
return ret; |
| 2565 |
} |
| 2566 |
|
| 2567 |
std::list<Vertex> make_order; |
| 2568 |
try { |
| 2569 |
boost::topological_sort(depList, std::front_inserter(make_order)); |
| 2570 |
} |
| 2571 |
catch (const std::exception& e) { |
| 2572 |
std::string msg("Document::getDependentDocuments: "); |
| 2573 |
msg += e.what(); |
| 2574 |
throw Base::RuntimeError(msg); |
| 2575 |
} |
| 2576 |
|
| 2577 |
for (auto& v : docMap) { |
| 2578 |
vertexMap[v.second] = v.first; |
| 2579 |
} |
| 2580 |
for (auto rIt = make_order.rbegin(); rIt != make_order.rend(); ++rIt) { |
| 2581 |
ret.push_back(vertexMap[*rIt]); |
| 2582 |
} |
| 2583 |
return ret; |
| 2584 |
} |
| 2585 |
|
| 2586 |
void Document::_rebuildDependencyList(const std::vector<DocumentObject*>& objs) |
| 2587 |
{ |
| 2588 |
(void)objs; |
| 2589 |
} |
| 2590 |
|
| 2591 |
/** |
| 2592 |
* @brief Signal that object identifiers, typically a property or document object has been renamed. |
| 2593 |
* |
| 2594 |
* This function iterates through all document object in the document, and calls its |
| 2595 |
* renameObjectIdentifiers functions. |
| 2596 |
* |
| 2597 |
* @param paths Map with current and new names |
| 2598 |
*/ |
| 2599 |
|
| 2600 |
void Document::renameObjectIdentifiers( |
| 2601 |
const std::map<ObjectIdentifier, ObjectIdentifier>& paths, |
| 2602 |
const std::function<bool(const DocumentObject*)>& selector) // NOLINT |
| 2603 |
{ |
| 2604 |
std::map<ObjectIdentifier, ObjectIdentifier> extendedPaths; |
| 2605 |
|
| 2606 |
auto it = paths.begin(); |
| 2607 |
while (it != paths.end()) { |
| 2608 |
extendedPaths[it->first.canonicalPath()] = it->second.canonicalPath(); |
| 2609 |
++it; |
| 2610 |
} |
| 2611 |
|
| 2612 |
for (const auto object : d->objectArray) { |
| 2613 |
if (selector(object)) { |
| 2614 |
object->renameObjectIdentifiers(extendedPaths); |
| 2615 |
} |
| 2616 |
} |
| 2617 |
} |
| 2618 |
|
| 2619 |
void Document::setPreRecomputeHook(const PreRecomputeHook& hook) |
| 2620 |
{ |
| 2621 |
d->_preRecomputeHook = hook; |
| 2622 |
} |
| 2623 |
|
| 2624 |
int Document::recompute(const std::vector<DocumentObject*>& objs, |
| 2625 |
bool force, |
| 2626 |
bool* hasError, |
| 2627 |
int options) |
| 2628 |
{ |
| 2629 |
ZoneScoped; |
| 2630 |
|
| 2631 |
if (d->undoing || d->rollback) { |
| 2632 |
if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { |
| 2633 |
FC_WARN("Ignore document recompute on undo/redo"); |
| 2634 |
} |
| 2635 |
return 0; |
| 2636 |
} |
| 2637 |
|
| 2638 |
int objectCount = 0; |
| 2639 |
if (testStatus(Document::PartialDoc)) { |
| 2640 |
if (mustExecute()) { |
| 2641 |
FC_WARN("Please reload partial document '" << Label.getValue() |
| 2642 |
<< "' for recomputation."); |
| 2643 |
} |
| 2644 |
return 0; |
| 2645 |
} |
| 2646 |
if (testStatus(Document::Recomputing)) { |
| 2647 |
// this is clearly a bug in the calling instance |
| 2648 |
FC_ERR("Recursive calling of recompute for document " << getName()); |
| 2649 |
return 0; |
| 2650 |
} |
| 2651 |
// The 'SkipRecompute' flag can be (tmp.) set to avoid too many |
| 2652 |
// time expensive recomputes |
| 2653 |
if (!force && testStatus(Document::SkipRecompute)) { |
| 2654 |
signalSkipRecompute(*this, objs); |
| 2655 |
return 0; |
| 2656 |
} |
| 2657 |
|
| 2658 |
// delete recompute log |
| 2659 |
d->clearRecomputeLog(); |
| 2660 |
|
| 2661 |
FC_TIME_INIT(t); |
| 2662 |
|
| 2663 |
Base::ObjectStatusLocker<Document::Status, Document> exe(Document::Recomputing, this); |
| 2664 |
|
| 2665 |
// This will hop into the main thread, fire signalBeforeRecompute(), |
| 2666 |
// and *block* the worker until the main thread is done, avoiding races |
| 2667 |
// between any running Python code and the rest of the recompute call. |
| 2668 |
if (d->_preRecomputeHook) { |
| 2669 |
d->_preRecomputeHook(); |
| 2670 |
} |
| 2671 |
|
| 2672 |
////////////////////////////////////////////////////////////////////////// |
| 2673 |
// FIXME Comment by Realthunder: |
| 2674 |
// the topologicalSrot() below cannot handle partial recompute, haven't got |
| 2675 |
// time to figure out the code yet, simply use back boost::topological_sort |
| 2676 |
// for now, that is, rely on getDependencyList() to do the sorting. The |
| 2677 |
// downside is, it didn't take advantage of the ready built InList, nor will |
| 2678 |
// it report for cyclic dependency. |
| 2679 |
////////////////////////////////////////////////////////////////////////// |
| 2680 |
|
| 2681 |
/* // get the sorted vector of all dependent objects and go though it from the end |
| 2682 |
auto depObjs = getDependencyList(objs.empty()?d->objectArray:objs); |
| 2683 |
vector<DocumentObject*> topoSortedObjects = topologicalSort(depObjs); |
| 2684 |
if (topoSortedObjects.size() != depObjs.size()){ |
| 2685 |
cerr << "Document::recompute(): cyclic dependency detected" << '\n'; |
| 2686 |
topoSortedObjects = d->partialTopologicalSort(depObjs); |
| 2687 |
} |
| 2688 |
std::reverse(topoSortedObjects.begin(),topoSortedObjects.end()); |
| 2689 |
*/ |
| 2690 |
|
| 2691 |
// alt: |
| 2692 |
auto topoSortedObjects = |
| 2693 |
getDependencyList(objs.empty() ? d->objectArray : objs, DepSort | options); |
| 2694 |
|
| 2695 |
for (auto obj : topoSortedObjects) { |
| 2696 |
obj->setStatus(ObjectStatus::PendingRecompute, true); |
| 2697 |
} |
| 2698 |
|
| 2699 |
ParameterGrp::handle hGrp = |
| 2700 |
GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document"); |
| 2701 |
bool canAbort = hGrp->GetBool("CanAbortRecompute", true); |
| 2702 |
|
| 2703 |
FC_TIME_INIT(t2); |
| 2704 |
|
| 2705 |
try { |
| 2706 |
std::set<DocumentObject*> filter; |
| 2707 |
size_t idx = 0; |
| 2708 |
// maximum two passes to allow some form of dependency inversion |
| 2709 |
for (int passes = 0; passes < 2 && idx < topoSortedObjects.size(); ++passes) { |
| 2710 |
std::unique_ptr<Base::SequencerLauncher> seq; |
| 2711 |
if (canAbort) { |
| 2712 |
seq = std::make_unique<Base::SequencerLauncher>("Recompute...", |
| 2713 |
topoSortedObjects.size()); |
| 2714 |
} |
| 2715 |
FC_LOG("Recompute pass " << passes); |
| 2716 |
for (; idx < topoSortedObjects.size(); ++idx) { |
| 2717 |
auto obj = topoSortedObjects[idx]; |
| 2718 |
if (!obj->isAttachedToDocument() || filter.find(obj) != filter.end()) { |
| 2719 |
continue; |
| 2720 |
} |
| 2721 |
// ask the object if it should be recomputed |
| 2722 |
bool doRecompute = false; |
| 2723 |
if (obj->mustRecompute()) { |
| 2724 |
doRecompute = true; |
| 2725 |
++objectCount; |
| 2726 |
int res = _recomputeFeature(obj); |
| 2727 |
if (res != 0) { |
| 2728 |
if (hasError) { |
| 2729 |
*hasError = true; |
| 2730 |
} |
| 2731 |
if (res < 0) { |
| 2732 |
passes = 2; |
| 2733 |
break; |
| 2734 |
} |
| 2735 |
// if something happened filter all object in its |
| 2736 |
// inListRecursive from the queue then proceed |
| 2737 |
obj->getInListEx(filter, true); |
| 2738 |
filter.insert(obj); |
| 2739 |
continue; |
| 2740 |
} |
| 2741 |
} |
| 2742 |
if (obj->isTouched() || doRecompute) { |
| 2743 |
signalRecomputedObject(*obj); |
| 2744 |
obj->purgeTouched(); |
| 2745 |
// set all dependent object touched to force recompute |
| 2746 |
for (auto inObjIt : obj->getInList()) { |
| 2747 |
inObjIt->enforceRecompute(); |
| 2748 |
} |
| 2749 |
} |
| 2750 |
if (seq) { |
| 2751 |
seq->next(true); |
| 2752 |
} |
| 2753 |
} |
| 2754 |
// check if all objects are recomputed but still thouched |
| 2755 |
for (size_t i = 0; i < topoSortedObjects.size(); ++i) { |
| 2756 |
auto obj = topoSortedObjects[i]; |
| 2757 |
obj->setStatus(ObjectStatus::Recompute2, false); |
| 2758 |
if (!filter.contains(obj) && obj->isTouched()) { |
| 2759 |
if (passes > 0) { |
| 2760 |
FC_ERR(obj->getFullName() << " still touched after recompute"); |
| 2761 |
} |
| 2762 |
else { |
| 2763 |
FC_LOG(obj->getFullName() << " still touched after recompute"); |
| 2764 |
if (idx >= topoSortedObjects.size()) { |
| 2765 |
// let's start the next pass on the first touched object |
| 2766 |
idx = i; |
| 2767 |
} |
| 2768 |
obj->setStatus(ObjectStatus::Recompute2, true); |
| 2769 |
} |
| 2770 |
} |
| 2771 |
} |
| 2772 |
} |
| 2773 |
} |
| 2774 |
catch (Base::Exception& e) { |
| 2775 |
e.reportException(); |
| 2776 |
} |
| 2777 |
|
| 2778 |
FC_TIME_LOG(t2, "Recompute"); |
| 2779 |
|
| 2780 |
for (auto obj : topoSortedObjects) { |
| 2781 |
if (!obj->isAttachedToDocument()) { |
| 2782 |
continue; |
| 2783 |
} |
| 2784 |
obj->setStatus(ObjectStatus::PendingRecompute, false); |
| 2785 |
obj->setStatus(ObjectStatus::Recompute2, false); |
| 2786 |
} |
| 2787 |
|
| 2788 |
signalRecomputed(*this, topoSortedObjects); |
| 2789 |
|
| 2790 |
FC_TIME_LOG(t, "Recompute total"); |
| 2791 |
|
| 2792 |
if (!d->_RecomputeLog.empty()) { |
| 2793 |
if (!testStatus(Status::IgnoreErrorOnRecompute)) { |
| 2794 |
for (auto it : topoSortedObjects) { |
| 2795 |
if (it->isError()) { |
| 2796 |
const char* text = getErrorDescription(it); |
| 2797 |
if (text) { |
| 2798 |
Base::Console().error("%s: %s\n", it->Label.getValue(), text); |
| 2799 |
} |
| 2800 |
} |
| 2801 |
} |
| 2802 |
} |
| 2803 |
} |
| 2804 |
|
| 2805 |
for (auto doc : GetApplication().getDocuments()) { |
| 2806 |
decltype(doc->d->pendingRemove) objects; |
| 2807 |
objects.swap(doc->d->pendingRemove); |
| 2808 |
for (auto& o : objects) { |
| 2809 |
try { |
| 2810 |
if (auto obj = o.getObject()) { |
| 2811 |
obj->getDocument()->removeObject(obj->getNameInDocument()); |
| 2812 |
} |
| 2813 |
} |
| 2814 |
catch (Base::Exception& e) { |
| 2815 |
e.reportException(); |
| 2816 |
FC_ERR("error when removing object " << o.getDocumentName() << '#' |
| 2817 |
<< o.getObjectName()); |
| 2818 |
} |
| 2819 |
} |
| 2820 |
} |
| 2821 |
return objectCount; |
| 2822 |
} |
| 2823 |
|
| 2824 |
/*! |
| 2825 |
Does almost the same as topologicalSort() until no object with an input degree of zero |
| 2826 |
can be found. It then searches for objects with an output degree of zero until neither |
| 2827 |
an object with input or output degree can be found. The remaining objects form one or |
| 2828 |
multiple cycles. |
| 2829 |
An alternative to this method might be: |
| 2830 |
https://en.wikipedia.org/wiki/Tarjan%E2%80%99s_strongly_connected_components_algorithm |
| 2831 |
*/ |
| 2832 |
std::vector<DocumentObject*> |
| 2833 |
DocumentP::partialTopologicalSort(const std::vector<DocumentObject*>& objects) |
| 2834 |
{ |
| 2835 |
vector<DocumentObject*> ret; |
| 2836 |
ret.reserve(objects.size()); |
| 2837 |
// pairs of input and output degree |
| 2838 |
map<DocumentObject*, std::pair<int, int>> countMap; |
| 2839 |
|
| 2840 |
for (auto objectIt : objects) { |
| 2841 |
// we need inlist with unique entries |
| 2842 |
auto in = objectIt->getInList(); |
| 2843 |
std::sort(in.begin(), in.end()); |
| 2844 |
in.erase(std::unique(in.begin(), in.end()), in.end()); |
| 2845 |
|
| 2846 |
// we need outlist with unique entries |
| 2847 |
auto out = objectIt->getOutList(); |
| 2848 |
std::sort(out.begin(), out.end()); |
| 2849 |
out.erase(std::unique(out.begin(), out.end()), out.end()); |
| 2850 |
|
| 2851 |
countMap[objectIt] = std::make_pair(in.size(), out.size()); |
| 2852 |
} |
| 2853 |
|
| 2854 |
std::list<DocumentObject*> degIn; |
| 2855 |
std::list<DocumentObject*> degOut; |
| 2856 |
|
| 2857 |
bool removeVertex = true; |
| 2858 |
while (removeVertex) { |
| 2859 |
removeVertex = false; |
| 2860 |
|
| 2861 |
// try input degree |
| 2862 |
auto degInIt = find_if(countMap.begin(), |
| 2863 |
countMap.end(), |
| 2864 |
[](pair<DocumentObject*, pair<int, int>> vertex) -> bool { |
| 2865 |
return vertex.second.first == 0; |
| 2866 |
}); |
| 2867 |
|
| 2868 |
if (degInIt != countMap.end()) { |
| 2869 |
removeVertex = true; |
| 2870 |
degIn.push_back(degInIt->first); |
| 2871 |
degInIt->second.first = degInIt->second.first - 1; |
| 2872 |
|
| 2873 |
// we need outlist with unique entries |
| 2874 |
auto out = degInIt->first->getOutList(); |
| 2875 |
std::sort(out.begin(), out.end()); |
| 2876 |
out.erase(std::unique(out.begin(), out.end()), out.end()); |
| 2877 |
|
| 2878 |
for (auto outListIt : out) { |
| 2879 |
auto outListMapIt = countMap.find(outListIt); |
| 2880 |
if (outListMapIt != countMap.end()) { |
| 2881 |
outListMapIt->second.first = outListMapIt->second.first - 1; |
| 2882 |
} |
| 2883 |
} |
| 2884 |
} |
| 2885 |
} |
| 2886 |
|
| 2887 |
// make the output degree negative if input degree is negative |
| 2888 |
// to mark the vertex as processed |
| 2889 |
for (auto& [obj, pair] : countMap) { |
| 2890 |
if (pair.first < 0) { |
| 2891 |
pair.second = -1; |
| 2892 |
} |
| 2893 |
} |
| 2894 |
|
| 2895 |
removeVertex = degIn.size() != objects.size(); |
| 2896 |
while (removeVertex) { |
| 2897 |
removeVertex = false; |
| 2898 |
|
| 2899 |
auto degOutIt = find_if(countMap.begin(), |
| 2900 |
countMap.end(), |
| 2901 |
[](pair<DocumentObject*, pair<int, int>> vertex) -> bool { |
| 2902 |
return vertex.second.second == 0; |
| 2903 |
}); |
| 2904 |
|
| 2905 |
if (degOutIt != countMap.end()) { |
| 2906 |
removeVertex = true; |
| 2907 |
degOut.push_front(degOutIt->first); |
| 2908 |
degOutIt->second.second = degOutIt->second.second - 1; |
| 2909 |
|
| 2910 |
// we need inlist with unique entries |
| 2911 |
auto in = degOutIt->first->getInList(); |
| 2912 |
std::sort(in.begin(), in.end()); |
| 2913 |
in.erase(std::unique(in.begin(), in.end()), in.end()); |
| 2914 |
|
| 2915 |
for (auto inListIt : in) { |
| 2916 |
auto inListMapIt = countMap.find(inListIt); |
| 2917 |
if (inListMapIt != countMap.end()) { |
| 2918 |
inListMapIt->second.second = inListMapIt->second.second - 1; |
| 2919 |
} |
| 2920 |
} |
| 2921 |
} |
| 2922 |
} |
| 2923 |
|
| 2924 |
// at this point we have no root object any more |
| 2925 |
for (auto countIt : countMap) { |
| 2926 |
if (countIt.second.first > 0 && countIt.second.second > 0) { |
| 2927 |
degIn.push_back(countIt.first); |
| 2928 |
} |
| 2929 |
} |
| 2930 |
|
| 2931 |
ret.insert(ret.end(), degIn.begin(), degIn.end()); |
| 2932 |
ret.insert(ret.end(), degOut.begin(), degOut.end()); |
| 2933 |
|
| 2934 |
return ret; |
| 2935 |
} |
| 2936 |
|
| 2937 |
std::vector<DocumentObject*> |
| 2938 |
DocumentP::topologicalSort(const std::vector<DocumentObject*>& objects) const |
| 2939 |
{ |
| 2940 |
// topological sort algorithm described here: |
| 2941 |
// https://de.wikipedia.org/wiki/Topologische_Sortierung#Algorithmus_f.C3.BCr_das_Topologische_Sortieren |
| 2942 |
vector<DocumentObject*> ret; |
| 2943 |
ret.reserve(objects.size()); |
| 2944 |
map<DocumentObject*, int> countMap; |
| 2945 |
|
| 2946 |
for (auto objectIt : objects) { |
| 2947 |
// We now support externally linked objects |
| 2948 |
// if(!obj->isAttachedToDocument() || obj->getDocument()!=this) |
| 2949 |
if (!objectIt->isAttachedToDocument()) { |
| 2950 |
continue; |
| 2951 |
} |
| 2952 |
// we need inlist with unique entries |
| 2953 |
auto in = objectIt->getInList(); |
| 2954 |
std::sort(in.begin(), in.end()); |
| 2955 |
in.erase(std::unique(in.begin(), in.end()), in.end()); |
| 2956 |
|
| 2957 |
countMap[objectIt] = in.size(); |
| 2958 |
} |
| 2959 |
|
| 2960 |
auto rootObjeIt = find_if(countMap.begin(), |
| 2961 |
countMap.end(), |
| 2962 |
[](pair<DocumentObject*, int> count) -> bool { |
| 2963 |
return count.second == 0; |
| 2964 |
}); |
| 2965 |
|
| 2966 |
if (rootObjeIt == countMap.end()) { |
| 2967 |
cerr << "Document::topologicalSort: cyclic dependency detected (no root object)" << '\n'; |
| 2968 |
return ret; |
| 2969 |
} |
| 2970 |
|
| 2971 |
while (rootObjeIt != countMap.end()) { |
| 2972 |
rootObjeIt->second = rootObjeIt->second - 1; |
| 2973 |
|
| 2974 |
// we need outlist with unique entries |
| 2975 |
auto out = rootObjeIt->first->getOutList(); |
| 2976 |
std::sort(out.begin(), out.end()); |
| 2977 |
out.erase(std::unique(out.begin(), out.end()), out.end()); |
| 2978 |
|
| 2979 |
for (auto outListIt : out) { |
| 2980 |
auto outListMapIt = countMap.find(outListIt); |
| 2981 |
if (outListMapIt != countMap.end()) { |
| 2982 |
outListMapIt->second = outListMapIt->second - 1; |
| 2983 |
} |
| 2984 |
} |
| 2985 |
ret.push_back(rootObjeIt->first); |
| 2986 |
|
| 2987 |
rootObjeIt = find_if(countMap.begin(), |
| 2988 |
countMap.end(), |
| 2989 |
[](pair<DocumentObject*, int> count) -> bool { |
| 2990 |
return count.second == 0; |
| 2991 |
}); |
| 2992 |
} |
| 2993 |
|
| 2994 |
return ret; |
| 2995 |
} |
| 2996 |
|
| 2997 |
std::vector<DocumentObject*> Document::topologicalSort() const |
| 2998 |
{ |
| 2999 |
return d->topologicalSort(d->objectArray); |
| 3000 |
} |
| 3001 |
|
| 3002 |
const char* Document::getErrorDescription(const DocumentObject* Obj) const |
| 3003 |
{ |
| 3004 |
return d->findRecomputeLog(Obj); |
| 3005 |
} |
| 3006 |
|
| 3007 |
// call the recompute of the Feature and handle the exceptions and errors. |
| 3008 |
int Document::_recomputeFeature(DocumentObject* Feat) // NOLINT |
| 3009 |
{ |
| 3010 |
FC_LOG("Recomputing " << Feat->getFullName()); |
| 3011 |
|
| 3012 |
DocumentObjectExecReturn* returnCode = nullptr; |
| 3013 |
try { |
| 3014 |
returnCode = Feat->ExpressionEngine.execute(PropertyExpressionEngine::ExecuteNonOutput); |
| 3015 |
if (returnCode == DocumentObject::StdReturn) { |
| 3016 |
returnCode = Feat->recompute(); |
| 3017 |
if (returnCode == DocumentObject::StdReturn) { |
| 3018 |
returnCode = |
| 3019 |
Feat->ExpressionEngine.execute(PropertyExpressionEngine::ExecuteOutput); |
| 3020 |
} |
| 3021 |
} |
| 3022 |
} |
| 3023 |
catch (Base::AbortException& e) { |
| 3024 |
e.reportException(); |
| 3025 |
FC_LOG("Failed to recompute " << Feat->getFullName() << ": " << e.what()); |
| 3026 |
d->addRecomputeLog("User abort", Feat); |
| 3027 |
return -1; |
| 3028 |
} |
| 3029 |
catch (const Base::MemoryException& e) { |
| 3030 |
FC_ERR("Memory exception in " << Feat->getFullName() << " thrown: " << e.what()); |
| 3031 |
d->addRecomputeLog("Out of memory exception", Feat); |
| 3032 |
return 1; |
| 3033 |
} |
| 3034 |
catch (Base::Exception& e) { |
| 3035 |
e.reportException(); |
| 3036 |
FC_LOG("Failed to recompute " << Feat->getFullName() << ": " << e.what()); |
| 3037 |
d->addRecomputeLog(e.what(), Feat); |
| 3038 |
return 1; |
| 3039 |
} |
| 3040 |
catch (std::exception& e) { |
| 3041 |
FC_ERR("Exception in " << Feat->getFullName() << " thrown: " << e.what()); |
| 3042 |
d->addRecomputeLog(e.what(), Feat); |
| 3043 |
return 1; |
| 3044 |
} |
| 3045 |
#ifndef FC_DEBUG |
| 3046 |
catch (...) { |
| 3047 |
FC_ERR("Unknown exception in " << Feat->getFullName() << " thrown"); |
| 3048 |
d->addRecomputeLog("Unknown exception!", Feat); |
| 3049 |
return 1; |
| 3050 |
} |
| 3051 |
#endif |
| 3052 |
|
| 3053 |
if (returnCode == DocumentObject::StdReturn) { |
| 3054 |
Feat->resetError(); |
| 3055 |
} |
| 3056 |
else { |
| 3057 |
returnCode->Which = Feat; |
| 3058 |
d->addRecomputeLog(returnCode); |
| 3059 |
FC_LOG("Failed to recompute " << Feat->getFullName() << ": " << returnCode->Why); |
| 3060 |
return 1; |
| 3061 |
} |
| 3062 |
return 0; |
| 3063 |
} |
| 3064 |
|
| 3065 |
bool Document::recomputeFeature(DocumentObject* feature, bool recursive) |
| 3066 |
{ |
| 3067 |
// delete recompute log |
| 3068 |
d->clearRecomputeLog(feature); |
| 3069 |
|
| 3070 |
// verify that the feature is (active) part of the document |
| 3071 |
if (!feature->isAttachedToDocument()) { |
| 3072 |
return false; |
| 3073 |
} |
| 3074 |
|
| 3075 |
if (recursive) { |
| 3076 |
bool hasError = false; |
| 3077 |
recompute({feature}, true, &hasError); |
| 3078 |
return !hasError; |
| 3079 |
} |
| 3080 |
_recomputeFeature(feature); |
| 3081 |
signalRecomputedObject(*feature); |
| 3082 |
return feature->isValid(); |
| 3083 |
} |
| 3084 |
|
| 3085 |
DocumentObject* Document::addObject(const char* sType, |
| 3086 |
const char* pObjectName, |
| 3087 |
const bool isNew, |
| 3088 |
const char* viewType, |
| 3089 |
const bool isPartial) |
| 3090 |
{ |
| 3091 |
const Base::Type type = |
| 3092 |
Base::Type::getTypeIfDerivedFrom(sType, DocumentObject::getClassTypeId(), true); |
| 3093 |
if (type.isBad()) { |
| 3094 |
std::stringstream str; |
| 3095 |
str << "Document::addObject: '" << sType << "' is not a document object type"; |
| 3096 |
throw Base::TypeError(str.str()); |
| 3097 |
} |
| 3098 |
|
| 3099 |
void* typeInstance = type.createInstance(); |
| 3100 |
if (!typeInstance) { |
| 3101 |
return nullptr; |
| 3102 |
} |
| 3103 |
|
| 3104 |
auto* pcObject = static_cast<DocumentObject*>(typeInstance); |
| 3105 |
pcObject->setDocument(this); |
| 3106 |
|
| 3107 |
_addObject(pcObject, |
| 3108 |
pObjectName, |
| 3109 |
AddObjectOption::SetNewStatus |
| 3110 |
| (isPartial ? AddObjectOption::SetPartialStatus : AddObjectOption::UnsetPartialStatus) |
| 3111 |
| (isNew ? AddObjectOption::DoSetup : AddObjectOption::None) |
| 3112 |
| AddObjectOption::ActivateObject, |
| 3113 |
viewType); |
| 3114 |
|
| 3115 |
// return the Object |
| 3116 |
return pcObject; |
| 3117 |
} |
| 3118 |
|
| 3119 |
std::vector<DocumentObject*> |
| 3120 |
Document::addObjects(const char* sType, const std::vector<std::string>& objectNames, bool isNew) |
| 3121 |
{ |
| 3122 |
Base::Type type = |
| 3123 |
Base::Type::getTypeIfDerivedFrom(sType, DocumentObject::getClassTypeId(), true); |
| 3124 |
if (type.isBad()) { |
| 3125 |
std::stringstream str; |
| 3126 |
str << "'" << sType << "' is not a document object type"; |
| 3127 |
throw Base::TypeError(str.str()); |
| 3128 |
} |
| 3129 |
|
| 3130 |
std::vector<DocumentObject*> objects; |
| 3131 |
objects.resize(objectNames.size()); |
| 3132 |
std::generate(objects.begin(), objects.end(), [&] { |
| 3133 |
return static_cast<DocumentObject*>(type.createInstance()); |
| 3134 |
}); |
| 3135 |
// the type instance could be a null pointer, it is enough to check the first element |
| 3136 |
if (!objects.empty() && !objects[0]) { |
| 3137 |
objects.clear(); |
| 3138 |
return objects; |
| 3139 |
} |
| 3140 |
|
| 3141 |
for (auto it = objects.begin(); it != objects.end(); ++it) { |
| 3142 |
size_t index = std::distance(objects.begin(), it); |
| 3143 |
DocumentObject* pcObject = *it; |
| 3144 |
pcObject->setDocument(this); |
| 3145 |
|
| 3146 |
// Add the object but only activate the last one |
| 3147 |
bool isLast = index == (objects.size() - 1); |
| 3148 |
_addObject(pcObject, |
| 3149 |
objectNames[index].c_str(), |
| 3150 |
AddObjectOption::SetNewStatus |
| 3151 |
| (isNew ? AddObjectOption::DoSetup : AddObjectOption::None) |
| 3152 |
| (isLast ? AddObjectOption::ActivateObject : AddObjectOption::None)); |
| 3153 |
} |
| 3154 |
|
| 3155 |
return objects; |
| 3156 |
} |
| 3157 |
|
| 3158 |
void Document::addObject(DocumentObject* pcObject, const char* pObjectName) |
| 3159 |
{ |
| 3160 |
if (pcObject->getDocument()) { |
| 3161 |
throw Base::RuntimeError("Document object is already added to a document"); |
| 3162 |
} |
| 3163 |
|
| 3164 |
pcObject->setDocument(this); |
| 3165 |
|
| 3166 |
_addObject(pcObject, pObjectName, AddObjectOption::SetNewStatus | AddObjectOption::ActivateObject); |
| 3167 |
} |
| 3168 |
|
| 3169 |
void Document::_addObject(DocumentObject* pcObject, const char* pObjectName, AddObjectOptions options, const char* viewType) |
| 3170 |
{ |
| 3171 |
// get unique name |
| 3172 |
string ObjectName; |
| 3173 |
if (!Base::Tools::isNullOrEmpty(pObjectName)) { |
| 3174 |
ObjectName = getUniqueObjectName(pObjectName); |
| 3175 |
} |
| 3176 |
else { |
| 3177 |
ObjectName = getUniqueObjectName(pcObject->getTypeId().getName()); |
| 3178 |
} |
| 3179 |
|
| 3180 |
// insert in the name map |
| 3181 |
d->objectMap[ObjectName] = pcObject; |
| 3182 |
d->objectNameManager.addExactName(ObjectName); |
| 3183 |
// cache the pointer to the name string in the Object (for performance of |
| 3184 |
// DocumentObject::getNameInDocument()) |
| 3185 |
pcObject->pcNameInDocument = &(d->objectMap.find(ObjectName)->first); |
| 3186 |
// Register the current Label even though it might be about to change |
| 3187 |
registerLabel(pcObject->Label.getStrValue()); |
| 3188 |
|
| 3189 |
// generate object id and add to id map + object array |
| 3190 |
if (pcObject->_Id == 0) { |
| 3191 |
pcObject->_Id = ++d->lastObjectId; |
| 3192 |
} |
| 3193 |
d->objectIdMap[pcObject->_Id] = pcObject; |
| 3194 |
d->objectArray.push_back(pcObject); |
| 3195 |
|
| 3196 |
// do no transactions if we do a rollback! |
| 3197 |
if (!d->rollback) { |
| 3198 |
// Undo stuff |
| 3199 |
_checkTransaction(nullptr, nullptr, __LINE__); |
| 3200 |
if (d->activeUndoTransaction) { |
| 3201 |
d->activeUndoTransaction->addObjectDel(pcObject); |
| 3202 |
} |
| 3203 |
} |
| 3204 |
// If we are restoring, don't set the Label object now; it will be restored later. This is to |
| 3205 |
// avoid potential duplicate label conflicts later. |
| 3206 |
if (options.testFlag(AddObjectOption::SetNewStatus) && !d->StatusBits.test(Restoring)) { |
| 3207 |
pcObject->Label.setValue(ObjectName); |
| 3208 |
} |
| 3209 |
|
| 3210 |
// Call the object-specific initialization |
| 3211 |
if (!isPerformingTransaction() && options.testFlag(AddObjectOption::DoSetup)) { |
| 3212 |
pcObject->setupObject(); |
| 3213 |
} |
| 3214 |
|
| 3215 |
if (options.testFlag(AddObjectOption::SetNewStatus)) { |
| 3216 |
pcObject->setStatus(ObjectStatus::New, true); |
| 3217 |
} |
| 3218 |
if (options.testFlag(AddObjectOption::SetPartialStatus) || options.testFlag(AddObjectOption::UnsetPartialStatus)) { |
| 3219 |
pcObject->setStatus(ObjectStatus::PartialObject, options.testFlag(AddObjectOption::SetPartialStatus)); |
| 3220 |
} |
| 3221 |
|
| 3222 |
if (Base::Tools::isNullOrEmpty(viewType)) { |
| 3223 |
viewType = pcObject->getViewProviderNameOverride(); |
| 3224 |
} |
| 3225 |
pcObject->_pcViewProviderName = viewType ? viewType : ""; |
| 3226 |
|
| 3227 |
signalNewObject(*pcObject); |
| 3228 |
|
| 3229 |
// do no transactions if we do a rollback! |
| 3230 |
if (!d->rollback && d->activeUndoTransaction) { |
| 3231 |
signalTransactionAppend(*pcObject, d->activeUndoTransaction); |
| 3232 |
} |
| 3233 |
|
| 3234 |
if (options.testFlag(AddObjectOption::ActivateObject)) { |
| 3235 |
d->activeObject = pcObject; |
| 3236 |
signalActivatedObject(*pcObject); |
| 3237 |
} |
| 3238 |
} |
| 3239 |
|
| 3240 |
bool Document::containsObject(const DocumentObject* pcObject) const |
| 3241 |
{ |
| 3242 |
// We could look for the object in objectMap (keyed by object name), |
| 3243 |
// or search in objectArray (a O(n) vector search) but looking by Id |
| 3244 |
// in objectIdMap would be fastest. |
| 3245 |
auto found = d->objectIdMap.find(pcObject->getID()); |
| 3246 |
return found != d->objectIdMap.end() && found->second == pcObject; |
| 3247 |
} |
| 3248 |
|
| 3249 |
/// Remove an object out of the document |
| 3250 |
void Document::removeObject(const char* sName) |
| 3251 |
{ |
| 3252 |
auto pos = d->objectMap.find(sName); |
| 3253 |
if (pos == d->objectMap.end()){ |
| 3254 |
FC_MSG("Object " << sName << " already deleted in document " << getName()); |
| 3255 |
return; |
| 3256 |
} |
| 3257 |
|
| 3258 |
if (pos->second->testStatus(ObjectStatus::PendingRecompute)) { |
| 3259 |
// TODO: shall we allow removal if there is active undo transaction? |
| 3260 |
FC_MSG("pending remove of " << sName << " after recomputing document " << getName()); |
| 3261 |
d->pendingRemove.emplace_back(pos->second); |
| 3262 |
return; |
| 3263 |
} |
| 3264 |
|
| 3265 |
_removeObject(pos->second, RemoveObjectOption::MayRemoveWhileRecomputing | RemoveObjectOption::MayDestroyOutOfTransaction); |
| 3266 |
} |
| 3267 |
void Document::_removeObject(DocumentObject* pcObject, RemoveObjectOptions options) |
| 3268 |
{ |
| 3269 |
if (!options.testFlag(RemoveObjectOption::MayRemoveWhileRecomputing) && testStatus(Document::Recomputing)) { |
| 3270 |
FC_ERR("Cannot delete " << pcObject->getFullName() << " while recomputing"); |
| 3271 |
return; |
| 3272 |
} |
| 3273 |
|
| 3274 |
TransactionLocker tlock; |
| 3275 |
|
| 3276 |
_checkTransaction(pcObject, nullptr, __LINE__); |
| 3277 |
|
| 3278 |
auto pos = d->objectMap.find(pcObject->getNameInDocument()); |
| 3279 |
if (pos == d->objectMap.end()) { |
| 3280 |
FC_ERR("Internal error, could not find " << pcObject->getFullName() << " to remove"); |
| 3281 |
} |
| 3282 |
|
| 3283 |
if (options.testFlag(RemoveObjectOption::PreserveChildrenVisibility) |
| 3284 |
&& !d->rollback && d->activeUndoTransaction && pcObject->hasChildElement()) { |
| 3285 |
// Preserve link group sub object global visibilities. Normally those |
| 3286 |
// claimed object should be hidden in global coordinate space. However, |
| 3287 |
// when the group is deleted, the user will naturally try to show the |
| 3288 |
// children, which may now in the global space. When the parent is |
| 3289 |
// undeleted, having its children shown in both the local and global |
| 3290 |
// coordinate space is very confusing. Hence, we preserve the visibility |
| 3291 |
// here |
| 3292 |
for (auto& sub : pcObject->getSubObjects()) { |
| 3293 |
if (sub.empty()) { |
| 3294 |
continue; |
| 3295 |
} |
| 3296 |
if (sub[sub.size() - 1] != '.') { |
| 3297 |
sub += '.'; |
| 3298 |
} |
| 3299 |
auto sobj = pcObject->getSubObject(sub.c_str()); |
| 3300 |
if (sobj && sobj->getDocument() == this && !sobj->Visibility.getValue()) { |
| 3301 |
d->activeUndoTransaction->addObjectChange(sobj, &sobj->Visibility); |
| 3302 |
} |
| 3303 |
} |
| 3304 |
} |
| 3305 |
|
| 3306 |
if (d->activeObject == pcObject) { |
| 3307 |
d->activeObject = nullptr; |
| 3308 |
} |
| 3309 |
|
| 3310 |
// Mark the object as about to be removed |
| 3311 |
pcObject->setStatus(ObjectStatus::Remove, true); |
| 3312 |
if (!d->undoing && !d->rollback) { |
| 3313 |
pcObject->unsetupObject(); |
| 3314 |
} |
| 3315 |
signalDeletedObject(*pcObject); |
| 3316 |
signalTransactionRemove(*pcObject, d->rollback ? nullptr : d->activeUndoTransaction); |
| 3317 |
breakDependency(pcObject, true); |
| 3318 |
|
| 3319 |
// TODO Check me if it's needed (2015-09-01, Fat-Zer) |
| 3320 |
// remove the tip if needed |
| 3321 |
if (Tip.getValue() == pcObject) { |
| 3322 |
Tip.setValue(nullptr); |
| 3323 |
TipName.setValue(""); |
| 3324 |
} |
| 3325 |
|
| 3326 |
// remove from map |
| 3327 |
pcObject->setStatus(ObjectStatus::Remove, false); // Unset the bit to be on the safe side |
| 3328 |
d->objectIdMap.erase(pcObject->_Id); |
| 3329 |
d->objectNameManager.removeExactName(pos->first); |
| 3330 |
unregisterLabel(pcObject->Label.getStrValue()); |
| 3331 |
|
| 3332 |
// do no transactions if we do a rollback! |
| 3333 |
if (!d->rollback && d->activeUndoTransaction) { |
| 3334 |
d->activeUndoTransaction->addObjectNew(pcObject); |
| 3335 |
} |
| 3336 |
|
| 3337 |
std::unique_ptr<DocumentObject> tobedestroyed; |
| 3338 |
if ((options.testFlag(RemoveObjectOption::MayDestroyOutOfTransaction) && !d->rollback && !d->activeUndoTransaction) |
| 3339 |
|| (options.testFlag(RemoveObjectOption::DestroyOnRollback) && d->rollback)) { |
| 3340 |
// if not saved in undo -> delete object later |
| 3341 |
std::unique_ptr<DocumentObject> delobj(pos->second); |
| 3342 |
tobedestroyed.swap(delobj); |
| 3343 |
tobedestroyed->setStatus(ObjectStatus::Destroy, true); |
| 3344 |
} |
| 3345 |
|
| 3346 |
for (auto it = d->objectArray.begin(); |
| 3347 |
it != d->objectArray.end(); |
| 3348 |
++it) { |
| 3349 |
if (*it == pcObject) { |
| 3350 |
d->objectArray.erase(it); |
| 3351 |
break; |
| 3352 |
} |
| 3353 |
} |
| 3354 |
|
| 3355 |
// In case the object gets deleted the pointer must be nullified |
| 3356 |
if (tobedestroyed) { |
| 3357 |
tobedestroyed->pcNameInDocument = nullptr; |
| 3358 |
} |
| 3359 |
|
| 3360 |
// Erase last to avoid invalidating pcObject->pcNameInDocument |
| 3361 |
// when it is still needed in Transaction::addObjectNew |
| 3362 |
d->objectMap.erase(pos); |
| 3363 |
} |
| 3364 |
|
| 3365 |
void Document::breakDependency(DocumentObject* pcObject, const bool clear) // NOLINT |
| 3366 |
{ |
| 3367 |
// Nullify all dependent objects |
| 3368 |
PropertyLinkBase::breakLinks(pcObject, d->objectArray, clear); |
| 3369 |
} |
| 3370 |
|
| 3371 |
std::vector<DocumentObject*> |
| 3372 |
Document::copyObject(const std::vector<DocumentObject*>& objs, bool recursive, bool returnAll) |
| 3373 |
{ |
| 3374 |
std::vector<DocumentObject*> deps; |
| 3375 |
if (!recursive) { |
| 3376 |
deps = objs; |
| 3377 |
} |
| 3378 |
else { |
| 3379 |
deps = getDependencyList(objs, DepNoXLinked | DepSort); |
| 3380 |
} |
| 3381 |
|
| 3382 |
if (!testStatus(TempDoc) && !isSaved() && PropertyXLink::hasXLink(deps)) { |
| 3383 |
throw Base::RuntimeError( |
| 3384 |
"Document must be saved at least once before link to external objects"); |
| 3385 |
} |
| 3386 |
|
| 3387 |
MergeDocuments md(this); |
| 3388 |
// if not copying recursively then suppress possible warnings |
| 3389 |
md.setVerbose(recursive); |
| 3390 |
|
| 3391 |
unsigned int memsize = 1000; // ~ for the meta-information |
| 3392 |
for (auto it : deps) { |
| 3393 |
memsize += it->getMemSize(); |
| 3394 |
} |
| 3395 |
|
| 3396 |
// if less than ~10 MB |
| 3397 |
bool use_buffer = (memsize < 0xA00000); |
| 3398 |
QByteArray res; |
| 3399 |
try { |
| 3400 |
res.reserve(memsize); |
| 3401 |
} |
| 3402 |
catch (const Base::MemoryException&) { |
| 3403 |
use_buffer = false; |
| 3404 |
} |
| 3405 |
|
| 3406 |
std::vector<DocumentObject*> imported; |
| 3407 |
if (use_buffer) { |
| 3408 |
Base::ByteArrayOStreambuf obuf(res); |
| 3409 |
std::ostream ostr(&obuf); |
| 3410 |
exportObjects(deps, ostr); |
| 3411 |
|
| 3412 |
Base::ByteArrayIStreambuf ibuf(res); |
| 3413 |
std::istream istr(nullptr); |
| 3414 |
istr.rdbuf(&ibuf); |
| 3415 |
imported = md.importObjects(istr); |
| 3416 |
} |
| 3417 |
else { |
| 3418 |
static Base::FileInfo fi(Application::getTempFileName()); |
| 3419 |
Base::ofstream ostr(fi, std::ios::out | std::ios::binary); |
| 3420 |
exportObjects(deps, ostr); |
| 3421 |
ostr.close(); |
| 3422 |
|
| 3423 |
Base::ifstream istr(fi, std::ios::in | std::ios::binary); |
| 3424 |
imported = md.importObjects(istr); |
| 3425 |
} |
| 3426 |
|
| 3427 |
if (returnAll || imported.size() != deps.size()) { |
| 3428 |
return imported; |
| 3429 |
} |
| 3430 |
|
| 3431 |
std::unordered_map<DocumentObject*, size_t> indices; |
| 3432 |
size_t i = 0; |
| 3433 |
for (auto o : deps) { |
| 3434 |
indices[o] = i++; |
| 3435 |
} |
| 3436 |
std::vector<DocumentObject*> result; |
| 3437 |
result.reserve(objs.size()); |
| 3438 |
for (auto o : objs) { |
| 3439 |
result.push_back(imported[indices[o]]); |
| 3440 |
} |
| 3441 |
return result; |
| 3442 |
} |
| 3443 |
|
| 3444 |
std::vector<DocumentObject*> |
| 3445 |
Document::importLinks(const std::vector<DocumentObject*>& objs) |
| 3446 |
{ |
| 3447 |
std::set<DocumentObject*> links; |
| 3448 |
getLinksTo(links, nullptr, GetLinkExternal, 0, objs); |
| 3449 |
|
| 3450 |
std::vector<DocumentObject*> vecObjs; |
| 3451 |
vecObjs.insert(vecObjs.end(), links.begin(), links.end()); |
| 3452 |
std::vector<DocumentObject*> depObjs = getDependencyList(vecObjs); |
| 3453 |
if (depObjs.empty()) { |
| 3454 |
FC_ERR("nothing to import"); |
| 3455 |
return depObjs; |
| 3456 |
} |
| 3457 |
|
| 3458 |
for (auto it = depObjs.begin(); it != depObjs.end();) { |
| 3459 |
auto obj = *it; |
| 3460 |
if (obj->getDocument() == this) { |
| 3461 |
it = depObjs.erase(it); |
| 3462 |
continue; |
| 3463 |
} |
| 3464 |
++it; |
| 3465 |
if (obj->testStatus(PartialObject)) { |
| 3466 |
throw Base::RuntimeError( |
| 3467 |
"Cannot import partial loaded object. Please reload the current document"); |
| 3468 |
} |
| 3469 |
} |
| 3470 |
|
| 3471 |
Base::FileInfo fi(Application::getTempFileName()); |
| 3472 |
{ |
| 3473 |
// save stuff to temp file |
| 3474 |
Base::ofstream str(fi, std::ios::out | std::ios::binary); |
| 3475 |
MergeDocuments mimeView(this); |
| 3476 |
exportObjects(depObjs, str); |
| 3477 |
str.close(); |
| 3478 |
} |
| 3479 |
Base::ifstream str(fi, std::ios::in | std::ios::binary); |
| 3480 |
MergeDocuments mimeView(this); |
| 3481 |
depObjs = mimeView.importObjects(str); |
| 3482 |
str.close(); |
| 3483 |
fi.deleteFile(); |
| 3484 |
|
| 3485 |
const auto& nameMap = mimeView.getNameMap(); |
| 3486 |
|
| 3487 |
// First, find all link type properties that needs to be changed |
| 3488 |
std::map<Property*, std::unique_ptr<Property>> propMap; |
| 3489 |
std::vector<Property*> propList; |
| 3490 |
for (auto obj : links) { |
| 3491 |
propList.clear(); |
| 3492 |
obj->getPropertyList(propList); |
| 3493 |
for (auto prop : propList) { |
| 3494 |
auto linkProp = freecad_cast<PropertyLinkBase*>(prop); |
| 3495 |
if (linkProp && !prop->testStatus(Property::Immutable) && !obj->isReadOnly(prop)) { |
| 3496 |
auto copy = linkProp->CopyOnImportExternal(nameMap); |
| 3497 |
if (copy) { |
| 3498 |
propMap[linkProp].reset(copy); |
| 3499 |
} |
| 3500 |
} |
| 3501 |
} |
| 3502 |
} |
| 3503 |
|
| 3504 |
// Then change them in one go. Note that we don't make change in previous |
| 3505 |
// loop, because a changed link property may break other depending link |
| 3506 |
// properties, e.g. a link sub referring to some sub object of an xlink, If |
| 3507 |
// that sub object is imported with a different name, and xlink is changed |
| 3508 |
// before this link sub, it will break. |
| 3509 |
for (auto& v : propMap) { |
| 3510 |
v.first->Paste(*v.second); |
| 3511 |
} |
| 3512 |
|
| 3513 |
return depObjs; |
| 3514 |
} |
| 3515 |
|
| 3516 |
DocumentObject* Document::moveObject(DocumentObject* obj, const bool recursive) |
| 3517 |
{ |
| 3518 |
if (!obj) { |
| 3519 |
return nullptr; |
| 3520 |
} |
| 3521 |
Document* that = obj->getDocument(); |
| 3522 |
if (that == this) { |
| 3523 |
return nullptr; // nothing todo |
| 3524 |
} |
| 3525 |
|
| 3526 |
// True object move without copy is only safe when undo is off on both |
| 3527 |
// documents. |
| 3528 |
if (!recursive && (d->iUndoMode == 0) && (that->d->iUndoMode == 0) && !that->d->rollback) { |
| 3529 |
// all object of the other document that refer to this object must be nullified |
| 3530 |
that->breakDependency(obj, false); |
| 3531 |
const std::string objname = getUniqueObjectName(obj->getNameInDocument()); |
| 3532 |
that->_removeObject(obj); |
| 3533 |
this->_addObject(obj, objname.c_str()); |
| 3534 |
obj->setDocument(this); |
| 3535 |
return obj; |
| 3536 |
} |
| 3537 |
|
| 3538 |
std::vector<DocumentObject*> deps; |
| 3539 |
if (recursive) { |
| 3540 |
deps = getDependencyList({obj}, DepNoXLinked | DepSort); |
| 3541 |
} |
| 3542 |
else { |
| 3543 |
deps.push_back(obj); |
| 3544 |
} |
| 3545 |
|
| 3546 |
const auto objs = copyObject(deps, false); |
| 3547 |
if (objs.empty()) { |
| 3548 |
return nullptr; |
| 3549 |
} |
| 3550 |
// Some object may delete its children if deleted, so we collect the IDs |
| 3551 |
// or all depending objects for safety reason. |
| 3552 |
std::vector<int> ids; |
| 3553 |
ids.reserve(deps.size()); |
| 3554 |
for (const auto o : deps) { |
| 3555 |
ids.push_back(static_cast<int>(o->getID())); |
| 3556 |
} |
| 3557 |
|
| 3558 |
// We only remove object if it is the moving object or it has no |
| 3559 |
// depending objects, i.e. an empty inList, which is why we need to |
| 3560 |
// iterate the depending list backwards. |
| 3561 |
for (auto iter = ids.rbegin(); iter != ids.rend(); ++iter) { |
| 3562 |
const auto o = that->getObjectByID(*iter); |
| 3563 |
if (!o) { |
| 3564 |
continue; |
| 3565 |
} |
| 3566 |
if (iter == ids.rbegin() || o->getInList().empty()) { |
| 3567 |
that->removeObject(o->getNameInDocument()); |
| 3568 |
} |
| 3569 |
} |
| 3570 |
return objs.back(); |
| 3571 |
} |
| 3572 |
|
| 3573 |
DocumentObject* Document::getActiveObject() const |
| 3574 |
{ |
| 3575 |
return d->activeObject; |
| 3576 |
} |
| 3577 |
|
| 3578 |
DocumentObject* Document::getObject(const char* Name) const |
| 3579 |
{ |
| 3580 |
const auto pos = d->objectMap.find(Name); |
| 3581 |
|
| 3582 |
return pos != d->objectMap.end() ?pos->second:nullptr; |
| 3583 |
} |
| 3584 |
|
| 3585 |
DocumentObject* Document::getObjectByID(const long id) const |
| 3586 |
{ |
| 3587 |
const auto it = d->objectIdMap.find(id); |
| 3588 |
|
| 3589 |
return it != d->objectIdMap.end() ?it->second:nullptr; |
| 3590 |
} |
| 3591 |
|
| 3592 |
|
| 3593 |
// Note: This method is only used in Tree.cpp slotChangeObject(), see explanation there |
| 3594 |
bool Document::isIn(const DocumentObject* pFeat) const |
| 3595 |
{ |
| 3596 |
for (const auto& [key, object] : d->objectMap) { |
| 3597 |
if (object == pFeat) { |
| 3598 |
return true; |
| 3599 |
} |
| 3600 |
} |
| 3601 |
|
| 3602 |
return false; |
| 3603 |
} |
| 3604 |
|
| 3605 |
const char* Document::getObjectName(const DocumentObject* pFeat) const |
| 3606 |
{ |
| 3607 |
for (const auto& [key, object] : d->objectMap) { |
| 3608 |
if (object == pFeat) { |
| 3609 |
return key.c_str(); |
| 3610 |
} |
| 3611 |
} |
| 3612 |
|
| 3613 |
return nullptr; |
| 3614 |
} |
| 3615 |
|
| 3616 |
std::string Document::getUniqueObjectName(const char* proposedName) const |
| 3617 |
{ |
| 3618 |
if (!proposedName || *proposedName == '\0') { |
| 3619 |
return {}; |
| 3620 |
} |
| 3621 |
std::string cleanName = Base::Tools::getIdentifier(proposedName); |
| 3622 |
|
| 3623 |
if (!d->objectNameManager.containsName(cleanName)) { |
| 3624 |
// Not in use yet, name is OK |
| 3625 |
return cleanName; |
| 3626 |
} |
| 3627 |
return d->objectNameManager.makeUniqueName(cleanName, 3); |
| 3628 |
} |
| 3629 |
|
| 3630 |
bool |
| 3631 |
Document::haveSameBaseName(const std::string& name, const std::string& label) |
| 3632 |
{ |
| 3633 |
// Both Labels and Names use the same decomposition rules for names, |
| 3634 |
// i.e. the default one supplied by UniqueNameManager, so we can use either |
| 3635 |
// of the name managers to do this test. |
| 3636 |
return d->objectNameManager.haveSameBaseName(name, label); |
| 3637 |
} |
| 3638 |
|
| 3639 |
std::string Document::getStandardObjectLabel(const char* modelName, int digitCount) const |
| 3640 |
{ |
| 3641 |
return d->objectLabelManager.makeUniqueName(modelName, digitCount); |
| 3642 |
} |
| 3643 |
|
| 3644 |
std::vector<DocumentObject*> Document::getDependingObjects() const |
| 3645 |
{ |
| 3646 |
return getDependencyList(d->objectArray); |
| 3647 |
} |
| 3648 |
|
| 3649 |
const std::vector<DocumentObject*>& Document::getObjects() const |
| 3650 |
{ |
| 3651 |
return d->objectArray; |
| 3652 |
} |
| 3653 |
|
| 3654 |
std::vector<DocumentObject*> Document::getObjectsOfType(const Base::Type& typeId) const |
| 3655 |
{ |
| 3656 |
std::vector<DocumentObject*> Objects; |
| 3657 |
for (auto it : d->objectArray) { |
| 3658 |
if (it->isDerivedFrom(typeId)) { |
| 3659 |
Objects.push_back(it); |
| 3660 |
} |
| 3661 |
} |
| 3662 |
return Objects; |
| 3663 |
} |
| 3664 |
|
| 3665 |
std::vector<DocumentObject*> Document::getObjectsOfType(const std::vector<Base::Type>& types) const |
| 3666 |
{ |
| 3667 |
std::vector<DocumentObject*> Objects; |
| 3668 |
for (auto it : d->objectArray) { |
| 3669 |
for (auto& typeId : types) { |
| 3670 |
if (it->isDerivedFrom(typeId)) { |
| 3671 |
Objects.push_back(it); |
| 3672 |
break; // Prevent adding several times the same object. |
| 3673 |
} |
| 3674 |
} |
| 3675 |
} |
| 3676 |
return Objects; |
| 3677 |
} |
| 3678 |
|
| 3679 |
std::vector<DocumentObject*> Document::getObjectsWithExtension(const Base::Type& typeId, |
| 3680 |
const bool derived) const |
| 3681 |
{ |
| 3682 |
|
| 3683 |
std::vector<DocumentObject*> Objects; |
| 3684 |
for (auto it : d->objectArray) { |
| 3685 |
if (it->hasExtension(typeId, derived)) { |
| 3686 |
Objects.push_back(it); |
| 3687 |
} |
| 3688 |
} |
| 3689 |
return Objects; |
| 3690 |
} |
| 3691 |
|
| 3692 |
|
| 3693 |
std::vector<DocumentObject*> |
| 3694 |
Document::findObjects(const Base::Type& typeId, const char* objname, const char* label) const |
| 3695 |
{ |
| 3696 |
boost::cmatch what; |
| 3697 |
boost::regex rx_name; |
| 3698 |
boost::regex rx_label; |
| 3699 |
|
| 3700 |
if (objname) { |
| 3701 |
rx_name.set_expression(objname); |
| 3702 |
} |
| 3703 |
|
| 3704 |
if (label) { |
| 3705 |
rx_label.set_expression(label); |
| 3706 |
} |
| 3707 |
|
| 3708 |
std::vector<DocumentObject*> Objects; |
| 3709 |
DocumentObject* found = nullptr; |
| 3710 |
for (const auto it : d->objectArray) { |
| 3711 |
if (it->isDerivedFrom(typeId)) { |
| 3712 |
found = it; |
| 3713 |
|
| 3714 |
if (!rx_name.empty() && !boost::regex_search(it->getNameInDocument(), what, rx_name)) { |
| 3715 |
found = nullptr; |
| 3716 |
} |
| 3717 |
|
| 3718 |
if (!rx_label.empty() && !boost::regex_search(it->Label.getValue(), what, rx_label)) { |
| 3719 |
found = nullptr; |
| 3720 |
} |
| 3721 |
|
| 3722 |
if (found) { |
| 3723 |
Objects.push_back(found); |
| 3724 |
} |
| 3725 |
} |
| 3726 |
} |
| 3727 |
return Objects; |
| 3728 |
} |
| 3729 |
|
| 3730 |
int Document::countObjectsOfType(const Base::Type& typeId) const |
| 3731 |
{ |
| 3732 |
return std::count_if(d->objectMap.begin(), d->objectMap.end(), [&](const auto& it) { |
| 3733 |
return it.second->isDerivedFrom(typeId); |
| 3734 |
}); |
| 3735 |
} |
| 3736 |
|
| 3737 |
int Document::countObjectsOfType(const char* typeName) const |
| 3738 |
{ |
| 3739 |
const Base::Type type = Base::Type::fromName(typeName); |
| 3740 |
return type.isBad() ? 0 : countObjectsOfType(type); |
| 3741 |
} |
| 3742 |
|
| 3743 |
PyObject* Document::getPyObject() |
| 3744 |
{ |
| 3745 |
return Py::new_reference_to(d->DocumentPythonObject); |
| 3746 |
} |
| 3747 |
|
| 3748 |
std::vector<DocumentObject*> Document::getRootObjects() const |
| 3749 |
{ |
| 3750 |
std::vector<DocumentObject*> ret; |
| 3751 |
|
| 3752 |
for (auto objectIt : d->objectArray) { |
| 3753 |
if (objectIt->getInList().empty()) { |
| 3754 |
ret.push_back(objectIt); |
| 3755 |
} |
| 3756 |
} |
| 3757 |
|
| 3758 |
return ret; |
| 3759 |
} |
| 3760 |
|
| 3761 |
std::vector<DocumentObject*> Document::getRootObjectsIgnoreLinks() const |
| 3762 |
{ |
| 3763 |
std::vector<DocumentObject*> ret; |
| 3764 |
|
| 3765 |
for (const auto &objectIt : d->objectArray) { |
| 3766 |
auto list = objectIt->getInList(); |
| 3767 |
bool noParents = list.empty(); |
| 3768 |
|
| 3769 |
if (!noParents) { |
| 3770 |
// App::Document getRootObjects returns the root objects of the dependency graph. |
| 3771 |
// So if an object is referenced by an App::Link, it will not be returned by that |
| 3772 |
// function. So here, as we want the tree-root level objects, we check if all the |
| 3773 |
// parents are links. In which case it's still a root object. |
| 3774 |
noParents = std::all_of(list.cbegin(), list.cend(), [](DocumentObject* obj) { |
| 3775 |
return obj->isDerivedFrom<Link>(); |
| 3776 |
}); |
| 3777 |
} |
| 3778 |
|
| 3779 |
if (noParents) { |
| 3780 |
ret.push_back(objectIt); |
| 3781 |
} |
| 3782 |
} |
| 3783 |
|
| 3784 |
return ret; |
| 3785 |
} |
| 3786 |
|
| 3787 |
void DocumentP::findAllPathsAt(const std::vector<Node>& all_nodes, |
| 3788 |
const size_t id, |
| 3789 |
std::vector<Path>& all_paths, |
| 3790 |
Path tmp) |
| 3791 |
{ |
| 3792 |
if (std::ranges::find(tmp, id) != tmp.end()) { |
| 3793 |
tmp.push_back(id); |
| 3794 |
all_paths.push_back(std::move(tmp)); |
| 3795 |
return; // a cycle |
| 3796 |
} |
| 3797 |
|
| 3798 |
tmp.push_back(id); |
| 3799 |
if (all_nodes[id].empty()) { |
| 3800 |
all_paths.push_back(std::move(tmp)); |
| 3801 |
return; |
| 3802 |
} |
| 3803 |
|
| 3804 |
for (size_t i = 0; i < all_nodes[id].size(); i++) { |
| 3805 |
const Path& tmp2(tmp); |
| 3806 |
findAllPathsAt(all_nodes, all_nodes[id][i], all_paths, tmp2); |
| 3807 |
} |
| 3808 |
} |
| 3809 |
|
| 3810 |
std::vector<std::list<DocumentObject*>> |
| 3811 |
Document::getPathsByOutList(const DocumentObject* from, const DocumentObject* to) const |
| 3812 |
{ |
| 3813 |
std::map<const DocumentObject*, size_t> indexMap; |
| 3814 |
for (size_t i = 0; i < d->objectArray.size(); ++i) { |
| 3815 |
indexMap[d->objectArray[i]] = i; |
| 3816 |
} |
| 3817 |
|
| 3818 |
std::vector<Node> all_nodes(d->objectArray.size()); |
| 3819 |
for (size_t i = 0; i < d->objectArray.size(); ++i) { |
| 3820 |
const DocumentObject* obj = d->objectArray[i]; |
| 3821 |
std::vector<DocumentObject*> outList = obj->getOutList(); |
| 3822 |
for (const auto it : outList) { |
| 3823 |
all_nodes[i].push_back(indexMap[it]); |
| 3824 |
} |
| 3825 |
} |
| 3826 |
|
| 3827 |
std::vector<std::list<DocumentObject*>> array; |
| 3828 |
if (from == to) { |
| 3829 |
return array; |
| 3830 |
} |
| 3831 |
|
| 3832 |
size_t index_from = indexMap[from]; |
| 3833 |
size_t index_to = indexMap[to]; |
| 3834 |
std::vector<Path> all_paths; |
| 3835 |
DocumentP::findAllPathsAt(all_nodes, index_from, all_paths, Path()); |
| 3836 |
|
| 3837 |
for (const Path& it : all_paths) { |
| 3838 |
auto jt = std::ranges::find(it, index_to); |
| 3839 |
if (jt != it.end()) { |
| 3840 |
array.push_back({}); |
| 3841 |
auto& path = array.back(); |
| 3842 |
for (auto kt = it.begin(); kt != jt; ++kt) { |
| 3843 |
path.push_back(d->objectArray[*kt]); |
| 3844 |
} |
| 3845 |
|
| 3846 |
path.push_back(d->objectArray[*jt]); |
| 3847 |
} |
| 3848 |
} |
| 3849 |
|
| 3850 |
// remove duplicates |
| 3851 |
std::sort(array.begin(), array.end()); |
| 3852 |
array.erase(std::unique(array.begin(), array.end()), array.end()); |
| 3853 |
|
| 3854 |
return array; |
| 3855 |
} |
| 3856 |
|
| 3857 |
bool Document::mustExecute() const |
| 3858 |
{ |
| 3859 |
if (PropertyXLink::hasXLink(this)) { |
| 3860 |
bool touched = false; |
| 3861 |
buildDependencyList(d->objectArray, 0, nullptr, nullptr, nullptr, &touched); |
| 3862 |
return touched; |
| 3863 |
} |
| 3864 |
|
| 3865 |
for (const auto It : d->objectArray) { |
| 3866 |
if (It->isTouched() || It->mustExecute() == 1) { |
| 3867 |
return true; |
| 3868 |
} |
| 3869 |
} |
| 3870 |
return false; |
| 3871 |
} |