KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > debug > ui > jres > AddVMDialog


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.jdt.internal.debug.ui.jres;
12
13
14 import java.io.File JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.net.URL JavaDoc;
17 import java.util.Arrays JavaDoc;
18 import java.util.Comparator JavaDoc;
19
20 import org.eclipse.core.resources.IResource;
21 import org.eclipse.core.resources.ResourcesPlugin;
22 import org.eclipse.core.runtime.IPath;
23 import org.eclipse.core.runtime.IStatus;
24 import org.eclipse.core.runtime.Path;
25 import org.eclipse.debug.core.DebugPlugin;
26 import org.eclipse.jdt.internal.debug.ui.IJavaDebugHelpContextIds;
27 import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
28 import org.eclipse.jdt.internal.debug.ui.SWTFactory;
29 import org.eclipse.jdt.internal.debug.ui.StatusInfo;
30 import org.eclipse.jdt.launching.AbstractVMInstallType;
31 import org.eclipse.jdt.launching.IVMInstall;
32 import org.eclipse.jdt.launching.IVMInstall2;
33 import org.eclipse.jdt.launching.IVMInstallType;
34 import org.eclipse.jdt.launching.VMStandin;
35 import org.eclipse.jface.dialogs.IDialogConstants;
36 import org.eclipse.jface.dialogs.IDialogSettings;
37 import org.eclipse.jface.dialogs.StatusDialog;
38 import org.eclipse.swt.SWT;
39 import org.eclipse.swt.custom.BusyIndicator;
40 import org.eclipse.swt.events.ModifyEvent;
41 import org.eclipse.swt.events.ModifyListener;
42 import org.eclipse.swt.events.SelectionEvent;
43 import org.eclipse.swt.events.SelectionListener;
44 import org.eclipse.swt.graphics.Point;
45 import org.eclipse.swt.layout.GridData;
46 import org.eclipse.swt.layout.GridLayout;
47 import org.eclipse.swt.widgets.Button;
48 import org.eclipse.swt.widgets.Combo;
49 import org.eclipse.swt.widgets.Composite;
50 import org.eclipse.swt.widgets.Control;
51 import org.eclipse.swt.widgets.DirectoryDialog;
52 import org.eclipse.swt.widgets.Shell;
53 import org.eclipse.swt.widgets.Text;
54 import org.eclipse.ui.PlatformUI;
55
56 import com.ibm.icu.text.MessageFormat;
57
58 /**
59  * Provides the Add VM dialog
60  */

61 public class AddVMDialog extends StatusDialog {
62     
63     private IAddVMDialogRequestor fRequestor;
64     private IVMInstall fEditedVM;
65     private IVMInstallType[] fVMTypes;
66     private IVMInstallType fSelectedVMType;
67     private Combo fVMCombo;
68     private Text fVMName;
69     private Text fVMArgs;
70     private Text fJRERoot;
71     private VMLibraryBlock fLibraryBlock;
72 // the VM install's javadoc location
73
private URL JavaDoc fJavadocLocation = null;
74     private boolean fAutoDetectJavadocLocation = false;
75     private IStatus[] fStatus;
76     private int fPrevIndex = -1;
77         
78     /**
79      * Constructor
80      * @param requestor dialog validation requester
81      * @param shell the parent shell
82      * @param vmInstallTypes the types of VM installs
83      * @param editedVM the editedVM
84      */

85     public AddVMDialog(IAddVMDialogRequestor requestor, Shell shell, IVMInstallType[] vmInstallTypes, IVMInstall editedVM) {
86         super(shell);
87         setShellStyle(getShellStyle() | SWT.RESIZE);
88         fRequestor = requestor;
89         fStatus = new IStatus[5];
90         for (int i= 0; i < fStatus.length; i++) {
91             fStatus[i] = new StatusInfo();
92         }
93         fVMTypes = vmInstallTypes;
94         sortVMTypes();
95         fSelectedVMType = editedVM != null ? editedVM.getVMInstallType() : vmInstallTypes[0];
96         fEditedVM = editedVM;
97     //only detect the javadoc location if not already set
98
fAutoDetectJavadocLocation = fEditedVM == null || fEditedVM.getJavadocLocation() == null;
99     }
100
101     /**
102      * This method is used to sort the array of VM install types, placing
103      * the 'Standard VM' type first, if it exists
104      *
105      * @since 3.3.0
106      */

107     private void sortVMTypes() {
108         Comparator JavaDoc compare = new Comparator JavaDoc() {
109             public int compare(Object JavaDoc o1, Object JavaDoc o2) {
110                 if(o1 instanceof IVMInstallType && o2 instanceof IVMInstallType) {
111                     return ((IVMInstallType) o1).getName().compareTo(((IVMInstallType) o2).getName());
112                 }
113                 return 0;
114             }
115         };
116         //first find the 'Standard VM' and set it at position 0
117
for(int i = 0; i < fVMTypes.length; i++) {
118             if(fVMTypes[i].getId().equals("org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType")) { //$NON-NLS-1$
119
if(i > 0) {
120                     IVMInstallType tmp = fVMTypes[0];
121                     fVMTypes[0] = fVMTypes[i];
122                     fVMTypes[i] = tmp;
123                     break;
124                 }
125                 else {
126                     break;
127                 }
128             }
129         }
130         if(fVMTypes[0].getId().equals("org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType")) { //$NON-NLS-1$
131
Arrays.sort(fVMTypes, 1, fVMTypes.length, compare);
132         }
133         else {
134             Arrays.sort(fVMTypes, compare);
135         }
136     }
137     
138     /* (non-Javadoc)
139      * @see org.eclipse.jface.dialogs.StatusDialog#configureShell(org.eclipse.swt.widgets.Shell)
140      */

141     protected void configureShell(Shell newShell) {
142         super.configureShell(newShell);
143         PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaDebugHelpContextIds.EDIT_JRE_DIALOG);
144     }
145     
146     /**
147      * Returns the VM name from the text control
148      * @return
149      */

150     protected String JavaDoc getVMName() {
151         return fVMName.getText();
152     }
153         
154     /**
155      * Returns the installation location as a file from the JRE root text control
156      * @return the installation location as a file
157      */

158     protected File JavaDoc getInstallLocation() {
159         return new File JavaDoc(fJRERoot.getText());
160     }
161         
162     /* (non-Javadoc)
163      * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
164      */

165     protected Control createDialogArea(Composite ancestor) {
166         Composite parent = (Composite)super.createDialogArea(ancestor);
167         ((GridLayout)parent.getLayout()).numColumns = 3;
168     //VM combo
169
SWTFactory.createLabel(parent, JREMessages.addVMDialog_jreType, 1);
170         fVMCombo = SWTFactory.createCombo(parent, SWT.READ_ONLY, 2, getVMTypeNames());
171     //VM name
172
SWTFactory.createLabel(parent, JREMessages.addVMDialog_jreName, 1);
173         fVMName = SWTFactory.createSingleText(parent, 2);
174     //VM root
175
SWTFactory.createLabel(parent, JREMessages.addVMDialog_jreHome, 1);
176         fJRERoot = SWTFactory.createSingleText(parent, 1);
177         Button browse = SWTFactory.createPushButton(parent, JREMessages.addVMDialog_browse1, null);
178     //VM args
179
SWTFactory.createLabel(parent, JREMessages.AddVMDialog_23, 1);
180         fVMArgs = SWTFactory.createSingleText(parent, 2);
181     //VM libraries block
182
SWTFactory.createLabel(parent, JREMessages.AddVMDialog_JRE_system_libraries__1, 3);
183         fLibraryBlock = new VMLibraryBlock(this);
184         Control block = fLibraryBlock.createControl(parent);
185         GridData gd = new GridData(GridData.FILL_BOTH);
186         gd.horizontalSpan = 3;
187         block.setLayoutData(gd);
188     
189     //init the fields
190
initializeFields();
191         
192     //add the listeners now to prevent them from monkeying with initialized settings
193
fVMCombo.addSelectionListener(new SelectionListener() {
194             public void widgetDefaultSelected(SelectionEvent e) {}
195             public void widgetSelected(SelectionEvent e) {
196                 updateVMType();
197             }
198         });
199         fVMName.addModifyListener(new ModifyListener() {
200             public void modifyText(ModifyEvent e) {
201                 validateVMName();
202                 updateStatusLine();
203             }
204         });
205         fJRERoot.addModifyListener(new ModifyListener() {
206             public void modifyText(ModifyEvent e) {
207                 validateJRELocation();
208                 updateStatusLine();
209             }
210         });
211         browse.addSelectionListener(new SelectionListener() {
212             public void widgetDefaultSelected(SelectionEvent e) {}
213             public void widgetSelected(SelectionEvent e) {
214                 DirectoryDialog dialog = new DirectoryDialog(getShell());
215                 dialog.setFilterPath(fJRERoot.getText());
216                 dialog.setMessage(JREMessages.addVMDialog_pickJRERootDialog_message);
217                 String JavaDoc newPath = dialog.open();
218                 if (newPath != null) {
219                     fJRERoot.setText(newPath);
220                 }
221             }
222         });
223         applyDialogFont(parent);
224         return parent;
225     }
226     
227     /**
228      * Updates the JRE location status and inits the library block
229      */

230     private void updateVMType() {
231         int selIndex = fVMCombo.getSelectionIndex();
232         if (selIndex == fPrevIndex) {
233             return;
234         }
235         fPrevIndex = selIndex;
236         if (selIndex >= 0 && selIndex < fVMTypes.length) {
237             fSelectedVMType= fVMTypes[selIndex];
238         }
239         validateJRELocation();
240         fLibraryBlock.initializeFrom(fEditedVM, fSelectedVMType);
241         updateStatusLine();
242     }
243     
244     /* (non-Javadoc)
245      * @see org.eclipse.jface.dialogs.StatusDialog#create()
246      */

247     public void create() {
248         super.create();
249         fVMName.setFocus();
250         selectVMType();
251     }
252     
253     /**
254      * Returns the VM type names
255      * @return an array of strings with the names of the applicable VMs
256      */

257     private String JavaDoc[] getVMTypeNames() {
258         String JavaDoc[] names = new String JavaDoc[fVMTypes.length];
259         for (int i = 0; i < fVMTypes.length; i++) {
260             names[i]= fVMTypes[i].getName();
261         }
262         return names;
263     }
264     
265     /**
266      * Selects the corresponding VM for fSelectedVMType
267      */

268     private void selectVMType() {
269         for (int i= 0; i < fVMTypes.length; i++) {
270             if (fSelectedVMType == fVMTypes[i]) {
271                 if(i < fVMCombo.getItemCount()) {
272                     fVMCombo.select(i);
273                     return;
274                 }
275             }
276         }
277     }
278     
279     /**
280      * Initialize the dialogs fields
281      */

282     private void initializeFields() {
283         if (fEditedVM == null) {
284             fVMName.setText(""); //$NON-NLS-1$
285
fJRERoot.setText(""); //$NON-NLS-1$
286
fLibraryBlock.initializeFrom(null, fSelectedVMType);
287             fVMArgs.setText(""); //$NON-NLS-1$
288
} else {
289             fVMCombo.setEnabled(false);
290             fVMName.setText(fEditedVM.getName());
291             fJRERoot.setText(fEditedVM.getInstallLocation().getAbsolutePath());
292             fLibraryBlock.initializeFrom(fEditedVM, fSelectedVMType);
293             if (fEditedVM instanceof IVMInstall2) {
294                 IVMInstall2 vm2 = (IVMInstall2) fEditedVM;
295                 String JavaDoc vmArgs = vm2.getVMArgs();
296                 if (vmArgs != null) {
297                     fVMArgs.setText(vmArgs);
298                 }
299             } else {
300                 String JavaDoc[] vmArgs = fEditedVM.getVMArguments();
301                 if (vmArgs != null) {
302                     StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
303                     int length= vmArgs.length;
304                     if (length > 0) {
305                         buffer.append(vmArgs[0]);
306                         for (int i = 1; i < length; i++) {
307                             buffer.append(' ').append(vmArgs[i]);
308                         }
309                     }
310                     fVMArgs.setText(buffer.toString());
311                 }
312             }
313         }
314         validateVMName();
315         updateStatusLine();
316     }
317     
318     /**
319      * Validates the JRE location
320      * @return the status after validating the JRE location
321      */

322     private IStatus validateJRELocation() {
323         String JavaDoc locationName = fJRERoot.getText();
324         IStatus s = null;
325         File JavaDoc file = null;
326         if (locationName.length() == 0) {
327             s = new StatusInfo(IStatus.INFO, JREMessages.addVMDialog_enterLocation);
328         }
329         else {
330             file = new File JavaDoc(locationName);
331             if (!file.exists()) {
332                 s = new StatusInfo(IStatus.ERROR, JREMessages.addVMDialog_locationNotExists);
333             }
334             else {
335                 final IStatus[] temp = new IStatus[1];
336                 final File JavaDoc tempFile = file;
337                 Runnable JavaDoc r = new Runnable JavaDoc() {
338                     public void run() {
339                         temp[0] = fSelectedVMType.validateInstallLocation(tempFile);
340                     }
341                 };
342                 BusyIndicator.showWhile(getShell().getDisplay(), r);
343                 s = temp[0];
344             }
345         }
346         if (s.isOK()) {
347             fLibraryBlock.setHomeDirectory(file);
348             String JavaDoc name = fVMName.getText();
349             if (name == null || name.trim().length() == 0) {
350                 // auto-generate VM name
351
try {
352                     String JavaDoc genName = null;
353                     IPath path = new Path(file.getCanonicalPath());
354                     int segs = path.segmentCount();
355                     if (segs == 1) {
356                         genName = path.segment(0);
357                     }
358                     else if (segs >= 2) {
359                         String JavaDoc last = path.lastSegment();
360                         if ("jre".equalsIgnoreCase(last)) { //$NON-NLS-1$
361
genName = path.segment(segs - 2);
362                         }
363                         else {
364                             genName = last;
365                         }
366                     }
367                     if (genName != null) {
368                         fVMName.setText(genName);
369                     }
370                 } catch (IOException JavaDoc e) {}
371             }
372         } else {
373             fLibraryBlock.setHomeDirectory(null);
374         }
375         fLibraryBlock.restoreDefaultLibraries();
376         detectJavadocLocation();
377         fStatus[1] = s;
378         return s;
379     }
380     
381     /**
382      * Auto-detects the default javadoc location
383      */

384     private void detectJavadocLocation() {
385         if (fAutoDetectJavadocLocation) {
386             if (fSelectedVMType instanceof AbstractVMInstallType) {
387                 AbstractVMInstallType type = (AbstractVMInstallType)fSelectedVMType;
388                 fJavadocLocation = type.getDefaultJavadocLocation(getInstallLocation());
389             }
390         } else {
391             fJavadocLocation = fEditedVM.getJavadocLocation();
392         }
393     }
394
395     /**
396      * Validates the entered name of the VM
397      * @return the status of the name validation
398      */

399     private IStatus validateVMName() {
400         StatusInfo status= new StatusInfo();
401         String JavaDoc name= fVMName.getText();
402         if (name == null || name.trim().length() == 0) {
403             status.setInfo(JREMessages.addVMDialog_enterName);
404         } else {
405             if (fRequestor.isDuplicateName(name) && (fEditedVM == null || !name.equals(fEditedVM.getName()))) {
406                 status.setError(JREMessages.addVMDialog_duplicateName);
407             } else {
408                 IStatus s = ResourcesPlugin.getWorkspace().validateName(name, IResource.FILE);
409                 if (!s.isOK()) {
410                     status.setError(MessageFormat.format(JREMessages.AddVMDialog_JRE_name_must_be_a_valid_file_name___0__1, new String JavaDoc[]{s.getMessage()}));
411                 }
412             }
413         }
414         fStatus[0] = status;
415         return status;
416     }
417     
418     /**
419      * Updates the status line to show/hide messages to the user
420      */

421     protected void updateStatusLine() {
422         IStatus max= null;
423         for (int i = 0; i < fStatus.length; i++) {
424             IStatus curr = fStatus[i];
425             if (curr.matches(IStatus.ERROR)) {
426                 updateStatus(curr);
427                 return;
428             }
429             if (max == null || curr.getSeverity() > max.getSeverity()) {
430                 max = curr;
431             }
432         }
433         updateStatus(max);
434     }
435     
436     /**
437      * Returns the URL for the javadoc location
438      * @return the URL for the javadoc location
439      */

440     protected URL JavaDoc getURL() {
441         return fJavadocLocation;
442     }
443     
444     /* (non-Javadoc)
445      * @see org.eclipse.jface.dialogs.Dialog#okPressed()
446      */

447     protected void okPressed() {
448         if (fEditedVM == null) {
449             IVMInstall vm = new VMStandin(fSelectedVMType, createUniqueId(fSelectedVMType));
450             setFieldValuesToVM(vm);
451             fRequestor.vmAdded(vm);
452         } else {
453             setFieldValuesToVM(fEditedVM);
454         }
455         super.okPressed();
456     }
457     
458     /**
459      * Creates a unique name for the VMInstallType
460      * @param vmType the vm install type
461      * @return a unique name
462      */

463     private String JavaDoc createUniqueId(IVMInstallType vmType) {
464         String JavaDoc id = null;
465         do {
466             id = String.valueOf(System.currentTimeMillis());
467         } while (vmType.findVMInstall(id) != null);
468         return id;
469     }
470     
471     /**
472      * init fields to the specified VM
473      * @param vm the VM to init from
474      */

475     protected void setFieldValuesToVM(IVMInstall vm) {
476         File JavaDoc dir = new File JavaDoc(fJRERoot.getText());
477         try {
478             vm.setInstallLocation(dir.getCanonicalFile());
479         }
480         catch (IOException JavaDoc e) {
481             vm.setInstallLocation(dir.getAbsoluteFile());
482         }
483         vm.setName(fVMName.getText());
484         vm.setJavadocLocation(getURL());
485         
486         String JavaDoc argString = fVMArgs.getText().trim();
487         if (vm instanceof IVMInstall2) {
488             IVMInstall2 vm2 = (IVMInstall2) vm;
489             if (argString != null && argString.length() > 0) {
490                 vm2.setVMArgs(argString);
491             }
492             else {
493                 vm2.setVMArgs(null);
494             }
495         }
496         else {
497             if (argString != null && argString.length() > 0) {
498                 vm.setVMArguments(DebugPlugin.parseArguments(argString));
499             }
500             else {
501                 vm.setVMArguments(null);
502             }
503         }
504         fLibraryBlock.performApply(vm);
505     }
506     
507     /**
508      * returns an absolute file or an empty file if the path is either null or zero length
509      * @param path the path to the file
510      * @return a new file
511      */

512     protected File JavaDoc getAbsoluteFileOrEmpty(String JavaDoc path) {
513         if (path == null || path.length() == 0) {
514             return new File JavaDoc(""); //$NON-NLS-1$
515
}
516         return new File JavaDoc(path).getAbsoluteFile();
517     }
518     
519     /**
520      * @return the status of the system library
521      */

522     protected IStatus getSystemLibraryStatus() {
523         return fStatus[3];
524     }
525     
526     /**
527      * Allows the VM page to set the status of the current system library
528      * @param status the specified status
529      */

530     protected void setSystemLibraryStatus(IStatus status) {
531         fStatus[3] = status;
532     }
533     
534     /**
535      * Updates the status of the ok button to reflect the given status.
536      * Subclasses may override this method to update additional buttons.
537      * @param status the status.
538      */

539     protected void updateButtonsEnableState(IStatus status) {
540         Button ok = getButton(IDialogConstants.OK_ID);
541         if (ok != null && !ok.isDisposed())
542             ok.setEnabled(status.getSeverity() == IStatus.OK);
543     }
544     
545     /**
546      * Returns the name of the section that this dialog stores its settings in
547      *
548      * @return String
549      */

550     protected String JavaDoc getDialogSettingsSectionName() {
551         return "ADD_VM_DIALOG_SECTION"; //$NON-NLS-1$
552
}
553     
554      /* (non-Javadoc)
555      * @see org.eclipse.jface.dialogs.Dialog#getDialogBoundsSettings()
556      */

557     protected IDialogSettings getDialogBoundsSettings() {
558          IDialogSettings settings = JDIDebugUIPlugin.getDefault().getDialogSettings();
559          IDialogSettings section = settings.getSection(getDialogSettingsSectionName());
560          if (section == null) {
561              section = settings.addNewSection(getDialogSettingsSectionName());
562          }
563          return section;
564     }
565     
566     /* (non-Javadoc)
567      * @see org.eclipse.jface.dialogs.Dialog#getInitialSize()
568      */

569     protected Point getInitialSize() {
570         IDialogSettings settings = getDialogBoundsSettings();
571         if(settings != null) {
572             try {
573                 int width = settings.getInt("DIALOG_WIDTH"); //$NON-NLS-1$
574
int height = settings.getInt("DIALOG_HEIGHT"); //$NON-NLS-1$
575
if(width > 0 & height > 0) {
576                     return new Point(width, height);
577                 }
578             }
579             catch (NumberFormatException JavaDoc nfe) {
580                 return new Point(500, 570);
581             }
582         }
583         return new Point(500, 570);
584     }
585
586     protected void setButtonLayoutData(Button button) {
587         super.setButtonLayoutData(button);
588     }
589     
590 }
591
Popular Tags