1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
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
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.diagram.handler;
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;
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;
75 * DeleteHandler is a canvas handler for Commands.DELETE commands for an
79 * The handler attempts to delete the current selection for pointer 0, meaning
80 * {@link Selection#SELECTION0}.
84 * The handler logic goes as follows:
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>
92 * @see Selection for the current diagram selection source
94 * @author Tuukka Lehtonen
96 * TODO: start using WorkbenchStatusLine participant
98 public class DeleteHandler extends AbstractDiagramParticipant {
100 public static final boolean DEBUG_DELETE = false;
102 @Dependency Selection sel;
104 private final IStatusLineManager statusLine;
106 public DeleteHandler(IStatusLineManager statusLine) {
107 this.statusLine = statusLine;
110 @EventHandler(priority = 0)
111 public boolean handleCommand(CommandEvent e) {
112 if (Commands.DELETE.equals( e.command )) {
113 IDiagram d = diagram;
117 Set<IElement> ss = sel.getSelection(0);
130 public boolean delete(final IDiagram d, Collection<IElement> ss) {
131 TimeLogger.resetTimeAndLog(getClass(), "delete");
133 Topology topology = d.getDiagramClass().getAtMostOneItemOfClass(Topology.class);
134 RelationshipHandler erh = d.getDiagramClass().getAtMostOneItemOfClass(RelationshipHandler.class);
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());
148 for (IElement child : ce.getSegments(null)) {
149 System.out.println("\t\t-segment " + child);
150 System.out.println("\t\t -class " + child.getElementClass());
154 System.out.println("delete requested for elements:");
155 for (IElement e : ss)
156 System.out.println("\t-element " + e);
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>();
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();
174 if (relationshipsProcessedForElement.add(el)) {
175 // Check for relationships to other elements and mark child
176 // elements to be removed before the parent element.
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());
189 // Mark the object also to be processed for removal.
190 elementsToProcess.addFirst(ee);
197 // Only process this element after we're sure that
198 // all its children have been processed.
199 elementsToProcess.addLast(el);
205 if (!processedElements.add(el))
208 TerminalTopology tt = el.getElementClass().getAtMostOneItemOfClass(TerminalTopology.class);
209 BendsHandler bh = el.getElementClass().getAtMostOneItemOfClass(BendsHandler.class);
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);
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.");
228 System.out.println("ADDED EDGE FOR REMOVAL: " + el);
232 System.out.println("ADDED ELEMENT FOR REMOVAL: " + el);
237 tt.getTerminals(el, terminals);
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))
246 System.out.println("TERMINAL CONNECTION WILL BE DISCONNECTED: " + c);
253 if (elements.isEmpty() && edges.isEmpty())
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);
268 final IDiagram diagram = this.diagram;
269 final ISynchronizationContext syncContext = ElementFactoryUtil.getContextChecked(diagram);
271 new DatabaseJob("Delete selection") {
273 protected IStatus run(IProgressMonitor 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);
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>();
294 public void perform(WriteGraph graph) throws DatabaseException {
295 validateRemoval(graph);
296 graph.markUndoPoint();
298 ConnectionUtil cu = new ConnectionUtil(graph);
301 for (IElement edge : edges) {
302 ConnectionEntity ce = edge.getHint(ElementHints.KEY_CONNECTION_ENTITY);
303 touchConnection( ce.getConnection() );
306 System.out.println("REMOVING EDGE: " + edge);
307 Object obj = ElementUtils.getObject(edge);
308 if (obj instanceof EdgeResource) {
309 cu.remove((EdgeResource) obj);
314 for (IElement element : elements) {
315 ConnectionHandler ch = element.getElementClass().getAtMostOneItemOfClass(ConnectionHandler.class);
318 System.out.println("MARKING CONNECTION TO BE REMOVED: " + element);
319 connectionsToRemove.add( (Resource) ElementUtils.getObject(element) );
321 ConnectionEntity ce = element.getHint(ElementHints.KEY_CONNECTION_ENTITY);
324 System.out.println("REMOVING BRANCH POINT: " + element);
325 new RemoveBranchpoint(element).perform(graph);
326 touchConnection( ce.getConnection() );
329 System.out.println("REMOVING ELEMENT: " + element);
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);
342 new RemoveElement((Resource)d.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE), (Resource)element.getHint(ElementHints.KEY_OBJECT)).perform(graph);
348 // Check all touched connections to see if they are empty.
349 for (Resource connection : touchedConnections) {
350 int removedConnectors = cu.removeUnusedConnectors(connection);
352 System.out.println("PRUNED " + removedConnectors + " CONNECTORS FROM TOUCHED CONNECTION " + connection);
354 int removedInteriorRouteNodes = cu.removeExtraInteriorRouteNodes(connection);
356 System.out.println("PRUNED " + removedInteriorRouteNodes + " INTERIOR ROUTE NODES FROM TOUCHED CONNECTION " + connection);
357 if (removedInteriorRouteNodes == 0)
360 int connectors = cu.getConnectedConnectors(connection, null).size();
362 System.out.println("\t" + connectors + " CONNECTORS LEFT");
363 if (connectors < 2) {
364 connectionsToRemove.add(connection);
368 // Remove selected/left-over empty connections
369 for (Resource connection : connectionsToRemove) {
371 System.out.println("REMOVING CONNECTION: " + connection);
372 RemoveElement.removeElement(graph, (Resource)d.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE), connection);
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);
390 if (!problems.isEmpty()) {
391 throw new CannotRemoveException(EString.implode(problems));
395 void touchConnection(Object c) {
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);
413 void message(final String message) {
414 if (statusLine == null)
416 swtExec(new Runnable() {
419 statusLine.setMessage(message);
420 statusLine.setErrorMessage(null);
425 void error(final String message) {
426 if (statusLine == null)
428 swtExec(new Runnable() {
431 statusLine.setErrorMessage(message);
436 void swtExec(Runnable r) {
437 ThreadUtils.asyncExec(SWTThread.getThreadAccess(Display.getDefault()), r);