KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > workingsets > WorkingSetConfigurationBlock


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.ui.workingsets;
12
13 import com.ibm.icu.text.Collator;
14
15 import java.util.ArrayList JavaDoc;
16 import java.util.Arrays JavaDoc;
17 import java.util.Comparator JavaDoc;
18 import java.util.HashSet JavaDoc;
19 import java.util.Iterator JavaDoc;
20 import java.util.List JavaDoc;
21
22 import org.eclipse.core.runtime.Assert;
23 import org.eclipse.core.runtime.IAdaptable;
24
25 import org.eclipse.swt.SWT;
26 import org.eclipse.swt.events.SelectionAdapter;
27 import org.eclipse.swt.events.SelectionEvent;
28 import org.eclipse.swt.graphics.FontMetrics;
29 import org.eclipse.swt.graphics.GC;
30 import org.eclipse.swt.layout.GridData;
31 import org.eclipse.swt.layout.GridLayout;
32 import org.eclipse.swt.widgets.Button;
33 import org.eclipse.swt.widgets.Combo;
34 import org.eclipse.swt.widgets.Composite;
35 import org.eclipse.swt.widgets.Label;
36
37 import org.eclipse.jface.dialogs.Dialog;
38 import org.eclipse.jface.dialogs.IDialogConstants;
39 import org.eclipse.jface.dialogs.IDialogSettings;
40 import org.eclipse.jface.resource.JFaceResources;
41 import org.eclipse.jface.viewers.IStructuredSelection;
42 import org.eclipse.jface.viewers.ITreeSelection;
43 import org.eclipse.jface.viewers.TreePath;
44 import org.eclipse.jface.window.Window;
45
46 import org.eclipse.ui.IWorkingSet;
47 import org.eclipse.ui.IWorkingSetManager;
48 import org.eclipse.ui.PlatformUI;
49
50
51 public class WorkingSetConfigurationBlock {
52     
53     //Some static methods for convenience
54

55     /**
56      * Retrieves a working set from the given <code>selection</code>
57      * or <b>null</b> if no working set could be retrieved.
58      *
59      * @param selection the selection to retrieve the working set from
60      * @return the selected working set or <b>null</b>
61      */

62     public static IWorkingSet[] getSelectedWorkingSet(IStructuredSelection selection) {
63         if (!(selection instanceof ITreeSelection))
64             return null;
65         
66         ITreeSelection treeSelection= (ITreeSelection)selection;
67         if (treeSelection.isEmpty())
68             return null;
69         
70         List JavaDoc elements= treeSelection.toList();
71         if (elements.size() == 1) {
72             Object JavaDoc element= elements.get(0);
73             TreePath[] paths= treeSelection.getPathsFor(element);
74             if (paths.length != 1)
75                 return null;
76         
77             TreePath path= paths[0];
78             if (path.getSegmentCount() == 0)
79                 return null;
80         
81             Object JavaDoc candidate= path.getSegment(0);
82             if (!(candidate instanceof IWorkingSet))
83                 return null;
84                 
85             return new IWorkingSet[] {(IWorkingSet)candidate};
86         } else {
87             ArrayList JavaDoc result= new ArrayList JavaDoc();
88             for (Iterator JavaDoc iterator= elements.iterator(); iterator.hasNext();) {
89                 Object JavaDoc element= iterator.next();
90                 if (element instanceof IWorkingSet) {
91                     result.add(element);
92                 }
93             }
94             return (IWorkingSet[])result.toArray(new IWorkingSet[result.size()]);
95         }
96     }
97     
98     /**
99      * Add the <code>element</code> to each given working set in
100      * <code>workingSets</code> if possible.
101      *
102      * @param element the element to add
103      * @param workingSets the working sets to add the element to
104      */

105     public static void addToWorkingSets(IAdaptable element, IWorkingSet[] workingSets) {
106         for (int i= 0; i < workingSets.length; i++) {
107             IWorkingSet workingSet= workingSets[i];
108             IAdaptable[] adaptedNewElements= workingSet.adaptElements(new IAdaptable[] {element});
109             if (adaptedNewElements.length == 1) {
110                 IAdaptable[] elements= workingSet.getElements();
111                 IAdaptable[] newElements= new IAdaptable[elements.length + 1];
112                 System.arraycopy(elements, 0, newElements, 0, elements.length);
113                 newElements[newElements.length - 1]= adaptedNewElements[0];
114                 workingSet.setElements(newElements);
115             }
116         }
117     }
118     
119     /**
120      * Filters the given working sets such that the following is true:
121      * for each IWorkingSet s in result: s.getId() is element of workingSetIds
122      *
123      * @param workingSets the array to filter
124      * @param workingSetIds the acceptable working set ids
125      * @return the filtered elements
126      */

127     public static IWorkingSet[] filter(IWorkingSet[] workingSets, String JavaDoc[] workingSetIds) {
128         ArrayList JavaDoc result= new ArrayList JavaDoc();
129         
130         for (int i= 0; i < workingSets.length; i++) {
131             if (accept(workingSets[i], workingSetIds))
132                 result.add(workingSets[i]);
133         }
134         
135         return (IWorkingSet[])result.toArray(new IWorkingSet[result.size()]);
136     }
137     
138     private static boolean accept(IWorkingSet set, String JavaDoc[] workingSetIDs) {
139         for (int i= 0; i < workingSetIDs.length; i++) {
140             if (workingSetIDs[i].equals(set.getId()))
141                 return true;
142         }
143         
144         return false;
145     }
146     
147     private static final String JavaDoc WORKINGSET_SELECTION_HISTORY= "workingset_selection_history"; //$NON-NLS-1$
148
private static final int MAX_HISTORY_SIZE= 5;
149     
150     private Label fLabel;
151     private Combo fWorkingSetCombo;
152     private Button fConfigure;
153     private IWorkingSet[] fSelectedWorkingSets;
154     private String JavaDoc fMessage;
155     private Button fEnableButton;
156     private ArrayList JavaDoc fSelectionHistory;
157     private final IDialogSettings fSettings;
158     private final String JavaDoc fEnableButtonText;
159     private final String JavaDoc[] fWorkingSetIds;
160
161     /**
162      * @param workingSetIds working set ids from which the user can choose
163      * @param enableButtonText the text shown for the enable button
164      * @param settings to store/load the selection history
165      */

166     public WorkingSetConfigurationBlock(String JavaDoc[] workingSetIds, String JavaDoc enableButtonText, IDialogSettings settings) {
167         Assert.isNotNull(workingSetIds);
168         Assert.isNotNull(enableButtonText);
169         Assert.isNotNull(settings);
170         
171         fWorkingSetIds= workingSetIds;
172         fEnableButtonText= enableButtonText;
173         fSelectedWorkingSets= new IWorkingSet[0];
174         fSettings= settings;
175         fSelectionHistory= loadSelectionHistory(settings, workingSetIds);
176     }
177
178     /**
179      * @param message the message to show to the user in the working set selection dialog
180      */

181     public void setDialogMessage(String JavaDoc message) {
182         fMessage= message;
183     }
184     
185     /**
186      * @param selection the selection to present in the UI or <b>null</b>
187      */

188     public void setSelection(IWorkingSet[] selection) {
189         if (selection == null)
190             selection= new IWorkingSet[0];
191         
192         fSelectedWorkingSets= selection;
193         if (fWorkingSetCombo != null)
194             updateSelectedWorkingSets();
195     }
196     
197     /**
198      * @return the selected working sets
199      */

200     public IWorkingSet[] getSelectedWorkingSets() {
201         if (fEnableButton.getSelection()) {
202             return fSelectedWorkingSets;
203         } else {
204             return new IWorkingSet[0];
205         }
206     }
207
208     /**
209      * Add this block to the <code>parent</parent>
210      *
211      * @param parent the parent to add the block to
212      */

213     public void createContent(final Composite parent) {
214         int numColumn= 3;
215         
216         Composite composite= new Composite(parent, SWT.NONE);
217         composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
218         composite.setLayout(new GridLayout(numColumn, false));
219         
220         fEnableButton= new Button(composite, SWT.CHECK);
221         fEnableButton.setText(fEnableButtonText);
222         GridData enableData= new GridData(SWT.FILL, SWT.CENTER, true, false);
223         enableData.horizontalSpan= numColumn;
224         fEnableButton.setLayoutData(enableData);
225         fEnableButton.setSelection(fSelectedWorkingSets.length > 0);
226                     
227         fLabel= new Label(composite, SWT.NONE);
228         fLabel.setText(WorkingSetMessages.WorkingSetConfigurationBlock_WorkingSetText_name);
229         
230         fWorkingSetCombo= new Combo(composite, SWT.READ_ONLY | SWT.BORDER);
231         GridData textData= new GridData(SWT.FILL, SWT.CENTER, true, false);
232         textData.horizontalSpan= numColumn - 2;
233         textData.horizontalIndent= 0;
234         fWorkingSetCombo.setLayoutData(textData);
235         
236         fConfigure= new Button(composite, SWT.PUSH);
237         fConfigure.setText(WorkingSetMessages.WorkingSetConfigurationBlock_SelectWorkingSet_button);
238         GridData configureData= new GridData(SWT.LEFT, SWT.CENTER, false, false);
239         configureData.widthHint= getButtonWidthHint(fConfigure);
240         fConfigure.setLayoutData(configureData);
241         fConfigure.addSelectionListener(new SelectionAdapter() {
242
243             public void widgetSelected(SelectionEvent e) {
244                 SimpleWorkingSetSelectionDialog dialog= new SimpleWorkingSetSelectionDialog(parent.getShell(), fWorkingSetIds, fSelectedWorkingSets);
245                 if (fMessage != null)
246                     dialog.setMessage(fMessage);
247
248                 if (dialog.open() == Window.OK) {
249                     IWorkingSet[] result= dialog.getSelection();
250                     if (result != null && result.length > 0) {
251                         fSelectedWorkingSets= result;
252                         PlatformUI.getWorkbench().getWorkingSetManager().addRecentWorkingSet(result[0]);
253                     } else {
254                         fSelectedWorkingSets= new IWorkingSet[0];
255                     }
256                     updateWorkingSetSelection();
257                 }
258             }
259         });
260         
261         fEnableButton.addSelectionListener(new SelectionAdapter() {
262             public void widgetSelected(SelectionEvent e) {
263                 updateEnableState(fEnableButton.getSelection());
264             }
265         });
266         updateEnableState(fEnableButton.getSelection());
267         
268         fWorkingSetCombo.addSelectionListener(new SelectionAdapter() {
269             public void widgetSelected(SelectionEvent e) {
270                 updateSelectedWorkingSets();
271             }
272         });
273         
274         fWorkingSetCombo.setItems(getHistoryEntries());
275         if (fSelectedWorkingSets.length == 0 && fSelectionHistory.size() > 0) {
276             fWorkingSetCombo.select(historyIndex((String JavaDoc)fSelectionHistory.get(0)));
277             updateSelectedWorkingSets();
278         } else {
279             updateWorkingSetSelection();
280         }
281     }
282     
283     private void updateEnableState(boolean enabled) {
284         fLabel.setEnabled(enabled);
285         fWorkingSetCombo.setEnabled(enabled && (fSelectedWorkingSets.length > 0 || getHistoryEntries().length > 0));
286         fConfigure.setEnabled(enabled);
287     }
288     
289     private void updateWorkingSetSelection() {
290         if (fSelectedWorkingSets.length > 0) {
291             fWorkingSetCombo.setEnabled(true);
292             StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
293
294             buf.append(fSelectedWorkingSets[0].getLabel());
295             for (int i= 1; i < fSelectedWorkingSets.length; i++) {
296                 IWorkingSet ws= fSelectedWorkingSets[i];
297                 buf.append(',').append(' ');
298                 buf.append(ws.getLabel());
299             }
300
301             String JavaDoc currentSelection= buf.toString();
302             int index= historyIndex(currentSelection);
303             historyInsert(currentSelection);
304             if (index >= 0) {
305                 fWorkingSetCombo.select(index);
306             } else {
307                 fWorkingSetCombo.setItems(getHistoryEntries());
308                 fWorkingSetCombo.select(historyIndex(currentSelection));
309             }
310         }else {
311             fEnableButton.setSelection(false);
312             updateEnableState(false);
313         }
314     }
315
316     private String JavaDoc[] getHistoryEntries() {
317         String JavaDoc[] history= (String JavaDoc[])fSelectionHistory.toArray(new String JavaDoc[fSelectionHistory.size()]);
318         Arrays.sort(history, new Comparator JavaDoc() {
319             public int compare(Object JavaDoc o1, Object JavaDoc o2) {
320                 return Collator.getInstance().compare(o1, o2);
321             }
322         });
323         return history;
324     }
325
326     private void historyInsert(String JavaDoc entry) {
327         fSelectionHistory.remove(entry);
328         fSelectionHistory.add(0, entry);
329         storeSelectionHistory(fSettings);
330     }
331
332     private int historyIndex(String JavaDoc entry) {
333         for (int i= 0; i < fWorkingSetCombo.getItemCount(); i++) {
334             if (fWorkingSetCombo.getItem(i).equals(entry))
335                 return i;
336         }
337         
338         return -1;
339     }
340     
341     private void updateSelectedWorkingSets() {
342         String JavaDoc item= fWorkingSetCombo.getItem(fWorkingSetCombo.getSelectionIndex());
343         String JavaDoc[] workingSetNames= item.split(", "); //$NON-NLS-1$
344

345         IWorkingSetManager workingSetManager= PlatformUI.getWorkbench().getWorkingSetManager();
346         fSelectedWorkingSets= new IWorkingSet[workingSetNames.length];
347         for (int i= 0; i < workingSetNames.length; i++) {
348             IWorkingSet set= workingSetManager.getWorkingSet(workingSetNames[i]);
349             Assert.isNotNull(set);
350             fSelectedWorkingSets[i]= set;
351         }
352     }
353     
354     private void storeSelectionHistory(IDialogSettings settings) {
355         String JavaDoc[] history;
356         if (fSelectionHistory.size() > MAX_HISTORY_SIZE) {
357             List JavaDoc subList= fSelectionHistory.subList(0, MAX_HISTORY_SIZE);
358             history= (String JavaDoc[])subList.toArray(new String JavaDoc[subList.size()]);
359         } else {
360             history= (String JavaDoc[])fSelectionHistory.toArray(new String JavaDoc[fSelectionHistory.size()]);
361         }
362         settings.put(WORKINGSET_SELECTION_HISTORY, history);
363     }
364     
365     private ArrayList JavaDoc loadSelectionHistory(IDialogSettings settings, String JavaDoc[] workingSetIds) {
366         String JavaDoc[] strings= settings.getArray(WORKINGSET_SELECTION_HISTORY);
367         if (strings == null || strings.length == 0)
368             return new ArrayList JavaDoc();
369         
370         ArrayList JavaDoc result= new ArrayList JavaDoc();
371         
372         HashSet JavaDoc workingSetIdsSet= new HashSet JavaDoc(Arrays.asList(workingSetIds));
373         
374         IWorkingSetManager workingSetManager= PlatformUI.getWorkbench().getWorkingSetManager();
375         for (int i= 0; i < strings.length; i++) {
376             String JavaDoc[] workingSetNames= strings[i].split(", "); //$NON-NLS-1$
377
boolean valid= true;
378             for (int j= 0; j < workingSetNames.length && valid; j++) {
379                 IWorkingSet workingSet= workingSetManager.getWorkingSet(workingSetNames[j]);
380                 if (workingSet == null) {
381                     valid= false;
382                 } else {
383                     if (!workingSetIdsSet.contains(workingSet.getId()))
384                         valid= false;
385                 }
386             }
387             if (valid) {
388                 result.add(strings[i]);
389             }
390         }
391         
392         return result;
393     }
394
395     private static int getButtonWidthHint(Button button) {
396         button.setFont(JFaceResources.getDialogFont());
397         
398         GC gc = new GC(button);
399         gc.setFont(button.getFont());
400         FontMetrics fontMetrics= gc.getFontMetrics();
401         gc.dispose();
402         
403         int widthHint= Dialog.convertHorizontalDLUsToPixels(fontMetrics, IDialogConstants.BUTTON_WIDTH);
404         return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);
405     }
406 }
Popular Tags