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 == null) return new StringList(new String[0]);
24 if(o instanceof StringList) return (StringList)o;
25 if(o instanceof List) return new StringList((List)o);
26 if(o instanceof String[]) return new StringList((String[])o);
27 throw new IllegalArgumentException("Unaccepted format for available " + o.getClass().getName());
31 protected void doUpdateProperties(SWTDocument document, Combo combo, JSONObject object) {
33 if(combo.isDisposed()) return;
35 if(modifyListener != null)
36 combo.removeModifyListener(modifyListener);
38 StringList availableList = extractAvailable(object.getJSONField("available"));
39 String selected = object.getJSONField("selected");
41 String[] available = availableList.strings;
42 String[] current = combo.getItems();
44 if(!Arrays.equals(available, current)) {
45 combo.clearSelection();
47 for(String key : available) {
53 for(;index<available.length;index++) if(available[index].equals(selected)) break;
55 if(index == available.length) {
56 combo.clearSelection();
61 if(modifyListener != null)
62 combo.addModifyListener(modifyListener);
67 protected Combo doCreateControl(final SWTDocument document, Composite parent, JSONObject object) {
68 final Combo combo = new Combo(parent, SWT.READ_ONLY);
69 final AbstractEventHandler onModify = object.getJSONField("onModify");
70 if(onModify != null) {
71 modifyListener = new ModifyListener() {
74 public void modifyText(ModifyEvent e) {
75 String[] items = combo.getItems();
76 int index = combo.getSelectionIndex();
77 if(index >=0 && index < items.length) {
78 CommandContextImpl parameters = new CommandContextImpl();
79 parameters.putString("selected", items[index]);
80 document.post(onModify, parameters);
86 combo.addModifyListener(modifyListener);