]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.diagram/src/org/simantics/diagram/handler/DeleteHandler.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.diagram / src / org / simantics / diagram / handler / DeleteHandler.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.diagram.handler;
13
14 import java.util.ArrayDeque;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Deque;
18 import java.util.HashMap;
19 import java.util.HashSet;
20 import java.util.Set;
21
22 import org.eclipse.core.runtime.IProgressMonitor;
23 import org.eclipse.core.runtime.IStatus;
24 import org.eclipse.core.runtime.Status;
25 import org.eclipse.jface.action.IStatusLineManager;
26 import org.eclipse.swt.widgets.Display;
27 import org.simantics.DatabaseJob;
28 import org.simantics.Simantics;
29 import org.simantics.db.ReadGraph;
30 import org.simantics.db.Resource;
31 import org.simantics.db.WriteGraph;
32 import org.simantics.db.common.request.WriteRequest;
33 import org.simantics.db.exception.DatabaseException;
34 import org.simantics.db.layer0.adapter.Remover;
35 import org.simantics.db.layer0.exception.CannotRemoveException;
36 import org.simantics.db.layer0.util.RemoverUtil;
37 import org.simantics.diagram.adapter.ElementFactoryUtil;
38 import org.simantics.diagram.content.ConnectionUtil;
39 import org.simantics.diagram.content.EdgeResource;
40 import org.simantics.diagram.internal.Activator;
41 import org.simantics.diagram.synchronization.ISynchronizationContext;
42 import org.simantics.diagram.synchronization.graph.RemoveBranchpoint;
43 import org.simantics.diagram.synchronization.graph.RemoveElement;
44 import org.simantics.diagram.ui.DiagramModelHints;
45 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
46 import org.simantics.g2d.connection.ConnectionEntity;
47 import org.simantics.g2d.connection.handler.ConnectionHandler;
48 import org.simantics.g2d.diagram.IDiagram;
49 import org.simantics.g2d.diagram.handler.PickRequest.PickFilter;
50 import org.simantics.g2d.diagram.handler.Relationship;
51 import org.simantics.g2d.diagram.handler.RelationshipHandler;
52 import org.simantics.g2d.diagram.handler.RelationshipHandler.Relation;
53 import org.simantics.g2d.diagram.handler.Topology;
54 import org.simantics.g2d.diagram.handler.Topology.Connection;
55 import org.simantics.g2d.diagram.handler.Topology.Terminal;
56 import org.simantics.g2d.diagram.participant.AbstractDiagramParticipant;
57 import org.simantics.g2d.diagram.participant.Selection;
58 import org.simantics.g2d.element.ElementClass;
59 import org.simantics.g2d.element.ElementHints;
60 import org.simantics.g2d.element.ElementUtils;
61 import org.simantics.g2d.element.IElement;
62 import org.simantics.g2d.element.handler.BendsHandler;
63 import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;
64 import org.simantics.g2d.element.handler.TerminalTopology;
65 import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;
66 import org.simantics.scenegraph.g2d.events.command.CommandEvent;
67 import org.simantics.scenegraph.g2d.events.command.Commands;
68 import org.simantics.utils.logging.TimeLogger;
69 import org.simantics.utils.strings.EString;
70 import org.simantics.utils.threads.SWTThread;
71 import org.simantics.utils.threads.ThreadUtils;
72 import org.simantics.utils.ui.dialogs.ShowMessage;
73
74 /**
75  * DeleteHandler is a canvas handler for Commands.DELETE commands for an
76  * IDiagram.
77  * 
78  * <p>
79  * The handler attempts to delete the current selection for pointer 0, meaning
80  * {@link Selection#SELECTION0}.
81  * </p>
82  * 
83  * <p>
84  * The handler logic goes as follows:
85  * </p>
86  * <ol>
87  * <li>Separate nodes and edges form the the removed selection</li>
88  * <li>Find all edges attached to the removed nodes and remove them too</li>
89  * <li>Delete connections that contain less than 2 terminal connections</li>
90  * </ol>
91  * 
92  * @see Selection for the current diagram selection source
93  * 
94  * @author Tuukka Lehtonen
95  * 
96  * TODO: start using WorkbenchStatusLine participant
97  */
98 public class DeleteHandler extends AbstractDiagramParticipant {
99
100     public static final boolean DEBUG_DELETE = false;
101
102     @Dependency Selection sel;
103
104     private final IStatusLineManager statusLine;
105
106     public DeleteHandler(IStatusLineManager statusLine) {
107         this.statusLine = statusLine;
108     }
109
110     @EventHandler(priority = 0)
111     public boolean handleCommand(CommandEvent e) {
112         if (Commands.DELETE.equals( e.command )) {
113             IDiagram d = diagram;
114             if (d == null)
115                 return true;
116
117             Set<IElement> ss = sel.getSelection(0);
118             if (ss.isEmpty())
119                 return true;
120
121             if (delete(d, ss)) {
122                 sel.clear(0);
123             }
124
125             return true;
126         }
127         return false;
128     }
129
130     public boolean delete(final IDiagram d, Collection<IElement> ss) {
131         TimeLogger.resetTimeAndLog(getClass(), "delete");
132         
133         Topology topology = d.getDiagramClass().getAtMostOneItemOfClass(Topology.class);
134         RelationshipHandler erh = d.getDiagramClass().getAtMostOneItemOfClass(RelationshipHandler.class);
135
136         if (DEBUG_DELETE) {
137             System.out.println("diagram: " + d);
138             for (IElement e : d.getSnapshot()) {
139                 ElementClass ec = e.getElementClass();
140                 System.out.println("\t-element " + e);
141                 System.out.println("\t  -class " + e.getElementClass());
142                 if (ec.containsClass(ConnectionHandler.class)) {
143                     ConnectionEntity ce = e.getHint(ElementHints.KEY_CONNECTION_ENTITY);
144                     for (IElement child : ce.getBranchPoints(null)) {
145                         System.out.println("\t\t-branch " + child);
146                         System.out.println("\t\t  -class " + child.getElementClass());
147                     }
148                     for (IElement child : ce.getSegments(null)) {
149                         System.out.println("\t\t-segment " + child);
150                         System.out.println("\t\t  -class " + child.getElementClass());
151                     }
152                 }
153             }
154             System.out.println("delete requested for elements:");
155             for (IElement e : ss)
156                 System.out.println("\t-element " + e);
157         }
158
159         // Analyze removals:
160         //  - separate elements and connections
161         //  - find all connections attached to the elements and remove them too
162         Deque<IElement> elementsToProcess = new ArrayDeque<IElement>(ss);
163         Set<IElement> processedElements = new HashSet<IElement>();
164         Set<IElement> relationshipsProcessedForElement = new HashSet<IElement>();
165
166         final Collection<IElement> elements = new ArrayList<IElement>();
167         final Set<IElement> edges = new HashSet<IElement>();
168         Collection<Connection> connections = new ArrayList<Connection>();
169         Collection<Terminal> terminals = new ArrayList<Terminal>();
170         Collection<Relation> relations = new ArrayList<Relation>();
171         while (!elementsToProcess.isEmpty()) {
172             IElement el = elementsToProcess.pollFirst();
173
174             if (relationshipsProcessedForElement.add(el)) {
175                 // Check for relationships to other elements and mark child
176                 // elements to be removed before the parent element.
177                 relations.clear();
178                 erh.getRelations(d, el, relations);
179                 if (!relations.isEmpty()) {
180                     boolean restart = false;
181                     for (Relation r : relations) {
182                         //System.out.println("FOUND RELATION: " + r);
183                         if (r.getRelationship() == Relationship.PARENT_OF) {
184                             if ((r.getObject() instanceof IElement)) {
185                                 IElement ee = (IElement) r.getObject();
186                                 if (d.containsElement(ee)) {
187                                     //System.out.println("DIAGRAM CONTAINS OBJECT: " + r.getObject());
188
189                                     // Mark the object also to be processed for removal.
190                                     elementsToProcess.addFirst(ee);
191                                     restart = true;
192                                 }
193                             }
194                         }
195                     }
196                     if (restart) {
197                         // Only process this element after we're sure that
198                         // all its children have been processed.
199                         elementsToProcess.addLast(el);
200                         continue;
201                     }
202                 }
203             }
204
205             if (!processedElements.add(el))
206                 continue;
207
208             TerminalTopology tt = el.getElementClass().getAtMostOneItemOfClass(TerminalTopology.class);
209             BendsHandler bh = el.getElementClass().getAtMostOneItemOfClass(BendsHandler.class);
210
211             if (bh != null) {
212                 // Verify that the edge is NOT between two branch points.
213                 // If it is, do not allow deletion because it is the only case
214                 // which can break a connection tree into a connection forest.
215                 // We do not want that to happen.
216                 Connection begin = topology.getConnection(el, EdgeEnd.Begin);
217                 Connection end = topology.getConnection(el, EdgeEnd.End);
218
219                 // Try to work with cases where the model is somewhat corrupt.
220                 if (begin != null && end != null) {
221                     if (PickFilter.FILTER_BRANCH_POINT.accept(begin.node) && PickFilter.FILTER_BRANCH_POINT.accept(end.node)) {
222                         error("Deletion of branch point connecting edges is not allowed. Must be connected to a node terminal.");
223                         return false;
224                     }
225                 }
226
227                 if (DEBUG_DELETE)
228                     System.out.println("ADDED EDGE FOR REMOVAL: " + el);
229                 edges.add(el);
230             } else {
231                 if (DEBUG_DELETE)
232                     System.out.println("ADDED ELEMENT FOR REMOVAL: " + el);
233                 elements.add(el);
234
235                 if (tt != null) {
236                     terminals.clear();
237                     tt.getTerminals(el, terminals);
238                     connections.clear();
239                     for (Terminal terminal : terminals)
240                         topology.getConnections(el, terminal, connections);
241                     for (Connection c : connections) {
242                         if (c.edge != null) {
243                             if (c.edge.getElementClass().containsClass(BendsHandler.class))
244                                 edges.add(c.edge);
245                             if (DEBUG_DELETE)
246                                 System.out.println("TERMINAL CONNECTION WILL BE DISCONNECTED: " + c);
247                         }
248                     }
249                 }
250             }
251         }
252
253         if (elements.isEmpty() && edges.isEmpty())
254             return false;
255
256         if (DEBUG_DELETE) {
257             System.out.println("gathered elements to delete:");
258             System.out.println("\telements:");
259             if (!elements.isEmpty())
260                 for (IElement e : elements)
261                     System.out.println("\t\t" + e);
262             System.out.println("\tedges:");
263             if (!edges.isEmpty())
264                 for (IElement e : edges)
265                     System.out.println("\t\t" + e);
266         }
267
268         final IDiagram diagram = this.diagram;
269         final ISynchronizationContext syncContext = ElementFactoryUtil.getContextChecked(diagram); 
270
271         new DatabaseJob("Delete selection") {
272             @Override
273             protected IStatus run(IProgressMonitor monitor) {
274                 try {
275                     delete(monitor);
276                     return Status.OK_STATUS;
277                 } catch (CannotRemoveException e) {
278                         ShowMessage.showInformation("Delete Selection Was Denied", e.getLocalizedMessage());
279                     return new Status(IStatus.CANCEL, Activator.PLUGIN_ID, e.getLocalizedMessage(), e);
280                 } catch (DatabaseException e) {
281                     return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Unexpected error in delete.", e);
282                 } finally {
283                     error(null);
284                     monitor.done();
285                 }
286             }
287
288             private void delete(IProgressMonitor monitor) throws DatabaseException {
289                 Simantics.getSession().syncRequest(new WriteRequest() {
290                     Set<Resource> connectionsToRemove = new HashSet<Resource>();
291                     Set<Resource> touchedConnections = new HashSet<Resource>();
292
293                     @Override
294                     public void perform(WriteGraph graph) throws DatabaseException {
295                         validateRemoval(graph);
296                         graph.markUndoPoint();
297
298                         ConnectionUtil cu = new ConnectionUtil(graph);
299
300                         // Remove edges
301                         for (IElement edge : edges) {
302                             ConnectionEntity ce = edge.getHint(ElementHints.KEY_CONNECTION_ENTITY);
303                             touchConnection( ce.getConnection() );
304
305                             if (DEBUG_DELETE)
306                                 System.out.println("REMOVING EDGE: " + edge);
307                             Object obj = ElementUtils.getObject(edge);
308                             if (obj instanceof EdgeResource) {
309                                 cu.remove((EdgeResource) obj);
310                             }
311                         }
312
313                         // Remove elements
314                         for (IElement element : elements) {
315                             ConnectionHandler ch = element.getElementClass().getAtMostOneItemOfClass(ConnectionHandler.class);
316                             if (ch != null) {
317                                 if (DEBUG_DELETE)
318                                     System.out.println("MARKING CONNECTION TO BE REMOVED: " + element);
319                                 connectionsToRemove.add( (Resource) ElementUtils.getObject(element) );
320                             } else {
321                                 ConnectionEntity ce = element.getHint(ElementHints.KEY_CONNECTION_ENTITY);
322                                 if(ce != null) {
323                                     if (DEBUG_DELETE)
324                                         System.out.println("REMOVING BRANCH POINT: " + element);
325                                     new RemoveBranchpoint(element).perform(graph);
326                                     touchConnection( ce.getConnection() );
327                                 } else {
328                                     if (DEBUG_DELETE)
329                                         System.out.println("REMOVING ELEMENT: " + element);
330
331                                     Object obj = ElementUtils.getObject(element);
332                                     if (obj instanceof Resource) {
333                                         // Get terminal connections for element
334                                         Collection<Resource> connectors = cu.getTerminalConnectors((Resource) obj, null);
335                                         for (Resource connector : connectors) {
336                                             Resource connection = ConnectionUtil.tryGetConnection(graph, connector);
337                                             if (connection != null)
338                                                 touchConnection( connection );
339                                             cu.disconnectFromAllRouteNodes(connector);
340                                         }
341
342                                         new RemoveElement((Resource)d.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE), (Resource)element.getHint(ElementHints.KEY_OBJECT)).perform(graph);
343                                     }
344                                 }
345                             }
346                         }
347
348                         // Check all touched connections to see if they are empty.
349                         for (Resource connection : touchedConnections) {
350                             int removedConnectors = cu.removeUnusedConnectors(connection);
351                             if (DEBUG_DELETE)
352                                 System.out.println("PRUNED " + removedConnectors + " CONNECTORS FROM TOUCHED CONNECTION " + connection);
353                             while (true) {
354                                 int removedInteriorRouteNodes = cu.removeExtraInteriorRouteNodes(connection);
355                                 if (DEBUG_DELETE)
356                                     System.out.println("PRUNED " + removedInteriorRouteNodes + " INTERIOR ROUTE NODES FROM TOUCHED CONNECTION " + connection);
357                                 if (removedInteriorRouteNodes == 0)
358                                     break;
359                             }
360                             int connectors = cu.getConnectedConnectors(connection, null).size();
361                             if (DEBUG_DELETE)
362                                 System.out.println("\t" + connectors + " CONNECTORS LEFT");
363                             if (connectors < 2) {
364                                 connectionsToRemove.add(connection);
365                             }
366                         }
367
368                         // Remove selected/left-over empty connections
369                         for (Resource connection : connectionsToRemove) {
370                             if (DEBUG_DELETE)
371                                 System.out.println("REMOVING CONNECTION: " + connection);
372                             RemoveElement.removeElement(graph, (Resource)d.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE), connection);
373                         }
374                     }
375
376                     private void validateRemoval(ReadGraph graph) throws DatabaseException, CannotRemoveException {
377                         ArrayList<String> problems = new ArrayList<String>(elements.size());
378                         for (IElement element : elements) {
379                             Object obj = ElementUtils.getObject(element);
380                             if (obj instanceof Resource) {
381                                 Remover remover = RemoverUtil.getPossibleRemover(graph, (Resource) obj);
382                                 if (remover != null) {
383                                     String problem = remover.canRemove(graph, new HashMap<Object, Object>(4));
384                                     if (problem != null) {
385                                         problems.add(problem);
386                                     }
387                                 }
388                             }
389                         }
390                         if (!problems.isEmpty()) {
391                             throw new CannotRemoveException(EString.implode(problems));
392                         }
393                     }
394
395                     void touchConnection(Object c) {
396                         if (DEBUG_DELETE)
397                             System.out.println("TOUCHED CONNECTION: " + c);
398                         if (c instanceof IElement) {
399                             Object obj = ElementUtils.getObject((IElement) c);
400                             if (obj instanceof Resource)
401                                 touchedConnections.add((Resource) obj);
402                         } else if (c instanceof Resource) {
403                             touchedConnections.add((Resource) c);
404                         }
405                     }
406                 });
407             }
408         }.schedule();
409
410         return true;
411     }
412
413     void message(final String message) {
414         if (statusLine == null)
415             return;
416         swtExec(new Runnable() {
417             @Override
418             public void run() {
419                 statusLine.setMessage(message);
420                 statusLine.setErrorMessage(null);
421             }
422         });
423     }
424
425     void error(final String message) {
426         if (statusLine == null)
427             return;
428         swtExec(new Runnable() {
429             @Override
430             public void run() {
431                 statusLine.setErrorMessage(message);
432             }
433         });
434     }
435
436     void swtExec(Runnable r) {
437         ThreadUtils.asyncExec(SWTThread.getThreadAccess(Display.getDefault()), r);
438     }
439
440 }