]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling.template2d.ui/src/org/simantics/modeling/template2d/ui/actions/AssignDrawingTemplate.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.modeling.template2d.ui / src / org / simantics / modeling / template2d / ui / actions / AssignDrawingTemplate.java
1 /*******************************************************************************
2  * Copyright (c) 2014 Association for Decentralized Information Management in
3  * 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  *     Semantum Oy - enabled template unassignment (#5030)
12  *     Semantum Oy - multi-selection support (#5425)
13  *******************************************************************************/
14 package org.simantics.modeling.template2d.ui.actions;
15
16 import gnu.trove.set.hash.THashSet;
17
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.List;
22 import java.util.Set;
23
24 import org.eclipse.jface.dialogs.IDialogConstants;
25 import org.eclipse.jface.dialogs.IDialogSettings;
26 import org.eclipse.jface.viewers.BaseLabelProvider;
27 import org.eclipse.jface.viewers.ILabelProvider;
28 import org.eclipse.jface.window.Window;
29 import org.eclipse.swt.graphics.Image;
30 import org.eclipse.swt.widgets.Button;
31 import org.eclipse.swt.widgets.Composite;
32 import org.eclipse.swt.widgets.Display;
33 import org.eclipse.swt.widgets.Shell;
34 import org.eclipse.ui.PlatformUI;
35 import org.simantics.NameLabelUtil;
36 import org.simantics.Simantics;
37 import org.simantics.db.ReadGraph;
38 import org.simantics.db.Resource;
39 import org.simantics.db.WriteGraph;
40 import org.simantics.db.common.CommentMetadata;
41 import org.simantics.db.common.request.PossibleIndexRoot;
42 import org.simantics.db.common.request.ReadRequest;
43 import org.simantics.db.common.request.WriteRequest;
44 import org.simantics.db.common.utils.NameUtils;
45 import org.simantics.db.exception.DatabaseException;
46 import org.simantics.db.layer0.adapter.ActionFactory;
47 import org.simantics.db.layer0.adapter.ActionFactory2;
48 import org.simantics.db.layer0.adapter.Instances;
49 import org.simantics.modeling.ModelingResources;
50 import org.simantics.modeling.template2d.ontology.Template2dResource;
51 import org.simantics.modeling.template2d.ui.Activator;
52 import org.simantics.structural.stubs.StructuralResource2;
53 import org.simantics.ui.workbench.dialogs.ResourceListDialog;
54 import org.simantics.utils.ObjectUtils;
55 import org.simantics.utils.datastructures.Pair;
56
57 public class AssignDrawingTemplate implements ActionFactory, ActionFactory2 {
58
59     @Override
60     public Runnable create(Collection<?> targets) {
61         final List<Resource> resources = new ArrayList<Resource>();
62         for (Object target : targets) {
63             if (!(target instanceof Resource))
64                 return null;
65             resources.add((Resource) target);
66         }
67         return (targets.isEmpty()) ? null : assign(resources);
68     }
69
70     @Override
71     public Runnable create(Object target) {
72         if(!(target instanceof Resource))
73             return null;
74         return assign(Collections.singletonList((Resource) target));
75     }
76
77     private Runnable assign(final Collection<Resource> composites) {
78         return new Runnable() {
79             @Override
80             public void run() {
81                 Simantics.getSession().asyncRequest(new ReadRequest() {
82                     @Override
83                     public void run(ReadGraph graph) throws DatabaseException {
84                         assign(graph, composites);
85                     }
86                 });
87             }
88         };
89     }
90
91     private void assign(ReadGraph graph, final Collection<Resource> composites) throws DatabaseException {
92         Template2dResource TEMPLATE2D = Template2dResource.getInstance(graph);
93         StructuralResource2 STR = StructuralResource2.getInstance(graph);
94         ModelingResources MOD = ModelingResources.getInstance(graph);
95
96         Instances query = graph.adapt(TEMPLATE2D.DrawingTemplate, Instances.class);
97         Resource root = null;
98         Set<Resource> initialResources = new THashSet<Resource>();
99
100         for (Resource composite : composites) {
101             if (!graph.isInstanceOf(composite, STR.Composite))
102                 return;
103
104             // Ensure all composites are part of the same index root.
105             Resource r = graph.sync(new PossibleIndexRoot(composite));
106             if (r == null || (root != null && !r.equals(root)))
107                 return;
108             root = r;
109
110             // Ensure each composite has a diagram.
111             Resource diagram = graph.getPossibleObject(composite, MOD.CompositeToDiagram);
112             if (diagram == null)
113                 return;
114
115             Resource initial = graph.getPossibleObject(diagram, TEMPLATE2D.HasDrawingTemplate);
116             if (initial != null)
117                 initialResources.add(initial);
118         }
119
120         final List<Pair<Resource, String>> elements = new ArrayList<Pair<Resource, String>>();
121
122         for (Resource template : query.find(graph, root)) {
123             String name = NameLabelUtil.modalName(graph, template);
124             elements.add(Pair.make(template, name));
125         }
126
127         Resource init = initialResources.size() == 1 ? initialResources.iterator().next() : null;
128         final Pair<Resource, String> initialSelection = init != null
129                 ? Pair.make(init, NameLabelUtil.modalName(graph, init))
130                 : null;
131
132         Display.getDefault().asyncExec(new Runnable() {
133             @Override
134             public void run() {
135                 queryDrawingTemplate(composites, elements, initialSelection);
136             }
137         });
138     }
139
140     private static void queryDrawingTemplate(
141             final Collection<Resource> composites,
142             List<Pair<Resource, String>> elements,
143             Pair<Resource, String> initialSelection
144             )
145     {
146         Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
147         ResourceListDialog dialog = new ResourceListDialog(shell, "Select template from list", "Select diagram template to assign " + ResourceListDialog.DEFAULT_LABEL_SUFFIX, new LabelProvider()) {
148             @Override
149             protected void createButtonsForButtonBar(Composite parent) {
150                 Button unassign = createButton(parent, IDialogConstants.CLIENT_ID, "Unassign", false);
151                 unassign.setToolTipText("Remove Diagram Template Assignment");
152                 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
153                 createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
154             }
155             @Override
156             protected void buttonPressed(int buttonId) {
157                 super.buttonPressed(buttonId);
158                 if (buttonId == IDialogConstants.CLIENT_ID) {
159                     setSelectionResult(new Object[0]);
160                     setReturnCode(OK);
161                     close();
162                 }
163             }
164             @Override
165             protected IDialogSettings getDialogBoundsSettings() {
166                 return Activator.getDefault().getDialogSettings();
167             }
168         };
169         dialog.setElements(elements);
170         dialog.setInitialSelection(initialSelection);
171         dialog.setMultipleSelection(false);
172         if (dialog.open() == Window.OK) {
173             @SuppressWarnings("unchecked")
174             Pair<Resource, String> result = (Pair<Resource, String>) dialog.getSingleResult();
175             final Resource template = result != null ? result.first : null;
176             if (!ObjectUtils.objectEquals(template, initialSelection)) {
177                 //System.out.println("setting template: " + template);
178                 Simantics.getSession().async(new WriteRequest() {
179                     @Override
180                     public void perform(WriteGraph graph) throws DatabaseException {
181                         assignTemplateToDiagrams(graph, composites, template);
182                     }
183                 });
184             }
185         }
186     }
187
188     private static class LabelProvider extends BaseLabelProvider implements ILabelProvider {
189
190         @Override
191         public Image getImage(Object element) {
192             return null;
193         }
194
195         @SuppressWarnings("unchecked")
196         @Override
197         public String getText(Object element) {
198             return ((Pair<?, String>) element).second;
199         }
200
201     }
202
203     public static void assignTemplateToDiagrams(WriteGraph graph, Collection<Resource> composites, Resource template) throws DatabaseException {
204         graph.markUndoPoint();
205         
206         ModelingResources MOD = ModelingResources.getInstance(graph);
207         Template2dResource TEMPLATE2D = Template2dResource.getInstance(graph);
208
209         StringBuilder comment = new StringBuilder();
210         if (template != null) {
211             comment.append("Assigned diagram template ").append(NameUtils.getSafeName(graph, template, true)).append(" to diagram");
212         } else {
213             comment.append("Removed diagram template from diagram");
214         }
215         if (composites.size() > 1)
216             comment.append('s');
217         comment.append('\n');
218
219         for (Resource composite : composites) {
220             Resource diagram = graph.getSingleObject(composite, MOD.CompositeToDiagram); 
221
222             graph.deny(diagram, TEMPLATE2D.HasDrawingTemplate);
223             if (template != null)
224                 graph.claim(diagram, TEMPLATE2D.HasDrawingTemplate, null, template);
225
226             comment.append('\t').append(NameUtils.getSafeName(graph, composite, true));
227         }
228
229         CommentMetadata cm = graph.getMetadata(CommentMetadata.class);
230         graph.addMetadata( cm.add( comment.toString() ) );
231     }
232
233 }