Debian Codegraph @

src/Gui/DAGView/DAGModel.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /***************************************************************************
3 * Copyright (c) 2015 Thomas Anderson <blobfish[at]gmx.com> *
4 * *
5 * This file is part of the FreeCAD CAx development system. *
6 * *
7 * This library is free software; you can redistribute it and/or *
8 * modify it under the terms of the GNU Library General Public *
9 * License as published by the Free Software Foundation; either *
10 * version 2 of the License, or (at your option) any later version. *
11 * *
12 * This library is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU Library General Public License for more details. *
16 * *
17 * You should have received a copy of the GNU Library General Public *
18 * License along with this library; see the file COPYING.LIB. If not, *
19 * write to the Free Software Foundation, Inc., 59 Temple Place, *
20 * Suite 330, Boston, MA 02111-1307, USA *
21 * *
22 ***************************************************************************/
23
24 #include <boost/graph/topological_sort.hpp>
25 #include <boost_graph_reverse_graph.hpp>
26 #include <memory>
27 #include <QBrush>
28 #include <QColor>
29 #include <QGraphicsPixmapItem>
30 #include <QGraphicsProxyWidget>
31 #include <QGraphicsSceneContextMenuEvent>
32 #include <QGraphicsSceneMouseEvent>
33 #include <QKeyEvent>
34 #include <QMenu>
35 #include <QPainter>
36 #include <QPen>
37 #include <QString>
38 #include <QTimer>
39
40 #include <Base/Console.h>
41 #include <Base/TimeInfo.h>
42 #include <App/Document.h>
43 #include <Gui/Application.h>
44 #include <Gui/BitmapFactory.h>
45 #include <Gui/Document.h>
46 #include <Gui/MainWindow.h>
47 #include <Gui/MenuManager.h>
48 #include <Gui/Selection/Selection.h>
49 #include <Gui/ViewProviderDocumentObject.h>
50
51 #include "DAGModel.h"
52
53
54 using namespace Gui;
55 using namespace DAG;
56 namespace sp = std::placeholders;
57
58 LineEdit::LineEdit(QWidget* parentIn)
59 : QLineEdit(parentIn)
60 {}
61
62 void LineEdit::keyPressEvent(QKeyEvent* eventIn)
63 {
64 if (eventIn->key() == Qt::Key_Escape) {
65 Q_EMIT rejectedSignal();
66 eventIn->accept();
67 return;
68 }
69 if ((eventIn->key() == Qt::Key_Enter) || (eventIn->key() == Qt::Key_Return)) {
70 Q_EMIT acceptedSignal();
71 eventIn->accept();
72 return;
73 }
74
75 QLineEdit::keyPressEvent(eventIn);
76 }
77
78 // I don't think I should have to call invalidate
79 // and definitely not on the whole scene!
80 // if we have performance problems, this will definitely
81 // be something to re-visit. I am not wasting anymore time on
82 // this right now.
83 // this->scene()->invalidate();
84 // this->scene()->invalidate(this->sceneTransform().inverted().mapRect(this->boundingRect()));
85 // update(boundingRect());
86 // note: I haven't tried this again since I turned BSP off.
87
88 Model::Model(QObject* parentIn, const Gui::Document& documentIn)
89 : QGraphicsScene(parentIn)
90 {
91 // turned off BSP as it was giving inconsistent discovery of items
92 // underneath cursor.
93 this->setItemIndexMethod(QGraphicsScene::NoIndex);
94
95 theGraph = std::make_shared<Graph>();
96 graphLink = std::make_shared<GraphLinkContainer>();
97 setupViewConstants();
98
99 graphDirty = false;
100 currentPrehighlight = nullptr;
101
102 ParameterGrp::handle group = App::GetApplication()
103 .GetUserParameter()
104 .GetGroup("BaseApp")
105 ->GetGroup("Preferences")
106 ->GetGroup("DAGView");
107 selectionMode = static_cast<SelectionMode>(group->GetInt("SelectionMode", 0));
108 group->SetInt("SelectionMode", static_cast<int>(selectionMode)); // ensure entry exists.
109
110 QIcon temp(Gui::BitmapFactory().iconFromTheme("dagViewVisible"));
111 visiblePixmapEnabled = temp.pixmap(iconSize, iconSize, QIcon::Normal, QIcon::On);
112 visiblePixmapDisabled = temp.pixmap(iconSize, iconSize, QIcon::Disabled, QIcon::Off);
113
114 QIcon passIcon(Gui::BitmapFactory().iconFromTheme("dagViewPass"));
115 passPixmap = passIcon.pixmap(iconSize, iconSize);
116 QIcon failIcon(Gui::BitmapFactory().iconFromTheme("dagViewFail"));
117 failPixmap = failIcon.pixmap(iconSize, iconSize);
118 QIcon pendingIcon(Gui::BitmapFactory().iconFromTheme("dagViewPending"));
119 pendingPixmap = pendingIcon.pixmap(iconSize, iconSize);
120
121 renameAction = new QAction(this);
122 renameAction->setText(tr("Rename"));
123 renameAction->setStatusTip(tr("Renames the object"));
124 #ifndef Q_OS_MAC
125 renameAction->setShortcut(Qt::Key_F2);
126 #endif
127 connect(renameAction, &QAction::triggered, this, &Model::renameAcceptedSlot);
128
129 editingFinishedAction = new QAction(this);
130 editingFinishedAction->setText(tr("Finish Editing"));
131 editingFinishedAction->setStatusTip(tr("Finishes editing the object"));
132 connect(this->editingFinishedAction, &QAction::triggered, this, &Model::editingFinishedSlot);
133
134 // NOLINTBEGIN
135 connectNewObject = documentIn.signalNewObject.connect(
136 std::bind(&Model::slotNewObject, this, sp::_1)
137 );
138 connectDelObject = documentIn.signalDeletedObject.connect(
139 std::bind(&Model::slotDeleteObject, this, sp::_1)
140 );
141 connectChgObject = documentIn.signalChangedObject.connect(
142 std::bind(&Model::slotChangeObject, this, sp::_1, sp::_2)
143 );
144 connectEdtObject = documentIn.signalInEdit.connect(std::bind(&Model::slotInEdit, this, sp::_1));
145 connectResObject = documentIn.signalResetEdit.connect(
146 std::bind(&Model::slotResetEdit, this, sp::_1)
147 );
148 // NOLINTEND
149
150 for (auto obj : documentIn.getDocument()->getObjects()) {
151 auto vpd = freecad_cast<Gui::ViewProviderDocumentObject*>(documentIn.getViewProvider(obj));
152 if (vpd) {
153 slotNewObject(*vpd);
154 }
155 }
156 }
157
158 Model::~Model()
159 {
160 if (connectNewObject.connected()) {
161 connectNewObject.disconnect();
162 }
163 if (connectDelObject.connected()) {
164 connectDelObject.disconnect();
165 }
166 if (connectChgObject.connected()) {
167 connectChgObject.disconnect();
168 }
169 if (connectEdtObject.connected()) {
170 connectEdtObject.disconnect();
171 }
172 if (connectResObject.connected()) {
173 connectResObject.disconnect();
174 }
175
176 removeAllItems();
177 }
178
179 void Model::setupViewConstants()
180 {
181 ParameterGrp::handle group = App::GetApplication()
182 .GetUserParameter()
183 .GetGroup("BaseApp")
184 ->GetGroup("Preferences")
185 ->GetGroup("DAGView");
186
187 // get font point size.
188 int fontPointSize = group->GetInt("FontPointSize", 0);
189 group->SetInt("FontPointSize", fontPointSize); // ensure entry exists.
190 if (fontPointSize != 0) {
191 QFont tempFont(this->font());
192 tempFont.setPointSize(fontPointSize);
193 this->setFont(tempFont);
194 }
195
196 // get direction
197 direction = group->GetFloat("Direction", 1.0);
198 if (direction != -1.0 && direction != 1.0) {
199 direction = 1.0;
200 }
201 group->SetFloat("Direction", direction); // ensure entry exists.
202
203 QFontMetrics fontMetric(this->font());
204 fontHeight = fontMetric.height();
205 verticalSpacing = 1.0;
206 rowHeight = (fontHeight + 2.0 * verticalSpacing) * direction; // pixel space top and bottom.
207 iconSize = fontHeight;
208 pointSize = fontHeight / 2.0;
209 pointSpacing = pointSize;
210 pointToIcon = iconSize;
211 iconToIcon = iconSize * 0.25;
212 iconToText = iconSize / 2.0;
213 rowPadding = fontHeight;
214 backgroundBrushes = {this->palette().base(), this->palette().alternateBase()};
215 forgroundBrushes = {
216 QBrush(Qt::red),
217 QBrush(Qt::darkRed),
218 QBrush(Qt::green),
219 QBrush(Qt::darkGreen),
220 QBrush(Qt::blue),
221 QBrush(Qt::darkBlue),
222 QBrush(Qt::cyan),
223 QBrush(Qt::darkCyan),
224 QBrush(Qt::magenta),
225 QBrush(Qt::darkMagenta),
226 // QBrush(Qt::yellow), can't read
227 QBrush(Qt::darkYellow),
228 QBrush(Qt::gray),
229 QBrush(Qt::darkGray),
230 QBrush(Qt::lightGray)
231 }; // reserve some of the these for highlight stuff.
232 }
233
234 void Model::slotNewObject(const ViewProviderDocumentObject& VPDObjectIn)
235 {
236 Vertex virginVertex = boost::add_vertex(*theGraph);
237
238 addVertexItemsToScene(virginVertex);
239
240 GraphLinkRecord virginRecord;
241 virginRecord.DObject = VPDObjectIn.getObject();
242 virginRecord.VPDObject = &VPDObjectIn;
243 virginRecord.rectItem = (*theGraph)[virginVertex].rectangle.get();
244 virginRecord.uniqueName = std::string(virginRecord.DObject->getNameInDocument());
245 virginRecord.vertex = virginVertex;
246 graphLink->insert(virginRecord);
247
248 // setup rectangle.
249 auto rectangle = (*theGraph)[virginVertex].rectangle.get();
250 rectangle->setEditingBrush(QBrush(Qt::yellow));
251
252 auto icon = (*theGraph)[virginVertex].icon;
253 icon->setPixmap(VPDObjectIn.getIcon().pixmap(iconSize, iconSize));
254 (*theGraph)[virginVertex].stateIcon->setPixmap(passPixmap);
255 (*theGraph)[virginVertex].text->setFont(this->font());
256 // NOLINTBEGIN
257 (*theGraph)[virginVertex].connChangeIcon
258 = const_cast<Gui::ViewProviderDocumentObject&>(VPDObjectIn)
259 .signalChangeIcon.connect(
260 std::bind(&Model::slotChangeIcon, this, boost::cref(VPDObjectIn), icon)
261 );
262 // NOLINTEND
263
264 graphDirty = true;
265 lastAddedVertex = Graph::null_vertex();
266 }
267
268 void Model::slotChangeIcon(
269 const ViewProviderDocumentObject& VPDObjectIn,
270 std::shared_ptr<QGraphicsPixmapItem> icon
271 )
272 {
273 icon->setPixmap(VPDObjectIn.getIcon().pixmap(iconSize, iconSize));
274 this->invalidate();
275 }
276
277 void Model::slotDeleteObject(const ViewProviderDocumentObject& VPDObjectIn)
278 {
279 Vertex vertex = findRecord(&VPDObjectIn, *graphLink).vertex;
280
281 // remove items from scene.
282 removeVertexItemsFromScene(vertex);
283
284 // remove connector items
285 auto outRange = boost::out_edges(vertex, *theGraph);
286 for (auto outEdgeIt = outRange.first; outEdgeIt != outRange.second; ++outEdgeIt) {
287 this->removeItem((*theGraph)[*outEdgeIt].connector.get());
288 }
289 auto inRange = boost::in_edges(vertex, *theGraph);
290 for (auto inEdgeIt = inRange.first; inEdgeIt != inRange.second; ++inEdgeIt) {
291 this->removeItem((*theGraph)[*inEdgeIt].connector.get());
292 }
293
294 if (vertex == lastAddedVertex) {
295 lastAddedVertex = Graph::null_vertex();
296 }
297
298 (*theGraph)[vertex].connChangeIcon.disconnect();
299
300 // remove the actual vertex.
301 boost::clear_vertex(vertex, *theGraph);
302 boost::remove_vertex(vertex, *theGraph);
303
304 eraseRecord(&VPDObjectIn, *graphLink);
305 graphDirty = true;
306 }
307
308 void Model::slotChangeObject(const ViewProviderDocumentObject& VPDObjectIn, const App::Property& propertyIn)
309 {
310 std::string name("Empty Name");
311 if (propertyIn.hasName()) {
312 name = propertyIn.getName();
313 }
314 assert(!name.empty());
315
316 // std::cout << std::endl << "inside changed object." << std::endl <<
317 // "Property name is: " << name << std::endl <<
318 // "Property type is: " << propertyIn.getTypeId().getName() << std::endl << std::endl;
319
320 // renaming of objects.
321 if (std::string("Label") == name) {
322 if (hasRecord(&VPDObjectIn, *graphLink)) {
323 const GraphLinkRecord& record = findRecord(&VPDObjectIn, *graphLink);
324 auto text = (*theGraph)[record.vertex].text.get();
325 text->setPlainText(QString::fromUtf8(record.DObject->Label.getValue()));
326 }
327 }
328 else if (propertyIn.isDerivedFrom<App::PropertyLinkBase>()) {
329 if (hasRecord(&VPDObjectIn, *graphLink)) {
330 const GraphLinkRecord& record = findRecord(&VPDObjectIn, *graphLink);
331 boost::clear_vertex(record.vertex, *theGraph);
332 graphDirty = true;
333 }
334 }
335 }
336
337 void Model::slotInEdit(const ViewProviderDocumentObject& VPDObjectIn)
338 {
339 RectItem* rect = (*theGraph)[findRecord(&VPDObjectIn, *graphLink).vertex].rectangle.get();
340 rect->editingStart();
341 this->invalidate();
342 }
343
344 void Model::slotResetEdit(const ViewProviderDocumentObject& VPDObjectIn)
345 {
346 RectItem* rect = (*theGraph)[findRecord(&VPDObjectIn, *graphLink).vertex].rectangle.get();
347 rect->editingFinished();
348 this->invalidate();
349 }
350
351 void Model::selectionChanged(const SelectionChanges& msg)
352 {
353 // TODO: note that treeview uses set selection which sends a message with just a document name
354 // and no object name. Have to explore further.
355
356 auto getAllEdges = [this](const Vertex& vertexIn) {
357 // is there really no function to get both in and out edges?
358 std::vector<Edge> out;
359
360 OutEdgeIterator outIt, outItEnd;
361 for (boost::tie(outIt, outItEnd) = boost::out_edges(vertexIn, *theGraph); outIt != outItEnd;
362 ++outIt) {
363 out.push_back(*outIt);
364 }
365
366 InEdgeIterator inIt, inItEnd;
367 for (boost::tie(inIt, inItEnd) = boost::in_edges(vertexIn, *theGraph); inIt != inItEnd;
368 ++inIt) {
369 out.push_back(*inIt);
370 }
371
372 return out;
373 };
374
375 auto highlightConnectorOn = [this, getAllEdges](const Vertex& vertexIn) {
376 QColor color = (*theGraph)[vertexIn].text->defaultTextColor();
377 QPen pen(color);
378 pen.setWidth(3.0);
379 auto edges = getAllEdges(vertexIn);
380 for (auto edge : edges) {
381 (*theGraph)[edge].connector->setPen(pen);
382 (*theGraph)[edge].connector->setZValue(1.0);
383 }
384 };
385
386 auto highlightConnectorOff = [this, getAllEdges](const Vertex& vertexIn) {
387 auto edges = getAllEdges(vertexIn);
388 for (auto edge : edges) {
389 (*theGraph)[edge].connector->setPen(QPen());
390 (*theGraph)[edge].connector->setZValue(0.0);
391 }
392 };
393
394 // lambda for clearing selections.
395 auto clearSelection = [this, highlightConnectorOff]() {
396 BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph)
397 {
398 RectItem* rect = (*theGraph)[currentVertex].rectangle.get();
399 assert(rect);
400 rect->selectionOff();
401 highlightConnectorOff(currentVertex);
402 }
403 };
404
405 // lambda for getting rectangle.
406 auto getRectangle = [this](const char* in) {
407 assert(in);
408 std::string name(in);
409 assert(!name.empty());
410 const GraphLinkRecord& record = findRecord(name, *graphLink);
411 RectItem* rect = (*theGraph)[record.vertex].rectangle.get();
412 assert(rect);
413 return rect;
414 };
415
416 if (msg.Type == SelectionChanges::AddSelection) {
417 if (msg.pObjectName) {
418 RectItem* rect = getRectangle(msg.pObjectName);
419 rect->selectionOn();
420 highlightConnectorOn(findRecord(std::string(msg.pObjectName), *graphLink).vertex);
421 }
422 }
423 else if (msg.Type == SelectionChanges::RmvSelection) {
424 if (msg.pObjectName) {
425 RectItem* rect = getRectangle(msg.pObjectName);
426 rect->selectionOff();
427 highlightConnectorOff(findRecord(std::string(msg.pObjectName), *graphLink).vertex);
428 }
429 }
430 else if (msg.Type == SelectionChanges::SetSelection) {
431 clearSelection();
432
433 auto selections = Gui::Selection().getSelection(msg.pDocName);
434 for (const auto& selection : selections) {
435 assert(selection.FeatName);
436 RectItem* rect = getRectangle(selection.FeatName);
437 rect->selectionOn();
438 highlightConnectorOn(findRecord(selection.FeatName, *graphLink).vertex);
439 }
440 }
441 else if (msg.Type == SelectionChanges::ClrSelection) {
442 clearSelection();
443 }
444
445 this->invalidate();
446 }
447
448 void Model::awake()
449 {
450 if (graphDirty) {
451 updateSlot();
452 this->invalidate();
453 }
454 updateStates();
455 }
456
457 void Model::updateSlot()
458 {
459 // empty outList means it is a root.
460 // empty inList means it is a leaf.
461
462 // NOTE: some of the following loops can/should be combined
463 // for speed. Not doing yet, as I want a simple algorithm until
464 // a more complete picture is formed.
465
466 Base::TimeElapsed startTime;
467
468 // here we will cycle through the graph updating edges.
469 // we have to do this first and in isolation because everything is dependent on an up to date graph.
470 BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph)
471 {
472 const App::DocumentObject* currentDObject = findRecord(currentVertex, *graphLink).DObject;
473 std::vector<App::DocumentObject*> otherDObjects = currentDObject->getOutList();
474 for (auto& currentOtherDObject : otherDObjects) {
475 if (!hasRecord(currentOtherDObject, *graphLink)) {
476 continue;
477 }
478 Vertex otherVertex = findRecord(currentOtherDObject, *graphLink).vertex;
479 bool result;
480 Edge edge;
481 boost::tie(edge, result) = boost::add_edge(currentVertex, otherVertex, *theGraph);
482 if (result) {
483 (*theGraph)[edge].connector = std::make_shared<QGraphicsPathItem>();
484 (*theGraph)[edge].connector->setZValue(0.0);
485 }
486 }
487 }
488
489 BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph)
490 {
491 if (!(*theGraph)[currentVertex].rectangle->scene()) {
492 addVertexItemsToScene(currentVertex);
493 }
494 }
495
496 // sync scene items for graph edge.
497 BGL_FORALL_EDGES(currentEdge, *theGraph, Graph)
498 {
499 if (!(*theGraph)[currentEdge].connector->scene()) {
500 this->addItem((*theGraph)[currentEdge].connector.get());
501 }
502 }
503
504 indexVerticesEdges();
505 Path sorted;
506 try {
507 boost::topological_sort(*theGraph, std::back_inserter(sorted));
508 }
509 catch (const boost::not_a_dag&) {
510 Base::Console().error("not a dag exception in DAGView::Model::updateSlot()\n");
511 // do not continuously report an error for cyclic graphs
512 graphDirty = false;
513 return;
514 }
515 // index the vertices in sort order.
516 int tempIndex = 0;
517 for (const auto& currentVertex : sorted) {
518 (*theGraph)[currentVertex].topoSortIndex = tempIndex;
519 tempIndex++;
520 }
521
522 // draw graph(nodes and connectors).
523 int currentRow = 0;
524 int currentColumn = -1; // we know first column is going to be root so will be kicked up to 0.
525 int maxColumn = currentColumn; // used for determining offset of icons and text.
526 qreal maxTextLength = 0;
527 for (const auto& currentVertex : sorted) {
528 if (boost::out_degree(currentVertex, *theGraph) == 0) {
529 currentColumn = 0;
530 }
531 else {
532 // loop parents and find an acceptable column.
533 int farthestParentIndex = sorted.size();
534 ColumnMask columnMask;
535 Path parentVertices;
536 OutEdgeIterator it, itEnd;
537 boost::tie(it, itEnd) = boost::out_edges(currentVertex, *theGraph);
538 for (; it != itEnd; ++it) {
539 // std::cout << std::endl << "name: " << findRecord(currentVertex,
540 // *graphLink).DObject->Label.getValue() << std::endl;
541
542 Vertex target = boost::target(*it, *theGraph);
543 parentVertices.push_back(target);
544 int currentParentIndex = (*theGraph)[target].topoSortIndex;
545 if (currentParentIndex < farthestParentIndex) {
546 Path::const_iterator start = sorted.begin() + currentParentIndex + 1; // 1 after
547 Path::const_iterator end = sorted.begin()
548 + (*theGraph)[currentVertex].topoSortIndex; // 1 before
549 Path::const_iterator it;
550 for (it = start; it != end; ++it) {
551 // std::cout << " parent: " << findRecord(*it,
552 // *graphLink).DObject->Label.getValue() << std::endl;
553
554 columnMask |= (*theGraph)[*it].column;
555 }
556 farthestParentIndex = currentParentIndex;
557 }
558 }
559
560 // have to create a smaller subset to get through std::cout.
561 // std::bitset<8> testSet;
562 // for (unsigned int index = 0; index < testSet.size(); ++index)
563 // testSet[index]= columnMask[index];
564 // std::cout << "mask for " << findRecord(currentVertex,
565 // *graphLink).DObject->Label.getValue() << " " <<
566 // testSet.to_string() << std::endl;
567
568 // now we should have a mask representing the columns that are being used.
569 // this is from the lowest parent, in the topo sort, to last entry.
570
571 // try to use the same column as one of the parents.(*theGraph)[*it].column
572 int destinationColumn = 0; // default to first column
573 for (const auto& currentParent : parentVertices) {
574 if (((*theGraph)[currentParent].column & columnMask).none()) {
575 // go with first visible parent for now.
576 destinationColumn = static_cast<int>(
577 columnFromMask((*theGraph)[currentParent].column)
578 );
579 break;
580 }
581 }
582 // if destination not valid look for the first open column.
583 if (columnMask.test(destinationColumn)) {
584 for (std::size_t index = 0; index < columnMask.size(); ++index) {
585 if (!columnMask.test(index)) {
586 destinationColumn = index;
587 break;
588 }
589 }
590 }
591
592 currentColumn = destinationColumn;
593 }
594
595 assert(currentColumn < static_cast<int>(ColumnMask().size())); // temp limitation.
596
597 maxColumn = std::max(currentColumn, maxColumn);
598 QBrush currentBrush(forgroundBrushes.at(currentColumn % forgroundBrushes.size()));
599
600 auto rectangle = (*theGraph)[currentVertex].rectangle.get();
601 rectangle->setRect(-rowPadding, 0.0, rowPadding, rowHeight); // calculate actual length later.
602 rectangle->setTransform(QTransform::fromTranslate(0, rowHeight * currentRow));
603 rectangle->setBackgroundBrush(backgroundBrushes[currentRow % backgroundBrushes.size()]);
604
605 auto point = (*theGraph)[currentVertex].point.get();
606 point->setRect(0.0, 0.0, pointSize, pointSize);
607 point->setTransform(
608 QTransform::fromTranslate(
609 pointSpacing * static_cast<qreal>(currentColumn),
610 rowHeight * currentRow + rowHeight / 2.0 - pointSize / 2.0
611 )
612 );
613 point->setBrush(currentBrush);
614
615 qreal cheat = 0.0;
616 if (direction == -1) {
617 cheat = rowHeight;
618 }
619
620 auto visiblePixmap = (*theGraph)[currentVertex].visibleIcon.get();
621 visiblePixmap->setTransform(
622 QTransform::fromTranslate(0.0, rowHeight * currentRow + cheat)
623 ); // calculate x location later.
624
625 auto statePixmap = (*theGraph)[currentVertex].stateIcon.get();
626 statePixmap->setTransform(
627 QTransform::fromTranslate(0.0, rowHeight * currentRow + cheat)
628 ); // calculate x location later.
629
630 auto pixmap = (*theGraph)[currentVertex].icon.get();
631 pixmap->setTransform(
632 QTransform::fromTranslate(0.0, rowHeight * currentRow + cheat)
633 ); // calculate x location later.
634
635 auto text = (*theGraph)[currentVertex].text.get();
636 text->setPlainText(
637 QString::fromUtf8(findRecord(currentVertex, *graphLink).DObject->Label.getValue())
638 );
639 text->setDefaultTextColor(currentBrush.color());
640 maxTextLength = std::max(maxTextLength, text->boundingRect().width());
641 text->setTransform(
642 QTransform::fromTranslate(0.0, rowHeight * currentRow - verticalSpacing * 2.0 + cheat)
643 ); // calculate x location later.
644 (*theGraph)[currentVertex].lastVisibleState = VisibilityState::None; // force visual update
645 // for color.
646
647 // store column and row int the graph. use for connectors later.
648 (*theGraph)[currentVertex].row = currentRow;
649 (*theGraph)[currentVertex].column.reset().set((currentColumn));
650
651 // our list is topo sorted so all dependents should be located, so we can build the
652 // connectors. will have some more logic for connector path, simple for now.
653 qreal currentX = pointSpacing * currentColumn + pointSize / 2.0;
654 qreal currentY = rowHeight * currentRow + rowHeight / 2.0;
655 OutEdgeIterator it, itEnd;
656 boost::tie(it, itEnd) = boost::out_edges(currentVertex, *theGraph);
657 for (; it != itEnd; ++it) {
658 Vertex target = boost::target(*it, *theGraph);
659 qreal dependentX = pointSpacing
660 * static_cast<int>(columnFromMask((*theGraph)[target].column))
661 + pointSize / 2.0; // on center.
662 columnFromMask((*theGraph)[target].column);
663 qreal dependentY = rowHeight * (*theGraph)[target].row + rowHeight / 2.0;
664
665 QGraphicsPathItem* pathItem = (*theGraph)[*it].connector.get();
666 pathItem->setBrush(Qt::NoBrush);
667 QPainterPath path;
668 path.moveTo(currentX, currentY);
669 if (currentColumn == static_cast<int>(columnFromMask((*theGraph)[target].column))) {
670 path.lineTo(currentX, dependentY); // straight connector in y.
671 }
672 else {
673 // connector with bend.
674 qreal radius = pointSpacing / 1.9; // no zero length line.
675
676 path.lineTo(currentX, dependentY + radius * direction);
677
678 qreal yPosition;
679 if (direction == -1.0) {
680 yPosition = dependentY - 2.0 * radius;
681 }
682 else {
683 yPosition = dependentY;
684 }
685 qreal width = 2.0 * radius;
686 qreal height = width;
687 if (dependentX > currentX) // radius to the right.
688 {
689 QRectF arcRect(currentX, yPosition, width, height);
690 path.arcTo(arcRect, 180.0, 90.0 * -direction);
691 }
692 else // radius to the left.
693 {
694 QRectF arcRect(currentX - 2.0 * radius, yPosition, width, height);
695 path.arcTo(arcRect, 0.0, 90.0 * direction);
696 }
697 path.lineTo(dependentX, dependentY);
698 }
699 pathItem->setPath(path);
700 }
701
702 currentRow++;
703 }
704
705 // now that we have the graph drawn we know where to place icons and text.
706 qreal columnSpacing = (maxColumn * pointSpacing);
707 for (const auto& currentVertex : sorted) {
708 qreal localCurrentX = columnSpacing;
709 localCurrentX += pointToIcon;
710 auto visiblePixmap = (*theGraph)[currentVertex].visibleIcon.get();
711 QTransform visibleIconTransform = QTransform::fromTranslate(localCurrentX, 0.0);
712 visiblePixmap->setTransform(visiblePixmap->transform() * visibleIconTransform);
713
714 localCurrentX += iconSize + iconToIcon;
715 auto statePixmap = (*theGraph)[currentVertex].stateIcon.get();
716 QTransform stateIconTransform = QTransform::fromTranslate(localCurrentX, 0.0);
717 statePixmap->setTransform(statePixmap->transform() * stateIconTransform);
718
719 localCurrentX += iconSize + iconToIcon;
720 auto pixmap = (*theGraph)[currentVertex].icon.get();
721 QTransform iconTransform = QTransform::fromTranslate(localCurrentX, 0.0);
722 pixmap->setTransform(pixmap->transform() * iconTransform);
723
724 localCurrentX += iconSize + iconToText;
725 auto text = (*theGraph)[currentVertex].text.get();
726 QTransform textTransform = QTransform::fromTranslate(localCurrentX, 0.0);
727 text->setTransform(text->transform() * textTransform);
728
729 auto rectangle = (*theGraph)[currentVertex].rectangle.get();
730 QRectF rect = rectangle->rect();
731 rect.setWidth(localCurrentX + maxTextLength + 2.0 * rowPadding);
732 rectangle->setRect(rect);
733 }
734
735 // Modeling_Challenge_Casting_ta4 with 59 features: "Initialize DAG View time: 0.007"
736 // keeping algo simple with extra loops only added 0.002 to above number.
737 // std::cout << "Initialize DAG View time: " << Base::TimeElapsed::diffTimeF(startTime,
738 // Base::TimeElapsed()) << std::endl;
739
740 // outputGraphviz<Graph>(*theGraph, "./graphviz.dot");
741 graphDirty = false;
742 }
743
744 void Model::indexVerticesEdges()
745 {
746 std::size_t index = 0;
747
748 // index vertices.
749 VertexIterator it, itEnd;
750 for (boost::tie(it, itEnd) = boost::vertices(*theGraph); it != itEnd; ++it) {
751 boost::put(boost::vertex_index, *theGraph, *it, index);
752 index++;
753 }
754
755 // index edges. didn't need this when I put it in.
756 EdgeIterator eit, eitEnd;
757 index = 0;
758 for (boost::tie(eit, eitEnd) = boost::edges(*theGraph); eit != eitEnd; ++eit) {
759 boost::put(boost::edge_index, *theGraph, *eit, index);
760 index++;
761 }
762 }
763
764 void Model::removeAllItems()
765 {
766 if (theGraph) {
767 BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph)
768 removeVertexItemsFromScene(currentVertex);
769
770 BGL_FORALL_EDGES(currentEdge, *theGraph, Graph)
771 {
772 if ((*theGraph)[currentEdge].connector->scene()) {
773 this->removeItem((*theGraph)[currentEdge].connector.get());
774 }
775 }
776 }
777 }
778
779 void Model::addVertexItemsToScene(const Gui::DAG::Vertex& vertexIn)
780 {
781 // these are either all in or all out. so just test rectangle.
782 if ((*theGraph)[vertexIn].rectangle->scene()) { // already in the scene.
783 return;
784 }
785 this->addItem((*theGraph)[vertexIn].rectangle.get());
786 this->addItem((*theGraph)[vertexIn].point.get());
787 this->addItem((*theGraph)[vertexIn].visibleIcon.get());
788 this->addItem((*theGraph)[vertexIn].stateIcon.get());
789 this->addItem((*theGraph)[vertexIn].icon.get());
790 this->addItem((*theGraph)[vertexIn].text.get());
791 }
792
793 void Model::removeVertexItemsFromScene(const Gui::DAG::Vertex& vertexIn)
794 {
795 // these are either all in or all out. so just test rectangle.
796 if (!(*theGraph)[vertexIn].rectangle->scene()) { // not in the scene.
797 return;
798 }
799 this->removeItem((*theGraph)[vertexIn].rectangle.get());
800 this->removeItem((*theGraph)[vertexIn].point.get());
801 this->removeItem((*theGraph)[vertexIn].visibleIcon.get());
802 this->removeItem((*theGraph)[vertexIn].stateIcon.get());
803 this->removeItem((*theGraph)[vertexIn].text.get());
804 this->removeItem((*theGraph)[vertexIn].icon.get());
805 }
806
807 void Model::updateStates()
808 {
809 // not sure I want to use the same pixmap merge for failing feature icons.
810 // thinking maybe red background or another column of icons for state?
811
812 BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph)
813 {
814 const GraphLinkRecord& record = findRecord(currentVertex, *graphLink);
815
816 auto visiblePixmap = (*theGraph)[currentVertex].visibleIcon.get();
817 VisibilityState currentVisibilityState = (record.VPDObject->isShow())
818 ? (VisibilityState::On)
819 : (VisibilityState::Off);
820 if ((currentVisibilityState != (*theGraph)[currentVertex].lastVisibleState)
821 || ((*theGraph)[currentVertex].lastVisibleState == VisibilityState::None)) {
822 if (record.VPDObject->isShow()) {
823 visiblePixmap->setPixmap(visiblePixmapEnabled);
824 }
825 else {
826 visiblePixmap->setPixmap(visiblePixmapDisabled);
827 }
828 (*theGraph)[currentVertex].lastVisibleState = currentVisibilityState;
829 }
830
831 FeatureState currentFeatureState = FeatureState::Pass;
832 if (record.DObject->isError()) {
833 currentFeatureState = FeatureState::Fail;
834 }
835 else if ((record.DObject->mustExecute() == 1)) {
836 currentFeatureState = FeatureState::Pending;
837 }
838 if (currentFeatureState != (*theGraph)[currentVertex].lastFeatureState) {
839 if (currentFeatureState == FeatureState::Pass) {
840 (*theGraph)[currentVertex].stateIcon->setPixmap(passPixmap);
841 }
842 else {
843 if (currentFeatureState == FeatureState::Fail) {
844 (*theGraph)[currentVertex].stateIcon->setPixmap(failPixmap);
845 }
846 else {
847 (*theGraph)[currentVertex].stateIcon->setPixmap(pendingPixmap);
848 }
849 }
850 (*theGraph)[currentVertex].stateIcon->setToolTip(
851 QString::fromLatin1(record.DObject->getStatusString())
852 );
853 (*theGraph)[currentVertex].lastFeatureState = currentFeatureState;
854 }
855 }
856 }
857
858 std::size_t Model::columnFromMask(const ColumnMask& maskIn)
859 {
860 std::string maskString = maskIn.to_string();
861 return maskString.size() - maskString.find('1') - 1;
862 }
863
864 RectItem* Model::getRectFromPosition(const QPointF& position)
865 {
866 RectItem* rect = nullptr;
867 auto theItems = this->items(position, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder);
868 for (auto currentItem : theItems) {
869 rect = dynamic_cast<RectItem*>(currentItem);
870 if (rect) {
871 break;
872 }
873 }
874
875 return rect;
876 }
877
878 void Model::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
879 {
880 auto clearPrehighlight = [this]() {
881 if (currentPrehighlight) {
882 currentPrehighlight->preHighlightOff();
883 currentPrehighlight = nullptr;
884 }
885 };
886
887 RectItem* rect = getRectFromPosition(event->scenePos());
888 if (!rect) {
889 clearPrehighlight();
890 return;
891 }
892
893 if (rect == currentPrehighlight) {
894 return;
895 }
896
897 clearPrehighlight();
898 rect->preHighlightOn();
899 currentPrehighlight = rect;
900 invalidate();
901
902 QGraphicsScene::mouseMoveEvent(event);
903 }
904
905 void Model::mousePressEvent(QGraphicsSceneMouseEvent* event)
906 {
907 auto goShiftSelect = [this, event]() {
908 QPointF currentPickPoint = event->scenePos();
909 QGraphicsLineItem intersectionLine(QLineF(lastPick, currentPickPoint));
910 QList<QGraphicsItem*> selection = collidingItems(&intersectionLine);
911 for (auto currentItem : selection) {
912 auto rect = dynamic_cast<RectItem*>(currentItem);
913 if (!rect) {
914 continue;
915 }
916 const GraphLinkRecord& selectionRecord = findRecord(rect, *graphLink);
917 Gui::Selection().addSelection(
918 selectionRecord.DObject->getDocument()->getName(),
919 selectionRecord.DObject->getNameInDocument()
920 );
921 }
922 };
923
924 auto toggleSelect = [](const App::DocumentObject* dObjectIn, RectItem* rectIn) {
925 if (rectIn->isSelected()) {
926 Gui::Selection().rmvSelection(
927 dObjectIn->getDocument()->getName(),
928 dObjectIn->getNameInDocument()
929 );
930 }
931 else {
932 Gui::Selection().addSelection(
933 dObjectIn->getDocument()->getName(),
934 dObjectIn->getNameInDocument()
935 );
936 }
937 };
938
939 if (proxy) {
940 renameAcceptedSlot();
941 }
942
943 if (event->button() == Qt::LeftButton) {
944 RectItem* rect = getRectFromPosition(event->scenePos());
945 if (rect) {
946 const GraphLinkRecord& record = findRecord(rect, *graphLink);
947
948 // don't like that I am doing this again here after getRectFromPosition call.
949 QGraphicsItem* item = itemAt(event->scenePos(), QTransform());
950 auto pixmapItem = dynamic_cast<QGraphicsPixmapItem*>(item);
951 if (pixmapItem && (pixmapItem == (*theGraph)[record.vertex].visibleIcon.get())) {
952 // get all selections, but for now just the current pick.
953 if ((*theGraph)[record.vertex].lastVisibleState == VisibilityState::Off) {
954 const_cast<ViewProviderDocumentObject*>(record.VPDObject)->show(); // const hack
955 }
956 else {
957 const_cast<ViewProviderDocumentObject*>(record.VPDObject)->hide(); // const hack
958 }
959
960 return;
961 }
962
963 const App::DocumentObject* dObject = record.DObject;
964 if (selectionMode == SelectionMode::Single) {
965 if (event->modifiers() & Qt::ControlModifier) {
966 toggleSelect(dObject, rect);
967 }
968 else if ((event->modifiers() & Qt::ShiftModifier) && lastPickValid) {
969 goShiftSelect();
970 }
971 else {
972 Gui::Selection().clearSelection(dObject->getDocument()->getName());
973 Gui::Selection().addSelection(
974 dObject->getDocument()->getName(),
975 dObject->getNameInDocument()
976 );
977 }
978 }
979 if (selectionMode == SelectionMode::Multiple) {
980 if ((event->modifiers() & Qt::ShiftModifier) && lastPickValid) {
981 goShiftSelect();
982 }
983 else {
984 toggleSelect(dObject, rect);
985 }
986 }
987 lastPickValid = true;
988 lastPick = event->scenePos();
989 }
990 else {
991 lastPickValid = false;
992 Gui::Selection().clearSelection(); // get document name?
993 }
994 }
995
996 QGraphicsScene::mousePressEvent(event);
997 }
998
999 void Model::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event)
1000 {
1001 if (event->button() == Qt::LeftButton) {
1002 auto selections = getAllSelected();
1003 if (selections.size() != 1) {
1004 return;
1005 }
1006 const GraphLinkRecord& record = findRecord(selections.front(), *graphLink);
1007 Gui::Document* doc = Gui::Application::Instance->getDocument(record.DObject->getDocument());
1008 MDIView* view = doc->getActiveView();
1009 if (view) {
1010 getMainWindow()->setActiveWindow(view);
1011 }
1012 const_cast<ViewProviderDocumentObject*>(record.VPDObject)->doubleClicked();
1013 }
1014
1015 QGraphicsScene::mouseDoubleClickEvent(event);
1016 }
1017
1018
1019 std::vector<Gui::DAG::Vertex> Model::getAllSelected()
1020 {
1021 std::vector<Gui::DAG::Vertex> out;
1022
1023 BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph)
1024 {
1025 if ((*theGraph)[currentVertex].rectangle->isSelected()) {
1026 out.push_back(currentVertex);
1027 }
1028 }
1029
1030 return out;
1031 }
1032
1033 void Model::contextMenuEvent(QGraphicsSceneContextMenuEvent* event)
1034 {
1035 RectItem* rect = getRectFromPosition(event->scenePos());
1036 if (rect) {
1037 const GraphLinkRecord& record = findRecord(rect, *graphLink);
1038
1039 // don't like that I am doing this again here after getRectFromPosition call.
1040 QGraphicsItem* item = itemAt(event->scenePos(), QTransform());
1041 auto pixmapItem = dynamic_cast<QGraphicsPixmapItem*>(item);
1042 if (pixmapItem && (pixmapItem == (*theGraph)[record.vertex].visibleIcon.get())) {
1043 visiblyIsolate(record.vertex);
1044 return;
1045 }
1046
1047 if (!rect->isSelected()) {
1048 Gui::Selection().clearSelection(record.DObject->getDocument()->getName());
1049 Gui::Selection().addSelection(
1050 record.DObject->getDocument()->getName(),
1051 record.DObject->getNameInDocument()
1052 );
1053 lastPickValid = true;
1054 lastPick = event->scenePos();
1055 }
1056
1057 MenuItem view;
1058 Gui::Application::Instance->setupContextMenu("Tree", &view);
1059 QMenu contextMenu;
1060 MenuManager::getInstance()->setupContextMenu(&view, contextMenu);
1061
1062 // actions for only one selection.
1063 std::vector<Gui::DAG::Vertex> selections = getAllSelected();
1064 if (selections.size() == 1) {
1065 contextMenu.addAction(renameAction);
1066 // when we have only one selection then we know it is rect from above.
1067 if (!rect->isEditing()) {
1068 const_cast<Gui::ViewProviderDocumentObject*>(record.VPDObject)
1069 ->setupContextMenu(&contextMenu, this, SLOT(editingStartSlot())); // const hack.
1070 }
1071 else {
1072 contextMenu.addAction(editingFinishedAction);
1073 }
1074 }
1075
1076 if (!contextMenu.actions().isEmpty()) {
1077 contextMenu.exec(event->screenPos());
1078 }
1079 }
1080
1081 QGraphicsScene::contextMenuEvent(event);
1082 }
1083
1084 void Model::onRenameSlot()
1085 {
1086 assert(!proxy);
1087 std::vector<Gui::DAG::Vertex> selections = getAllSelected();
1088 assert(selections.size() == 1);
1089
1090 auto lineEdit = new LineEdit();
1091 auto text = (*theGraph)[selections.front()].text.get();
1092 lineEdit->setText(text->toPlainText());
1093 connect(lineEdit, &LineEdit::acceptedSignal, this, &Model::renameAcceptedSlot);
1094 connect(lineEdit, &LineEdit::rejectedSignal, this, &Model::renameRejectedSlot);
1095
1096 proxy = this->addWidget(lineEdit);
1097 proxy->setGeometry(text->sceneBoundingRect());
1098
1099 lineEdit->selectAll();
1100 QTimer::singleShot(0, lineEdit, qOverload<>(&QLineEdit::setFocus));
1101 }
1102
1103 void Model::renameAcceptedSlot()
1104 {
1105 assert(proxy);
1106
1107 std::vector<Gui::DAG::Vertex> selections = getAllSelected();
1108 assert(selections.size() == 1);
1109 const GraphLinkRecord& record = findRecord(selections.front(), *graphLink);
1110
1111 auto lineEdit = qobject_cast<LineEdit*>(proxy->widget());
1112 assert(lineEdit);
1113 const_cast<App::DocumentObject*>(record.DObject)
1114 ->Label.setValue(lineEdit->text().toUtf8().constData()); // const hack
1115
1116 finishRename();
1117 }
1118
1119 void Model::renameRejectedSlot()
1120 {
1121 finishRename();
1122 }
1123
1124 void Model::finishRename()
1125 {
1126 assert(proxy);
1127 this->removeItem(proxy);
1128 proxy->deleteLater();
1129 proxy = nullptr;
1130 this->invalidate();
1131 }
1132
1133 void Model::editingStartSlot()
1134 {
1135 auto action = qobject_cast<QAction*>(sender());
1136 if (action) {
1137 int edit = action->data().toInt();
1138 auto selections = getAllSelected();
1139 assert(selections.size() == 1);
1140 const GraphLinkRecord& record = findRecord(selections.front(), *graphLink);
1141 Gui::Document* doc = Gui::Application::Instance->getDocument(record.DObject->getDocument());
1142 MDIView* view = doc->getActiveView();
1143 if (view) {
1144 getMainWindow()->setActiveWindow(view);
1145 }
1146 doc->setEdit(const_cast<ViewProviderDocumentObject*>(record.VPDObject), edit);
1147 }
1148 }
1149
1150 void Model::editingFinishedSlot()
1151 {
1152 auto selections = getAllSelected();
1153 assert(selections.size() == 1);
1154 const GraphLinkRecord& record = findRecord(selections.front(), *graphLink);
1155 Gui::Document* doc = Gui::Application::Instance->getDocument(record.DObject->getDocument());
1156 doc->commitCommand();
1157 doc->resetEdit();
1158 doc->getDocument()->recompute();
1159 }
1160
1161 void Model::visiblyIsolate(Gui::DAG::Vertex sourceIn)
1162 {
1163 auto buildSkipTypes = []() {
1164 std::vector<Base::Type> out;
1165 Base::Type type;
1166 type = Base::Type::fromName("App::DocumentObjectGroup");
1167 if (!type.isBad()) {
1168 out.push_back(type);
1169 }
1170 type = Base::Type::fromName("App::Part");
1171 if (!type.isBad()) {
1172 out.push_back(type);
1173 }
1174 type = Base::Type::fromName("PartDesign::Body");
1175 if (!type.isBad()) {
1176 out.push_back(type);
1177 }
1178
1179 return out;
1180 };
1181
1182 auto testSkipType = [](const App::DocumentObject* dObject, const std::vector<Base::Type>& types) {
1183 for (const auto& currentType : types) {
1184 if (dObject->isDerivedFrom(currentType)) {
1185 return true;
1186 }
1187 }
1188 return false;
1189 };
1190
1191 indexVerticesEdges();
1192 Path connectedVertices;
1193 ConnectionVisitor visitor(connectedVertices);
1194 boost::breadth_first_search(*theGraph, sourceIn, boost::visitor(visitor));
1195 boost::breadth_first_search(boost::make_reverse_graph(*theGraph), sourceIn, boost::visitor(visitor));
1196
1197 // note source vertex is added twice to Path. Once for each search.
1198 static std::vector<Base::Type> skipTypes = buildSkipTypes();
1199 for (const auto& currentVertex : connectedVertices) {
1200 const GraphLinkRecord& record = findRecord(currentVertex, *graphLink);
1201 if (testSkipType(record.DObject, skipTypes)) {
1202 continue;
1203 }
1204 const_cast<ViewProviderDocumentObject*>(record.VPDObject)->hide(); // const hack
1205 }
1206
1207 const GraphLinkRecord& sourceRecord = findRecord(sourceIn, *graphLink);
1208 if (!testSkipType(sourceRecord.DObject, skipTypes)) {
1209 const_cast<ViewProviderDocumentObject*>(sourceRecord.VPDObject)->show(); // const hack
1210 }
1211 }
1212
1213
1214 #include <moc_DAGModel.cpp>