KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > quickaccess > QuickAccessDialog


1 /*******************************************************************************
2  * Copyright (c) 2005, 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.ui.internal.quickaccess;
12
13 import java.util.ArrayList JavaDoc;
14 import java.util.HashMap JavaDoc;
15 import java.util.Iterator JavaDoc;
16 import java.util.LinkedList JavaDoc;
17 import java.util.List JavaDoc;
18 import java.util.Map JavaDoc;
19
20 import org.eclipse.core.commands.Command;
21 import org.eclipse.core.runtime.Assert;
22 import org.eclipse.jface.bindings.TriggerSequence;
23 import org.eclipse.jface.bindings.keys.KeySequence;
24 import org.eclipse.jface.bindings.keys.SWTKeySupport;
25 import org.eclipse.jface.dialogs.Dialog;
26 import org.eclipse.jface.dialogs.IDialogSettings;
27 import org.eclipse.jface.dialogs.PopupDialog;
28 import org.eclipse.jface.layout.GridDataFactory;
29 import org.eclipse.jface.layout.GridLayoutFactory;
30 import org.eclipse.jface.layout.TableColumnLayout;
31 import org.eclipse.jface.resource.FontDescriptor;
32 import org.eclipse.jface.resource.ImageDescriptor;
33 import org.eclipse.jface.resource.JFaceResources;
34 import org.eclipse.jface.resource.LocalResourceManager;
35 import org.eclipse.jface.viewers.ColumnWeightData;
36 import org.eclipse.jface.window.DefaultToolTip;
37 import org.eclipse.jface.window.ToolTip;
38 import org.eclipse.osgi.util.NLS;
39 import org.eclipse.swt.SWT;
40 import org.eclipse.swt.custom.BusyIndicator;
41 import org.eclipse.swt.events.ControlAdapter;
42 import org.eclipse.swt.events.ControlEvent;
43 import org.eclipse.swt.events.KeyAdapter;
44 import org.eclipse.swt.events.KeyEvent;
45 import org.eclipse.swt.events.KeyListener;
46 import org.eclipse.swt.events.ModifyEvent;
47 import org.eclipse.swt.events.ModifyListener;
48 import org.eclipse.swt.events.MouseAdapter;
49 import org.eclipse.swt.events.MouseEvent;
50 import org.eclipse.swt.events.SelectionEvent;
51 import org.eclipse.swt.events.SelectionListener;
52 import org.eclipse.swt.graphics.Color;
53 import org.eclipse.swt.graphics.Font;
54 import org.eclipse.swt.graphics.FontMetrics;
55 import org.eclipse.swt.graphics.GC;
56 import org.eclipse.swt.graphics.Point;
57 import org.eclipse.swt.graphics.Rectangle;
58 import org.eclipse.swt.graphics.TextLayout;
59 import org.eclipse.swt.graphics.TextStyle;
60 import org.eclipse.swt.widgets.Composite;
61 import org.eclipse.swt.widgets.Control;
62 import org.eclipse.swt.widgets.Event;
63 import org.eclipse.swt.widgets.Listener;
64 import org.eclipse.swt.widgets.Shell;
65 import org.eclipse.swt.widgets.Table;
66 import org.eclipse.swt.widgets.TableColumn;
67 import org.eclipse.swt.widgets.TableItem;
68 import org.eclipse.swt.widgets.Text;
69 import org.eclipse.ui.IWorkbenchPage;
70 import org.eclipse.ui.IWorkbenchWindow;
71 import org.eclipse.ui.internal.IWorkbenchGraphicConstants;
72 import org.eclipse.ui.internal.WorkbenchImages;
73 import org.eclipse.ui.internal.WorkbenchPlugin;
74 import org.eclipse.ui.internal.progress.ProgressManagerUtil;
75 import org.eclipse.ui.keys.IBindingService;
76 import org.eclipse.ui.themes.ColorUtil;
77
78 /**
79  * @since 3.3
80  *
81  */

82 public class QuickAccessDialog extends PopupDialog {
83     private static final int INITIAL_COUNT_PER_PROVIDER = 5;
84     private static final int MAX_COUNT_TOTAL = 20;
85
86     private Text filterText;
87
88     private QuickAccessProvider[] providers;
89     private IWorkbenchWindow window;
90
91     private Table table;
92
93     private LocalResourceManager resourceManager = new LocalResourceManager(
94             JFaceResources.getResources());
95
96     private static final String JavaDoc TEXT_ARRAY = "textArray"; //$NON-NLS-1$
97
private static final String JavaDoc TEXT_ENTRIES = "textEntries"; //$NON-NLS-1$
98
private static final String JavaDoc ORDERED_PROVIDERS = "orderedProviders"; //$NON-NLS-1$
99
private static final String JavaDoc ORDERED_ELEMENTS = "orderedElements"; //$NON-NLS-1$
100
static final int MAXIMUM_NUMBER_OF_ELEMENTS = 60;
101     static final int MAXIMUM_NUMBER_OF_TEXT_ENTRIES_PER_ELEMENT = 3;
102
103     protected String JavaDoc rememberedText;
104
105     protected Map JavaDoc textMap = new HashMap JavaDoc();
106
107     protected Map JavaDoc elementMap = new HashMap JavaDoc();
108
109     private LinkedList JavaDoc previousPicksList = new LinkedList JavaDoc();
110
111     protected Map JavaDoc providerMap;
112     // private Font italicsFont;
113
private Color grayColor;
114     private TextLayout textLayout;
115     private TriggerSequence[] invokingCommandKeySequences;
116     private Command invokingCommand;
117     private KeyAdapter keyAdapter;
118     private boolean showAllMatches = false;
119     protected boolean resized = false;
120
121     /**
122      * @param parent
123      */

124     QuickAccessDialog(IWorkbenchWindow window, final Command invokingCommand) {
125         super(ProgressManagerUtil.getDefaultParent(), SWT.RESIZE, true, true,
126                 true, true, null,
127                 QuickAccessMessages.QuickAccess_StartTypingToFindMatches);
128
129         this.window = window;
130         BusyIndicator.showWhile(window.getShell() == null ? null : window
131                 .getShell().getDisplay(), new Runnable JavaDoc() {
132             public void run() {
133                 QuickAccessDialog.this.providers = new QuickAccessProvider[] {
134                         new PreviousPicksProvider(), new EditorProvider(),
135                         new ViewProvider(), new PerspectiveProvider(),
136                         new CommandProvider(), new ActionProvider(),
137                         new WizardProvider(), new PreferenceProvider(),
138                         new PropertiesProvider() };
139                 providerMap = new HashMap JavaDoc();
140                 for (int i = 0; i < providers.length; i++) {
141                     providerMap.put(providers[i].getId(), providers[i]);
142                 }
143                 restoreDialog();
144                 QuickAccessDialog.this.invokingCommand = invokingCommand;
145                 if (QuickAccessDialog.this.invokingCommand != null
146                         && !QuickAccessDialog.this.invokingCommand.isDefined()) {
147                     QuickAccessDialog.this.invokingCommand = null;
148                 } else {
149                     // Pre-fetch key sequence - do not change because scope will
150
// change later.
151
getInvokingCommandKeySequences();
152                 }
153                 // create early
154
create();
155             }
156         });
157         // Ugly hack to avoid bug 184045. If this gets fixed, replace the
158
// following code with a call to refresh("").
159
getShell().getDisplay().asyncExec(new Runnable JavaDoc() {
160             public void run() {
161                 final Shell shell = getShell();
162                 if (shell != null && !shell.isDisposed()) {
163                     Point size = shell.getSize();
164                     shell.setSize(size.x, size.y + 1);
165                 }
166             }
167         });
168     }
169
170     protected Control createTitleControl(Composite parent) {
171         filterText = new Text(parent, SWT.NONE);
172
173         GC gc = new GC(parent);
174         gc.setFont(parent.getFont());
175         FontMetrics fontMetrics = gc.getFontMetrics();
176         gc.dispose();
177
178         GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true,
179                 false).hint(SWT.DEFAULT,
180                 Dialog.convertHeightInCharsToPixels(fontMetrics, 1)).applyTo(
181                 filterText);
182
183         filterText.addKeyListener(getKeyAdapter());
184         filterText.addKeyListener(new KeyListener() {
185             public void keyPressed(KeyEvent e) {
186                 if (e.keyCode == 0x0D) {
187                     handleSelection();
188                     return;
189                 } else if (e.keyCode == SWT.ARROW_DOWN) {
190                     int index = table.getSelectionIndex();
191                     if (index != -1 && table.getItemCount() > index + 1) {
192                         table.setSelection(index + 1);
193                     }
194                     table.setFocus();
195                 } else if (e.keyCode == SWT.ARROW_UP) {
196                     int index = table.getSelectionIndex();
197                     if (index != -1 && index >= 1) {
198                         table.setSelection(index - 1);
199                         table.setFocus();
200                     }
201                 } else if (e.character == 0x1B) // ESC
202
close();
203             }
204
205             public void keyReleased(KeyEvent e) {
206                 // do nothing
207
}
208         });
209         filterText.addModifyListener(new ModifyListener() {
210             public void modifyText(ModifyEvent e) {
211                 String JavaDoc text = ((Text) e.widget).getText().toLowerCase();
212                 refresh(text);
213             }
214         });
215
216         return filterText;
217     }
218
219     /*
220      * (non-Javadoc)
221      *
222      * @see org.eclipse.jface.dialogs.PopupDialog#createDialogArea(org.eclipse.swt.widgets.Composite)
223      */

224     protected Control createDialogArea(Composite parent) {
225         Composite composite = (Composite) super.createDialogArea(parent);
226         boolean isWin32 = "win32".equals(SWT.getPlatform()); //$NON-NLS-1$
227
GridLayoutFactory.fillDefaults().extendedMargins(isWin32 ? 0 : 3, 3, 2, 2).applyTo(composite);
228         Composite tableComposite = new Composite(composite, SWT.NONE);
229         GridDataFactory.fillDefaults().grab(true, true).applyTo(tableComposite);
230         TableColumnLayout tableColumnLayout = new TableColumnLayout();
231         tableComposite.setLayout(tableColumnLayout);
232         table = new Table(tableComposite, SWT.SINGLE | SWT.FULL_SELECTION);
233         textLayout = new TextLayout(table.getDisplay());
234         textLayout.setOrientation(getDefaultOrientation());
235         Font boldFont = resourceManager.createFont(FontDescriptor.createFrom(
236                 table.getFont()).setStyle(SWT.BOLD));
237         textLayout.setFont(table.getFont());
238         textLayout.setText(QuickAccessMessages.QuickAccess_AvailableCategories);
239         int maxProviderWidth = (int) (textLayout.getBounds().width * 1.1);
240         textLayout.setFont(boldFont);
241         for (int i = 0; i < providers.length; i++) {
242             QuickAccessProvider provider = providers[i];
243             textLayout.setText(provider.getName());
244             int width = (int) (textLayout.getBounds().width * 1.1);
245             if (width > maxProviderWidth) {
246                 maxProviderWidth = width;
247             }
248         }
249         tableColumnLayout.setColumnData(new TableColumn(table, SWT.NONE),
250                 new ColumnWeightData(0, maxProviderWidth));
251         tableColumnLayout.setColumnData(new TableColumn(table, SWT.NONE),
252                 new ColumnWeightData(100, 100));
253         table.getShell().addControlListener(new ControlAdapter() {
254             public void controlResized(ControlEvent e) {
255                 if (!showAllMatches) {
256                     if (!resized) {
257                         resized = true;
258                         e.display.timerExec(100, new Runnable JavaDoc() {
259                             public void run() {
260                                 if (getShell() != null
261                                         && !getShell().isDisposed()) {
262                                     refresh(filterText.getText().toLowerCase());
263                                 }
264                                 resized = false;
265                             }
266                         });
267                     }
268                 }
269             }
270         });
271
272         new DefaultToolTip(table, ToolTip.NO_RECREATE, false) {
273             private QuickAccessEntry getEntry(Event event) {
274                 TableItem item = table.getItem(new Point(event.x, event.y));
275                 if (item != null) {
276                     return (QuickAccessEntry) item.getData();
277                 }
278                 return null;
279             }
280
281             protected String JavaDoc getText(Event event) {
282                 QuickAccessEntry entry = getEntry(event);
283                 if (entry != null) {
284                     return entry.element.getLabel();
285                 }
286                 return null;
287             }
288
289             protected boolean shouldCreateToolTip(Event event) {
290                 table.setToolTipText(""); //$NON-NLS-1$
291
return getEntry(event) != null
292                         && super.shouldCreateToolTip(event);
293             }
294
295             protected Object JavaDoc getToolTipArea(Event event) {
296                 return getEntry(event);
297             }
298         }.activate();
299
300         table.addKeyListener(getKeyAdapter());
301         table.addKeyListener(new KeyListener() {
302             public void keyPressed(KeyEvent e) {
303                 if (e.keyCode == SWT.ARROW_UP && table.getSelectionIndex() == 0) {
304                     filterText.setFocus();
305                 } else if (e.character == SWT.ESC) {
306                     close();
307                 }
308             }
309
310             public void keyReleased(KeyEvent e) {
311                 // do nothing
312
}
313         });
314         table.addMouseListener(new MouseAdapter() {
315             public void mouseUp(MouseEvent e) {
316
317                 if (table.getSelectionCount() < 1)
318                     return;
319
320                 if (e.button != 1)
321                     return;
322
323                 if (table.equals(e.getSource())) {
324                     Object JavaDoc o= table.getItem(new Point(e.x, e.y));
325                     TableItem selection= table.getSelection()[0];
326                     if (selection.equals(o))
327                         handleSelection();
328                 }
329             }
330         });
331
332         table.addSelectionListener(new SelectionListener() {
333             public void widgetSelected(SelectionEvent e) {
334                 // do nothing
335
}
336
337             public void widgetDefaultSelected(SelectionEvent e) {
338                 handleSelection();
339             }
340         });
341
342         // italicsFont = resourceManager.createFont(FontDescriptor.createFrom(
343
// table.getFont()).setStyle(SWT.ITALIC));
344
grayColor = resourceManager.createColor(ColorUtil.blend(table
345                 .getBackground().getRGB(), table.getForeground().getRGB()));
346         final TextStyle boldStyle = new TextStyle(boldFont, null, null);
347         Listener listener = new Listener() {
348             public void handleEvent(Event event) {
349                 QuickAccessEntry entry = (QuickAccessEntry) event.item
350                         .getData();
351                 if (entry != null) {
352                     switch (event.type) {
353                     case SWT.MeasureItem:
354                         entry.measure(event, textLayout, resourceManager,
355                                 boldStyle);
356                         break;
357                     case SWT.PaintItem:
358                         entry.paint(event, textLayout, resourceManager,
359                                 boldStyle, grayColor);
360                         break;
361                     case SWT.EraseItem:
362                         entry.erase(event);
363                         break;
364                     }
365                 }
366             }
367         };
368         table.addListener(SWT.MeasureItem, listener);
369         table.addListener(SWT.EraseItem, listener);
370         table.addListener(SWT.PaintItem, listener);
371                 
372         return composite;
373     }
374
375     /**
376      *
377      */

378     private int computeNumberOfItems() {
379         int height = table.getClientArea().height;
380         int lineWidth = table.getLinesVisible() ? table.getGridLineWidth() : 0;
381         return (height - lineWidth) / (table.getItemHeight() + lineWidth);
382     }
383
384     /**
385      *
386      */

387     private void refresh(String JavaDoc filter) {
388         int numItems = computeNumberOfItems();
389
390         // perfect match, to be selected in the table if not null
391
QuickAccessElement perfectMatch = (QuickAccessElement) elementMap
392                 .get(filter);
393
394         List JavaDoc[] entries = computeMatchingEntries(filter, perfectMatch, numItems);
395
396         int selectionIndex = refreshTable(perfectMatch, entries);
397
398         if (table.getItemCount() > 0) {
399             table.setSelection(selectionIndex);
400         } else if (filter.length() == 0) {
401             {
402                 TableItem item = new TableItem(table, SWT.NONE);
403                 item.setText(0,
404                         QuickAccessMessages.QuickAccess_AvailableCategories);
405                 item.setForeground(0, grayColor);
406             }
407             for (int i = 0; i < providers.length; i++) {
408                 QuickAccessProvider provider = providers[i];
409                 TableItem item = new TableItem(table, SWT.NONE);
410                 item.setText(1, provider.getName());
411                 item.setForeground(1, grayColor);
412             }
413         }
414
415         if (filter.length() == 0) {
416             setInfoText(QuickAccessMessages.QuickAccess_StartTypingToFindMatches);
417         } else {
418             TriggerSequence[] sequences = getInvokingCommandKeySequences();
419             if (showAllMatches || sequences == null || sequences.length == 0) {
420                 setInfoText(""); //$NON-NLS-1$
421
} else {
422                 setInfoText(NLS
423                         .bind(
424                                 QuickAccessMessages.QuickAccess_PressKeyToShowAllMatches,
425                                 sequences[0].format()));
426             }
427         }
428     }
429
430     final protected TriggerSequence[] getInvokingCommandKeySequences() {
431         if (invokingCommandKeySequences == null) {
432             if (invokingCommand != null) {
433                 IBindingService bindingService = (IBindingService) window
434                         .getWorkbench().getAdapter(IBindingService.class);
435                 invokingCommandKeySequences = bindingService
436                         .getActiveBindingsFor(invokingCommand.getId());
437             }
438         }
439         return invokingCommandKeySequences;
440     }
441
442     private KeyAdapter getKeyAdapter() {
443         if (keyAdapter == null) {
444             keyAdapter = new KeyAdapter() {
445                 public void keyPressed(KeyEvent e) {
446                     int accelerator = SWTKeySupport
447                             .convertEventToUnmodifiedAccelerator(e);
448                     KeySequence keySequence = KeySequence
449                             .getInstance(SWTKeySupport
450                                     .convertAcceleratorToKeyStroke(accelerator));
451                     TriggerSequence[] sequences = getInvokingCommandKeySequences();
452                     if (sequences == null)
453                         return;
454                     for (int i = 0; i < sequences.length; i++) {
455                         if (sequences[i].equals(keySequence)) {
456                             e.doit = false;
457                             toggleShowAllMatches();
458                             return;
459                         }
460                     }
461                 }
462             };
463         }
464         return keyAdapter;
465     }
466
467     private void toggleShowAllMatches() {
468         showAllMatches = !showAllMatches;
469         refresh(filterText.getText().toLowerCase());
470     }
471
472     private int refreshTable(QuickAccessElement perfectMatch, List JavaDoc[] entries) {
473         if (table.getItemCount() > entries.length
474                 && table.getItemCount() - entries.length > 20) {
475             table.removeAll();
476         }
477         TableItem[] items = table.getItems();
478         int selectionIndex = -1;
479         int index = 0;
480         for (int i = 0; i < providers.length; i++) {
481             if (entries[i] != null) {
482                 boolean firstEntry = true;
483                 for (Iterator JavaDoc it = entries[i].iterator(); it.hasNext();) {
484                     QuickAccessEntry entry = (QuickAccessEntry) it.next();
485                     entry.firstInCategory = firstEntry;
486                     firstEntry = false;
487                     if (!it.hasNext()) {
488                         entry.lastInCategory = true;
489                     }
490                     TableItem item;
491                     if (index < items.length) {
492                         item = items[index];
493                         table.clear(index);
494                     } else {
495                         item = new TableItem(table, SWT.NONE);
496                     }
497                     if (perfectMatch == entry.element && selectionIndex == -1) {
498                         selectionIndex = index;
499                     }
500                     item.setData(entry);
501                     item.setText(0, entry.provider.getName());
502                     item.setText(1, entry.element.getLabel());
503                     if (SWT.getPlatform().equals("wpf")) { //$NON-NLS-1$
504
item.setImage(1, entry.getImage(entry.element,
505                             resourceManager));
506                     }
507                     index++;
508                 }
509             }
510         }
511         if (index < items.length) {
512             table.remove(index, items.length - 1);
513         }
514         if (selectionIndex == -1) {
515             selectionIndex = 0;
516         }
517         return selectionIndex;
518     }
519
520     private List JavaDoc[] computeMatchingEntries(String JavaDoc filter,
521             QuickAccessElement perfectMatch, int maxCount) {
522         // collect matches in an array of lists
523
List JavaDoc[] entries = new ArrayList JavaDoc[providers.length];
524         int[] indexPerProvider = new int[providers.length];
525         int countPerProvider = Math.min(maxCount / 4,
526                 INITIAL_COUNT_PER_PROVIDER);
527         int countTotal = 0;
528         boolean perfectMatchAdded = true;
529         if (perfectMatch != null) {
530             // reserve one entry for the perfect match
531
maxCount--;
532             perfectMatchAdded = false;
533         }
534         boolean done;
535         do {
536             // will be set to false if we find a provider with remaining
537
// elements
538
done = true;
539             for (int i = 0; i < providers.length
540                     && (showAllMatches || countTotal < maxCount); i++) {
541                 if (entries[i] == null) {
542                     entries[i] = new ArrayList JavaDoc();
543                     indexPerProvider[i] = 0;
544                 }
545                 int count = 0;
546                 QuickAccessProvider provider = providers[i];
547                 if (filter.length() > 0
548                         || provider instanceof PreviousPicksProvider
549                         || showAllMatches) {
550                     QuickAccessElement[] elements = provider
551                             .getElementsSorted();
552                     int j = indexPerProvider[i];
553                     while (j < elements.length
554                             && (showAllMatches || (count < countPerProvider && countTotal < maxCount))) {
555                         QuickAccessElement element = elements[j];
556                         QuickAccessEntry entry;
557                         if (filter.length() == 0) {
558                             if (i == 0 || showAllMatches) {
559                                 entry = new QuickAccessEntry(element, provider,
560                                         new int[0][0], new int[0][0]);
561                             } else {
562                                 entry = null;
563                             }
564                         } else {
565                             entry = element.match(filter, provider);
566                         }
567                         if (entry != null) {
568                             entries[i].add(entry);
569                             count++;
570                             countTotal++;
571                             if (i == 0 && entry.element == perfectMatch) {
572                                 perfectMatchAdded = true;
573                                 maxCount = MAX_COUNT_TOTAL;
574                             }
575                         }
576                         j++;
577                     }
578                     indexPerProvider[i] = j;
579                     if (j < elements.length) {
580                         done = false;
581                     }
582                 }
583             }
584             // from now on, add one element per provider
585
countPerProvider = 1;
586         } while ((showAllMatches || countTotal < maxCount) && !done);
587         if (!perfectMatchAdded) {
588             QuickAccessEntry entry = perfectMatch.match(filter, providers[0]);
589             if (entry != null) {
590                 if (entries[0] == null) {
591                     entries[0] = new ArrayList JavaDoc();
592                     indexPerProvider[0] = 0;
593                 }
594                 entries[0].add(entry);
595             }
596         }
597         return entries;
598     }
599
600     protected Control getFocusControl() {
601         return filterText;
602     }
603
604     public boolean close() {
605         storeDialog(getDialogSettings());
606         if (textLayout != null && !textLayout.isDisposed()) {
607             textLayout.dispose();
608         }
609         if (resourceManager != null) {
610             resourceManager.dispose();
611             resourceManager = null;
612         }
613         return super.close();
614     }
615
616     protected Point getInitialSize() {
617         if (!getPersistBounds()) {
618             return new Point(350, 420);
619         }
620         return super.getInitialSize();
621     }
622
623     protected Point getInitialLocation(Point initialSize) {
624         if (!getPersistBounds()) {
625             Point size = new Point(400, 400);
626             Rectangle parentBounds = getParentShell().getBounds();
627             int x = parentBounds.x + parentBounds.width / 2 - size.x / 2;
628             int y = parentBounds.y + parentBounds.height / 2 - size.y / 2;
629             return new Point(x, y);
630         }
631         return super.getInitialLocation(initialSize);
632     }
633
634     protected IDialogSettings getDialogSettings() {
635         final IDialogSettings workbenchDialogSettings = WorkbenchPlugin
636                 .getDefault().getDialogSettings();
637         IDialogSettings result = workbenchDialogSettings.getSection(getId());
638         if (result == null) {
639             result = workbenchDialogSettings.addNewSection(getId());
640         }
641         return result;
642     }
643
644     protected String JavaDoc getId() {
645         return "org.eclipse.ui.internal.QuickAccess"; //$NON-NLS-1$
646
}
647
648     private void storeDialog(IDialogSettings dialogSettings) {
649         String JavaDoc[] orderedElements = new String JavaDoc[previousPicksList.size()];
650         String JavaDoc[] orderedProviders = new String JavaDoc[previousPicksList.size()];
651         String JavaDoc[] textEntries = new String JavaDoc[previousPicksList.size()];
652         ArrayList JavaDoc arrayList = new ArrayList JavaDoc();
653         for (int i = 0; i < orderedElements.length; i++) {
654             QuickAccessElement quickAccessElement = (QuickAccessElement) previousPicksList
655                     .get(i);
656             ArrayList JavaDoc elementText = (ArrayList JavaDoc) textMap.get(quickAccessElement);
657             Assert.isNotNull(elementText);
658             orderedElements[i] = quickAccessElement.getId();
659             orderedProviders[i] = quickAccessElement.getProvider().getId();
660             arrayList.addAll(elementText);
661             textEntries[i] = elementText.size() + ""; //$NON-NLS-1$
662
}
663         String JavaDoc[] textArray = (String JavaDoc[]) arrayList.toArray(new String JavaDoc[arrayList
664                 .size()]);
665         dialogSettings.put(ORDERED_ELEMENTS, orderedElements);
666         dialogSettings.put(ORDERED_PROVIDERS, orderedProviders);
667         dialogSettings.put(TEXT_ENTRIES, textEntries);
668         dialogSettings.put(TEXT_ARRAY, textArray);
669     }
670
671     private void restoreDialog() {
672         IDialogSettings dialogSettings = getDialogSettings();
673         if (dialogSettings != null) {
674             String JavaDoc[] orderedElements = dialogSettings
675                     .getArray(ORDERED_ELEMENTS);
676             String JavaDoc[] orderedProviders = dialogSettings
677                     .getArray(ORDERED_PROVIDERS);
678             String JavaDoc[] textEntries = dialogSettings.getArray(TEXT_ENTRIES);
679             String JavaDoc[] textArray = dialogSettings.getArray(TEXT_ARRAY);
680             elementMap = new HashMap JavaDoc();
681             textMap = new HashMap JavaDoc();
682             previousPicksList = new LinkedList JavaDoc();
683             if (orderedElements != null && orderedProviders != null
684                     && textEntries != null && textArray != null) {
685                 int arrayIndex = 0;
686                 for (int i = 0; i < orderedElements.length; i++) {
687                     QuickAccessProvider quickAccessProvider = (QuickAccessProvider) providerMap
688                             .get(orderedProviders[i]);
689                     int numTexts = Integer.parseInt(textEntries[i]);
690                     if (quickAccessProvider != null) {
691                         QuickAccessElement quickAccessElement = quickAccessProvider
692                                 .getElementForId(orderedElements[i]);
693                         if (quickAccessElement != null) {
694                             ArrayList JavaDoc arrayList = new ArrayList JavaDoc();
695                             for (int j = arrayIndex; j < arrayIndex + numTexts; j++) {
696                                 String JavaDoc text = textArray[j];
697                                 // text length can be zero for old workspaces, see bug 190006
698
if (text.length() > 0) {
699                                     arrayList.add(text);
700                                     elementMap.put(text, quickAccessElement);
701                                 }
702                             }
703                             textMap.put(quickAccessElement, arrayList);
704                             previousPicksList.add(quickAccessElement);
705                         }
706                     }
707                     arrayIndex += numTexts;
708                 }
709             }
710         }
711     }
712
713     protected void handleElementSelected(String JavaDoc text, Object JavaDoc selectedElement) {
714         IWorkbenchPage activePage = window.getActivePage();
715         if (activePage != null) {
716             if (selectedElement instanceof QuickAccessElement) {
717                 addPreviousPick(text, selectedElement);
718                 storeDialog(getDialogSettings());
719                 QuickAccessElement element = (QuickAccessElement) selectedElement;
720                 element.execute();
721             }
722         }
723     }
724
725     /**
726      * @param element
727      */

728     private void addPreviousPick(String JavaDoc text, Object JavaDoc element) {
729         // previousPicksList:
730
// Remove element from previousPicksList so there are no duplicates
731
// If list is max size, remove last(oldest) element
732
// Remove entries for removed element from elementMap and textMap
733
// Add element to front of previousPicksList
734
previousPicksList.remove(element);
735         if (previousPicksList.size() == MAXIMUM_NUMBER_OF_ELEMENTS) {
736             Object JavaDoc removedElement = previousPicksList.removeLast();
737             ArrayList JavaDoc removedList = (ArrayList JavaDoc) textMap.remove(removedElement);
738             for (int i = 0; i < removedList.size(); i++) {
739                 elementMap.remove(removedList.get(i));
740             }
741         }
742         previousPicksList.addFirst(element);
743
744         // textMap:
745
// Get list of strings for element from textMap
746
// Create new list for element if there isn't one and put
747
// element->textList in textMap
748
// Remove rememberedText from list
749
// If list is max size, remove first(oldest) string
750
// Remove text from elementMap
751
// Add rememberedText to list of strings for element in textMap
752
ArrayList JavaDoc textList = (ArrayList JavaDoc) textMap.get(element);
753         if (textList == null) {
754             textList = new ArrayList JavaDoc();
755             textMap.put(element, textList);
756         }
757         
758         textList.remove(text);
759         if (textList.size() == MAXIMUM_NUMBER_OF_TEXT_ENTRIES_PER_ELEMENT) {
760             Object JavaDoc removedText = textList.remove(0);
761             elementMap.remove(removedText);
762         }
763
764         if (text.length() > 0) {
765             textList.add(text);
766             
767             // elementMap:
768
// Put rememberedText->element in elementMap
769
// If it replaced a different element update textMap and
770
// PreviousPicksList
771
Object JavaDoc replacedElement = elementMap.put(text, element);
772             if (replacedElement != null && !replacedElement.equals(element)) {
773                 textList = (ArrayList JavaDoc) textMap.get(replacedElement);
774                 if (textList != null) {
775                     textList.remove(text);
776                     if (textList.isEmpty()) {
777                         textMap.remove(replacedElement);
778                         previousPicksList.remove(replacedElement);
779                     }
780                 }
781             }
782         }
783     }
784
785     /**
786      *
787      */

788     private void handleSelection() {
789         QuickAccessElement selectedElement = null;
790         String JavaDoc text = filterText.getText().toLowerCase();
791         if (table.getSelectionCount() == 1) {
792             QuickAccessEntry entry = (QuickAccessEntry) table
793                     .getSelection()[0].getData();
794             selectedElement = entry == null ? null : entry.element;
795         }
796         close();
797         if (selectedElement != null) {
798             handleElementSelected(text, selectedElement);
799         }
800     }
801
802     private class PreviousPicksProvider extends QuickAccessProvider {
803
804         public QuickAccessElement getElementForId(String JavaDoc id) {
805             return null;
806         }
807
808         public QuickAccessElement[] getElements() {
809             return (QuickAccessElement[]) previousPicksList
810                     .toArray(new QuickAccessElement[previousPicksList.size()]);
811         }
812
813         public QuickAccessElement[] getElementsSorted() {
814             return getElements();
815         }
816
817         public String JavaDoc getId() {
818             return "org.eclipse.ui.previousPicks"; //$NON-NLS-1$
819
}
820
821         public ImageDescriptor getImageDescriptor() {
822             return WorkbenchImages
823                     .getImageDescriptor(IWorkbenchGraphicConstants.IMG_OBJ_NODE);
824         }
825
826         public String JavaDoc getName() {
827             return QuickAccessMessages.QuickAccess_Previous;
828         }
829     }
830
831 }
832
Popular Tags