KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > cheatsheets > dialogs > CheatSheetCategoryBasedSelectionDialog


1 /*******************************************************************************
2  * Copyright (c) 2002, 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.cheatsheets.dialogs;
12
13 import java.io.File JavaDoc;
14 import java.net.MalformedURLException JavaDoc;
15 import java.net.URL JavaDoc;
16 import java.util.ArrayList JavaDoc;
17 import java.util.List JavaDoc;
18
19 import org.eclipse.core.runtime.IPath;
20 import org.eclipse.core.runtime.IStatus;
21 import org.eclipse.core.runtime.Path;
22 import org.eclipse.core.runtime.Status;
23 import org.eclipse.jface.dialogs.Dialog;
24 import org.eclipse.jface.dialogs.IDialogConstants;
25 import org.eclipse.jface.dialogs.IDialogSettings;
26 import org.eclipse.jface.dialogs.TrayDialog;
27 import org.eclipse.jface.viewers.DoubleClickEvent;
28 import org.eclipse.jface.viewers.IContentProvider;
29 import org.eclipse.jface.viewers.IDoubleClickListener;
30 import org.eclipse.jface.viewers.ISelection;
31 import org.eclipse.jface.viewers.ISelectionChangedListener;
32 import org.eclipse.jface.viewers.IStructuredSelection;
33 import org.eclipse.jface.viewers.LabelProvider;
34 import org.eclipse.jface.viewers.SelectionChangedEvent;
35 import org.eclipse.jface.viewers.StructuredSelection;
36 import org.eclipse.jface.viewers.TreeViewer;
37 import org.eclipse.jface.viewers.Viewer;
38 import org.eclipse.jface.viewers.ViewerFilter;
39 import org.eclipse.osgi.util.NLS;
40 import org.eclipse.swt.SWT;
41 import org.eclipse.swt.custom.SashForm;
42 import org.eclipse.swt.events.ModifyEvent;
43 import org.eclipse.swt.events.ModifyListener;
44 import org.eclipse.swt.events.SelectionAdapter;
45 import org.eclipse.swt.events.SelectionEvent;
46 import org.eclipse.swt.events.SelectionListener;
47 import org.eclipse.swt.graphics.Image;
48 import org.eclipse.swt.layout.GridData;
49 import org.eclipse.swt.layout.GridLayout;
50 import org.eclipse.swt.widgets.Button;
51 import org.eclipse.swt.widgets.Combo;
52 import org.eclipse.swt.widgets.Composite;
53 import org.eclipse.swt.widgets.Control;
54 import org.eclipse.swt.widgets.FileDialog;
55 import org.eclipse.swt.widgets.Label;
56 import org.eclipse.swt.widgets.Shell;
57 import org.eclipse.swt.widgets.Text;
58 import org.eclipse.ui.ISharedImages;
59 import org.eclipse.ui.PlatformUI;
60 import org.eclipse.ui.activities.ITriggerPoint;
61 import org.eclipse.ui.activities.WorkbenchActivityHelper;
62 import org.eclipse.ui.cheatsheets.OpenCheatSheetAction;
63 import org.eclipse.ui.internal.cheatsheets.CheatSheetPlugin;
64 import org.eclipse.ui.internal.cheatsheets.ICheatSheetResource;
65 import org.eclipse.ui.internal.cheatsheets.Messages;
66 import org.eclipse.ui.internal.cheatsheets.data.ParserStatusUtility;
67 import org.eclipse.ui.internal.cheatsheets.registry.CheatSheetCollectionElement;
68 import org.eclipse.ui.internal.cheatsheets.registry.CheatSheetCollectionSorter;
69 import org.eclipse.ui.internal.cheatsheets.registry.CheatSheetElement;
70 import org.eclipse.ui.internal.cheatsheets.state.DefaultStateManager;
71 import org.eclipse.ui.internal.cheatsheets.views.CheatSheetView;
72 import org.eclipse.ui.internal.cheatsheets.views.ViewUtilities;
73 import org.eclipse.ui.model.BaseWorkbenchContentProvider;
74 import org.eclipse.ui.model.WorkbenchAdapter;
75
76 /**
77  * Dialog to allow the user to select a cheat sheet from a list.
78  */

79 public class CheatSheetCategoryBasedSelectionDialog extends TrayDialog //extends SelectionDialog
80
implements ISelectionChangedListener {
81     private static final String JavaDoc CHEAT_SHEET_SELECTION_HELP_ID = "org.eclipse.ui.cheatsheets.cheatSheetSelection"; //$NON-NLS-1$
82

83     private IDialogSettings settings;
84
85     private CheatSheetCollectionElement cheatsheetCategories;
86
87     private CheatSheetElement currentSelection;
88
89     private TreeViewer treeViewer;
90
91     private Text desc;
92
93     private Button showAllButton;
94     
95     private Button selectRegisteredRadio;
96     
97     private Button selectFileRadio;
98     
99     private Button selectUrlRadio;
100
101     private Combo selectFileCombo;
102     
103     private Combo selectUrlCombo;
104
105     private ActivityViewerFilter activityViewerFilter = new ActivityViewerFilter();
106
107     private boolean okButtonState;
108
109     // id constants
110

111     private static final String JavaDoc DIALOG_SETTINGS_SECTION = "CheatSheetCategoryBasedSelectionDialog"; //$NON-NLS-1$
112

113     private final static String JavaDoc STORE_EXPANDED_CATEGORIES_ID = "CheatSheetCategoryBasedSelectionDialog.STORE_EXPANDED_CATEGORIES_ID"; //$NON-NLS-1$
114

115     private final static String JavaDoc STORE_SELECTED_CHEATSHEET_ID = "CheatSheetCategoryBasedSelectionDialog.STORE_SELECTED_CHEATSHEET_ID"; //$NON-NLS-1$
116

117     private final static String JavaDoc STORE_RADIO_SETTING = "CheatSheetCategoryBasedSelectionDialog.STORE_RADIO_SELECTION"; //$NON-NLS-1$
118

119     private final static String JavaDoc STORE_CHEATSHEET_FILENAME = "CheatSheetCategoryBasedSelectionDialog.STORE_CHEATSHEET_FILENAME"; //$NON-NLS-1$
120

121     private final static String JavaDoc STORE_CHEATSHEET_URL = "CheatSheetCategoryBasedSelectionDialog.STORE_CHEATSHEET_URL"; //$NON-NLS-1$
122

123     private final static String JavaDoc STORE_URL_MRU = "CheatSheetCategoryBasedSelectionDialog.STORE_URL_MRU"; //$NON-NLS-1$
124
private final static String JavaDoc STORE_FILE_MRU = "CheatSheetCategoryBasedSelectionDialog.STORE_FILE_MRU"; //$NON-NLS-1$
125

126     private static final int MOST_RECENT_LENGTH = 3;
127     private static final int RADIO_REGISTERED = 1;
128     private static final int RADIO_FILE = 2;
129     private static final int RADIO_URL = 3;
130     
131     private Button browseFileButton;
132
133     private String JavaDoc title;
134
135     private IStatus status = Status.OK_STATUS;
136     
137     
138     List JavaDoc mostRecentFiles = new ArrayList JavaDoc();
139     List JavaDoc mostRecentUrls = new ArrayList JavaDoc();
140
141     private static class ActivityViewerFilter extends ViewerFilter {
142         private boolean hasEncounteredFilteredItem = false;
143
144         /*
145          * (non-Javadoc)
146          *
147          * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer,
148          * java.lang.Object, java.lang.Object)
149          */

150         public boolean select(Viewer viewer, Object JavaDoc parentElement,
151                 Object JavaDoc element) {
152             if (WorkbenchActivityHelper.filterItem(element)) {
153                 setHasEncounteredFilteredItem(true);
154                 return false;
155             }
156             return true;
157         }
158
159         /**
160          * @return returns whether the filter has filtered an item
161          */

162         public boolean getHasEncounteredFilteredItem() {
163             return hasEncounteredFilteredItem;
164         }
165
166         /**
167          * @param sets
168          * whether the filter has filtered an item
169          */

170         public void setHasEncounteredFilteredItem(
171                 boolean hasEncounteredFilteredItem) {
172             this.hasEncounteredFilteredItem = hasEncounteredFilteredItem;
173         }
174     }
175
176     private class CheatsheetLabelProvider extends LabelProvider {
177         public String JavaDoc getText(Object JavaDoc obj) {
178             if (obj instanceof WorkbenchAdapter) {
179                 return ((WorkbenchAdapter) obj).getLabel(null);
180             }
181             return super.getText(obj);
182         }
183
184         public Image getImage(Object JavaDoc obj) {
185             if (obj instanceof CheatSheetElement) {
186                 CheatSheetElement element = (CheatSheetElement)obj;
187                 if (element.isComposite()) {
188                     return CheatSheetPlugin.getPlugin().getImageRegistry().get(
189                             ICheatSheetResource.COMPOSITE_OBJ);
190                 }
191                 return CheatSheetPlugin.getPlugin().getImageRegistry().get(
192                         ICheatSheetResource.CHEATSHEET_OBJ);
193             }
194             return PlatformUI.getWorkbench().getSharedImages().getImage(
195                     ISharedImages.IMG_OBJ_FOLDER);
196         }
197     }
198
199     /**
200      * Creates an instance of this dialog to display the a list of cheat sheets.
201      *
202      * @param shell
203      * the parent shell
204      */

205     public CheatSheetCategoryBasedSelectionDialog(Shell shell,
206             CheatSheetCollectionElement cheatsheetCategories) {
207         super(shell);
208
209         this.cheatsheetCategories = cheatsheetCategories;
210
211         this.title = Messages.CHEAT_SHEET_SELECTION_DIALOG_TITLE;
212
213         setShellStyle(getShellStyle() | SWT.RESIZE);
214     }
215
216     /*
217      * (non-Javadoc) Method declared on Window.
218      */

219     protected void configureShell(Shell newShell) {
220         super.configureShell(newShell);
221         if (title != null) {
222             newShell.setText(title);
223         }
224         newShell.setImage(CheatSheetPlugin.getPlugin().getImage(ICheatSheetResource.CHEATSHEET_VIEW));
225     }
226
227     /*
228      * (non-Javadoc) Method declared on Dialog.
229      */

230     protected void createButtonsForButtonBar(Composite parent) {
231         super.createButtonsForButtonBar(parent);
232
233         enableOKButton(okButtonState);
234     }
235
236     /*
237      * (non-Javadoc) Method declared on Dialog.
238      */

239     protected Control createDialogArea(Composite parent) {
240         initializeDialogUnits(parent);
241         
242         IDialogSettings workbenchSettings = CheatSheetPlugin.getPlugin()
243                 .getDialogSettings();
244         IDialogSettings dialogSettings = workbenchSettings
245                 .getSection(DIALOG_SETTINGS_SECTION);
246         if (dialogSettings == null)
247             dialogSettings = workbenchSettings
248                     .addNewSection(DIALOG_SETTINGS_SECTION);
249
250         setDialogSettings(dialogSettings);
251
252         // top level group
253
Composite outerContainer = (Composite) super.createDialogArea(parent);
254
255         PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, CHEAT_SHEET_SELECTION_HELP_ID);
256         GridLayout gridLayout = new GridLayout();
257         gridLayout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
258         gridLayout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
259         gridLayout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
260         gridLayout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
261         outerContainer.setLayout(gridLayout);
262         outerContainer.setLayoutData(new GridData(GridData.FILL_BOTH));
263
264         // Create label
265
createMessageArea(outerContainer);
266         
267         // Create radio button
268
selectRegisteredRadio = new Button(outerContainer, SWT.RADIO);
269         selectRegisteredRadio.setText(Messages.SELECTION_DIALOG_OPEN_REGISTERED);
270         
271         SashForm sform = new SashForm(outerContainer, SWT.VERTICAL);
272         GridData data = new GridData(GridData.FILL_BOTH);
273         data.heightHint = 300;
274         sform.setLayoutData(data);
275         
276         // category tree pane
277
treeViewer = new TreeViewer(sform, SWT.SINGLE | SWT.H_SCROLL
278                 | SWT.V_SCROLL | SWT.BORDER);
279         treeViewer.getTree().setLayoutData(data);
280         treeViewer.setContentProvider(getCheatSheetProvider());
281         treeViewer.setLabelProvider(new CheatsheetLabelProvider());
282         treeViewer.setComparator(CheatSheetCollectionSorter.INSTANCE);
283         treeViewer.addFilter(activityViewerFilter);
284         treeViewer.addSelectionChangedListener(this);
285         treeViewer.setInput(cheatsheetCategories);
286
287         desc = new Text(sform, SWT.MULTI | SWT.WRAP);
288         desc.setEditable(false);
289
290         sform.setWeights(new int[] {10, 2});
291         
292         if (activityViewerFilter.getHasEncounteredFilteredItem())
293             createShowAllButton(outerContainer);
294
295         // Add double-click listener
296
treeViewer.addDoubleClickListener(new IDoubleClickListener() {
297             public void doubleClick(DoubleClickEvent event) {
298                 IStructuredSelection selection = (IStructuredSelection)event.getSelection();
299                 Object JavaDoc obj = selection.getFirstElement();
300                 if (obj instanceof CheatSheetCollectionElement) {
301                     boolean state = treeViewer.getExpandedState(obj);
302                     treeViewer.setExpandedState(obj, !state);
303                 }
304                 else {
305                     okPressed();
306                 }
307             }
308         });
309         
310         // Create radio button for select from file
311
selectFileRadio = new Button(outerContainer, SWT.RADIO);
312         selectFileRadio.setText(Messages.SELECTION_DIALOG_OPEN_FROM_FILE);
313         
314         Composite selectFileComposite = new Composite(outerContainer, SWT.NULL);
315         GridLayout selectFileLayout = new GridLayout();
316         selectFileLayout.marginWidth = 0;
317         selectFileLayout.marginHeight = 0;
318         selectFileLayout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
319         selectFileLayout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
320         selectFileLayout.numColumns = 2;
321         selectFileComposite.setLayout(selectFileLayout);
322         GridData sfCompositeData = new GridData(GridData.FILL_HORIZONTAL);
323         sfCompositeData.widthHint = 300;
324         selectFileComposite.setLayoutData(sfCompositeData);
325         selectFileCombo = new Combo(selectFileComposite, SWT.BORDER);
326         GridData sfTextData = new GridData(GridData.FILL_HORIZONTAL);
327         selectFileCombo.setLayoutData(sfTextData);
328         browseFileButton = new Button(selectFileComposite, SWT.NULL);
329         browseFileButton.setText(Messages.SELECTION_DIALOG_FILEPICKER_BROWSE);
330         setButtonLayoutData(browseFileButton);
331         
332         // Create radio button for select from URL
333
selectUrlRadio = new Button(outerContainer, SWT.RADIO);
334         selectUrlRadio.setText(Messages.SELECTION_DIALOG_OPEN_FROM_URL);
335         selectUrlCombo = new Combo(outerContainer, SWT.BORDER);
336         GridData suTextData = new GridData(GridData.FILL_HORIZONTAL);
337         selectUrlCombo.setLayoutData(suTextData);
338         
339         restoreWidgetValues();
340         restoreFileSettings();
341
342         if (!treeViewer.getSelection().isEmpty())
343             // we only set focus if a selection was restored
344
treeViewer.getTree().setFocus();
345
346         Dialog.applyDialogFont(outerContainer);
347         selectFileCombo.addModifyListener(new FileAndUrlListener());
348         browseFileButton.addSelectionListener(new BrowseListener());
349         selectRegisteredRadio.addSelectionListener(new RadioSelectionListener());
350         selectUrlRadio.addSelectionListener(new RadioSelectionListener());
351         selectUrlCombo.addModifyListener(new FileAndUrlListener());
352         checkRadioButtons();
353         return outerContainer;
354     }
355     
356     private class RadioSelectionListener implements SelectionListener {
357
358         public void widgetSelected(SelectionEvent e) {
359             checkRadioButtons();
360         }
361
362         public void widgetDefaultSelected(SelectionEvent e) {
363             // do nothing
364
}
365     }
366     
367     private class BrowseListener implements SelectionListener {
368
369         public void widgetSelected(SelectionEvent e) {
370             // Launch a file dialog to select a cheatsheet file
371
FileDialog fileDlg = new FileDialog(getShell());
372             fileDlg.setFilterExtensions(new String JavaDoc[]{"*.xml"}); //$NON-NLS-1$
373
fileDlg.setText(Messages.SELECTION_DIALOG_FILEPICKER_TITLE);
374             fileDlg.open();
375             String JavaDoc filename = fileDlg.getFileName();
376             if (filename != null) {
377                 IPath folderPath = new Path(fileDlg.getFilterPath());
378                 IPath filePath = folderPath.append(filename);
379                 selectFileCombo.setText(filePath.toOSString());
380                 checkRadioButtons();
381             }
382         }
383
384         public void widgetDefaultSelected(SelectionEvent e) {
385             // do nothing
386
}
387     }
388     
389     private class FileAndUrlListener implements ModifyListener {
390
391         public void modifyText(ModifyEvent e) {
392             setOkButton();
393         }
394     }
395
396     /*
397      * Check the state of the Radio buttons and disable those parts of the UI that don't apply
398      */

399     private void checkRadioButtons() {
400         selectFileCombo.setEnabled(selectFileRadio.getSelection());
401         browseFileButton.setEnabled(selectFileRadio.getSelection());
402         if (showAllButton != null) {
403             showAllButton.setEnabled(selectRegisteredRadio.getSelection());
404         }
405         treeViewer.getTree().setEnabled(selectRegisteredRadio.getSelection());
406         selectUrlCombo.setEnabled(selectUrlRadio.getSelection());
407         setOkButton();
408     }
409
410     /**
411      * Create a show all button in the parent.
412      *
413      * @param parent
414      * the parent <code>Composite</code>.
415      */

416     private void createShowAllButton(Composite parent) {
417         showAllButton = new Button(parent, SWT.CHECK);
418         showAllButton
419                 .setText(Messages.CheatSheetCategoryBasedSelectionDialog_showAll);
420         showAllButton.addSelectionListener(new SelectionAdapter() {
421
422             /*
423              * (non-Javadoc)
424              *
425              * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
426              */

427             public void widgetSelected(SelectionEvent e) {
428                 if (showAllButton.getSelection()) {
429                     treeViewer.resetFilters();
430                 } else {
431                     treeViewer.addFilter(activityViewerFilter);
432                 }
433             }
434         });
435     }
436
437     /**
438      * Method enableOKButton enables/diables the OK button for the dialog and
439      * saves the state, allowing the enabling/disabling to occur even if the
440      * button has not been created yet.
441      *
442      * @param value
443      */

444     private void enableOKButton(boolean value) {
445         Button button = getButton(IDialogConstants.OK_ID);
446
447         okButtonState = value;
448         if (button != null) {
449             button.setEnabled(value);
450         }
451     }
452
453     /**
454      * Expands the cheatsheet categories in this page's category viewer that
455      * were expanded last time this page was used. If a category that was
456      * previously expanded no longer exists then it is ignored.
457      */

458     protected CheatSheetCollectionElement expandPreviouslyExpandedCategories() {
459         String JavaDoc[] expandedCategoryPaths = settings
460                 .getArray(STORE_EXPANDED_CATEGORIES_ID);
461         List JavaDoc categoriesToExpand = new ArrayList JavaDoc(expandedCategoryPaths.length);
462
463         for (int i = 0; i < expandedCategoryPaths.length; i++) {
464             CheatSheetCollectionElement category = cheatsheetCategories
465                     .findChildCollection(new Path(expandedCategoryPaths[i]));
466             if (category != null) // ie.- it still exists
467
categoriesToExpand.add(category);
468         }
469
470         if (!categoriesToExpand.isEmpty())
471             treeViewer.setExpandedElements(categoriesToExpand.toArray());
472         return categoriesToExpand.isEmpty() ? null
473                 : (CheatSheetCollectionElement) categoriesToExpand
474                         .get(categoriesToExpand.size() - 1);
475     }
476
477     /**
478      * Returns the content provider for this page.
479      */

480     protected IContentProvider getCheatSheetProvider() {
481         // want to get the cheatsheets of the collection element
482
return new BaseWorkbenchContentProvider() {
483             public Object JavaDoc[] getChildren(Object JavaDoc o) {
484                 Object JavaDoc[] cheatsheets;
485                 if (o instanceof CheatSheetCollectionElement) {
486                     cheatsheets = ((CheatSheetCollectionElement) o)
487                             .getCheatSheets();
488                 } else {
489                     cheatsheets = new Object JavaDoc[0];
490                 }
491                 Object JavaDoc[] subCategories = super.getChildren(o);
492                 if (cheatsheets.length == 0) {
493                     return subCategories;
494                 } else if (subCategories.length == 0) {
495                     return cheatsheets;
496                 } else {
497                     Object JavaDoc[] result = new Object JavaDoc[cheatsheets.length + subCategories.length];
498                     System.arraycopy(subCategories, 0, result, 0, subCategories.length);
499                     System.arraycopy(cheatsheets, 0, result, subCategories.length, cheatsheets.length);
500                     return result;
501                 }
502             }
503         };
504     }
505
506     /**
507      * Returns the single selected object contained in the passed
508      * selectionEvent, or <code>null</code> if the selectionEvent contains
509      * either 0 or 2+ selected objects.
510      */

511     protected Object JavaDoc getSingleSelection(ISelection selection) {
512         IStructuredSelection ssel = (IStructuredSelection) selection;
513         return ssel.size() == 1 ? ssel.getFirstElement() : null;
514     }
515
516     /**
517      * The user selected either new cheatsheet category(s) or cheatsheet
518      * element(s). Proceed accordingly.
519      *
520      * @param newSelection
521      * ISelection
522      */

523     public void selectionChanged(SelectionChangedEvent selectionEvent) {
524         Object JavaDoc obj = getSingleSelection(selectionEvent.getSelection());
525         if (obj instanceof CheatSheetCollectionElement) {
526             currentSelection = null;
527         } else {
528             currentSelection = (CheatSheetElement) obj;
529         }
530
531         if (currentSelection != null) {
532             desc.setText(currentSelection.getDescription());
533         } else {
534             desc.setText(""); //$NON-NLS-1$
535
}
536         setOkButton();
537     }
538     
539     private void setOkButton() {
540         if (selectRegisteredRadio.getSelection()) {
541             enableOKButton(currentSelection != null);
542         } else if (selectFileRadio.getSelection() ){
543             enableOKButton(selectFileCombo.getText().length() > 0);
544         } else {
545             enableOKButton(selectUrlCombo.getText().length() > 0);
546         }
547     }
548
549     /*
550      * (non-Javadoc) Method declared on Dialog.
551      */

552     protected void okPressed() {
553         /*
554          * Prevent the cheat sheet from opening inside this dialog's tray
555          * because it is about to close.
556          */

557         getShell().setVisible(false);
558         
559         if (selectFileRadio.getSelection()) {
560             setResultFromFile();
561         } else if (selectRegisteredRadio.getSelection() ){
562             setResultFromTree();
563         } else {
564             setResultFromUrl();
565         }
566
567         // save our selection state
568
saveWidgetValues();
569
570         super.okPressed();
571     }
572
573     private void setResultFromTree() {
574         if (currentSelection != null) {
575             ITriggerPoint triggerPoint = PlatformUI.getWorkbench()
576                     .getActivitySupport().getTriggerPointManager()
577                     .getTriggerPoint(ICheatSheetResource.TRIGGER_POINT_ID);
578             if (WorkbenchActivityHelper.allowUseOf(triggerPoint,
579                     currentSelection)) {
580                 new OpenCheatSheetAction(currentSelection.getID()).run();
581             }
582         }
583     }
584
585     private void setResultFromFile() {
586         // Use the filename without extension as the id of this cheatsheet
587
IPath filePath = new Path(selectFileCombo.getText());
588         String JavaDoc id = filePath.lastSegment();
589         int extensionIndex = id.indexOf('.');
590         if (extensionIndex > 0) {
591             id = id.substring(0, extensionIndex);
592         }
593         // Use the id as the name
594
URL JavaDoc url = null;
595         boolean opened = false;
596         
597         try {
598             File JavaDoc contentFile = new File JavaDoc(selectFileCombo.getText());
599             url = contentFile.toURL();
600             new OpenCheatSheetAction(id, id ,url).run();
601             opened = true;
602         } catch (MalformedURLException JavaDoc e) {
603             opened = false;
604         }
605         if (!opened) {
606             String JavaDoc message = NLS.bind(Messages.ERROR_OPENING_FILE, (new Object JavaDoc[] {selectFileCombo.getText()}));
607             status = new Status(IStatus.ERROR, ICheatSheetResource.CHEAT_SHEET_PLUGIN_ID, ParserStatusUtility.PARSER_ERROR, message, null);
608             CheatSheetView view = ViewUtilities.showCheatSheetView();
609             view.getCheatSheetViewer().showError(message);
610         }
611     }
612     
613     private void setResultFromUrl() {
614         // Use the filename without extension as the id of this cheatsheet
615
IPath filePath = new Path(selectUrlCombo.getText());
616         String JavaDoc id = filePath.lastSegment();
617         int extensionIndex = id.indexOf('.');
618         if (extensionIndex > 0) {
619             id = id.substring(0, extensionIndex);
620         }
621         // Use the id as the name
622
URL JavaDoc url = null;
623         boolean opened = false;
624         CheatSheetView view = ViewUtilities.showCheatSheetView();
625         if (view == null) {
626             return;
627         }
628         try {
629             url = new URL JavaDoc(selectUrlCombo.getText());
630             view.getCheatSheetViewer().setInput(id, id, url, new DefaultStateManager(), true);
631             opened = true;
632         } catch (MalformedURLException JavaDoc e) {
633             opened = false;
634         }
635         if (!opened) {
636             String JavaDoc message = NLS.bind(Messages.ERROR_OPENING_FILE, (new Object JavaDoc[] {selectUrlCombo.getText()}));
637             status = new Status(IStatus.ERROR, ICheatSheetResource.CHEAT_SHEET_PLUGIN_ID, ParserStatusUtility.PARSER_ERROR, message, null);
638             view.getCheatSheetViewer().showError(message);
639         }
640     }
641
642     /**
643      * Set's widgets to the values that they held last time this page was
644      * opened
645      */

646     protected void restoreWidgetValues() {
647         String JavaDoc[] expandedCategoryPaths = settings
648                 .getArray(STORE_EXPANDED_CATEGORIES_ID);
649         if (expandedCategoryPaths == null)
650             return; // no stored values
651

652         CheatSheetCollectionElement category = expandPreviouslyExpandedCategories();
653         if (category != null)
654             selectPreviouslySelectedCheatSheet(category);
655     }
656     
657     /**
658      * Restores the state of the radio button and file name fields
659      */

660     private void restoreFileSettings() {
661         int radioSetting = RADIO_REGISTERED;
662         try {
663              radioSetting = settings.getInt(STORE_RADIO_SETTING);
664         }
665         catch(NumberFormatException JavaDoc n) {
666         }
667         selectFileRadio.setSelection(radioSetting == RADIO_FILE);
668         selectRegisteredRadio.setSelection(radioSetting == RADIO_REGISTERED);
669         selectUrlRadio.setSelection(radioSetting == RADIO_URL);
670         String JavaDoc fileName = settings.get(STORE_CHEATSHEET_FILENAME);
671         if (fileName != null) {
672             selectFileCombo.setText(fileName);
673         }
674         String JavaDoc url = settings.get(STORE_CHEATSHEET_URL);
675         if (url != null) {
676             selectUrlCombo.setText(url);
677         }
678         loadMRU(mostRecentUrls, STORE_URL_MRU, selectUrlCombo);
679         loadMRU(mostRecentFiles, STORE_FILE_MRU, selectFileCombo);
680     }
681
682     private void loadMRU(List JavaDoc mostRecentList, String JavaDoc key, Combo combo) {
683         for (int i = 0; i < MOST_RECENT_LENGTH; i++) {
684             String JavaDoc name = settings.get(key + i);
685             if (name != null) {
686                 mostRecentList.add(name);
687                 combo.add(name);
688             }
689         }
690     }
691     
692     private void saveMRU(List JavaDoc mostRecentList, String JavaDoc key, String JavaDoc selection) {
693         if (selection.length() > 0 && !mostRecentList.contains(selection)) {
694             mostRecentList.add(0, selection);
695         }
696         for (int i = 0; i < MOST_RECENT_LENGTH & i < mostRecentList.size(); i++) {
697             String JavaDoc name = (String JavaDoc)mostRecentList.get(i);
698             if (name.length() > 0) {
699                 settings.put(key + i, name);
700             }
701         }
702     }
703
704     /**
705      * Store the current values of self's widgets so that they can be restored
706      * in the next instance of self
707      *
708      */

709     public void saveWidgetValues() {
710         storeExpandedCategories();
711         storeSelectedCheatSheet();
712         storeFileSettings();
713     }
714
715     /**
716      * Selects the cheatsheet category and cheatsheet in this page that were
717      * selected last time this page was used. If a category or cheatsheet that
718      * was previously selected no longer exists then it is ignored.
719      */

720     protected void selectPreviouslySelectedCheatSheet(
721             CheatSheetCollectionElement category) {
722         String JavaDoc cheatsheetId = settings.get(STORE_SELECTED_CHEATSHEET_ID);
723         if (cheatsheetId == null)
724             return;
725         CheatSheetElement cheatsheet = category.findCheatSheet(cheatsheetId,
726                 false);
727         if (cheatsheet == null)
728             return; // cheatsheet no longer exists, or has moved
729

730         treeViewer.setSelection(new StructuredSelection(cheatsheet));
731     }
732
733     /**
734      * Set the dialog store to use for widget value storage and retrieval
735      *
736      * @param settings
737      * IDialogSettings
738      */

739     public void setDialogSettings(IDialogSettings settings) {
740         this.settings = settings;
741     }
742
743     /**
744      * Stores the collection of currently-expanded categories in this page's
745      * dialog store, in order to recreate this page's state in the next instance
746      * of this page.
747      */

748     protected void storeExpandedCategories() {
749         Object JavaDoc[] expandedElements = treeViewer.getExpandedElements();
750         String JavaDoc[] expandedElementPaths = new String JavaDoc[expandedElements.length];
751         for (int i = 0; i < expandedElements.length; ++i) {
752             expandedElementPaths[i] = ((CheatSheetCollectionElement) expandedElements[i])
753                     .getPath().toString();
754         }
755         settings.put(STORE_EXPANDED_CATEGORIES_ID, expandedElementPaths);
756     }
757
758     /**
759      * Stores the currently-selected category and cheatsheet in this page's
760      * dialog store, in order to recreate this page's state in the next instance
761      * of this page.
762      */

763     protected void storeSelectedCheatSheet() {
764         CheatSheetElement element = null;
765
766         Object JavaDoc el = getSingleSelection(treeViewer.getSelection());
767         if (el == null)
768             return;
769
770         if (el instanceof CheatSheetElement) {
771             element = (CheatSheetElement) el;
772         } else
773             return;
774
775         settings.put(STORE_SELECTED_CHEATSHEET_ID, element.getID());
776     }
777     
778     /**
779      * Stores the state of the radio button and file name fields
780      */

781     private void storeFileSettings() {
782         int radioSetting = 0;
783         if (selectRegisteredRadio.getSelection()) {
784             radioSetting = 1;
785         }
786         if (selectFileRadio.getSelection()) {
787             radioSetting = 2;
788         }
789         if (selectUrlRadio.getSelection()) {
790             radioSetting = 3;
791         }
792         settings.put(STORE_RADIO_SETTING, radioSetting);
793         settings.put(STORE_CHEATSHEET_FILENAME, selectFileCombo.getText());
794         settings.put(STORE_CHEATSHEET_URL, selectUrlCombo.getText());
795
796         saveMRU(mostRecentUrls, STORE_URL_MRU, selectUrlCombo.getText());
797         saveMRU(mostRecentFiles, STORE_FILE_MRU, selectFileCombo.getText());
798     }
799     
800     /* (non-Javadoc)
801      * @see org.eclipse.jface.window.Dialog#getDialogBoundsSettings()
802      *
803      * @since 3.2
804      */

805     protected IDialogSettings getDialogBoundsSettings() {
806         IDialogSettings settings = CheatSheetPlugin.getPlugin().getDialogSettings();
807         IDialogSettings section = settings.getSection(DIALOG_SETTINGS_SECTION);
808         if (section == null) {
809             section = settings.addNewSection(DIALOG_SETTINGS_SECTION);
810         }
811         return section;
812     }
813     
814     private Label createMessageArea(Composite composite) {
815         Label label = new Label(composite, SWT.NONE);
816         label.setText(Messages.CHEAT_SHEET_SELECTION_DIALOG_MSG);
817         label.setFont(composite.getFont());
818         return label;
819     }
820
821     public IStatus getStatus() {
822         return status ;
823     }
824 }
825
Popular Tags