1 package org.simantics.document.swt.core.widget;
3 import java.util.Arrays;
6 import org.eclipse.swt.SWT;
7 import org.eclipse.swt.events.ModifyEvent;
8 import org.eclipse.swt.events.ModifyListener;
9 import org.eclipse.swt.widgets.Combo;
10 import org.eclipse.swt.widgets.Composite;
11 import org.simantics.document.server.JSONObject;
12 import org.simantics.document.server.handler.AbstractEventHandler;
13 import org.simantics.document.server.io.CommandContextImpl;
14 import org.simantics.document.swt.core.SWTDocument;
15 import org.simantics.document.swt.core.base.LeafWidgetManager;
16 import org.simantics.document.swt.core.bean.StringList;
18 public class ComboWidget extends LeafWidgetManager<Combo> {
20 private ModifyListener modifyListener = null;
22 private StringList extractAvailable(Object o) {
23 if(o instanceof StringList) return (StringList)o;
24 if(o instanceof List) return new StringList((List)o);
25 if(o instanceof String[]) return new StringList((String[])o);
26 throw new IllegalArgumentException("Unaccepted format for available " + o.getClass().getName());
30 protected void doUpdateProperties(SWTDocument document, Combo combo, JSONObject object) {
32 if(combo.isDisposed()) return;
34 if(modifyListener != null)
35 combo.removeModifyListener(modifyListener);
37 StringList availableList = extractAvailable(object.getJSONField("available"));
38 String selected = object.getJSONField("selected");
40 String[] available = availableList.strings;
41 String[] current = combo.getItems();
43 if(!Arrays.equals(available, current)) {
44 combo.clearSelection();
46 for(String key : available) {
52 for(;index<available.length;index++) if(available[index].equals(selected)) break;
54 if(index == available.length) {
55 combo.clearSelection();
60 if(modifyListener != null)
61 combo.addModifyListener(modifyListener);
66 protected Combo doCreateControl(final SWTDocument document, Composite parent, JSONObject object) {
67 final Combo combo = new Combo(parent, SWT.READ_ONLY);
68 final AbstractEventHandler onModify = object.getJSONField("onModify");
69 if(onModify != null) {
70 modifyListener = new ModifyListener() {
73 public void modifyText(ModifyEvent e) {
74 String[] items = combo.getItems();
75 int index = combo.getSelectionIndex();
76 if(index >=0 && index < items.length) {
77 CommandContextImpl parameters = new CommandContextImpl();
78 parameters.putString("selected", items[index]);
79 document.post(onModify, parameters);
85 combo.addModifyListener(modifyListener);