]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/actions/ModeledActions.java
Make Write-interfaces as @FunctionalInterface for lambdas
[simantics/platform.git] / bundles / org.simantics.modeling.ui / src / org / simantics / modeling / ui / actions / ModeledActions.java
1 /*******************************************************************************
2  * Copyright (c) 2011, 2016 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  *     Semantum Oy - refactoring
12  *******************************************************************************/
13 package org.simantics.modeling.ui.actions;
14
15 import java.util.ArrayList;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.Comparator;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Set;
24
25 import org.eclipse.core.runtime.CoreException;
26 import org.eclipse.core.runtime.IAdaptable;
27 import org.eclipse.core.runtime.IConfigurationElement;
28 import org.eclipse.core.runtime.IExecutableExtension;
29 import org.eclipse.core.runtime.IStatus;
30 import org.eclipse.core.runtime.Status;
31 import org.eclipse.jface.action.Action;
32 import org.eclipse.jface.action.ActionContributionItem;
33 import org.eclipse.jface.action.IContributionItem;
34 import org.eclipse.jface.action.MenuManager;
35 import org.eclipse.jface.action.Separator;
36 import org.simantics.browsing.ui.NodeContext;
37 import org.simantics.browsing.ui.common.NodeContextBuilder;
38 import org.simantics.browsing.ui.model.InvalidContribution;
39 import org.simantics.browsing.ui.model.actions.ActionBrowseContext;
40 import org.simantics.browsing.ui.model.actions.IActionCategory;
41 import org.simantics.db.ReadGraph;
42 import org.simantics.db.Resource;
43 import org.simantics.db.exception.DatabaseException;
44 import org.simantics.issues.common.IssueUtils;
45 import org.simantics.modeling.ui.Activator;
46 import org.simantics.project.ontology.ProjectResource;
47 import org.simantics.ui.contribution.DynamicMenuContribution;
48 import org.simantics.ui.selection.WorkbenchSelectionElement;
49 import org.simantics.ui.selection.WorkbenchSelectionUtils;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 public class ModeledActions extends DynamicMenuContribution implements IExecutableExtension {
54     private static final Logger LOGGER = LoggerFactory.getLogger(IssueUtils.class);
55
56     public static final Set<String> defaultBrowseContexts = Collections.singleton(ProjectResource.URIs.ProjectActionContext);
57
58     protected Set<String> browseContexts = defaultBrowseContexts;
59
60     public static final Comparator<Action> ACTION_COMPARATOR = new Comparator<Action>() {
61         @Override
62         public int compare(Action o1, Action o2) {
63             String t1 = o1.getText();
64             String t2 = o2.getText();
65             if(t1 == null) {
66                 if(t2 == null)
67                     return 0;
68                 else
69                     return -1;
70             }           
71             else {
72                 if(t2 == null)
73                     return 1;
74                 else
75                     return t1.compareTo(t2);
76             }
77         }
78     };
79
80     @Override
81     public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException {
82         if(data instanceof String) {
83             String str = (String)data;
84             String[] parms = str.split(";");
85             for(String parm : parms) {
86                 String[] keyValue = parm.split("=");
87                 if(keyValue.length == 2) {
88                     String key = keyValue[0].trim();
89                     if("context".equals(key)) {
90                         browseContexts = Collections.singleton(keyValue[1]);
91                     }
92                 }
93             }
94         }
95     }
96
97     protected Collection<String> getBrowseContexts() {
98         return browseContexts;
99     }
100
101     protected Collection<Resource> getBrowseContextResources(ReadGraph graph) throws DatabaseException {
102         Collection<String> names = getBrowseContexts(); 
103         ArrayList<Resource> result = new ArrayList<>(names.size());
104         for(String name : names)
105             result.add(graph.getResource(name));
106         return result;
107     }
108
109     protected List<NodeContext> getContexts(Object[] selection) {
110         if (selection.length == 0)
111             return Collections.emptyList();
112
113         ArrayList<NodeContext> result = new ArrayList<>(selection.length);
114
115         for (Object o : selection) {
116             if ((o instanceof IAdaptable)) {
117                     NodeContext nodeContext = ((IAdaptable) o).getAdapter(NodeContext.class);
118                     if (nodeContext != null)
119                         result.add(nodeContext);
120             } else if (o instanceof WorkbenchSelectionElement) {
121                 try {
122                                         Resource res = WorkbenchSelectionUtils.getPossibleResource((WorkbenchSelectionElement)o);
123                                         if(res != null) {
124                                                 result.add(NodeContextBuilder.buildWithInput(res));
125                                         }
126                                 } catch (DatabaseException e) {
127                                     LOGGER.error("Failed to get node contexts for selection.", e);
128                                 }
129             }
130         }
131
132         return result;
133     }
134
135     protected List<NodeContext> getContexts(ReadGraph graph, Object[] selection) throws DatabaseException {
136         return getContexts(selection);
137     }
138
139     protected static IContributionItem[] toContributionItems(Map<IActionCategory, List<Action>> map) {
140         if (map.isEmpty())
141             return NONE;
142
143         IActionCategory[] categories = map.keySet().toArray(new IActionCategory[map.size()]);
144         Arrays.sort(categories, IActionCategory.ACTION_CATEGORY_COMPARATOR);
145
146         ArrayList<IContributionItem> items = new ArrayList<IContributionItem>();
147         boolean first = true;
148         for (IActionCategory category : categories) {
149             List<Action> actions = map.get(category);
150             Collections.sort(actions, ACTION_COMPARATOR);
151
152             if (category != null && category.isSubmenu()) {
153                 MenuManager manager = new MenuManager(category.getLabel());
154                 for (Action action : actions)
155                     manager.add(new ActionContributionItem(action));
156                 items.add(manager);
157             }
158             else {
159                 if (first)
160                     first = false;
161                 else
162                     items.add(new Separator(category == null ? "" : category.getLabel()));
163                 for (Action action : actions)
164                     items.add(new ActionContributionItem(action));
165             }
166         }
167         return items.toArray(new IContributionItem[items.size()]);
168     }
169
170     @Override
171     protected Object[] getSelectedObjects() {
172         Object[] sel = super.getSelectedObjects();
173         List<NodeContext> contexts = getContexts(sel);
174         return contexts.toArray(NodeContext.NONE);
175     }
176
177     @Override
178     protected IContributionItem[] getContributionItems(ReadGraph graph, Object[] selection)
179             throws DatabaseException
180     {
181         List<NodeContext> contexts = Arrays.asList( (NodeContext[]) selection );
182         if (contexts.isEmpty())
183             return NONE;
184
185         try {
186             NodeContext nodeContext = contexts.get(0);
187
188             ActionBrowseContext defaultContext = ActionBrowseContext.create(graph, getBrowseContextResources(graph));
189             ActionBrowseContext browseContext = ActionBrowseContext.get(graph, nodeContext, defaultContext);
190
191             Map<IActionCategory, List<Action>> result = browseContext.getActions(graph, nodeContext, contexts);
192             Map<IActionCategory, List<Action>> current = result;
193
194             for (int i = 1; i < contexts.size(); i++) {
195
196                 browseContext = ActionBrowseContext.get(graph, nodeContext, defaultContext);
197
198                 Map<IActionCategory, List<Action>> m = browseContext.getActions(graph, contexts.get(i), contexts);
199
200                 result = new HashMap<>();
201
202                 for(Map.Entry<IActionCategory, List<Action>> entry : m.entrySet()) {
203                     List<Action> exist = current.get(entry.getKey());
204                     if (exist == null)
205                         continue;
206
207                     ArrayList<Action> l = new ArrayList<Action>();
208                     for(Action e : exist) {
209                         String id = e.getId();
210                         boolean found = false;
211                         for(Action a : entry.getValue()) {
212                             if(id.equals(a.getId())) {
213                                 found = true;
214                                 break;
215                             }
216                         }
217                         if(found) l.add(e);
218                     }
219                     if(!l.isEmpty()) result.put(entry.getKey(), l);
220                 }
221
222                 current = result;
223
224             }
225
226             return toContributionItems(result);
227
228         } catch (InvalidContribution e) {
229             Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
230                     "Invalid contribution encountered in " + getClass().getSimpleName() + ".", e));
231         }
232         return NONE;
233     }
234
235 }