KickJava   Java API By Example, From Geeks To Geeks.

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


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 import java.io.File JavaDoc;
14 import java.io.IOException JavaDoc;
15 import java.lang.reflect.InvocationTargetException JavaDoc;
16 import java.util.ArrayList JavaDoc;
17 import java.util.HashSet JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.List JavaDoc;
20 import java.util.Set JavaDoc;
21
22 import org.eclipse.core.runtime.IProgressMonitor;
23 import org.eclipse.core.runtime.IStatus;
24 import org.eclipse.core.runtime.ListenerList;
25 import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
26 import org.eclipse.jdt.internal.debug.ui.SWTFactory;
27 import org.eclipse.jdt.launching.AbstractVMInstallType;
28 import org.eclipse.jdt.launching.IVMInstall;
29 import org.eclipse.jdt.launching.IVMInstallType;
30 import org.eclipse.jdt.launching.JavaRuntime;
31 import org.eclipse.jdt.launching.VMStandin;
32 import org.eclipse.jdt.ui.ISharedImages;
33 import org.eclipse.jdt.ui.JavaUI;
34 import org.eclipse.jface.dialogs.IDialogConstants;
35 import org.eclipse.jface.dialogs.IDialogSettings;
36 import org.eclipse.jface.dialogs.MessageDialog;
37 import org.eclipse.jface.dialogs.ProgressMonitorDialog;
38 import org.eclipse.jface.operation.IRunnableWithProgress;
39 import org.eclipse.jface.viewers.CheckStateChangedEvent;
40 import org.eclipse.jface.viewers.CheckboxTableViewer;
41 import org.eclipse.jface.viewers.DoubleClickEvent;
42 import org.eclipse.jface.viewers.ICheckStateListener;
43 import org.eclipse.jface.viewers.IDoubleClickListener;
44 import org.eclipse.jface.viewers.ISelection;
45 import org.eclipse.jface.viewers.ISelectionChangedListener;
46 import org.eclipse.jface.viewers.ISelectionProvider;
47 import org.eclipse.jface.viewers.IStructuredContentProvider;
48 import org.eclipse.jface.viewers.IStructuredSelection;
49 import org.eclipse.jface.viewers.ITableLabelProvider;
50 import org.eclipse.jface.viewers.LabelProvider;
51 import org.eclipse.jface.viewers.SelectionChangedEvent;
52 import org.eclipse.jface.viewers.StructuredSelection;
53 import org.eclipse.jface.viewers.Viewer;
54 import org.eclipse.jface.viewers.ViewerComparator;
55 import org.eclipse.jface.window.Window;
56 import org.eclipse.swt.SWT;
57 import org.eclipse.swt.events.KeyAdapter;
58 import org.eclipse.swt.events.KeyEvent;
59 import org.eclipse.swt.events.SelectionAdapter;
60 import org.eclipse.swt.events.SelectionEvent;
61 import org.eclipse.swt.graphics.Cursor;
62 import org.eclipse.swt.graphics.Font;
63 import org.eclipse.swt.graphics.Image;
64 import org.eclipse.swt.layout.GridData;
65 import org.eclipse.swt.layout.GridLayout;
66 import org.eclipse.swt.widgets.Button;
67 import org.eclipse.swt.widgets.Composite;
68 import org.eclipse.swt.widgets.Control;
69 import org.eclipse.swt.widgets.DirectoryDialog;
70 import org.eclipse.swt.widgets.Event;
71 import org.eclipse.swt.widgets.Label;
72 import org.eclipse.swt.widgets.Listener;
73 import org.eclipse.swt.widgets.Shell;
74 import org.eclipse.swt.widgets.Table;
75 import org.eclipse.swt.widgets.TableColumn;
76
77 import com.ibm.icu.text.MessageFormat;
78
79 /**
80  * A composite that displays installed JRE's in a table. JREs can be
81  * added, removed, edited, and searched for.
82  * <p>
83  * This block implements ISelectionProvider - it sends selection change events
84  * when the checked JRE in the table changes, or when the "use default" button
85  * check state changes.
86  * </p>
87  */

88 public class InstalledJREsBlock implements IAddVMDialogRequestor, ISelectionProvider {
89     
90     /**
91      * This block's control
92      */

93     private Composite fControl;
94     
95     /**
96      * VMs being displayed
97      */

98     private List JavaDoc fVMs = new ArrayList JavaDoc();
99     
100     /**
101      * The main list control
102      */

103     private CheckboxTableViewer fVMList;
104     
105     // Action buttons
106
private Button fAddButton;
107     private Button fRemoveButton;
108     private Button fEditButton;
109     private Button fCopyButton;
110     private Button fSearchButton;
111     
112     // index of column used for sorting
113
private int fSortColumn = 0;
114     
115     /**
116      * Selection listeners (checked JRE changes)
117      */

118     private ListenerList fSelectionListeners = new ListenerList();
119     
120     /**
121      * Previous selection
122      */

123     private ISelection fPrevSelection = new StructuredSelection();
124
125     private Table fTable;
126             
127     // Make sure that VMStandin ids are unique if multiple calls to System.currentTimeMillis()
128
// happen very quickly
129
private static String JavaDoc fgLastUsedID;
130     
131     /**
132      * Content provider to show a list of JREs
133      */

134     class JREsContentProvider implements IStructuredContentProvider {
135         public Object JavaDoc[] getElements(Object JavaDoc input) {
136             return fVMs.toArray();
137         }
138         public void inputChanged(Viewer viewer, Object JavaDoc oldInput, Object JavaDoc newInput) {
139         }
140         public void dispose() {
141         }
142     }
143     
144     /**
145      * Label provider for installed JREs table.
146      */

147     class VMLabelProvider extends LabelProvider implements ITableLabelProvider {
148
149         /**
150          * @see ITableLabelProvider#getColumnText(Object, int)
151          */

152         public String JavaDoc getColumnText(Object JavaDoc element, int columnIndex) {
153             if (element instanceof IVMInstall) {
154                 IVMInstall vm= (IVMInstall)element;
155                 switch(columnIndex) {
156                     case 0:
157                         if (isContributed(vm)) {
158                             return MessageFormat.format(JREMessages.InstalledJREsBlock_19, new String JavaDoc[]{vm.getName()});
159                         }
160                         return vm.getName();
161                     case 1:
162                         return vm.getInstallLocation().getAbsolutePath();
163                     case 2:
164                         return vm.getVMInstallType().getName();
165                 }
166             }
167             return element.toString();
168         }
169
170         /**
171          * @see ITableLabelProvider#getColumnImage(Object, int)
172          */

173         public Image getColumnImage(Object JavaDoc element, int columnIndex) {
174             if (columnIndex == 0) {
175                 return JavaUI.getSharedImages().getImage(ISharedImages.IMG_OBJS_LIBRARY);
176             }
177             return null;
178         }
179
180     }
181     
182     /* (non-Javadoc)
183      * @see org.eclipse.jface.viewers.ISelectionProvider#addSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
184      */

185     public void addSelectionChangedListener(ISelectionChangedListener listener) {
186         fSelectionListeners.add(listener);
187     }
188
189     /* (non-Javadoc)
190      * @see org.eclipse.jface.viewers.ISelectionProvider#getSelection()
191      */

192     public ISelection getSelection() {
193         return new StructuredSelection(fVMList.getCheckedElements());
194     }
195
196     /* (non-Javadoc)
197      * @see org.eclipse.jface.viewers.ISelectionProvider#removeSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
198      */

199     public void removeSelectionChangedListener(ISelectionChangedListener listener) {
200         fSelectionListeners.remove(listener);
201     }
202
203     /* (non-Javadoc)
204      * @see org.eclipse.jface.viewers.ISelectionProvider#setSelection(org.eclipse.jface.viewers.ISelection)
205      */

206     public void setSelection(ISelection selection) {
207         if (selection instanceof IStructuredSelection) {
208             if (!selection.equals(fPrevSelection)) {
209                 fPrevSelection = selection;
210                 Object JavaDoc jre = ((IStructuredSelection)selection).getFirstElement();
211                 if (jre == null) {
212                     fVMList.setCheckedElements(new Object JavaDoc[0]);
213                 } else {
214                     fVMList.setCheckedElements(new Object JavaDoc[]{jre});
215                     fVMList.reveal(jre);
216                 }
217                 fireSelectionChanged();
218             }
219         }
220     }
221
222     /**
223      * Creates this block's control in the given control.
224      *
225      * @param ancestor containing control
226      * @param useManageButton whether to present a single 'manage...' button to
227      * the user that opens the installed JREs pref page for JRE management,
228      * or to provide 'add, remove, edit, and search' buttons.
229      */

230     public void createControl(Composite ancestor) {
231         
232         Composite parent= new Composite(ancestor, SWT.NULL);
233         GridLayout layout= new GridLayout();
234         layout.numColumns= 2;
235         layout.marginHeight = 0;
236         layout.marginWidth = 0;
237         parent.setLayout(layout);
238         Font font = ancestor.getFont();
239         parent.setFont(font);
240         fControl = parent;
241         
242         GridData data;
243                 
244         Label tableLabel = new Label(parent, SWT.NONE);
245         tableLabel.setText(JREMessages.InstalledJREsBlock_15);
246         data = new GridData();
247         data.horizontalSpan = 2;
248         tableLabel.setLayoutData(data);
249         tableLabel.setFont(font);
250                 
251         fTable= new Table(parent, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
252         
253         data= new GridData(GridData.FILL_BOTH);
254         data.widthHint = 450;
255         fTable.setLayoutData(data);
256         fTable.setFont(font);
257                 
258         fTable.setHeaderVisible(true);
259         fTable.setLinesVisible(true);
260
261         TableColumn column1= new TableColumn(fTable, SWT.NULL);
262         column1.setText(JREMessages.InstalledJREsBlock_0);
263         column1.addSelectionListener(new SelectionAdapter() {
264             public void widgetSelected(SelectionEvent e) {
265                 sortByName();
266             }
267         });
268     
269         TableColumn column2= new TableColumn(fTable, SWT.NULL);
270         column2.setText(JREMessages.InstalledJREsBlock_1);
271         column2.addSelectionListener(new SelectionAdapter() {
272             public void widgetSelected(SelectionEvent e) {
273                 sortByLocation();
274             }
275         });
276         
277         TableColumn column3= new TableColumn(fTable, SWT.NULL);
278         column3.setText(JREMessages.InstalledJREsBlock_2);
279         column3.addSelectionListener(new SelectionAdapter() {
280             public void widgetSelected(SelectionEvent e) {
281                 sortByType();
282             }
283         });
284
285         fVMList= new CheckboxTableViewer(fTable);
286         fVMList.setLabelProvider(new VMLabelProvider());
287         fVMList.setContentProvider(new JREsContentProvider());
288         // by default, sort by name
289
sortByName();
290         
291         fVMList.addSelectionChangedListener(new ISelectionChangedListener() {
292             public void selectionChanged(SelectionChangedEvent evt) {
293                 enableButtons();
294             }
295         });
296         
297         fVMList.addCheckStateListener(new ICheckStateListener() {
298             public void checkStateChanged(CheckStateChangedEvent event) {
299                 if (event.getChecked()) {
300                     setCheckedJRE((IVMInstall)event.getElement());
301                 } else {
302                     setCheckedJRE(null);
303                 }
304             }
305         });
306         
307         fVMList.addDoubleClickListener(new IDoubleClickListener() {
308             public void doubleClick(DoubleClickEvent e) {
309                 if (!fVMList.getSelection().isEmpty()) {
310                     editVM();
311                 }
312             }
313         });
314         fTable.addKeyListener(new KeyAdapter() {
315             public void keyPressed(KeyEvent event) {
316                 if (event.character == SWT.DEL && event.stateMask == 0) {
317                     removeVMs();
318                 }
319             }
320         });
321         
322         Composite buttons= new Composite(parent, SWT.NULL);
323         buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
324         layout= new GridLayout();
325         layout.marginHeight= 0;
326         layout.marginWidth= 0;
327         buttons.setLayout(layout);
328         buttons.setFont(font);
329         
330         fAddButton = createPushButton(buttons, JREMessages.InstalledJREsBlock_3);
331         fAddButton.addListener(SWT.Selection, new Listener() {
332             public void handleEvent(Event evt) {
333                 addVM();
334             }
335         });
336         
337         fEditButton= createPushButton(buttons, JREMessages.InstalledJREsBlock_4);
338         fEditButton.addListener(SWT.Selection, new Listener() {
339             public void handleEvent(Event evt) {
340                 editVM();
341             }
342         });
343         
344         fCopyButton = createPushButton(buttons, JREMessages.InstalledJREsBlock_16);
345         fCopyButton.addListener(SWT.Selection, new Listener() {
346             public void handleEvent(Event evt) {
347                 copyVM();
348             }
349         });
350         
351         fRemoveButton= createPushButton(buttons, JREMessages.InstalledJREsBlock_5);
352         fRemoveButton.addListener(SWT.Selection, new Listener() {
353             public void handleEvent(Event evt) {
354                 removeVMs();
355             }
356         });
357         
358         // copied from ListDialogField.CreateSeparator()
359
Label separator= new Label(buttons, SWT.NONE);
360         separator.setVisible(false);
361         GridData gd= new GridData();
362         gd.horizontalAlignment= GridData.FILL;
363         gd.verticalAlignment= GridData.BEGINNING;
364         gd.heightHint= 4;
365         separator.setLayoutData(gd);
366         
367         fSearchButton = createPushButton(buttons, JREMessages.InstalledJREsBlock_6);
368         fSearchButton.addListener(SWT.Selection, new Listener() {
369             public void handleEvent(Event evt) {
370                 search();
371             }
372         });
373         
374         fillWithWorkspaceJREs();
375         enableButtons();
376         fAddButton.setEnabled(JavaRuntime.getVMInstallTypes().length > 0);
377     }
378     
379     /**
380      * Adds a duplicate of the selected VM to the block
381      * @since 3.2
382      */

383     protected void copyVM() {
384         IStructuredSelection selection = (IStructuredSelection) fVMList.getSelection();
385         Iterator JavaDoc it = selection.iterator();
386
387         ArrayList JavaDoc newEntries = new ArrayList JavaDoc();
388         while (it.hasNext()) {
389             IVMInstall selectedVM = (IVMInstall) it.next();
390
391             // duplicate & add vm
392
VMStandin standin = new VMStandin(selectedVM, createUniqueId(selectedVM.getVMInstallType()));
393             standin.setName(generateName(selectedVM.getName()));
394             AddVMDialog dialog = new AddVMDialog(this, getShell(), JavaRuntime.getVMInstallTypes(), standin);
395             dialog.setTitle(JREMessages.InstalledJREsBlock_18);
396             if (dialog.open() != Window.OK) {
397                 return;
398             }
399             newEntries.add(standin);
400             fVMs.add(standin);
401         }
402         fVMList.refresh();
403         fVMList.setSelection(new StructuredSelection(newEntries.toArray()));
404     }
405
406     /**
407      * Compares the given name against current names and adds the appropriate numerical
408      * suffix to ensure that it is unique.
409      * @param name the name with which to ensure uniqueness
410      * @return the unique version of the given name
411      * @since 3.2
412      */

413     public String JavaDoc generateName(String JavaDoc name){
414             if (!isDuplicateName(name)) {
415                 return name;
416             }
417             
418             if (name.matches(".*\\(\\d*\\)")) { //$NON-NLS-1$
419
int start = name.lastIndexOf('(');
420                 int end = name.lastIndexOf(')');
421                 String JavaDoc stringInt = name.substring(start+1, end);
422                 int numericValue = Integer.parseInt(stringInt);
423                 String JavaDoc newName = name.substring(0, start+1) + (numericValue+1) + ")"; //$NON-NLS-1$
424
return generateName(newName);
425             } else {
426                 return generateName(name + " (1)"); //$NON-NLS-1$
427
}
428         }
429     
430     /**
431      * Fire current selection
432      */

433     private void fireSelectionChanged() {
434         SelectionChangedEvent event = new SelectionChangedEvent(this, getSelection());
435         Object JavaDoc[] listeners = fSelectionListeners.getListeners();
436         for (int i = 0; i < listeners.length; i++) {
437             ISelectionChangedListener listener = (ISelectionChangedListener)listeners[i];
438             listener.selectionChanged(event);
439         }
440     }
441
442     /**
443      * Sorts by VM type, and name within type.
444      */

445     private void sortByType() {
446         fVMList.setComparator(new ViewerComparator() {
447             public int compare(Viewer viewer, Object JavaDoc e1, Object JavaDoc e2) {
448                 if ((e1 instanceof IVMInstall) && (e2 instanceof IVMInstall)) {
449                     IVMInstall left= (IVMInstall)e1;
450                     IVMInstall right= (IVMInstall)e2;
451                     String JavaDoc leftType= left.getVMInstallType().getName();
452                     String JavaDoc rightType= right.getVMInstallType().getName();
453                     int res= leftType.compareToIgnoreCase(rightType);
454                     if (res != 0) {
455                         return res;
456                     }
457                     return left.getName().compareToIgnoreCase(right.getName());
458                 }
459                 return super.compare(viewer, e1, e2);
460             }
461             
462             public boolean isSorterProperty(Object JavaDoc element, String JavaDoc property) {
463                 return true;
464             }
465         });
466         fSortColumn = 3;
467     }
468     
469     /**
470      * Sorts by VM name.
471      */

472     private void sortByName() {
473         fVMList.setComparator(new ViewerComparator() {
474             public int compare(Viewer viewer, Object JavaDoc e1, Object JavaDoc e2) {
475                 if ((e1 instanceof IVMInstall) && (e2 instanceof IVMInstall)) {
476                     IVMInstall left= (IVMInstall)e1;
477                     IVMInstall right= (IVMInstall)e2;
478                     return left.getName().compareToIgnoreCase(right.getName());
479                 }
480                 return super.compare(viewer, e1, e2);
481             }
482             
483             public boolean isSorterProperty(Object JavaDoc element, String JavaDoc property) {
484                 return true;
485             }
486         });
487         fSortColumn = 1;
488     }
489     
490     /**
491      * Sorts by VM location.
492      */

493     private void sortByLocation() {
494         fVMList.setComparator(new ViewerComparator() {
495             public int compare(Viewer viewer, Object JavaDoc e1, Object JavaDoc e2) {
496                 if ((e1 instanceof IVMInstall) && (e2 instanceof IVMInstall)) {
497                     IVMInstall left= (IVMInstall)e1;
498                     IVMInstall right= (IVMInstall)e2;
499                     return left.getInstallLocation().getAbsolutePath().compareToIgnoreCase(right.getInstallLocation().getAbsolutePath());
500                 }
501                 return super.compare(viewer, e1, e2);
502             }
503             
504             public boolean isSorterProperty(Object JavaDoc element, String JavaDoc property) {
505                 return true;
506             }
507         });
508         fSortColumn = 2;
509     }
510         
511     private void enableButtons() {
512         IStructuredSelection selection = (IStructuredSelection) fVMList.getSelection();
513         int selectionCount= selection.size();
514         fEditButton.setEnabled(selectionCount == 1);
515         fCopyButton.setEnabled(selectionCount > 0);
516         if (selectionCount > 0 && selectionCount < fVMList.getTable().getItemCount()) {
517             Iterator JavaDoc iterator = selection.iterator();
518             while (iterator.hasNext()) {
519                 IVMInstall install = (IVMInstall)iterator.next();
520                 if (isContributed(install)) {
521                     fRemoveButton.setEnabled(false);
522                     return;
523                 }
524             }
525             fRemoveButton.setEnabled(true);
526         } else {
527             fRemoveButton.setEnabled(false);
528         }
529     }
530     
531     private boolean isContributed(IVMInstall install) {
532         return JavaRuntime.isContributedVMInstall(install.getId());
533     }
534     
535     protected Button createPushButton(Composite parent, String JavaDoc label) {
536         return SWTFactory.createPushButton(parent, label, null);
537     }
538     
539     /**
540      * Returns this block's control
541      *
542      * @return control
543      */

544     public Control getControl() {
545         return fControl;
546     }
547     
548     /**
549      * Sets the JREs to be displayed in this block
550      *
551      * @param vms JREs to be displayed
552      */

553     protected void setJREs(IVMInstall[] vms) {
554         fVMs.clear();
555         for (int i = 0; i < vms.length; i++) {
556             fVMs.add(vms[i]);
557         }
558         fVMList.setInput(fVMs);
559         fVMList.refresh();
560     }
561     
562     /**
563      * Returns the JREs currently being displayed in this block
564      *
565      * @return JREs currently being displayed in this block
566      */

567     public IVMInstall[] getJREs() {
568         return (IVMInstall[])fVMs.toArray(new IVMInstall[fVMs.size()]);
569     }
570     
571     /**
572      * Bring up a dialog that lets the user create a new VM definition.
573      */

574     private void addVM() {
575         AddVMDialog dialog= new AddVMDialog(this, getShell(), JavaRuntime.getVMInstallTypes(), null);
576         dialog.setTitle(JREMessages.InstalledJREsBlock_7);
577         if (dialog.open() != Window.OK) {
578             return;
579         }
580         fVMList.refresh();
581     }
582     
583     /**
584      * @see IAddVMDialogRequestor#vmAdded(IVMInstall)
585      */

586     public void vmAdded(IVMInstall vm) {
587         fVMs.add(vm);
588         fVMList.refresh();
589     }
590     
591     /**
592      * @see IAddVMDialogRequestor#isDuplicateName(String)
593      */

594     public boolean isDuplicateName(String JavaDoc name) {
595         for (int i= 0; i < fVMs.size(); i++) {
596             IVMInstall vm = (IVMInstall)fVMs.get(i);
597             if (vm.getName().equals(name)) {
598                 return true;
599             }
600         }
601         return false;
602     }
603     
604     private void editVM() {
605         IStructuredSelection selection= (IStructuredSelection)fVMList.getSelection();
606         IVMInstall vm= (IVMInstall)selection.getFirstElement();
607         if (vm == null) {
608             return;
609         }
610         if (isContributed(vm)) {
611             VMDetailsDialog dialog= new VMDetailsDialog(getShell(), vm);
612             dialog.open();
613         } else {
614             AddVMDialog dialog= new AddVMDialog(this, getShell(), JavaRuntime.getVMInstallTypes(), vm);
615             dialog.setTitle(JREMessages.InstalledJREsBlock_8);
616             if (dialog.open() != Window.OK) {
617                 return;
618             }
619             fVMList.refresh(vm);
620         }
621     }
622     
623     private void removeVMs() {
624         IStructuredSelection selection= (IStructuredSelection)fVMList.getSelection();
625         IVMInstall[] vms = new IVMInstall[selection.size()];
626         Iterator JavaDoc iter = selection.iterator();
627         int i = 0;
628         while (iter.hasNext()) {
629             vms[i] = (IVMInstall)iter.next();
630             i++;
631         }
632         removeJREs(vms);
633     }
634     
635     /**
636      * Removes the given VMs from the table.
637      *
638      * @param vms
639      */

640     public void removeJREs(IVMInstall[] vms) {
641         IStructuredSelection prev = (IStructuredSelection) getSelection();
642         for (int i = 0; i < vms.length; i++) {
643             fVMs.remove(vms[i]);
644         }
645         fVMList.refresh();
646         IStructuredSelection curr = (IStructuredSelection) getSelection();
647         if (!curr.equals(prev)) {
648             IVMInstall[] installs = getJREs();
649             if (curr.size() == 0 && installs.length == 1) {
650                 // pick a default VM automatically
651
setSelection(new StructuredSelection(installs[0]));
652             } else {
653                 fireSelectionChanged();
654             }
655         }
656     }
657     
658     /**
659      * Search for installed VMs in the file system
660      */

661     protected void search() {
662         
663         // choose a root directory for the search
664
DirectoryDialog dialog = new DirectoryDialog(getShell());
665         dialog.setMessage(JREMessages.InstalledJREsBlock_9);
666         dialog.setText(JREMessages.InstalledJREsBlock_10);
667         String JavaDoc path = dialog.open();
668         if (path == null) {
669             return;
670         }
671         
672         // ignore installed locations
673
final Set JavaDoc exstingLocations = new HashSet JavaDoc();
674         Iterator JavaDoc iter = fVMs.iterator();
675         while (iter.hasNext()) {
676             exstingLocations.add(((IVMInstall)iter.next()).getInstallLocation());
677         }
678         
679         // search
680
final File JavaDoc rootDir = new File JavaDoc(path);
681         final List JavaDoc locations = new ArrayList JavaDoc();
682         final List JavaDoc types = new ArrayList JavaDoc();
683
684         IRunnableWithProgress r = new IRunnableWithProgress() {
685             public void run(IProgressMonitor monitor) {
686                 monitor.beginTask(JREMessages.InstalledJREsBlock_11, IProgressMonitor.UNKNOWN);
687                 search(rootDir, locations, types, exstingLocations, monitor);
688                 monitor.done();
689             }
690         };
691         
692         try {
693             ProgressMonitorDialog progress = new ProgressMonitorDialog(getShell()) {
694                 /*
695                  * Overridden createCancelButton to replace Cancel label with Stop label
696                  * More accurately reflects action taken when button pressed.
697                  * Bug [162902]
698                  */

699                 protected void createCancelButton(Composite parent) {
700                     cancel = createButton(parent, IDialogConstants.CANCEL_ID,
701                             IDialogConstants.STOP_LABEL, true);
702                     if (arrowCursor == null) {
703                         arrowCursor = new Cursor(cancel.getDisplay(), SWT.CURSOR_ARROW);
704                     }
705                     cancel.setCursor(arrowCursor);
706                     setOperationCancelButtonEnabled(enableCancelButton);
707                 }
708             };
709             progress.run(true, true, r);
710         } catch (InvocationTargetException JavaDoc e) {
711             JDIDebugUIPlugin.log(e);
712         } catch (InterruptedException JavaDoc e) {
713             // canceled
714
return;
715         }
716         
717         if (locations.isEmpty()) {
718             MessageDialog.openInformation(getShell(), JREMessages.InstalledJREsBlock_12, MessageFormat.format(JREMessages.InstalledJREsBlock_13, new String JavaDoc[]{path})); //
719
} else {
720             iter = locations.iterator();
721             Iterator JavaDoc iter2 = types.iterator();
722             while (iter.hasNext()) {
723                 File JavaDoc location = (File JavaDoc)iter.next();
724                 IVMInstallType type = (IVMInstallType)iter2.next();
725                 IVMInstall vm = new VMStandin(type, createUniqueId(type));
726                 String JavaDoc name = location.getName();
727                 String JavaDoc nameCopy = new String JavaDoc(name);
728                 int i = 1;
729                 while (isDuplicateName(nameCopy)) {
730                     nameCopy = name + '(' + i++ + ')';
731                 }
732                 vm.setName(nameCopy);
733                 vm.setInstallLocation(location);
734                 if (type instanceof AbstractVMInstallType) {
735                     //set default java doc location
736
AbstractVMInstallType abs = (AbstractVMInstallType)type;
737                     vm.setJavadocLocation(abs.getDefaultJavadocLocation(location));
738                 }
739                 vmAdded(vm);
740             }
741         }
742         
743     }
744     
745     protected Shell getShell() {
746         return getControl().getShell();
747     }
748
749     /**
750      * Find a unique VM id. Check existing 'real' VMs, as well as the last id used for
751      * a VMStandin.
752      */

753     private String JavaDoc createUniqueId(IVMInstallType vmType) {
754         String JavaDoc id= null;
755         do {
756             id= String.valueOf(System.currentTimeMillis());
757         } while (vmType.findVMInstall(id) != null || id.equals(fgLastUsedID));
758         fgLastUsedID = id;
759         return id;
760     }
761     
762     /**
763      * Searches the specified directory recursively for installed VMs, adding each
764      * detected VM to the <code>found</code> list. Any directories specified in
765      * the <code>ignore</code> are not traversed.
766      *
767      * @param directory
768      * @param found
769      * @param types
770      * @param ignore
771      */

772     protected void search(File JavaDoc directory, List JavaDoc found, List JavaDoc types, Set JavaDoc ignore, IProgressMonitor monitor) {
773         if (monitor.isCanceled()) {
774             return;
775         }
776
777         String JavaDoc[] names = directory.list();
778         if (names == null) {
779             return;
780         }
781         List JavaDoc subDirs = new ArrayList JavaDoc();
782         for (int i = 0; i < names.length; i++) {
783             if (monitor.isCanceled()) {
784                 return;
785             }
786             File JavaDoc file = new File JavaDoc(directory, names[i]);
787             try {
788                 monitor.subTask(MessageFormat.format(JREMessages.InstalledJREsBlock_14, new String JavaDoc[]{Integer.toString(found.size()), file.getCanonicalPath()}));
789             } catch (IOException JavaDoc e) {
790             }
791             IVMInstallType[] vmTypes = JavaRuntime.getVMInstallTypes();
792             if (file.isDirectory()) {
793                 if (!ignore.contains(file)) {
794                     boolean validLocation = false;
795                     
796                     // Take the first VM install type that claims the location as a
797
// valid VM install. VM install types should be smart enough to not
798
// claim another type's VM, but just in case...
799
for (int j = 0; j < vmTypes.length; j++) {
800                         if (monitor.isCanceled()) {
801                             return;
802                         }
803                         IVMInstallType type = vmTypes[j];
804                         IStatus status = type.validateInstallLocation(file);
805                         if (status.isOK()) {
806                             found.add(file);
807                             types.add(type);
808                             validLocation = true;
809                             break;
810                         }
811                     }
812                     if (!validLocation) {
813                         subDirs.add(file);
814                     }
815                 }
816             }
817         }
818         while (!subDirs.isEmpty()) {
819             File JavaDoc subDir = (File JavaDoc)subDirs.remove(0);
820             search(subDir, found, types, ignore, monitor);
821             if (monitor.isCanceled()) {
822                 return;
823             }
824         }
825         
826     }
827     
828     /**
829      * Sets the checked JRE, possible <code>null</code>
830      *
831      * @param vm JRE or <code>null</code>
832      */

833     public void setCheckedJRE(IVMInstall vm) {
834         if (vm == null) {
835             setSelection(new StructuredSelection());
836         } else {
837             setSelection(new StructuredSelection(vm));
838         }
839     }
840     
841     /**
842      * Returns the checked JRE or <code>null</code> if none.
843      *
844      * @return the checked JRE or <code>null</code> if none
845      */

846     public IVMInstall getCheckedJRE() {
847         Object JavaDoc[] objects = fVMList.getCheckedElements();
848         if (objects.length == 0) {
849             return null;
850         }
851         return (IVMInstall)objects[0];
852     }
853     
854     /**
855      * Persist table settings into the give dialog store, prefixed
856      * with the given key.
857      *
858      * @param settings dialog store
859      * @param qualifier key qualifier
860      */

861     public void saveColumnSettings(IDialogSettings settings, String JavaDoc qualifier) {
862         int columnCount = fTable.getColumnCount();
863         for (int i = 0; i < columnCount; i++) {
864             settings.put(qualifier + ".columnWidth" + i, fTable.getColumn(i).getWidth()); //$NON-NLS-1$
865
}
866         settings.put(qualifier + ".sortColumn", fSortColumn); //$NON-NLS-1$
867
}
868     
869     /**
870      * Restore table settings from the given dialog store using the
871      * given key.
872      *
873      * @param settings dialog settings store
874      * @param qualifier key to restore settings from
875      */

876     public void restoreColumnSettings(IDialogSettings settings, String JavaDoc qualifier) {
877         fVMList.getTable().layout(true);
878         restoreColumnWidths(settings, qualifier);
879         try {
880             fSortColumn = settings.getInt(qualifier + ".sortColumn"); //$NON-NLS-1$
881
} catch (NumberFormatException JavaDoc e) {
882             fSortColumn = 1;
883         }
884         switch (fSortColumn) {
885             case 1:
886                 sortByName();
887                 break;
888             case 2:
889                 sortByLocation();
890                 break;
891             case 3:
892                 sortByType();
893                 break;
894         }
895     }
896     
897     private void restoreColumnWidths(IDialogSettings settings, String JavaDoc qualifier) {
898         int columnCount = fTable.getColumnCount();
899         for (int i = 0; i < columnCount; i++) {
900             int width = -1;
901             
902             try {
903                 width = settings.getInt(qualifier + ".columnWidth" + i); //$NON-NLS-1$
904
} catch (NumberFormatException JavaDoc e) {}
905             
906             if (width <= 0) {
907                 fTable.getColumn(i).pack();
908             } else {
909                 fTable.getColumn(i).setWidth(width);
910             }
911         }
912     }
913     
914     /**
915      * Populates the JRE table with existing JREs defined in the workspace.
916      */

917     protected void fillWithWorkspaceJREs() {
918         // fill with JREs
919
List JavaDoc standins = new ArrayList JavaDoc();
920         IVMInstallType[] types = JavaRuntime.getVMInstallTypes();
921         for (int i = 0; i < types.length; i++) {
922             IVMInstallType type = types[i];
923             IVMInstall[] installs = type.getVMInstalls();
924             for (int j = 0; j < installs.length; j++) {
925                 IVMInstall install = installs[j];
926                 standins.add(new VMStandin(install));
927             }
928         }
929         setJREs((IVMInstall[])standins.toArray(new IVMInstall[standins.size()]));
930     }
931         
932 }
933
Popular Tags