]> gerrit.simantics Code Review - simantics/platform.git/blob
7fd6340cfbc859770bf889ed36fd5e2074f28367
[simantics/platform.git] /
1 package org.simantics.modeling.ui.componentTypeEditor;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.List;
6 import java.util.regex.Matcher;
7 import java.util.regex.Pattern;
8
9 import org.eclipse.jface.dialogs.IMessageProvider;
10 import org.eclipse.jface.layout.GridDataFactory;
11 import org.eclipse.jface.layout.GridLayoutFactory;
12 import org.eclipse.swt.SWT;
13 import org.eclipse.swt.custom.StyledText;
14 import org.eclipse.swt.custom.TableEditor;
15 import org.eclipse.swt.events.SelectionAdapter;
16 import org.eclipse.swt.events.SelectionEvent;
17 import org.eclipse.swt.graphics.Point;
18 import org.eclipse.swt.graphics.Rectangle;
19 import org.eclipse.swt.widgets.Button;
20 import org.eclipse.swt.widgets.Combo;
21 import org.eclipse.swt.widgets.Composite;
22 import org.eclipse.swt.widgets.Display;
23 import org.eclipse.swt.widgets.Event;
24 import org.eclipse.swt.widgets.Label;
25 import org.eclipse.swt.widgets.Shell;
26 import org.eclipse.swt.widgets.Table;
27 import org.eclipse.swt.widgets.TableItem;
28 import org.eclipse.swt.widgets.Text;
29 import org.eclipse.ui.forms.widgets.Form;
30 import org.eclipse.ui.forms.widgets.FormToolkit;
31 import org.simantics.Simantics;
32 import org.simantics.databoard.type.NumberType;
33 import org.simantics.databoard.units.internal.library.UnitLibrary;
34 import org.simantics.databoard.util.Limit;
35 import org.simantics.databoard.util.Range;
36 import org.simantics.databoard.util.RangeException;
37 import org.simantics.db.RequestProcessor;
38 import org.simantics.db.Resource;
39 import org.simantics.db.WriteGraph;
40 import org.simantics.db.common.NamedResource;
41 import org.simantics.db.common.request.WriteRequest;
42 import org.simantics.db.exception.DatabaseException;
43 import org.simantics.layer0.Layer0;
44 import org.simantics.modeling.userComponent.ComponentTypeCommands;
45 import org.simantics.scl.runtime.function.Function2;
46 import org.simantics.scl.runtime.function.Function4;
47 import org.simantics.utils.ui.ErrorLogger;
48
49 public class ComponentTypeViewerData {
50     /**
51      * Used to validate property names.
52      */
53     public static final Pattern PROPERTY_NAME_PATTERN =
54             Pattern.compile("([a-z]|_[0-9a-zA-Z_])[0-9a-zA-Z_]*");
55
56     public static final String[] PROPERTY_TYPE_SUGGESTIONS = new String[] {
57         "Double",
58         "Integer",
59         "Float",
60         "String",
61         "Boolean",
62         "Long",
63         "[Double]",
64         "[Integer]",
65         "[Float]",
66         "[String]",
67         "[Boolean]",
68         "[Long]",
69         "Vector Double",
70         "Vector Integer",
71         "Vector Float",
72         "Vector String",
73         "Vector Boolean",
74         "Vector Long"        
75     };
76     
77     public Resource componentType;
78     public FormToolkit tk;
79     public Form form;
80     public UnitLibrary unitLibrary = UnitLibrary.createDefault();
81     public boolean readOnly;
82     public NamedResource[] connectionPoints;
83     public ComponentTypeViewerPropertyInfo[] properties;
84
85     public ComponentTypeViewerData(FormToolkit tk, Resource componentType, Form form) {
86         this.tk = tk;
87         this.componentType = componentType;
88         this.form = form;
89     }
90
91     public void editName(Table table, TableEditor editor, final ComponentTypeViewerPropertyInfo propertyInfo, TableItem selectedItem, int column,
92             Pattern namePattern) {
93         editName(table, editor, propertyInfo, selectedItem, column,
94                 (pInfo, name) -> validatePropertyName(pInfo, name, namePattern));
95     }
96
97     public void editName(Table table, TableEditor editor, final ComponentTypeViewerPropertyInfo propertyInfo, TableItem selectedItem, int column,
98             Function2<ComponentTypeViewerPropertyInfo, String, String> nameValidator) {
99         int extraStyle = propertyInfo.immutable ? SWT.READ_ONLY : 0;
100         final Text text = new Text(table, SWT.NONE | extraStyle);
101         org.eclipse.swt.widgets.Listener listener = 
102                 new org.eclipse.swt.widgets.Listener() {
103             @Override
104             public void handleEvent(Event e) {
105                 if (e.type == SWT.Dispose) {
106                     form.setMessage(null);
107                     return;
108                 }
109
110                 if (e.type == SWT.Modify) {
111                     // validate current name
112                     String error = nameValidator.apply(propertyInfo, text.getText());
113                     if (error != null) {
114                         text.setBackground(text.getDisplay().getSystemColor(SWT.COLOR_RED));
115                         form.setMessage(error, IMessageProvider.ERROR);
116                     } else {
117                         text.setBackground(null);
118                         form.setMessage(null);
119                     }
120                     return;
121                 }
122
123                 if (e.type == SWT.Traverse) {
124                     if (e.detail == SWT.TRAVERSE_ESCAPE) {
125                         text.dispose();
126                         e.doit = false;
127                         return;
128                     }
129                     if (e.detail == SWT.TRAVERSE_ARROW_NEXT || e.detail == SWT.TRAVERSE_ARROW_PREVIOUS || e.detail == SWT.TRAVERSE_MNEMONIC)
130                         return;
131                     e.doit = false;
132                 }
133                 final String newValue = text.getText();
134                 text.dispose();
135
136                 String error = nameValidator.apply(propertyInfo, newValue);
137                 if (error != null)
138                     return;
139
140                 if (propertyInfo.immutable)
141                     return;
142
143                 Simantics.getSession().async(new WriteRequest() {
144                     @Override
145                     public void perform(WriteGraph graph)
146                             throws DatabaseException {
147                         graph.markUndoPoint();
148                         Layer0 L0 = Layer0.getInstance(graph);
149                         String prevName = graph.getPossibleRelatedValue2(propertyInfo.resource, L0.HasName);
150                         String oldCamelCasedLabel = prevName != null ? ComponentTypeCommands.camelCaseNameToLabel(prevName) : "";
151                         String oldLabel = graph.getPossibleRelatedValue(propertyInfo.resource, L0.HasLabel);
152                         boolean setLabel = oldLabel == null
153                                 || oldLabel.isEmpty()
154                                 || oldCamelCasedLabel.isEmpty()
155                                 || oldCamelCasedLabel.equals(oldLabel);
156
157                         ComponentTypeCommands.rename(graph, propertyInfo.resource, newValue);
158                         if (setLabel)
159                             ComponentTypeCommands.setLabel(graph, propertyInfo.resource, ComponentTypeCommands.camelCaseNameToLabel(newValue));
160                     }
161                 });
162             }
163         };
164         text.addListener(SWT.Modify, listener);
165         text.addListener(SWT.Deactivate, listener);
166         text.addListener(SWT.Traverse, listener);
167         text.addListener(SWT.Dispose, listener);
168
169         text.setText(selectedItem.getText(column));
170         text.selectAll();
171         text.setFocus();
172
173         editor.setEditor(text, selectedItem, column);
174     }
175
176     public void editType(Table table, TableEditor editor, final ComponentTypeViewerPropertyInfo propertyInfo, TableItem selectedItem, int column, final boolean convertDefaultValue) {
177         int extraStyle = propertyInfo.immutable ? SWT.READ_ONLY : 0;
178         final Combo combo = new Combo(table, SWT.NONE | extraStyle);
179         combo.setText(selectedItem.getText(column));
180         for(String suggestion : PROPERTY_TYPE_SUGGESTIONS)
181             combo.add(suggestion);
182         org.eclipse.swt.widgets.Listener listener = 
183                 new org.eclipse.swt.widgets.Listener() {
184             @Override
185             public void handleEvent(Event e) {
186                 if(e.type == SWT.Traverse) {
187                     if (e.detail == SWT.TRAVERSE_ESCAPE) {
188                         combo.dispose();
189                         e.doit = false;
190                         return;
191                     }
192                     if (e.detail == SWT.TRAVERSE_ARROW_NEXT
193                             || e.detail == SWT.TRAVERSE_ARROW_PREVIOUS
194                             || e.detail == SWT.TRAVERSE_MNEMONIC)
195                         return;
196                 }
197                 final String newValue = combo.getText();
198                 if (e.type == SWT.Traverse) {
199                     e.doit = false;
200                 }
201                 combo.dispose();
202
203                 if (propertyInfo.immutable)
204                     return;
205
206                 Simantics.getSession().async(new WriteRequest() {
207                     @Override
208                     public void perform(WriteGraph graph)
209                             throws DatabaseException {
210                         graph.markUndoPoint();
211                         ComponentTypeCommands.editType(graph, componentType, propertyInfo.resource, convertDefaultValue, newValue);
212                     }
213                 });
214             }
215         };
216         combo.setFocus();
217         editor.setEditor(combo, selectedItem, column);
218         combo.addListener(SWT.FocusOut, listener);
219         combo.addListener(SWT.Traverse, listener);
220     }
221
222     protected void editUnit(Table table, TableEditor editor, final ComponentTypeViewerPropertyInfo propertyInfo, TableItem selectedItem, int column) {
223         // Disallow unit editing for non-numeric configuration properties
224         if (propertyInfo.numberType == null && propertyInfo.sectionSpecificData == null)
225             return;
226
227         int extraStyle = propertyInfo.immutable ? SWT.READ_ONLY : 0;
228         final Combo combo = new Combo(table, SWT.NONE | extraStyle);
229         String initialValue = selectedItem.getText(column);
230         List<String> units = new ArrayList<>( unitLibrary.getUnits() );
231         Collections.sort(units, String.CASE_INSENSITIVE_ORDER);
232         int i = -1;
233         int selected = -1;
234         for (String unit : units) {
235             combo.add(unit);
236             if (unit.equals(initialValue))
237                 combo.select(i);
238         }
239         if (selected == -1)
240             combo.setText(initialValue);
241
242         org.eclipse.swt.widgets.Listener listener = 
243                 new org.eclipse.swt.widgets.Listener() {
244             @Override
245             public void handleEvent(Event e) {
246                 if(e.type == SWT.Traverse) {
247                     if (e.detail == SWT.TRAVERSE_ESCAPE) {
248                         combo.dispose();
249                         e.doit = false;
250                         return;
251                     }
252                     if (e.detail == SWT.TRAVERSE_ARROW_NEXT
253                             || e.detail == SWT.TRAVERSE_ARROW_PREVIOUS
254                             || e.detail == SWT.TRAVERSE_MNEMONIC)
255                         return;
256                 }
257                 final String newValue = combo.getText();
258                 if(e.type == SWT.Traverse) {
259                     e.doit = false;
260                 }
261                 combo.dispose();
262
263                 if (propertyInfo.immutable)
264                     return;
265
266                 Simantics.getSession().async(new WriteRequest() {
267                     @Override
268                     public void perform(WriteGraph graph)
269                             throws DatabaseException {
270                         graph.markUndoPoint();
271                         ComponentTypeCommands.setUnit(graph, componentType, propertyInfo.resource, newValue);
272                     }
273                 });
274             }
275         };
276         combo.setFocus();
277         editor.setEditor(combo, selectedItem, column);
278         combo.addListener(SWT.Deactivate, listener);
279         combo.addListener(SWT.Traverse, listener);
280     }
281
282     public void editValue(Table table, TableEditor editor,
283             final ComponentTypeViewerPropertyInfo propertyInfo,
284             TableItem selectedItem, int column,
285             final StringWriter writer,
286             final Function4<RequestProcessor, Resource, Resource, String, String> validator)
287     {
288         int extraStyle = writer == null ? SWT.READ_ONLY : 0;
289         final Text text = new Text(table, SWT.NONE | extraStyle);
290         text.setText(selectedItem.getText(column));
291         org.eclipse.swt.widgets.Listener listener = 
292                 new org.eclipse.swt.widgets.Listener() {
293             @Override
294             public void handleEvent(Event e) {
295                 if(e.type == SWT.Traverse) {
296                     if (e.detail == SWT.TRAVERSE_ESCAPE) {
297                         text.dispose();
298                         e.doit = false;
299                         return;
300                     }
301                     if (e.detail == SWT.TRAVERSE_ARROW_NEXT
302                             || e.detail == SWT.TRAVERSE_ARROW_PREVIOUS
303                             || e.detail == SWT.TRAVERSE_MNEMONIC)
304                         return;
305                 }
306                 final String newValue = text.getText();
307                 if(e.type == SWT.Traverse) {
308                     e.doit = false;
309                 }
310                 text.dispose();
311
312                 String error = validator.apply(Simantics.getSession(), componentType, propertyInfo.resource, newValue);
313                 if (error != null)
314                     return;
315
316                 if (writer != null) {
317                     Simantics.getSession().async(new WriteRequest() {
318                         @Override
319                         public void perform(WriteGraph graph) throws DatabaseException {
320                             writer.perform(graph, newValue);
321                         }
322                     });
323                 }
324             }
325         };
326         text.selectAll();
327         text.setFocus();
328         editor.setEditor(text, selectedItem, column);
329         text.addListener(SWT.FocusOut, listener);
330         text.addListener(SWT.Traverse, listener);
331
332         if (validator != null) {
333             org.eclipse.swt.widgets.Listener validationListener = new org.eclipse.swt.widgets.Listener() {
334                 @Override
335                 public void handleEvent(Event e) {
336                     final String newValue = text.getText();
337                     String error = validator.apply(Simantics.getSession(), componentType, propertyInfo.resource, newValue);
338                     if (error != null) {
339                         text.setBackground(text.getDisplay().getSystemColor(SWT.COLOR_RED));
340                         text.setToolTipText(error);
341                         return;
342                     } else {
343                         text.setBackground(null);
344                         text.setToolTipText(null);
345                     }
346                 }
347             };
348             text.addListener(SWT.Modify, validationListener);
349         }
350     }
351
352     private Range parseRange(NumberType numberType, String minStr, String maxStr, boolean lowInclusive, boolean highInclusive) throws RangeException {
353         try {
354             String rangeStr = (lowInclusive ? "[" : "(")  + minStr + ".." + maxStr + (highInclusive ? "]" : ")");
355             return Range.valueOf(rangeStr);
356         } catch (IllegalArgumentException e) {
357             // Limits are invalid
358             throw new RangeException(e.getMessage(), e);
359         }
360     }
361     
362     private static Combo createRangeInclusionCombo(Composite parent, boolean inclusive) {
363         Combo rng = new Combo(parent, SWT.READ_ONLY);
364         rng.add("Inclusive");
365         rng.add("Exclusive");
366         rng.select(inclusive ? 0 : 1);
367         return rng;
368     }
369     
370     protected void editRange(Table table, TableEditor editor, final ComponentTypeViewerPropertyInfo propertyInfo, TableItem selectedItem, Rectangle selectedItemBounds, int column) {
371         // Disallow range editing when the property is not numeric
372         if (propertyInfo.numberType == null)
373             return;
374
375         int extraTextStyle = propertyInfo.immutable ? SWT.READ_ONLY : 0;
376
377         // Parse initial range value
378         Range range = null;
379         String rangeStr = selectedItem.getText(column);
380         try {
381             range = Range.valueOf(rangeStr);
382         } catch (RangeException ex) {
383             range = new Range(Limit.nolimit(), Limit.nolimit());
384         }
385
386         final Shell shell = new Shell(table.getShell(), SWT.ON_TOP);
387         GridLayoutFactory.fillDefaults().applyTo(shell);
388
389         Composite composite = new Composite(shell, SWT.NONE);
390         GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
391         GridLayoutFactory.swtDefaults().numColumns(3).applyTo(composite);
392
393         Label low = new Label(composite, SWT.NONE);
394         low.setText("Minimum Value:");
395         final Text lowText = new Text(composite, SWT.BORDER | extraTextStyle);
396         GridDataFactory.fillDefaults().grab(true, false).hint(100, SWT.DEFAULT).applyTo(lowText);
397         final Combo lowSelector = createRangeInclusionCombo(composite, !range.getLower().isExclusive());
398         Label high = new Label(composite, SWT.NONE);
399         high.setText("Maximum Value:");
400         final Text highText = new Text(composite, SWT.BORDER | extraTextStyle);
401         GridDataFactory.fillDefaults().grab(true, false).hint(100, SWT.DEFAULT).applyTo(highText);
402         final Combo highSelector = createRangeInclusionCombo(composite, !range.getUpper().isExclusive());
403
404         Composite buttonComposite = new Composite(shell, SWT.NONE);
405         GridDataFactory.fillDefaults().grab(true, false).align(SWT.TRAIL, SWT.FILL).applyTo(buttonComposite);
406         GridLayoutFactory.swtDefaults().numColumns(2).equalWidth(true).applyTo(buttonComposite);
407
408         Button ok = new Button(buttonComposite, SWT.NONE);
409         ok.setText("&OK");
410         GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).applyTo(ok);
411         Button cancel = new Button(buttonComposite, SWT.NONE);
412         cancel.setText("&Cancel");
413         GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).applyTo(ok);
414
415         if (range.getLower().getValue() != null)
416             lowText.setText(range.getLower().getValue().toString());
417         if (range.getUpper().getValue() != null)
418             highText.setText(range.getUpper().getValue().toString());
419
420         shell.addListener(SWT.Deactivate, new org.eclipse.swt.widgets.Listener() {
421             @Override
422             public void handleEvent(Event event) {
423                 shell.dispose();
424             }
425         });
426
427         ok.addSelectionListener(new SelectionAdapter() {
428             public void widgetSelected(SelectionEvent e) {
429                 try {
430                     final Range newRange = parseRange(propertyInfo.numberType,
431                             lowText.getText().trim(),
432                             highText.getText().trim(),
433                             lowSelector.getSelectionIndex() == 0 ? true : false,
434                             highSelector.getSelectionIndex() == 0 ? true : false);
435
436                     shell.dispose();
437
438                     if (propertyInfo.immutable)
439                         return;
440
441                     Simantics.getSession().async(new WriteRequest() {
442                         @Override
443                         public void perform(WriteGraph graph)
444                                 throws DatabaseException {
445                             graph.markUndoPoint();
446                             ComponentTypeCommands.setRange(graph, componentType, propertyInfo.resource, newRange == null ? null : newRange.toString());
447                         }
448                     });
449                 } catch (RangeException ex) {
450                     ErrorLogger.defaultLogError(ex);
451                 }
452             }
453         });
454         cancel.addSelectionListener(new SelectionAdapter() {
455             public void widgetSelected(SelectionEvent e) {
456                 shell.dispose();
457             }
458         });
459
460         shell.pack();
461         Point size = shell.getSize();
462
463         Display display = table.getDisplay();
464         Rectangle clientArea = display.getClientArea();
465         Point bt = table.toDisplay(selectedItemBounds.x, selectedItemBounds.y);
466         Rectangle b = selectedItemBounds;
467         b.x = bt.x;
468         b.y = bt.y;
469         b.width = size.x;
470         b.height = size.y;
471         if ((b.x + b.width) > clientArea.width)
472             b.x -= b.x + b.width - clientArea.width;
473         if (b.height > clientArea.height)
474             b.height = clientArea.height;
475         if ((b.y + b.height) > clientArea.height)
476             b.y -= b.y + b.height - clientArea.height;
477
478         shell.setBounds(selectedItemBounds);
479         shell.open();
480     }
481
482     protected void editMultilineText(Table table, TableEditor editor,
483             final ComponentTypeViewerPropertyInfo propertyInfo, TableItem selectedItem,
484             Rectangle selectedItemBounds, int column, final StringWriter writer)
485     {
486         final Shell shell = new Shell(table.getShell(), SWT.ON_TOP);
487         GridLayoutFactory.fillDefaults().spacing(0, 0).applyTo(shell);
488         final StyledText text = new StyledText(shell, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | (propertyInfo.immutable ? SWT.READ_ONLY : 0));
489         GridDataFactory.fillDefaults().grab(true, true).applyTo(text);
490         text.setText(selectedItem.getText(column));
491         org.eclipse.swt.widgets.Listener listener = 
492                 new org.eclipse.swt.widgets.Listener() {
493             @Override
494             public void handleEvent(Event e) {
495                 final String newValue = text.getText();
496
497                 if (e.type == SWT.Traverse) {
498                     if (e.detail == SWT.TRAVERSE_ESCAPE) {
499                         shell.dispose();
500                         e.doit = false;
501                         return;
502                     }
503                     if (e.detail == SWT.TRAVERSE_ARROW_NEXT
504                             || e.detail == SWT.TRAVERSE_ARROW_PREVIOUS
505                             || e.detail == SWT.TRAVERSE_MNEMONIC)
506                         return;
507                     if ((e.stateMask & SWT.CTRL) == 0)
508                         return;
509                     e.doit = false;
510                 }
511
512                 shell.dispose();
513
514                 if (propertyInfo.immutable)
515                     return;
516
517                 if (writer != null) {
518                     Simantics.getSession().async(new WriteRequest() {
519                         @Override
520                         public void perform(WriteGraph graph) throws DatabaseException {
521                             writer.perform(graph, newValue);
522                         }
523                     });
524                 }
525             }
526         };
527
528         String helpText = propertyInfo.immutable ? "ESC to close." : "Ctrl+Enter to apply changes, ESC to cancel.";
529         Label help = tk.createLabel(shell, helpText, SWT.BORDER | SWT.FLAT);
530         GridDataFactory.fillDefaults().grab(true, false).align(SWT.FILL, SWT.CENTER).applyTo(help);
531         help.setForeground( tk.getColors().createColor( "fg", tk.getColors().getSystemColor(SWT.COLOR_LIST_SELECTION) ) );
532
533         Display display = table.getDisplay();
534         Rectangle clientArea = display.getClientArea();
535         Point bt = table.toDisplay(selectedItemBounds.x, selectedItemBounds.y);
536         Rectangle b = selectedItemBounds;
537         b.x = bt.x;
538         b.y = bt.y;
539         b.height = 200;
540         if ((b.x + b.width) > clientArea.width)
541             b.x -= b.x + b.width - clientArea.width;
542         if (b.height > clientArea.height)
543             b.height = clientArea.height;
544         if ((b.y + b.height) > clientArea.height)
545             b.y -= b.y + b.height - clientArea.height;
546
547         shell.setBounds(selectedItemBounds);
548         shell.open();
549
550         text.selectAll();
551         text.setFocus();
552
553         text.addListener(SWT.Traverse, listener);
554         shell.addListener(SWT.Deactivate, listener);
555     }
556
557     private String validatePropertyName(ComponentTypeViewerPropertyInfo propertyInfo, String propertyName, Pattern namePattern) {
558         if (propertyName.equals(propertyInfo.name))
559             return null;
560         for (ComponentTypeViewerPropertyInfo info : properties) {
561             if (propertyName.equals(info.name))
562                 return "Property name '" + propertyName + "' is already in use.";
563         }
564         for (NamedResource cp : connectionPoints) {
565             if (propertyName.equals(cp.getName()))
566                 return "Name '" + propertyName + "' is already used for a terminal.";
567         }
568         Matcher m = namePattern.matcher(propertyName);
569         if (!m.matches())
570             return "Property name '" + propertyName + "' contains invalid characters, does not match pattern "
571                     + namePattern.pattern() + ".";
572         return null;
573     }
574
575 }