View | Details | Raw Unified | Return to bug 253860
Collapse All | Expand All

(-)src/org/eclipse/mtj/core/model/device/preprocess/DeviceSymbolDefinitionSetFactory.java (+22 lines)
Lines 11-16 Link Here
11
 */
11
 */
12
package org.eclipse.mtj.core.model.device.preprocess;
12
package org.eclipse.mtj.core.model.device.preprocess;
13
13
14
import java.util.HashMap;
14
import java.util.Iterator;
15
import java.util.Iterator;
15
import java.util.Map;
16
import java.util.Map;
16
import java.util.Properties;
17
import java.util.Properties;
Lines 92-95 Link Here
92
93
93
        return definitionSet;
94
        return definitionSet;
94
    }
95
    }
96
    
97
    public static SymbolDefinitionSet createSymbolDefinitionSet(String name, HashMap<String, String> symbols) {
98
    	
99
    	SymbolDefinitionSet definitionSet = new SymbolDefinitionSet(name);
100
        definitionSet.define(name);
101
102
        for (Iterator<String> iterator = symbols.keySet().iterator(); iterator.hasNext();) {
103
            String key = iterator.next();
104
            try {
105
                String value = symbols.get(key);
106
                definitionSet.define(key, value);
107
            } 
108
            catch (RuntimeException e) {
109
                MTJCorePlugin.log(IStatus.ERROR, e);
110
            }
111
        }
112
    	
113
        return definitionSet;
114
    }
115
    
116
    
95
}
117
}
(-)src/org/eclipse/mtj/core/model/preprocessor/SymbolDefinitionSet.java (-13 / +16 lines)
Lines 18-23 Link Here
18
import java.util.HashMap;
18
import java.util.HashMap;
19
import java.util.Iterator;
19
import java.util.Iterator;
20
import java.util.Map;
20
import java.util.Map;
21
import java.util.Properties;
21
22
22
import org.eclipse.mtj.core.model.preprocessor.symbol.SymbolUtils;
23
import org.eclipse.mtj.core.model.preprocessor.symbol.SymbolUtils;
23
import org.eclipse.mtj.core.persistence.IPersistable;
24
import org.eclipse.mtj.core.persistence.IPersistable;
Lines 163-168 Link Here
163
                map.put(key, value);
164
                map.put(key, value);
164
            }
165
            }
165
        }
166
        }
167
        
168
        Properties properties = persistenceProvider.loadProperties(KEYS_KEY);
169
        if(properties != null) {
170
	        Iterator<?> iterator = properties.keySet().iterator();
171
	        while(iterator.hasNext()) {
172
	        	String key = (String) iterator.next();
173
	        	String value = properties.getProperty(key);
174
	        	map.put(key, value);
175
	        }
176
        }
177
        
166
    }
178
    }
167
179
168
    /**
180
    /**
Lines 194-217 Link Here
194
        // Store off the entries in the object
206
        // Store off the entries in the object
195
        StringBuffer sb = new StringBuffer();
207
        StringBuffer sb = new StringBuffer();
196
        Iterator<?> entries = map.entrySet().iterator();
208
        Iterator<?> entries = map.entrySet().iterator();
209
        Properties properties = new Properties();
197
        while (entries.hasNext()) {
210
        while (entries.hasNext()) {
198
            Map.Entry<?, ?> entry = (Map.Entry<?, ?>) entries.next();
211
            Map.Entry<?, ?> entry = (Map.Entry<?, ?>) entries.next();
199
212
200
            // Add the key to the list of keys
213
            properties.put(entry.getKey(), entry.getValue());
201
            String key = (String) entry.getKey();
202
            sb.append(key);
203
            if (entries.hasNext()) {
204
                sb.append(",");
205
            }
206
207
            // Add the entry to the object
208
            persistenceProvider.storeString(key, entry.getValue().toString());
209
        }
214
        }
210
215
211
        // Store the list of the keys that can be used to reconstruct
216
        persistenceProvider.storeProperties(KEYS_KEY, properties);
212
        // this object as a comma-separated list
217
        
213
        persistenceProvider.storeString(KEYS_KEY + getStorableName(), sb
214
                .toString());
215
    }
218
    }
216
219
217
    /**
220
    /**
(-)src/org/eclipse/mtj/ui/internal/preferences/SymbolDefinitionsPreferencePage.java (-5 / +44 lines)
Lines 52-58 Link Here
52
import org.eclipse.jface.viewers.TextCellEditor;
52
import org.eclipse.jface.viewers.TextCellEditor;
53
import org.eclipse.jface.viewers.Viewer;
53
import org.eclipse.jface.viewers.Viewer;
54
import org.eclipse.jface.viewers.ViewerSorter;
54
import org.eclipse.jface.viewers.ViewerSorter;
55
import org.eclipse.jface.window.Window;
56
import org.eclipse.jface.wizard.WizardDialog;
55
import org.eclipse.mtj.core.internal.MTJCorePlugin;
57
import org.eclipse.mtj.core.internal.MTJCorePlugin;
58
import org.eclipse.mtj.core.model.device.DeviceRegistry;
59
import org.eclipse.mtj.core.model.device.IDevice;
56
import org.eclipse.mtj.core.model.preprocessor.ISymbolDefinitionSetChangeListener;
60
import org.eclipse.mtj.core.model.preprocessor.ISymbolDefinitionSetChangeListener;
57
import org.eclipse.mtj.core.model.preprocessor.SymbolDefinitionSet;
61
import org.eclipse.mtj.core.model.preprocessor.SymbolDefinitionSet;
58
import org.eclipse.mtj.core.model.preprocessor.SymbolDefinitionSetRegistry;
62
import org.eclipse.mtj.core.model.preprocessor.SymbolDefinitionSetRegistry;
Lines 456-461 Link Here
456
460
457
    private Button addSetButton;
461
    private Button addSetButton;
458
    private Button addSymbolButton;
462
    private Button addSymbolButton;
463
    private Button importSetButton;
459
    // Tracks the current definitions in the table viewer until they
464
    // Tracks the current definitions in the table viewer until they
460
    // are committed back to the underlying model
465
    // are committed back to the underlying model
461
    private ArrayList<SymbolDefinition> currentDefinitions;
466
    private ArrayList<SymbolDefinition> currentDefinitions;
Lines 642-647 Link Here
642
    }
647
    }
643
648
644
    /**
649
    /**
650
     * The import set button has been selected.
651
     */
652
    private void handleImportSetButton() {
653
    	
654
    	SymbolDefinitionsImportWizard wizard = new SymbolDefinitionsImportWizard();
655
    	
656
        WizardDialog dialog = new WizardDialog(this.getShell(), wizard);
657
        if(dialog.open() == Window.OK) {
658
        	definitionsComboViewer.refresh();
659
        }
660
        //try {
661
    		
662
    	//}
663
    	//catch(PersistenceException e) {
664
    	//	handleException("Error import definition set", e);
665
    	//}
666
    
667
    }
668
    
669
    /**
645
     * The add symbol button has been selected.
670
     * The add symbol button has been selected.
646
     */
671
     */
647
    private void handleAddSymbolButton() {
672
    private void handleAddSymbolButton() {
Lines 812-833 Link Here
812
            handleException("Error retrieving symbol definitions", e1);
837
            handleException("Error retrieving symbol definitions", e1);
813
        }
838
        }
814
839
840
        
815
        SymbolDefinitionSetRegistry.singleton
841
        SymbolDefinitionSetRegistry.singleton
816
                .addSymbolDefinitionSetChangeListener(new ISymbolDefinitionSetChangeListener() {
842
                .addSymbolDefinitionSetChangeListener(new ISymbolDefinitionSetChangeListener() {
817
818
                    /*
843
                    /*
819
                     * (non-Javadoc)
844
                     * (non-Javadoc)
820
                     * @seeorg.eclipse.mtj.core.model.preprocessor.
845
                     * @seeorg.eclipse.mtj.core.model.preprocessor.
821
                     * ISymbolDefinitionSetChangeListener
846
                     * ISymbolDefinitionSetChangeListener
822
                     * #symbolDefinitionSetChanged()
847
                     * #symbolDefinitionSetChanged()
823
                     */
848
                     */
824
                    public void symbolDefinitionSetChanged() {
849
                    
850
                public void symbolDefinitionSetChanged() {
851
                	
825
                        try {
852
                        try {
826
                            definitionSetsinput = SymbolDefinitionSetRegistry.singleton
853
                            definitionSetsinput = SymbolDefinitionSetRegistry.singleton
827
                                    .getAllSetDefinitions();
854
                                    .getAllSetDefinitions();
828
                            if ((definitionsComboViewer != null)
855
                            if ((definitionsComboViewer != null) && 
829
                                    && (!definitionsComboViewer.getControl()
856
                                (!definitionsComboViewer.getControl().isDisposed()) &&
830
                                            .isDisposed())) {
857
                                workbench.getActiveWorkbenchWindow() != null) {
831
858
832
                                definitionsComboViewer.refresh();
859
                                definitionsComboViewer.refresh();
833
                            }
860
                            }
Lines 838-843 Link Here
838
865
839
                    }
866
                    }
840
                });
867
                });
868
                
841
869
842
        Composite composite = new Composite(parent, SWT.NONE);
870
        Composite composite = new Composite(parent, SWT.NONE);
843
        composite.setLayout(new GridLayout(1, true));
871
        composite.setLayout(new GridLayout(1, true));
Lines 892-897 Link Here
892
                handleRemoveSetButton();
920
                handleRemoveSetButton();
893
            }
921
            }
894
        });
922
        });
923
        
924
        importSetButton = new Button(nameButtonComposite, SWT.PUSH);
925
        importSetButton.setText("Import");
926
        importSetButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
927
        importSetButton.addSelectionListener(new SelectionAdapter() {
928
            @Override
929
            public void widgetSelected(SelectionEvent e) {
930
                handleImportSetButton();
931
            }
932
        });
933
        
895
934
896
        symbolsGroup = new Group(composite, SWT.FILL);
935
        symbolsGroup = new Group(composite, SWT.FILL);
897
        symbolsGroup.setLayout(new GridLayout(2, false));
936
        symbolsGroup.setLayout(new GridLayout(2, false));
(-)src/org/eclipse/mtj/ui/internal/preferences/SymbolDefinitionsImportWizard.java (+357 lines)
Line 0 Link Here
1
package org.eclipse.mtj.ui.internal.preferences;
2
3
import java.io.File;
4
import java.io.FileInputStream;
5
import java.io.IOException;
6
import java.io.InputStream;
7
import java.lang.reflect.InvocationTargetException;
8
import java.util.Enumeration;
9
import java.util.HashMap;
10
import java.util.HashMap;
11
import java.util.Iterator;
12
import java.util.StringTokenizer;
13
import java.util.Vector;
14
import java.util.jar.JarEntry;
15
import java.util.jar.JarFile;
16
17
import javax.xml.parsers.DocumentBuilder;
18
import javax.xml.parsers.DocumentBuilderFactory;
19
import javax.xml.parsers.ParserConfigurationException;
20
21
import org.eclipse.core.runtime.CoreException;
22
import org.eclipse.core.runtime.IProgressMonitor;
23
import org.eclipse.core.runtime.IStatus;
24
import org.eclipse.jface.operation.IRunnableWithProgress;
25
import org.eclipse.jface.preference.IPreferenceStore;
26
import org.eclipse.jface.wizard.IWizardContainer;
27
import org.eclipse.jface.wizard.Wizard;
28
import org.eclipse.mtj.core.IMTJCoreConstants;
29
import org.eclipse.mtj.core.internal.MTJCorePlugin;
30
import org.eclipse.mtj.core.model.device.DeviceFactory;
31
import org.eclipse.mtj.core.model.device.preprocess.DeviceSymbolDefinitionSetFactory;
32
import org.eclipse.mtj.core.model.preprocessor.SymbolDefinitionSet;
33
import org.eclipse.mtj.core.model.preprocessor.SymbolDefinitionSetRegistry;
34
import org.eclipse.mtj.ui.internal.MTJUIPlugin;
35
import org.eclipse.ui.PlatformUI;
36
import org.eclipse.ui.progress.IProgressService;
37
import org.w3c.dom.Document;
38
import org.w3c.dom.Element;
39
import org.w3c.dom.NodeList;
40
import org.xml.sax.SAXException;
41
42
public class SymbolDefinitionsImportWizard extends Wizard {
43
44
45
	private static final String J2MEPOLISH_CAPABILITY_SEPARATOR = ",";
46
	
47
	private SymbolDefinitionsImportWizardPage wizardPage;
48
	
49
	private String importDirectory = null;
50
	
51
	public SymbolDefinitionsImportWizard() {
52
        
53
		super();
54
        setNeedsProgressMonitor(true);
55
        setWindowTitle("Import Devices");
56
        
57
    }
58
59
	
60
	@Override
61
	public boolean performFinish() {
62
		IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
63
		switch(wizardPage.getImportType()) {
64
			case SymbolDefinitionsImportWizardPage.IMPORT_FROM_ANTENNA_JAR:
65
				try {
66
					progressService.run(true, true, getProcessImportFromAntennaJarFile());
67
				} 
68
				catch (InvocationTargetException e) {
69
					e.printStackTrace();
70
				} 
71
				catch (InterruptedException e) {
72
					e.printStackTrace();
73
				}
74
				break;
75
				
76
			case SymbolDefinitionsImportWizardPage.IMPORT_J2MEPOLISH_FORMAT:
77
				importDirectory = wizardPage.getDirectory();
78
				try {
79
					progressService.run(true, true, getProcessImportFromXMLFiles());
80
				} 
81
				catch (InvocationTargetException e) {
82
					e.printStackTrace();
83
				} 
84
				catch (InterruptedException e) {
85
					e.printStackTrace();
86
				}
87
				break;
88
			case SymbolDefinitionsImportWizardPage.IMPORT_MTJ_FORMAT:
89
		
90
				break;
91
		}
92
		
93
		return true;
94
	}
95
96
97
	@Override
98
	public void addPages() {
99
		 wizardPage = new SymbolDefinitionsImportWizardPage();
100
	     addPage(wizardPage);
101
	}
102
103
	
104
	private IRunnableWithProgress getProcessImportFromAntennaJarFile() {
105
		
106
		// The runnable to do import definitions
107
		return new IRunnableWithProgress() {
108
			public void run(IProgressMonitor monitor) {
109
				JarFile antennaFileJar = null;
110
				try {
111
					IPreferenceStore preferenceStore = MTJUIPlugin.getDefault().getCorePreferenceStore();
112
					String antennaFile = preferenceStore.getString(IMTJCoreConstants.PREF_ANTENNA_JAR);
113
114
					// search devices.xml & groups.xml from Antenna Jar file
115
					InputStream devicesInputStream = null;
116
					InputStream groupsInputStream = null;
117
					antennaFileJar = new JarFile(new File(antennaFile));
118
					Enumeration<JarEntry> e = antennaFileJar.entries();
119
					while(e.hasMoreElements()) {
120
						JarEntry entry = e.nextElement();
121
						if(entry.getName().toLowerCase().equals("devices.xml")) {
122
							devicesInputStream = antennaFileJar.getInputStream(entry);
123
						}
124
						if(entry.getName().toLowerCase().equals("groups.xml")) {
125
							groupsInputStream = antennaFileJar.getInputStream(entry);
126
						}
127
					}
128
					if(devicesInputStream != null && groupsInputStream != null) {
129
						try {
130
							importFromJ2MEPolishFormat(devicesInputStream, groupsInputStream);
131
						}
132
						catch(Exception ex) {
133
							ex.printStackTrace();
134
						}
135
					}
136
				} 
137
				catch (IOException e) {
138
					e.printStackTrace();
139
				}
140
				finally {
141
					try {
142
						antennaFileJar.close();
143
					}
144
					catch(Exception e) {
145
					}
146
				}
147
					
148
		    }
149
		};
150
		
151
	}
152
	
153
	private IRunnableWithProgress getProcessImportFromXMLFiles() {
154
		
155
		// The runnable to do import definitions
156
		return new IRunnableWithProgress() {
157
			public void run(IProgressMonitor monitor) {
158
				InputStream devicesInputStream = null;
159
				InputStream groupsInputStream = null;
160
				try {
161
					// search devices.xml & groups.xml from Antenna Jar file
162
					devicesInputStream = new FileInputStream(new File(importDirectory + File.separator + "devices.xml"));
163
					groupsInputStream = new FileInputStream(new File(importDirectory + File.separator + "groups.xml"));
164
					if(devicesInputStream != null && groupsInputStream != null) {
165
						try {
166
							importFromJ2MEPolishFormat(devicesInputStream, groupsInputStream);
167
						}
168
						catch(Exception ex) {
169
							ex.printStackTrace();
170
						}
171
					}
172
				} 
173
				catch (IOException e) {
174
					e.printStackTrace();
175
				}
176
				finally {
177
					try {
178
						devicesInputStream.close();
179
					}
180
					catch(Exception e) {
181
					}
182
					try {
183
						groupsInputStream.close();
184
					}
185
					catch(Exception e) {
186
					}
187
				}
188
					
189
		    }
190
		};
191
192
	}
193
	
194
195
	/*
196
	 * Functions for importFromJ2MEPolishFormat:
197
	 *  	- importFromJ2MEPolishFormat
198
	 *  	- prepareGroups
199
	 *  	- getGroupCapabilities
200
	 *      - copyCapabilities
201
	 *      - copyCapability
202
	 *      - mergeCapabilities
203
	 */
204
	private void importFromJ2MEPolishFormat(InputStream devicesInputStream, InputStream groupsInputStream) {
205
		
206
		try {
207
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
208
			DocumentBuilder db = dbf.newDocumentBuilder();
209
			
210
			Document devicesDOM = db.parse(devicesInputStream);
211
			Document groupsDOM = db.parse(groupsInputStream);
212
			
213
			HashMap<String, Element> groups = prepareGroups(groupsDOM);
214
			
215
			NodeList nl = devicesDOM.getElementsByTagName("device");
216
			for(int i = 0; i < nl.getLength(); i++) {
217
				
218
				HashMap<String, String> capabilities = new HashMap<String, String>();
219
				HashMap<String, String> groupCapabilities;
220
				String features;
221
				
222
				Element deviceElement = (Element) nl.item(i);
223
				String name = ((Element) deviceElement.getElementsByTagName("identifier").item(0)).getTextContent();
224
				
225
				Element featuresElement = (Element) deviceElement.getElementsByTagName("features").item(0);
226
				if(featuresElement != null) {
227
					features = featuresElement.getTextContent();
228
					capabilities.put("features", features);
229
				}
230
	
231
				Element groupElement = (Element) deviceElement.getElementsByTagName("groups").item(0);
232
				if(groupElement != null) {
233
					StringTokenizer st = new StringTokenizer(groupElement.getTextContent(), J2MEPOLISH_CAPABILITY_SEPARATOR);
234
					while(st.hasMoreTokens()) {
235
						String group = st.nextToken().trim();
236
						groupCapabilities = getGroupCapabilities(groups, group);
237
						copyCapabilities(capabilities, groupCapabilities);
238
					}
239
					capabilities.put("groups", groupElement.getTextContent().toLowerCase());
240
				}
241
				
242
				NodeList capabilitiesNL = deviceElement.getElementsByTagName("capability");
243
				for(int j = 0; j < capabilitiesNL.getLength(); j++) {
244
					Element capabilityElement = (Element) capabilitiesNL.item(j);
245
					copyCapability(capabilities, capabilityElement.getAttribute("name"), capabilityElement.getAttribute("value"));
246
				}
247
				
248
				capabilities.put(name, "true");
249
				
250
				StringTokenizer st = new StringTokenizer(name, J2MEPOLISH_CAPABILITY_SEPARATOR);
251
				while(st.hasMoreTokens()) {
252
					String device = st.nextToken().trim();
253
					device = device.replace('/', '_');
254
					device = device.replace('(', '_');
255
					device = device.replace(')', '_');
256
257
					SymbolDefinitionSet definitionSet = DeviceSymbolDefinitionSetFactory.createSymbolDefinitionSet(device, capabilities);
258
					SymbolDefinitionSetRegistry.singleton.addDefinitionSet(definitionSet);
259
				}
260
			}
261
			SymbolDefinitionSetRegistry.singleton.store();
262
			
263
		}
264
		catch(Exception e) {
265
			MTJCorePlugin.log(IStatus.ERROR, e);
266
		}
267
		
268
	}
269
	
270
	private HashMap<String, Element> prepareGroups(Document groupsDOM) {
271
272
		HashMap<String, Element> result = new HashMap<String, Element>();
273
		
274
		NodeList nl = groupsDOM.getElementsByTagName("group");
275
		for(int i = 0; i < nl.getLength(); i++) {
276
			Element groupElement = (Element) nl.item(i);
277
			String name = ((Element) groupElement.getElementsByTagName("name").item(0)).getTextContent();
278
			result.put(name, groupElement);
279
		}
280
		
281
		return result;
282
	}
283
	
284
	private HashMap<String, String> getGroupCapabilities(HashMap<String, Element> groups, String name) {
285
		
286
		Element groupElement = groups.get(name);
287
		
288
		HashMap<String, String> result = new HashMap<String, String>();
289
		
290
		NodeList nl = groupElement.getElementsByTagName("parent");
291
		if(nl != null && nl.getLength() > 0) {
292
			Element parent = (Element) nl.item(0);
293
			String parentValue = parent.getTextContent(); 
294
			if(parentValue != null && !parent.getTextContent().equals("")) {
295
				HashMap<String, String> parentCapabilities = getGroupCapabilities(groups, parent.getTextContent());
296
				copyCapabilities(result, parentCapabilities);
297
			}
298
		}
299
		
300
		
301
		nl = groupElement.getElementsByTagName("capability");
302
		for(int i = 0; i < nl.getLength(); i++) {
303
			Element capabilityElement = (Element) nl.item(i);
304
			result.put(capabilityElement.getAttribute("name"), capabilityElement.getAttribute("value"));
305
		}
306
		
307
		return result;
308
		
309
	}
310
	
311
	private void copyCapabilities(HashMap<String, String> capabilities, HashMap<String, String> parentCapabilities) {
312
		Iterator<String> i = parentCapabilities.keySet().iterator();
313
		while(i.hasNext()) {
314
			String capability = i.next();
315
			copyCapability(capabilities, capability, parentCapabilities.get(capability));
316
		}
317
	}
318
	
319
	
320
	private void copyCapability(HashMap<String, String> capabilities, String name, String capability) {
321
		
322
		String currentCapabilityValue = capabilities.get(name);
323
		if(currentCapabilityValue == null || currentCapabilityValue.equals("")) {
324
			capabilities.put(name, capability);
325
		}
326
		else {
327
			String mergedCapabilities = mergeCapabilities(currentCapabilityValue, capability);
328
			capabilities.put(name, mergedCapabilities);
329
		}
330
		
331
	}
332
	
333
	private String mergeCapabilities(String currentCapability, String newCapability) {
334
		
335
		Vector<String> v = new Vector<String>();
336
		StringTokenizer st = new StringTokenizer(currentCapability, J2MEPOLISH_CAPABILITY_SEPARATOR);
337
		while(st.hasMoreTokens()) {
338
			v.add(st.nextToken().trim());
339
		}
340
		st = new StringTokenizer(newCapability, J2MEPOLISH_CAPABILITY_SEPARATOR);
341
		while(st.hasMoreTokens()) {
342
			String capability = st.nextToken().trim();
343
			if(v.indexOf(capability) == -1) {
344
				v.add(capability);
345
			}
346
		}
347
		String result = "";
348
		for(int i = 0; i < v.size(); i++) {
349
			if(i > 0) {
350
				result = result.concat(",");
351
			}
352
			result = result.concat(v.elementAt(i));
353
		}
354
		
355
		return result;
356
	}
357
}
(-)src/org/eclipse/mtj/ui/internal/preferences/SymbolDefinitionsImportWizardPage.java (+246 lines)
Line 0 Link Here
1
package org.eclipse.mtj.ui.internal.preferences;
2
3
import java.io.File;
4
5
import javax.sql.rowset.Predicate;
6
7
import org.eclipse.jface.dialogs.IDialogSettings;
8
import org.eclipse.jface.preference.FieldEditor;
9
import org.eclipse.jface.preference.FileFieldEditor;
10
import org.eclipse.jface.preference.IPreferenceStore;
11
import org.eclipse.jface.wizard.WizardPage;
12
import org.eclipse.mtj.core.IMTJCoreConstants;
13
import org.eclipse.mtj.ui.internal.MTJUIPlugin;
14
import org.eclipse.swt.SWT;
15
import org.eclipse.swt.events.ControlAdapter;
16
import org.eclipse.swt.events.ControlEvent;
17
import org.eclipse.swt.events.ModifyEvent;
18
import org.eclipse.swt.events.ModifyListener;
19
import org.eclipse.swt.events.SelectionAdapter;
20
import org.eclipse.swt.events.SelectionEvent;
21
import org.eclipse.swt.graphics.Point;
22
import org.eclipse.swt.layout.GridData;
23
import org.eclipse.swt.layout.GridLayout;
24
import org.eclipse.swt.widgets.Button;
25
import org.eclipse.swt.widgets.Composite;
26
import org.eclipse.swt.widgets.DirectoryDialog;
27
import org.eclipse.swt.widgets.FileDialog;
28
import org.eclipse.swt.widgets.Group;
29
import org.eclipse.swt.widgets.Label;
30
import org.eclipse.swt.widgets.Text;
31
32
public class SymbolDefinitionsImportWizardPage extends WizardPage {
33
34
	public static final int IMPORT_FROM_ANTENNA_JAR  = 0;
35
	public static final int IMPORT_J2MEPOLISH_FORMAT = 1;
36
	public static final int IMPORT_MTJ_FORMAT        = 2;
37
	
38
	private static final String[] BUTTON_TEXTS = new String[] {
39
    	"Import from Antenna.jar library", 
40
    	"Import from XML files (devices.xml, groups.xml)",
41
	};
42
	
43
	public static final String NAME = "symbolDefinitionsImportPage";
44
	
45
	private static final String KEY_WIDTH =  "dialogWidth";
46
	private static final String KEY_HEIGHT = "dialogHeight";
47
	
48
	private Button[] importTypeRadios;
49
	private Label importFileLabel;
50
	private Text importDirectory;
51
	private Button importFileBrowseButton;
52
	private String antennaFile;
53
	
54
	
55
	public SymbolDefinitionsImportWizardPage() {
56
		
57
		super(NAME, "Import Symbol Definitions", null);
58
		
59
		setPageComplete(true);
60
		
61
	}
62
	
63
	@Override
64
	public void createControl(Composite parent) {
65
	
66
		parent.setLayoutData(new GridData(GridData.FILL_BOTH));
67
		
68
		final Composite composite = new Composite(parent, SWT.NONE);
69
		
70
		composite.setLayout(new GridLayout(1, false));
71
		composite.setLayoutData(new GridData(GridData.FILL_BOTH));
72
		composite.addControlListener(new ControlAdapter() {
73
			@Override
74
			public void controlResized(ControlEvent e) {
75
				storeSize();
76
			}
77
		});
78
		setControl(composite);
79
		
80
		IPreferenceStore preferenceStore = MTJUIPlugin.getDefault().getCorePreferenceStore();
81
		antennaFile = preferenceStore.getString(IMTJCoreConstants.PREF_ANTENNA_JAR);
82
		
83
		addImportSelectorControls(composite);
84
85
		// Set the size if previously stored away
86
		
87
		Point size = retrieveSize();
88
		if (size != null) {
89
			composite.setSize(size);
90
		}
91
92
	}
93
	
94
	/**
95
	 * Add the controls that allow the user to select the type of import.
96
	 * 
97
	 * @param parent
98
	 */
99
	private void addImportSelectorControls(Composite parent) {
100
		
101
		Group importTypeGroup = new Group(parent, SWT.NONE);
102
		importTypeGroup.setText(" From ");
103
		importTypeGroup.setLayout(new GridLayout(1, false));
104
		importTypeGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
105
		
106
		importTypeRadios = new Button[BUTTON_TEXTS.length];
107
		for (int i = 0; i < BUTTON_TEXTS.length; i++) {
108
			importTypeRadios[i] = new Button(importTypeGroup, SWT.RADIO);
109
			importTypeRadios[i].setText(BUTTON_TEXTS[i]);
110
	    }
111
		
112
		// set default selection
113
		importTypeRadios[0].setSelection(true);
114
		
115
		importTypeRadios[1].addSelectionListener(new SelectionAdapter() {
116
			@Override
117
			public void widgetSelected(SelectionEvent e) {
118
				if(((Button) e.getSource()).getSelection()) {
119
					updateControlEnable(true);
120
				}
121
				else {
122
					updateControlEnable(false);
123
				}
124
				updateFinishButton();
125
			}
126
		});
127
		
128
		addChooseFileControl(importTypeGroup);
129
		updateControlEnable(false);
130
		updateFinishButton();
131
		
132
	}
133
	
134
	private void addChooseFileControl(Composite parent) {
135
		
136
		Composite composite = new Composite(parent, SWT.NONE);
137
		composite.setLayout(new GridLayout(3, false));
138
		composite.setLayoutData(new GridData(GridData.FILL_BOTH));
139
		
140
		importFileLabel = new Label(composite, SWT.NONE);
141
		importFileLabel.setText("Specify directory:");
142
		
143
		importDirectory = new Text(composite, SWT.BORDER);
144
		importDirectory.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
145
		importDirectory.addModifyListener(new ModifyListener() {
146
			public void modifyText(ModifyEvent e) {
147
				updateFinishButton();
148
			}
149
		});
150
		
151
		importFileBrowseButton = new Button(composite, SWT.PUSH);
152
		importFileBrowseButton.setText("Browse...");
153
		importFileBrowseButton.addSelectionListener(new SelectionAdapter() {
154
			@Override
155
			public void widgetSelected(SelectionEvent e) {
156
				handleBrowseButton();
157
			}
158
		});
159
		
160
	}
161
	
162
	public String getDirectory() {
163
		return importDirectory.getText();
164
	}
165
	
166
	
167
	/**
168
	 * Store off the size of the control in the dialog settings.
169
	 */
170
	private void storeSize() {
171
		IDialogSettings settings = getDialogSettings();
172
		Point size = getControl().getSize();
173
		if(settings != null) {
174
			settings.put(KEY_WIDTH, size.x);
175
			settings.put(KEY_HEIGHT, size.y);
176
		}
177
	}
178
	
179
	/**
180
	 * Retrieve the previously stored size or <code>null</code> if not found.
181
	 * 
182
	 * @return
183
	 */
184
	private Point retrieveSize() {
185
		Point size = null;
186
		IDialogSettings settings = getDialogSettings();
187
		if(settings != null && settings.get(KEY_WIDTH) != null) {
188
			size = new Point(settings.getInt(KEY_WIDTH), settings.getInt(KEY_HEIGHT));
189
		}
190
		return size;
191
	}
192
193
	private void handleBrowseButton() {
194
		
195
		DirectoryDialog dialog = new DirectoryDialog(getShell());
196
		String directory = dialog.open();
197
		if (directory != null) {
198
			importDirectory.setText(directory);
199
			updateFinishButton();
200
		}
201
		
202
	}
203
	
204
	private void updateControlEnable(boolean value) {
205
		
206
		importFileLabel.setEnabled(value);
207
		importFileBrowseButton.setEnabled(value);
208
		importDirectory.setEnabled(value);
209
		
210
	}
211
	
212
	public void updateFinishButton() {
213
		
214
		if(importTypeRadios[0].getSelection()) {
215
			if(!new File(antennaFile).exists()) {
216
				setPageComplete(false);
217
				setErrorMessage("error2");
218
				setErrorMessage("Antenna.jar library is not specified.");
219
				return;
220
			}
221
		}
222
		else if(importTypeRadios[1].getSelection()) {
223
			String directory = importDirectory.getText().trim();
224
			if(!new File(directory + File.separator + "devices.xml").exists() ||
225
			   !new File(directory + File.separator + "groups.xml").exists()) {
226
				setPageComplete(false);
227
				setErrorMessage("Directory doesn't contain files devices.xml and groups.xml.");
228
				return;
229
			}
230
		}
231
		setErrorMessage(null);
232
		setPageComplete(true);
233
	}
234
	
235
	
236
	public int getImportType() {
237
		if(importTypeRadios[0].getSelection()) {
238
			return IMPORT_FROM_ANTENNA_JAR;
239
		}
240
		else if(importTypeRadios[1].getSelection()) {
241
			return IMPORT_J2MEPOLISH_FORMAT;
242
		}
243
		return IMPORT_MTJ_FORMAT;
244
	}
245
	
246
}

Return to bug 253860