/
Document.cpp
4395 lines (3766 loc) · 162 KB
/
Document.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* Copyright (c) Jürgen Riegel (juergen.riegel@web.de) 2002 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
/*!
\defgroup Document Document
\ingroup APP
\brief The Base class of the FreeCAD Document
This is (besides the App::Application class) the most important class in FreeCAD.
It contains all the data of the opened, saved, or newly created FreeCAD Document.
The App::Document manages the Undo and Redo mechanism and the linking of documents.
\namespace App \class App::Document
This is besides the Application class the most important class in FreeCAD
It contains all the data of the opened, saved or newly created FreeCAD Document.
The Document manage the Undo and Redo mechanism and the linking of documents.
Note: the documents are not free objects. They are completely handled by the
App::Application. Only the Application can Open or destroy a document.
\section Exception Exception handling
As the document is the main data structure of FreeCAD we have to take a close
look at how Exceptions affect the integrity of the App::Document.
\section UndoRedo Undo Redo an Transactions
Undo Redo handling is one of the major mechanism of a document in terms of
user friendliness and speed (no one will wait for Undo too long).
\section Dependency Graph and dependency handling
The FreeCAD document handles the dependencies of its DocumentObjects with
an adjacence list. This gives the opportunity to calculate the shortest
recompute path. Also, it enables more complicated dependencies beyond trees.
@see App::Application
@see App::DocumentObject
*/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <algorithm>
# include <sstream>
# include <climits>
# include <bitset>
# include <random>
#endif
#include <boost/algorithm/string.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/subgraph.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/strong_components.hpp>
#ifdef USE_OLD_DAG
#include <boost/graph/topological_sort.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/visitors.hpp>
#endif //USE_OLD_DAG
#include <boost/bind.hpp>
#include <boost/regex.hpp>
#include <unordered_set>
#include <unordered_map>
#include <random>
#include <QCoreApplication>
#include <QCryptographicHash>
#include "Document.h"
#include "Application.h"
#include "DocumentObject.h"
#include "MergeDocuments.h"
#include <App/DocumentPy.h>
#include <Base/Console.h>
#include <Base/Exception.h>
#include <Base/FileInfo.h>
#include <Base/TimeInfo.h>
#include <Base/Interpreter.h>
#include <Base/Reader.h>
#include <Base/Writer.h>
#include <Base/Stream.h>
#include <Base/FileInfo.h>
#include <Base/Tools.h>
#include <Base/Uuid.h>
#include <Base/Sequencer.h>
#ifdef _MSC_VER
#include <zipios++/zipios-config.h>
#endif
#include <zipios++/zipfile.h>
#include <zipios++/zipinputstream.h>
#include <zipios++/zipoutputstream.h>
#include <zipios++/meta-iostreams.h>
#include "Application.h"
#include "Transactions.h"
#include "GeoFeatureGroupExtension.h"
#include "Origin.h"
#include "OriginGroupExtension.h"
#include "Link.h"
#include "GeoFeature.h"
FC_LOG_LEVEL_INIT("App", true, true, true)
using Base::Console;
using Base::streq;
using Base::Writer;
using namespace App;
using namespace std;
using namespace boost;
using namespace zipios;
#if FC_DEBUG
# define FC_LOGFEATUREUPDATE
#endif
// typedef boost::property<boost::vertex_root_t, DocumentObject* > VertexProperty;
typedef boost::adjacency_list <
boost::vecS, // class OutEdgeListS : a Sequence or an AssociativeContainer
boost::vecS, // class VertexListS : a Sequence or a RandomAccessContainer
boost::directedS, // class DirectedS : This is a directed graph
boost::no_property, // class VertexProperty:
boost::no_property, // class EdgeProperty:
boost::no_property, // class GraphProperty:
boost::listS // class EdgeListS:
> DependencyList;
typedef boost::graph_traits<DependencyList> Traits;
typedef Traits::vertex_descriptor Vertex;
typedef Traits::edge_descriptor Edge;
typedef std::vector <size_t> Node;
typedef std::vector <size_t> Path;
namespace App {
static bool _IsRestoring;
static bool _IsRelabeling;
// Pimpl class
struct DocumentP
{
// Array to preserve the creation order of created objects
std::vector<DocumentObject*> objectArray;
std::unordered_set<App::DocumentObject*> touchedObjs;
std::unordered_map<std::string,DocumentObject*> objectMap;
std::unordered_map<long,DocumentObject*> objectIdMap;
std::unordered_map<std::string, bool> partialLoadObjects;
long lastObjectId;
DocumentObject* activeObject;
Transaction *activeUndoTransaction;
int iTransactionMode;
bool rollback;
bool undoing; ///< document in the middle of undo or redo
bool committing;
std::bitset<32> StatusBits;
int iUndoMode;
unsigned int UndoMemSize;
unsigned int UndoMaxStackSize;
#ifdef USE_OLD_DAG
DependencyList DepList;
std::map<DocumentObject*,Vertex> VertexObjectList;
std::map<Vertex,DocumentObject*> vertexMap;
#endif //USE_OLD_DAG
std::multimap<const App::DocumentObject*,
std::unique_ptr<App::DocumentObjectExecReturn> > _RecomputeLog;
DocumentP() {
static std::random_device _RD;
static std::mt19937 _RGEN(_RD());
static std::uniform_int_distribution<> _RDIST(0,5000);
// Set some random offset to reduce likelihood of ID collison when
// copying shape from other document. It is probably better to randomize
// on each object ID.
lastObjectId = _RDIST(_RGEN);
activeObject = 0;
activeUndoTransaction = 0;
iTransactionMode = 0;
rollback = false;
undoing = false;
committing = false;
StatusBits.set((size_t)Document::Closable, true);
StatusBits.set((size_t)Document::KeepTrailingDigits, true);
StatusBits.set((size_t)Document::Restoring, false);
iUndoMode = 0;
UndoMemSize = 0;
UndoMaxStackSize = 20;
}
void addRecomputeLog(const char *why, App::DocumentObject *obj) {
addRecomputeLog(new DocumentObjectExecReturn(why,obj));
}
void addRecomputeLog(const std::string &why, App::DocumentObject *obj) {
addRecomputeLog(new DocumentObjectExecReturn(why,obj));
}
void addRecomputeLog(DocumentObjectExecReturn *returnCode) {
if(!returnCode->Which) {
delete returnCode;
return;
}
_RecomputeLog.emplace(returnCode->Which, std::unique_ptr<DocumentObjectExecReturn>(returnCode));
returnCode->Which->setStatus(ObjectStatus::Error,true);
}
void clearRecomputeLog(const App::DocumentObject *obj=0) {
if(!obj)
_RecomputeLog.clear();
else
_RecomputeLog.erase(obj);
}
const char *findRecomputeLog(const App::DocumentObject *obj) {
auto range = _RecomputeLog.equal_range(obj);
if(range.first == range.second)
return 0;
return (--range.second)->second->Why.c_str();
}
static
void findAllPathsAt(const std::vector <Node> &all_nodes, size_t id,
std::vector <Path> &all_paths, Path tmp);
std::vector<App::DocumentObject*>
topologicalSort(const std::vector<App::DocumentObject*>& objects) const;
std::vector<App::DocumentObject*>
static partialTopologicalSort(const std::vector<App::DocumentObject*>& objects);
};
} // namespace App
PROPERTY_SOURCE(App::Document, App::PropertyContainer)
bool Document::testStatus(Status pos) const
{
return d->StatusBits.test((size_t)pos);
}
void Document::setStatus(Status pos, bool on)
{
d->StatusBits.set((size_t)pos, on);
}
void Document::writeDependencyGraphViz(std::ostream &out)
{
// // caching vertex to DocObject
//std::map<Vertex,DocumentObject*> VertexMap;
//for(std::map<DocumentObject*,Vertex>::const_iterator It1= _DepConMap.begin();It1 != _DepConMap.end(); ++It1)
// VertexMap[It1->second] = It1->first;
out << "digraph G {" << endl;
out << "\tordering=out;" << endl;
out << "\tnode [shape = box];" << endl;
for (auto It = d->objectMap.begin(); It != d->objectMap.end();++It) {
out << "\t" << It->first << ";" <<endl;
std::vector<DocumentObject*> OutList = It->second->getOutList();
for (std::vector<DocumentObject*>::const_iterator It2=OutList.begin();It2!=OutList.end();++It2)
if (*It2)
out << "\t" << It->first << "->" << (*It2)->getNameInDocument() << ";" <<endl;
}
/*
graph_traits<DependencyList>::edge_iterator ei, ei_end;
for (tie(ei,ei_end) = edges(_DepList); ei != ei_end; ++ei)
out << "\t"
<< VertexMap[source(*ei, _DepList)]->getNameInDocument()
<< " -> "
<< VertexMap[target(*ei, _DepList)]->getNameInDocument()
<< ";" << endl;
*/
out << "}" << endl;
}
void Document::exportGraphviz(std::ostream& out) const
{
/* Typedefs for a graph with graphviz attributes */
typedef std::map<std::string, std::string> GraphvizAttributes;
typedef boost::subgraph< adjacency_list<vecS, vecS, directedS,
property<vertex_attribute_t, GraphvizAttributes>,
property<edge_index_t, int, property<edge_attribute_t, GraphvizAttributes> >,
property<graph_name_t, std::string,
property<graph_graph_attribute_t, GraphvizAttributes,
property<graph_vertex_attribute_t, GraphvizAttributes,
property<graph_edge_attribute_t, GraphvizAttributes>
> > > > > Graph;
/**
* @brief The GraphCreator class
*
* This class creates the dependency graph for a document.
*
*/
class GraphCreator {
public:
GraphCreator(struct DocumentP* _d) : d(_d), vertex_no(0), seed(std::random_device()()), distribution(0,255) {
build();
}
const Graph & getGraph() const { return DepList; }
private:
void build() {
// Set attribute(s) for main graph
get_property(DepList, graph_graph_attribute)["compound"] = "true";
addSubgraphs();
buildAdjacencyList();
addEdges();
markCycles();
markOutOfScopeLinks();
}
/**
* @brief getId returns a canonical string for a DocumentObject.
* @param docObj Document object to get an ID from
* @return A string
*/
std::string getId(const DocumentObject * docObj) {
return std::string((docObj)->getDocument()->getName()) + "#" + docObj->getNameInDocument();
}
/**
* @brief getId returns a canonical string for an ObjectIdentifier;
* @param path
* @return A string
*/
std::string getId(const ObjectIdentifier & path) {
DocumentObject * docObj = path.getDocumentObject();
if (!docObj)
return std::string();
return std::string((docObj)->getDocument()->getName()) + "#" + docObj->getNameInDocument() + "." + path.getPropertyName() + path.getSubPathStr();
}
std::string getClusterName(const DocumentObject * docObj) const {
return std::string("cluster") + docObj->getNameInDocument();
}
void setGraphLabel(Graph& g, const DocumentObject* obj) const {
std::string name(obj->getNameInDocument());
std::string label(obj->Label.getValue());
if (name == label)
get_property(g, graph_graph_attribute)["label"] = name;
else
get_property(g, graph_graph_attribute)["label"] = name + "\n(" + label + ")";
}
/**
* @brief setGraphAttributes Set graph attributes on a subgraph for a DocumentObject node.
* @param obj DocumentObject
*/
void setGraphAttributes(const DocumentObject * obj) {
assert(GraphList.find(obj) != GraphList.end());
get_property(*GraphList[obj], graph_name) = getClusterName(obj);
get_property(*GraphList[obj], graph_graph_attribute)["bgcolor"] = "#e0e0e0";
get_property(*GraphList[obj], graph_graph_attribute)["style"] = "rounded,filled";
setGraphLabel(*GraphList[obj], obj);
}
/**
* @brief setPropertyVertexAttributes Set vertex attributes for a Property node in a graph.
* @param g Graph
* @param vertex Property node
* @param name Name of node
*/
void setPropertyVertexAttributes(Graph & g, Vertex vertex, const std::string & name) {
get(vertex_attribute, g)[vertex]["label"] = name;
get(vertex_attribute, g)[vertex]["shape"] = "box";
get(vertex_attribute, g)[vertex]["style"] = "dashed";
get(vertex_attribute, g)[vertex]["fontsize"] = "8pt";
}
/**
* @brief addExpressionSubgraphIfNeeded Add a subgraph to the main graph if it is needed, i.e. there are defined at least one
* expression in the document object, or other objects are referencing properties in it.
* @param obj DocumentObject to assess.
* @param CSSubgraphs Boolean if the GeoFeatureGroups are created as subgraphs
*/
void addExpressionSubgraphIfNeeded(DocumentObject * obj, bool CSsubgraphs) {
auto expressions = obj->ExpressionEngine.getExpressions();
if (!expressions.empty()) {
Graph* graph = nullptr;
graph = &DepList;
if (CSsubgraphs) {
auto group = GeoFeatureGroupExtension::getGroupOfObject(obj);
if (group) {
auto it = GraphList.find(group);
if (it != GraphList.end())
graph = it->second;
}
}
// If documentObject has an expression, create a subgraph for it
if (graph && !GraphList[obj]) {
GraphList[obj] = &graph->create_subgraph();
setGraphAttributes(obj);
}
// Create subgraphs for all documentobjects that it depends on; it will depend on some property there
auto i = expressions.begin();
while (i != expressions.end()) {
std::set<ObjectIdentifier> deps;
i->second->getIdentifiers(deps);
std::set<ObjectIdentifier>::const_iterator j = deps.begin();
while (j != deps.end()) {
DocumentObject * o = j->getDocumentObject();
// Doesn't exist already?
if (o && !GraphList[o]) {
if (CSsubgraphs) {
auto group = GeoFeatureGroupExtension::getGroupOfObject(o);
auto graph2 = group ? GraphList[group] : &DepList;
if (graph2) {
GraphList[o] = &graph2->create_subgraph();
setGraphAttributes(o);
}
}
else if (graph) {
GraphList[o] = &graph->create_subgraph();
setGraphAttributes(o);
}
}
++j;
}
++i;
}
}
}
/**
* @brief add Add @docObj to the graph, including all expressions (and dependencies) it includes.
* @param docObj The document object to add.
* @param name Name of node.
*/
void add(DocumentObject * docObj, const std::string & name, const std::string & label, bool CSSubgraphs) {
//don't add objects twice
if(std::find(objects.begin(), objects.end(), docObj) != objects.end())
return;
//find the correct graph to add the vertex to. Check first expression graphs, afterwards
//the parent CS and origin graphs
Graph * sgraph = GraphList[docObj];
if(CSSubgraphs) {
if(!sgraph) {
auto group = GeoFeatureGroupExtension::getGroupOfObject(docObj);
if(group) {
if(docObj->isDerivedFrom(App::OriginFeature::getClassTypeId()))
sgraph = GraphList[group->getExtensionByType<OriginGroupExtension>()->Origin.getValue()];
else
sgraph = GraphList[group];
}
}
if(!sgraph) {
if(docObj->isDerivedFrom(OriginFeature::getClassTypeId()))
sgraph = GraphList[static_cast<OriginFeature*>(docObj)->getOrigin()];
}
}
if(!sgraph)
sgraph = &DepList;
// Keep a list of all added document objects.
objects.insert(docObj);
// Add vertex to graph. Track global and local index
LocalVertexList[getId(docObj)] = add_vertex(*sgraph);
GlobalVertexList[getId(docObj)] = vertex_no++;
// If node is in main graph, style it with rounded corners. If not, make it invisible.
if (!GraphList[docObj]) {
get(vertex_attribute, *sgraph)[LocalVertexList[getId(docObj)]]["style"] = "filled";
get(vertex_attribute, *sgraph)[LocalVertexList[getId(docObj)]]["shape"] = "Mrecord";
// Set node label
if (name == label)
get(vertex_attribute, *sgraph)[LocalVertexList[getId(docObj)]]["label"] = name;
else
get(vertex_attribute, *sgraph)[LocalVertexList[getId(docObj)]]["label"] = name + "\n(" + label + ")";
}
else {
get(vertex_attribute, *sgraph)[LocalVertexList[getId(docObj)]]["style"] = "invis";
get(vertex_attribute, *sgraph)[LocalVertexList[getId(docObj)]]["fixedsize"] = "true";
get(vertex_attribute, *sgraph)[LocalVertexList[getId(docObj)]]["width"] = "0";
get(vertex_attribute, *sgraph)[LocalVertexList[getId(docObj)]]["height"] = "0";
}
// Add expressions and its dependencies
auto expressions = docObj->ExpressionEngine.getExpressions();
auto i = expressions.begin();
// Add nodes for each property that has an expression attached to it
while (i != expressions.end()) {
std::map<std::string, Vertex>::const_iterator k = GlobalVertexList.find(getId(i->first));
if (k == GlobalVertexList.end()) {
int vid = LocalVertexList[getId(i->first)] = add_vertex(*sgraph);
GlobalVertexList[getId(i->first)] = vertex_no++;
setPropertyVertexAttributes(*sgraph, vid, i->first.toString());
}
++i;
}
// Add all dependencies
i = expressions.begin();
while (i != expressions.end()) {
// Get dependencies
std::set<ObjectIdentifier> deps;
i->second->getIdentifiers(deps);
// Create subgraphs for all documentobjects that it depends on; it will depend on some property there
std::set<ObjectIdentifier>::const_iterator j = deps.begin();
while (j != deps.end()) {
DocumentObject * depObjDoc = j->getDocumentObject();
std::map<std::string, Vertex>::const_iterator k = GlobalVertexList.find(getId(*j));
if (k == GlobalVertexList.end()) {
Graph * depSgraph = GraphList[depObjDoc] ? GraphList[depObjDoc] : &DepList;
LocalVertexList[getId(*j)] = add_vertex(*depSgraph);
GlobalVertexList[getId(*j)] = vertex_no++;
setPropertyVertexAttributes(*depSgraph, LocalVertexList[getId(*j)], j->getPropertyName() + j->getSubPathStr());
}
++j;
}
++i;
}
}
void recursiveCSSubgraphs(DocumentObject* cs, DocumentObject* parent) {
auto graph = parent ? GraphList[parent] : &DepList;
// check if the value for the key 'parent' is null
if (!graph)
return;
auto& sub = graph->create_subgraph();
GraphList[cs] = ⊂
get_property(sub, graph_name) = getClusterName(cs);
//build random color string
std::stringstream stream;
stream << "#" << std::setfill('0') << std::setw(2)<< std::hex << distribution(seed)
<< std::setfill('0') << std::setw(2)<< std::hex << distribution(seed)
<< std::setfill('0') << std::setw(2)<< std::hex << distribution(seed) << 80;
std::string result(stream.str());
get_property(sub, graph_graph_attribute)["bgcolor"] = result;
get_property(sub, graph_graph_attribute)["style"] = "rounded,filled";
setGraphLabel(sub, cs);
for(auto obj : cs->getOutList()) {
if (obj->hasExtension(GeoFeatureGroupExtension::getExtensionClassTypeId())) {
// in case of dependencies loops check if obj is already part of the
// map to avoid infinite recursions
auto it = GraphList.find(obj);
if (it == GraphList.end())
recursiveCSSubgraphs(obj, cs);
}
}
//setup the origin if available
if(cs->hasExtension(App::OriginGroupExtension::getExtensionClassTypeId())) {
auto origin = cs->getExtensionByType<OriginGroupExtension>()->Origin.getValue();
if (!origin) {
std::cerr << "Origin feature not found" << std::endl;
return;
}
auto& osub = sub.create_subgraph();
GraphList[origin] = &osub;
get_property(osub, graph_name) = getClusterName(origin);
get_property(osub, graph_graph_attribute)["bgcolor"] = "none";
setGraphLabel(osub, origin);
}
}
void addSubgraphs() {
ParameterGrp::handle depGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/DependencyGraph");
bool CSSubgraphs = depGrp->GetBool("GeoFeatureSubgraphs", true);
if(CSSubgraphs) {
//first build up the coordinate system subgraphs
for (auto objectIt : d->objectArray) {
// do not require an empty inlist (#0003465: Groups breaking dependency graph)
if (objectIt->hasExtension(GeoFeatureGroupExtension::getExtensionClassTypeId()))
recursiveCSSubgraphs(objectIt, nullptr);
}
}
// Internal document objects
for (auto It = d->objectMap.begin(); It != d->objectMap.end();++It)
addExpressionSubgraphIfNeeded(It->second, CSSubgraphs);
// Add external document objects
for (auto It = d->objectMap.begin(); It != d->objectMap.end();++It) {
std::vector<DocumentObject*> OutList = It->second->getOutList();
for (std::vector<DocumentObject*>::const_iterator It2=OutList.begin();It2!=OutList.end();++It2) {
if (*It2) {
std::map<std::string,Vertex>::const_iterator item = GlobalVertexList.find(getId(*It2));
if (item == GlobalVertexList.end())
addExpressionSubgraphIfNeeded(*It2, CSSubgraphs);
}
}
}
}
// Filling up the adjacency List
void buildAdjacencyList() {
ParameterGrp::handle depGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/DependencyGraph");
bool CSSubgraphs = depGrp->GetBool("GeoFeatureSubgraphs", true);
// Add internal document objects
for (auto It = d->objectMap.begin(); It != d->objectMap.end();++It)
add(It->second, It->second->getNameInDocument(), It->second->Label.getValue(), CSSubgraphs);
// Add external document objects
for (auto It = d->objectMap.begin(); It != d->objectMap.end();++It) {
std::vector<DocumentObject*> OutList = It->second->getOutList();
for (std::vector<DocumentObject*>::const_iterator It2=OutList.begin();It2!=OutList.end();++It2) {
if (*It2) {
std::map<std::string,Vertex>::const_iterator item = GlobalVertexList.find(getId(*It2));
if (item == GlobalVertexList.end())
add(*It2,
std::string((*It2)->getDocument()->getName()) + "#" + (*It2)->getNameInDocument(),
std::string((*It2)->getDocument()->getName()) + "#" + (*It2)->Label.getValue(),
CSSubgraphs);
}
}
}
}
void addEdges() {
// Get edge properties for main graph
const boost::property_map<Graph, boost::edge_attribute_t>::type& edgeAttrMap = boost::get(boost::edge_attribute, DepList);
// Track edges between document objects connected by expression dependencies
std::set<std::pair<const DocumentObject*, const DocumentObject*> > existingEdges;
// Add edges between properties
std::set<const DocumentObject*>::const_iterator j = objects.begin();
while (j != objects.end()) {
const DocumentObject * docObj = *j;
// Add expressions and its dependencies
auto expressions = docObj->ExpressionEngine.getExpressions();
auto i = expressions.begin();
while (i != expressions.end()) {
std::set<ObjectIdentifier> deps;
i->second->getIdentifiers(deps);
// Create subgraphs for all documentobjects that it depends on; it will depend on some property there
std::set<ObjectIdentifier>::const_iterator k = deps.begin();
while (k != deps.end()) {
DocumentObject * depObjDoc = k->getDocumentObject();
Edge edge;
bool inserted;
tie(edge, inserted) = add_edge(GlobalVertexList[getId(i->first)], GlobalVertexList[getId(*k)], DepList);
// Add this edge to the set of all expression generated edges
existingEdges.insert(std::make_pair(docObj, depObjDoc));
// Edges between properties should be a bit smaller, and dashed
edgeAttrMap[edge]["arrowsize"] = "0.5";
edgeAttrMap[edge]["style"] = "dashed";
++k;
}
++i;
}
++j;
}
ParameterGrp::handle depGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/DependencyGraph");
bool omitGeoFeatureGroups = depGrp->GetBool("GeoFeatureSubgraphs", true);
// Add edges between document objects
for (auto It = d->objectMap.begin(); It != d->objectMap.end();++It) {
if(omitGeoFeatureGroups) {
//coordinate systems are represented by subgraphs
if(It->second->hasExtension(GeoFeatureGroupExtension::getExtensionClassTypeId()))
continue;
//as well as origins
if(It->second->isDerivedFrom(Origin::getClassTypeId()))
continue;
}
std::map<DocumentObject*, int> dups;
std::vector<DocumentObject*> OutList = It->second->getOutList();
const DocumentObject * docObj = It->second;
for (std::vector<DocumentObject*>::const_iterator It2=OutList.begin();It2!=OutList.end();++It2) {
if (*It2) {
// Count duplicate edges
bool inserted = edge(GlobalVertexList[getId(docObj)], GlobalVertexList[getId(*It2)], DepList).second;
if (inserted) {
dups[*It2]++;
continue;
}
// Skip edge if an expression edge already exists
if (existingEdges.find(std::make_pair(docObj, *It2)) != existingEdges.end())
continue;
// Add edge
Edge edge;
tie(edge, inserted) = add_edge(GlobalVertexList[getId(docObj)], GlobalVertexList[getId(*It2)], DepList);
// Set properties to make arrows go between subgraphs if needed
if (GraphList[docObj])
edgeAttrMap[edge]["ltail"] = getClusterName(docObj);
if (GraphList[*It2])
edgeAttrMap[edge]["lhead"] = getClusterName(*It2);
}
}
// Set labels for duplicate edges
for (std::map<DocumentObject*, int>::const_iterator It2 = dups.begin(); It2 != dups.end(); ++It2) {
Edge e(edge(GlobalVertexList[getId(It->second)], GlobalVertexList[getId(It2->first)], DepList).first);
std::stringstream s;
s << " " << (It2->second + 1) << "x";
edgeAttrMap[e]["label"] = s.str();
}
}
}
typedef std::unordered_multimap<Vertex, Edge> EdgeMap;
void removeEdges(EdgeMap & in_edges,
EdgeMap & out_edges,
std::pair<EdgeMap::iterator, EdgeMap::iterator > i_pair,
std::function<Vertex (const Edge&)> select_vertex) {
auto i = i_pair.first;
while (i != i_pair.second) {
// Remove from in edges in other nodes
auto in_i_pair = in_edges.equal_range(select_vertex(i->second));
auto in_i = in_i_pair.first;
while (in_i != in_i_pair.second) {
if (in_i->second == i->second)
in_i = in_edges.erase(in_i);
else
++in_i;
}
// Remove node from out_edges
i = out_edges.erase(i);
}
}
void markCycles() {
bool changed = true;
std::unordered_set<Vertex> in_use;
EdgeMap in_edges;
EdgeMap out_edges;
// Add all vertices to the in_use set
graph_traits<Graph>::vertex_iterator vi, vi_end;
tie(vi, vi_end) = vertices(DepList);
for (; vi != vi_end; ++vi)
in_use.insert(*vi);
// Add all edges to the in_edges and out_edges multimaps
graph_traits<Graph>::edge_iterator ei, ei_end;
tie(ei, ei_end) = edges(DepList);
for (; ei != ei_end; ++ei) {
in_edges.insert(std::make_pair<Vertex, Edge>(target(*ei, DepList), *ei));
out_edges.insert(std::make_pair<Vertex, Edge>(source(*ei, DepList), *ei));
}
// Go through dependency graph and remove nodes with either no input or output
// A normal DAG without any cycles will get all its edges removed.
// If one or more cycles exist in the graph, there will remain nodes with
// both in and out edges.
while (changed) {
auto uvi = in_use.begin();
auto uvi_end = in_use.end();
// Flag that no changes has occurred so far. If the loop goes through
// without this flag being set to true, we are done.
changed = false;
while (uvi != uvi_end) {
auto i_in_deg_pair = in_edges.equal_range(*uvi);
auto i_out_deg_pair = out_edges.equal_range(*uvi);
if (i_in_deg_pair.first == in_edges.end() && i_out_deg_pair.first == out_edges.end()) {
uvi = in_use.erase(uvi);
continue;
}
// Remove out edges of nodes that don't have a single edge in
if (i_in_deg_pair.first == in_edges.end()) {
removeEdges(in_edges, out_edges, i_out_deg_pair, [&](Edge e) { return target(e, DepList); });
changed = true;
i_out_deg_pair = out_edges.equal_range(*uvi);
}
// Remove in edges of nodes that don't have a single edge out
if (i_out_deg_pair.first == out_edges.end()) {
removeEdges(out_edges, in_edges, i_in_deg_pair, [&](Edge e) { return source(e, DepList); });
changed = true;
}
++uvi;
}
}
// Update colors in graph
const boost::property_map<Graph, boost::edge_attribute_t>::type& edgeAttrMap = boost::get(boost::edge_attribute, DepList);
for (auto ei = out_edges.begin(), ei_end = out_edges.end(); ei != ei_end; ++ei)
edgeAttrMap[ei->second]["color"] = "red";
}
void markOutOfScopeLinks() {
const boost::property_map<Graph, boost::edge_attribute_t>::type& edgeAttrMap = boost::get(boost::edge_attribute, DepList);
for( auto obj : objects) {
std::vector<App::DocumentObject*> invalids;
GeoFeatureGroupExtension::getInvalidLinkObjects(obj, invalids);
//isLinkValid returns true for non-link properties
for(auto linkedObj : invalids) {
auto res = edge(GlobalVertexList[getId(obj)], GlobalVertexList[getId(linkedObj)], DepList);
if(res.second)
edgeAttrMap[res.first]["color"] = "red";
}
}
}
const struct DocumentP* d;
Graph DepList;
int vertex_no;
std::map<std::string, Vertex> LocalVertexList;
std::map<std::string, Vertex> GlobalVertexList;
std::set<const DocumentObject*> objects;
std::map<const DocumentObject*, Graph*> GraphList;
//random color generation
std::mt19937 seed;
std::uniform_int_distribution<int> distribution;
};
GraphCreator g(d);
boost::write_graphviz(out, g.getGraph());
}
//bool _has_cycle_dfs(const DependencyList & g, vertex_t u, default_color_type * color)
//{
// color[u] = gray_color;
// graph_traits < DependencyList >::adjacency_iterator vi, vi_end;
// for (tie(vi, vi_end) = adjacent_vertices(u, g); vi != vi_end; ++vi)
// if (color[*vi] == white_color)
// if (has_cycle_dfs(g, *vi, color))
// return true; // cycle detected, return immediately
// else if (color[*vi] == gray_color) // *vi is an ancestor!
// return true;
// color[u] = black_color;
// return false;
//}
bool Document::checkOnCycle(void)
{/*
std::vector < default_color_type > color(num_vertices(_DepList), white_color);
graph_traits < DependencyList >::vertex_iterator vi, vi_end;
for (tie(vi, vi_end) = vertices(_DepList); vi != vi_end; ++vi)
if (color[*vi] == white_color)
if (_has_cycle_dfs(_DepList, *vi, &color[0]))
return true; */
return false;
}
bool Document::undo(int id)
{
if (d->iUndoMode) {
if(id) {
auto it = mUndoMap.find(id);
if(it == mUndoMap.end())
return false;
if(it->second != d->activeUndoTransaction) {
while(mUndoTransactions.size() && mUndoTransactions.back()!=it->second)
undo(0);
}
}
if (d->activeUndoTransaction)
_commitTransaction(true);
if (mUndoTransactions.empty())
return false;
// redo
d->activeUndoTransaction = new Transaction(mUndoTransactions.back()->getID());
d->activeUndoTransaction->Name = mUndoTransactions.back()->Name;
Base::FlagToggler<bool> flag(d->undoing);
// applying the undo
mUndoTransactions.back()->apply(*this,false);
// save the redo
mRedoMap[d->activeUndoTransaction->getID()] = d->activeUndoTransaction;
mRedoTransactions.push_back(d->activeUndoTransaction);
d->activeUndoTransaction = 0;
mUndoMap.erase(mUndoTransactions.back()->getID());
delete mUndoTransactions.back();
mUndoTransactions.pop_back();
signalUndo(*this);
return true;
}
return false;
}
bool Document::redo(int id)
{
if (d->iUndoMode) {
if(id) {
auto it = mRedoMap.find(id);
if(it == mRedoMap.end())
return false;
while(mRedoTransactions.size() && mRedoTransactions.back()!=it->second)
redo(0);
}
if (d->activeUndoTransaction)
_commitTransaction(true);
assert(mRedoTransactions.size()!=0);
// undo
d->activeUndoTransaction = new Transaction(mRedoTransactions.back()->getID());
d->activeUndoTransaction->Name = mRedoTransactions.back()->Name;
// do the redo
Base::FlagToggler<bool> flag(d->undoing);
mRedoTransactions.back()->apply(*this,true);
mUndoMap[d->activeUndoTransaction->getID()] = d->activeUndoTransaction;
mUndoTransactions.push_back(d->activeUndoTransaction);
d->activeUndoTransaction = 0;
mRedoMap.erase(mRedoTransactions.back()->getID());
delete mRedoTransactions.back();
mRedoTransactions.pop_back();