]> gerrit.simantics Code Review - simantics/sysdyn.git/blob
e8c51d205b7086511f731f3f6790af38ac915c58
[simantics/sysdyn.git] /
1 /*******************************************************************************\r
2  * Copyright (c) 2007, 2014 Association for Decentralized Information Management in\r
3  * Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
13 \r
14 import java.util.Arrays;\r
15 import java.util.List;\r
16 import java.util.Map;\r
17 \r
18 import org.eclipse.jface.layout.GridDataFactory;\r
19 import org.eclipse.jface.layout.GridLayoutFactory;\r
20 import org.eclipse.jface.text.BadLocationException;\r
21 import org.eclipse.jface.text.IDocument;\r
22 import org.eclipse.swt.SWT;\r
23 import org.eclipse.swt.custom.VerifyKeyListener;\r
24 import org.eclipse.swt.events.FocusAdapter;\r
25 import org.eclipse.swt.events.FocusEvent;\r
26 import org.eclipse.swt.events.FocusListener;\r
27 import org.eclipse.swt.events.KeyListener;\r
28 import org.eclipse.swt.events.ModifyListener;\r
29 import org.eclipse.swt.graphics.Point;\r
30 import org.eclipse.swt.widgets.Button;\r
31 import org.eclipse.swt.widgets.Composite;\r
32 import org.eclipse.swt.widgets.Event;\r
33 import org.eclipse.swt.widgets.Label;\r
34 import org.eclipse.swt.widgets.Listener;\r
35 import org.eclipse.swt.widgets.Table;\r
36 import org.simantics.databoard.Bindings;\r
37 import org.simantics.db.ReadGraph;\r
38 import org.simantics.db.Resource;\r
39 import org.simantics.db.WriteGraph;\r
40 import org.simantics.db.common.CommentMetadata;\r
41 import org.simantics.db.common.request.ReadRequest;\r
42 import org.simantics.db.common.request.WriteRequest;\r
43 import org.simantics.db.common.utils.ListUtils;\r
44 import org.simantics.db.exception.DatabaseException;\r
45 import org.simantics.db.layer0.util.RemoverUtil;\r
46 import org.simantics.db.request.Read;\r
47 import org.simantics.layer0.Layer0;\r
48 import org.simantics.sysdyn.SysdynResource;\r
49 import org.simantics.sysdyn.manager.SysdynModel;\r
50 import org.simantics.sysdyn.manager.SysdynModelManager;\r
51 import org.simantics.sysdyn.representation.Stock;\r
52 import org.simantics.sysdyn.representation.Valve;\r
53 import org.simantics.ui.SimanticsUI;\r
54 import org.simantics.utils.datastructures.Pair;\r
55 \r
56 public class StockExpression implements IExpression {\r
57 \r
58     private final ExpressionWidgetInput input;\r
59     private ExpressionField integralExpression, initialExpression;\r
60     private ExpressionField lastSelectedText;\r
61     \r
62     public StockExpression(ExpressionWidgetInput input) {\r
63         this.input = input;\r
64     }\r
65     \r
66     @Override\r
67     public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {\r
68         GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);\r
69         String initialEquation = data.get("initialEquation") != null ? (String)data.get("initialEquation") : "";\r
70         String integralEquation = data.get("integral") != null ? (String)data.get("integral") : getDefaultIntegral(input.expression);\r
71 \r
72 \r
73         Label label = new Label(parent, SWT.NONE);\r
74         label.setText("Integral");\r
75 \r
76         Composite integralComposite = new Composite(parent, SWT.NONE);\r
77         GridDataFactory.fillDefaults().grab(true, true).applyTo(integralComposite);\r
78         GridLayoutFactory.fillDefaults().numColumns(2).applyTo(integralComposite);\r
79         \r
80         integralExpression = new ExpressionField(integralComposite, SWT.BORDER, allowedVariables, true, input);\r
81         integralExpression.setExpression(integralEquation);\r
82         GridDataFactory.fillDefaults().grab(true, true).applyTo(integralExpression);\r
83         integralExpression.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
84 \r
85             @Override\r
86             public void focusLost(FocusEvent e) {\r
87                 lastSelectedText = integralExpression;\r
88             }\r
89         });\r
90         \r
91         Button defaultButton = new Button(integralComposite, SWT.PUSH);\r
92         defaultButton.setText("Use default");\r
93         defaultButton.addListener(SWT.Selection, new Listener() {\r
94 \r
95                 @Override\r
96                 public void handleEvent(Event event) {\r
97                         switch (event.type) {\r
98                         case SWT.Selection:\r
99                                 StockExpression.this.integralExpression.setExpression(getDefaultIntegral(input.expression));\r
100                                 SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
101 \r
102                                         @Override\r
103                                         public void perform(WriteGraph graph)\r
104                                                         throws DatabaseException {\r
105                                                 // Delete the possible integral expression from the database to note \r
106                                                 // that we are in the "default" mode.\r
107                                                 graph.startUndoContext();\r
108                                                 SysdynResource sr = SysdynResource.getInstance(graph);\r
109                                                 graph.deny(input.expression, sr.StockExpression_useCustomIntegral);\r
110                                                 graph.claimLiteral(input.expression, sr.StockExpression_integralEquation, getDefaultIntegral(graph, input.expression));\r
111                                                 \r
112                                         CommentMetadata cm = graph.getMetadata(CommentMetadata.class);\r
113                                         graph.addMetadata(cm.add("Use default"));\r
114                                                 \r
115                                         }\r
116                                 });\r
117                                 break;\r
118                         }\r
119                 }\r
120 \r
121         });\r
122 \r
123         label = new Label(parent, SWT.NONE);\r
124         label.setText("Initial\nValue");\r
125 \r
126         initialExpression = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);\r
127         initialExpression.setExpression(initialEquation);\r
128         GridDataFactory.fillDefaults().grab(true, true).applyTo(initialExpression);\r
129         initialExpression.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
130 \r
131             @Override\r
132             public void focusLost(FocusEvent e) {\r
133                 lastSelectedText = initialExpression;\r
134             }\r
135         });\r
136 \r
137         lastSelectedText = initialExpression;\r
138     }\r
139 \r
140     @Override\r
141     public void focus() {\r
142         this.lastSelectedText.focus();\r
143     }\r
144 \r
145     @Override\r
146     public List<ExpressionField> getExpressionFields() {\r
147         return Arrays.asList(this.integralExpression, this.initialExpression);\r
148     }\r
149 \r
150     @Override\r
151     public void readData(final Resource expression, final Map<String, Object> data) {\r
152         Pair<String, String> equations = null;\r
153         if (expression != null && data.get("initialEquation") == null) {\r
154                 try {\r
155                     equations = SimanticsUI.getSession().syncRequest(new Read<Pair<String, String>>() {\r
156         \r
157                         @Override\r
158                         public Pair<String, String> perform(ReadGraph graph) throws DatabaseException {\r
159                             SysdynResource sr = SysdynResource.getInstance(graph);\r
160                             if (graph.isInstanceOf(expression, sr.StockExpression)) {\r
161                                 String initialEquation = graph.getPossibleRelatedValue(expression, sr.StockExpression_initialEquation);\r
162                                 String integralEquation = graph.getPossibleRelatedValue(expression, sr.StockExpression_integralEquation);\r
163                                 initialEquation = (initialEquation != null) ? initialEquation : "";\r
164                                 return new Pair<String, String>(integralEquation, initialEquation);\r
165                             } else {\r
166                                 return new Pair<String, String>(null, "");\r
167                             }\r
168                         }\r
169         \r
170                     });\r
171                 } catch (DatabaseException e1) {\r
172                     e1.printStackTrace();\r
173                 }\r
174                 data.put("initialEquation", equations.second);\r
175         }\r
176 \r
177         if (equations.first == null) {\r
178                 try {\r
179                                 SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
180 \r
181                                         @Override\r
182                                         public void perform(WriteGraph graph) throws DatabaseException {\r
183                                                 SysdynResource sr = SysdynResource.getInstance(graph);\r
184                                         graph.claimLiteral(input.expression, sr.StockExpression_integralEquation, getDefaultIntegral(graph, input.expression));\r
185                                         graph.startUndoContext();\r
186                                 CommentMetadata cm = graph.getMetadata(CommentMetadata.class);\r
187                                 graph.addMetadata(cm.add("Set expression"));\r
188                                         }\r
189 \r
190                                 });\r
191                         } catch (DatabaseException e) {\r
192                                 // TODO Auto-generated catch block\r
193                                 e.printStackTrace();\r
194                         }\r
195                 \r
196                 data.put("integral", getDefaultIntegral(expression));\r
197         } else {\r
198                 try {\r
199                         final String integral = equations.first;\r
200                                 SimanticsUI.getSession().syncRequest(new ReadRequest() {\r
201 \r
202                                         @Override\r
203                                         public void run(ReadGraph graph) throws DatabaseException {\r
204                                                 SysdynResource sr = SysdynResource.getInstance(graph);\r
205                                         if (graph.hasStatement(input.expression, sr.StockExpression_useCustomIntegral)) {\r
206                                                 data.put("integral", integral);\r
207                                         } else {\r
208                                                 data.put("integral", getDefaultIntegral(graph, expression));\r
209                                         }\r
210                                         }\r
211 \r
212                                 });\r
213                         } catch (DatabaseException e) {\r
214                                 data.put("integral", equations.first);\r
215                                 e.printStackTrace();\r
216                         }\r
217         }\r
218 \r
219     }\r
220 \r
221     @Override\r
222     public void replaceSelection(String var) {\r
223         if(lastSelectedText != null) {\r
224             IDocument doc = lastSelectedText.getDocument();\r
225             try {\r
226                 Point selection = lastSelectedText.getSelection();\r
227                 doc.replace(selection.x, selection.y, var);\r
228                 lastSelectedText.setSelection(selection.x + var.length());\r
229             } catch (BadLocationException e) {\r
230                 e.printStackTrace();\r
231             }\r
232         }\r
233     }\r
234 \r
235     @Override\r
236     public void save(final Resource expression, final Map<String, Object> data) {\r
237         final String currentInitial = this.initialExpression.getExpression();\r
238         final String currentIntegral = this.integralExpression.getExpression();\r
239         if (currentIntegral == null) {\r
240                 this.integralExpression.setExpression(getDefaultIntegral(expression));\r
241         }\r
242         if(!currentInitial.equals(data.get("initialEquation"))\r
243                         || currentIntegral == null\r
244                         || !currentIntegral.equals(data.get("integral"))) {\r
245             SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
246 \r
247                 @Override\r
248                 public void perform(WriteGraph g)\r
249                 throws DatabaseException {\r
250                     SysdynResource sr = SysdynResource.getInstance(g);\r
251                     Layer0 l0 = Layer0.getInstance(g);\r
252                     \r
253                     if(!g.isInstanceOf(expression, sr.StockExpression)) {\r
254                         Resource variable = g.getPossibleObject(expression, l0.PartOf);\r
255                         Resource expressionList = g.getPossibleObject(variable, sr.Variable_expressionList);\r
256                         Resource temp = g.newResource();\r
257                         ListUtils.replace(g, expressionList, expression, temp);\r
258                         \r
259                         for(Resource predicate : g.getPredicates(expression)) {\r
260                             g.deny(expression, predicate);\r
261                         }\r
262                         g.claim(expression, l0.InstanceOf, null, sr.StockExpression);\r
263 \r
264                         ListUtils.replace(g, expressionList, temp, expression);\r
265 \r
266                         RemoverUtil.remove(g, temp);\r
267 \r
268                         g.claim(expression, l0.PartOf, variable);\r
269                     }\r
270                     g.claimLiteral(expression, sr.StockExpression_initialEquation, currentInitial);\r
271                     \r
272                     if (!currentIntegral.equals(g.getPossibleRelatedValue(expression, sr.StockExpression_integralEquation, Bindings.STRING))) {\r
273                         // If the value is not same as default, enable the custom tag\r
274                         g.claim(expression, sr.StockExpression_useCustomIntegral, expression);\r
275                     }\r
276                     g.claimLiteral(expression, sr.StockExpression_integralEquation, currentIntegral);\r
277                     \r
278                     g.startUndoContext();\r
279                                 CommentMetadata cm = g.getMetadata(CommentMetadata.class);\r
280                                 g.addMetadata(cm.add("Save"));\r
281 \r
282                 }\r
283 \r
284             });\r
285         }\r
286         this.initialExpression.setExpression(currentInitial);\r
287         this.integralExpression.setExpression(currentIntegral);\r
288     }\r
289 \r
290     @Override\r
291     public void updateData(Map<String, Object> data) {\r
292         if(this.initialExpression != null && this.initialExpression.getExpression() != null)\r
293             data.put("initialEquation", this.initialExpression.getExpression());\r
294         if(this.integralExpression != null && this.integralExpression.getExpression() != null)\r
295             data.put("integral", this.integralExpression.getExpression());\r
296     }\r
297 \r
298     \r
299     private static String getDefaultIntegral(ReadGraph graph, Resource expression) throws DatabaseException {\r
300         SysdynResource sr = SysdynResource.getInstance(graph);\r
301         Layer0 l0 = Layer0.getInstance(graph);\r
302     \r
303             // find the variable\r
304             Resource variable = graph.getPossibleObject(expression, l0.PartOf);\r
305             if(variable == null)\r
306                 return "";\r
307             \r
308                 SysdynModelManager sdm = SysdynModelManager.getInstance(graph.getSession());\r
309                 SysdynModel model = sdm.getModel(graph, graph.getSingleObject(variable, l0.PartOf));\r
310                 model.update(graph);\r
311                 \r
312                 Stock stock = (Stock)model.getElement(variable);\r
313             \r
314                 String range = graph.getPossibleRelatedValue(expression, sr.Expression_arrayRange);\r
315                 if(range == null)\r
316                         range = "";\r
317         \r
318             StringBuilder builder = new StringBuilder();\r
319             builder.append("");\r
320             for(Valve in : stock.getIncomingValves()) {\r
321                 builder.append(" + " + in.getName() + range);\r
322             }\r
323             for(Valve out : stock.getOutgoingValves()) {\r
324                 builder.append(" - " + out.getName() + range);\r
325             }\r
326             if (builder.indexOf(" + ") == 0)\r
327                 builder.delete(0, 3);\r
328             \r
329             return builder.toString().trim();   \r
330     }\r
331     \r
332     \r
333     private static String getDefaultIntegral(final Resource expression) {\r
334         \r
335         String integral = "";\r
336         if(expression == null)\r
337                 return integral;\r
338         try {\r
339             integral = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
340 \r
341                 @Override\r
342                 public String perform(ReadGraph graph) throws DatabaseException {\r
343                         return getDefaultIntegral(graph, expression);\r
344                 }\r
345 \r
346             });\r
347         } catch (DatabaseException e) {\r
348             e.printStackTrace();\r
349         }\r
350         return integral;\r
351     }\r
352 \r
353     @Override\r
354     public void addKeyListener(KeyListener listener) {\r
355         this.initialExpression.getSourceViewer().getTextWidget().addKeyListener(listener);\r
356         this.integralExpression.getSourceViewer().getTextWidget().addKeyListener(listener);\r
357 \r
358     }\r
359 \r
360     @Override\r
361     public void addModifyListener(ModifyListener listener) {\r
362         this.initialExpression.getSourceViewer().getTextWidget().addModifyListener(listener);\r
363         this.integralExpression.getSourceViewer().getTextWidget().addModifyListener(listener);\r
364 \r
365     }\r
366 \r
367     @Override\r
368     public void addFocusListener(FocusListener listener) {\r
369         this.initialExpression.getSourceViewer().getTextWidget().addFocusListener(listener);\r
370         this.integralExpression.getSourceViewer().getTextWidget().addFocusListener(listener);\r
371     }\r
372     \r
373         @Override\r
374         public void addVerifyKeyListener(VerifyKeyListener listener) {\r
375                 this.initialExpression.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
376                 this.integralExpression.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
377         }\r
378 \r
379 }\r