KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > cheatsheets > views > CheatSheetViewer


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.views;
12
13 import java.net.MalformedURLException JavaDoc;
14 import java.net.URL JavaDoc;
15 import java.util.ArrayList JavaDoc;
16 import java.util.Enumeration JavaDoc;
17 import java.util.Hashtable JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.ListIterator JavaDoc;
20 import java.util.Map JavaDoc;
21 import java.util.Properties JavaDoc;
22 import java.util.StringTokenizer JavaDoc;
23
24 import org.eclipse.core.runtime.FileLocator;
25 import org.eclipse.core.runtime.IStatus;
26 import org.eclipse.core.runtime.Path;
27 import org.eclipse.core.runtime.Platform;
28 import org.eclipse.core.runtime.Status;
29 import org.eclipse.help.ui.internal.views.HelpTray;
30 import org.eclipse.help.ui.internal.views.IHelpPartPage;
31 import org.eclipse.help.ui.internal.views.ReusableHelpPart;
32 import org.eclipse.jface.action.Action;
33 import org.eclipse.jface.dialogs.MessageDialog;
34 import org.eclipse.jface.dialogs.TrayDialog;
35 import org.eclipse.jface.window.Window;
36 import org.eclipse.osgi.util.NLS;
37 import org.eclipse.swt.SWT;
38 import org.eclipse.swt.events.DisposeEvent;
39 import org.eclipse.swt.events.DisposeListener;
40 import org.eclipse.swt.graphics.Cursor;
41 import org.eclipse.swt.layout.GridData;
42 import org.eclipse.swt.layout.GridLayout;
43 import org.eclipse.swt.widgets.Composite;
44 import org.eclipse.swt.widgets.Control;
45 import org.eclipse.swt.widgets.Display;
46 import org.eclipse.swt.widgets.Event;
47 import org.eclipse.swt.widgets.Label;
48 import org.eclipse.swt.widgets.Listener;
49 import org.eclipse.swt.widgets.Menu;
50 import org.eclipse.swt.widgets.Shell;
51 import org.eclipse.swt.widgets.Widget;
52 import org.eclipse.ui.IMemento;
53 import org.eclipse.ui.PlatformUI;
54 import org.eclipse.ui.cheatsheets.CheatSheetListener;
55 import org.eclipse.ui.cheatsheets.ICheatSheetEvent;
56 import org.eclipse.ui.cheatsheets.ICheatSheetViewer;
57 import org.eclipse.ui.forms.widgets.FormToolkit;
58 import org.eclipse.ui.forms.widgets.ImageHyperlink;
59 import org.eclipse.ui.internal.cheatsheets.CheatSheetPlugin;
60 import org.eclipse.ui.internal.cheatsheets.CheatSheetStopWatch;
61 import org.eclipse.ui.internal.cheatsheets.ICheatSheetResource;
62 import org.eclipse.ui.internal.cheatsheets.Messages;
63 import org.eclipse.ui.internal.cheatsheets.actions.IMenuContributor;
64 import org.eclipse.ui.internal.cheatsheets.composite.model.CompositeCheatSheetModel;
65 import org.eclipse.ui.internal.cheatsheets.composite.views.CompositeCheatSheetPage;
66 import org.eclipse.ui.internal.cheatsheets.data.CheatSheet;
67 import org.eclipse.ui.internal.cheatsheets.data.CheatSheetParser;
68 import org.eclipse.ui.internal.cheatsheets.data.CheatSheetSaveHelper;
69 import org.eclipse.ui.internal.cheatsheets.data.ICheatSheet;
70 import org.eclipse.ui.internal.cheatsheets.data.IParserTags;
71 import org.eclipse.ui.internal.cheatsheets.data.ParserInput;
72 import org.eclipse.ui.internal.cheatsheets.registry.CheatSheetElement;
73 import org.eclipse.ui.internal.cheatsheets.registry.CheatSheetRegistryReader;
74 import org.eclipse.ui.internal.cheatsheets.state.DefaultStateManager;
75 import org.eclipse.ui.internal.cheatsheets.state.ICheatSheetStateManager;
76 import org.eclipse.ui.internal.cheatsheets.state.NoSaveStateManager;
77 import org.eclipse.ui.internal.cheatsheets.state.TrayStateManager;
78 import org.osgi.framework.Bundle;
79
80 public class CheatSheetViewer implements ICheatSheetViewer, IMenuContributor {
81
82     //CS Elements
83
private CheatSheetElement contentElement;
84     private ParserInput parserInput;
85     private String JavaDoc currentID;
86     private int currentItemNum;
87     // Used to indicate if an invalid cheat sheet id was specified via setInput.
88
private boolean invalidCheatSheetId = false;
89     // Used to indicate if a null cheat sheet id was specified via setInput.
90
private boolean nullCheatSheetId = false;
91
92     private CheatSheetParser parser;
93     private ICheatSheet model;
94     private CheatSheetManager manager;
95     private CheatSheetSaveHelper saveHelper;
96
97     private CheatSheetExpandRestoreAction expandRestoreAction;
98     private Action copyAction;
99
100     //ITEMS
101
private ViewItem currentItem;
102
103     //Lists
104
private ArrayList JavaDoc expandRestoreList = new ArrayList JavaDoc();
105     private ArrayList JavaDoc viewItemList = new ArrayList JavaDoc();
106
107     //Composites
108
protected Composite control;
109
110     private Cursor busyCursor;
111     
112     // The page currently displayed, may be a CheatSheetPage, CompositeCheatSheetPage
113
// or ErrorPage
114
private Page currentPage;
115     private Label howToBegin;
116     private boolean inDialog;
117     private Listener listener;
118     
119     private ICheatSheetStateManager stateManager; // The state manager to use when saving
120
private ICheatSheetStateManager preTrayManager; // The state manager in use before a tray was opened
121
private String JavaDoc restorePath;
122     
123     private int dialogReturnCode;
124     private boolean isRestricted;
125     
126     /**
127      * The constructor.
128      *
129      * @param inDialog whether or not this viewer will be placed in a modal dialog
130      */

131     public CheatSheetViewer(boolean inDialog) {
132         currentItemNum = -1;
133         this.inDialog = inDialog;
134         saveHelper = new CheatSheetSaveHelper();
135     }
136
137     public void advanceIntroItem() {
138         resetItemState();
139         /* LP-item event */
140         // fireManagerItemEvent(ICheatSheetItemEvent.ITEM_DEACTIVATED, introItem);
141

142         currentItemNum = 1;
143         ViewItem nextItem = getViewItemAtIndex(currentItemNum);
144         if (nextItem.item.isDynamic()) {
145             nextItem.handleButtons();
146         }
147         nextItem.setAsCurrentActiveItem();
148         /* LP-item event */
149         // fireManagerItemEvent(ICheatSheetItemEvent.ITEM_ACTIVATED, nextItem);
150
collapseAllButCurrent(false);
151         
152         saveCurrentSheet();
153     }
154
155     /**
156      * Reset the state of all the items in this cheatsheet
157      */

158     private void resetItemState() {
159         IntroItem introItem = (IntroItem) getViewItemAtIndex(0);
160         boolean isStarted = introItem.isCompleted();
161
162         expandRestoreList = new ArrayList JavaDoc();
163         if(expandRestoreAction != null)
164             expandRestoreAction.setCollapsed(false);
165
166         clearBackgrounds();
167         clearIcons();
168         collapseAllButtons();
169         if(isStarted)
170             initManager();
171
172         for (Iterator JavaDoc iter = viewItemList.iterator(); iter.hasNext();) {
173             ViewItem item = (ViewItem) iter.next();
174             if (item instanceof CoreItem) {
175                 CoreItem c = (CoreItem) item;
176                 ArrayList JavaDoc l = c.getListOfSubItemCompositeHolders();
177                 if (l != null)
178                     for (int j = 0; j < l.size(); j++) {
179                         ((SubItemCompositeHolder) l.get(j)).setSkipped(false);
180                         ((SubItemCompositeHolder) l.get(j)).setCompleted(false);
181                     }
182             }
183         }
184
185         if (isStarted)
186             getManager().fireEvent(ICheatSheetEvent.CHEATSHEET_RESTARTED);
187         else
188             getManager().fireEvent(ICheatSheetEvent.CHEATSHEET_STARTED);
189
190         isStarted = true;
191         introItem.setAsNormalCollapsed();
192         introItem.setComplete();
193         introItem.setRestartImage();
194     }
195
196     /*package*/
197     /*
198      * This function can do one of three things
199      * 1. If this item has a completion message which has not been displayed, display it
200      * 2. Otherwise if this is the final item return to the introduction
201      * 3. If neither condition 1 or 2 is satisfied move to the next item
202      */

203     void advanceItem(ImageHyperlink link, boolean markAsCompleted) {
204         currentItem = (ViewItem) link.getData();
205         int indexNextItem = getIndexOfItem(currentItem) +1;
206         boolean isFinalItem = indexNextItem >= viewItemList.size();
207         
208         if (markAsCompleted
209                 && currentItem.hasCompletionMessage()
210                 && !currentItem.isCompletionMessageExpanded()) {
211             currentItem.setCompletionMessageExpanded(isFinalItem);
212             currentItem.setComplete();
213             if (isFinalItem) {
214                 getManager().fireEvent(ICheatSheetEvent.CHEATSHEET_COMPLETED);
215             }
216             saveCurrentSheet();
217             return;
218         }
219
220         if (indexNextItem < currentItemNum) {
221             ViewItem vi = getViewItemAtIndex(currentItemNum);
222             vi.setAsNormalNonCollapsed();
223         }
224         if (currentItem != null) {
225             //set that item to it's original color.
226
currentItem.setAsNormalCollapsed();
227             //set that item as complete.
228
if (markAsCompleted) {
229                 if (!currentItem.isCompleted()) {
230                     currentItem.setComplete();
231                 }
232                 /* LP-item event */
233                 // fireManagerItemEvent(ICheatSheetItemEvent.ITEM_COMPLETED, currentItem);
234
// fireManagerItemEvent(ICheatSheetItemEvent.ITEM_DEACTIVATED, currentItem);
235
} else {
236                 currentItem.setSkipped();
237                 /* LP-item event */
238                 // fireManagerItemEvent(ICheatSheetItemEvent.ITEM_SKIPPED, currentItem);
239
// fireManagerItemEvent(ICheatSheetItemEvent.ITEM_DEACTIVATED, currentItem);
240
}
241         }
242         if (!isFinalItem) {
243             ViewItem nextItem = getViewItemAtIndex(indexNextItem);
244             currentItemNum = indexNextItem;
245             if (nextItem != null) {
246                 //Handle lazy button instantiation here.
247
if (nextItem.item.isDynamic()) {
248                     ((CoreItem) nextItem).handleButtons();
249                 }
250                 nextItem.setAsCurrentActiveItem();
251                 /* LP-item event */
252                 // fireManagerItemEvent(ICheatSheetItemEvent.ITEM_ACTIVATED, nextItem);
253
currentItem = nextItem;
254             }
255
256             FormToolkit.ensureVisible(currentItem.getMainItemComposite());
257         } else if (indexNextItem == viewItemList.size()) {
258             if (!currentItem.isCompletionMessageExpanded()) { // The event will already have been fired
259
getManager().fireEvent(ICheatSheetEvent.CHEATSHEET_COMPLETED);
260             }
261             showIntroItem();
262         }
263
264         saveCurrentSheet();
265     }
266
267     private void showIntroItem() {
268         ViewItem item = getViewItemAtIndex(0);
269         item.setAsCurrentActiveItem();
270     }
271
272     /*package*/ void advanceSubItem(ImageHyperlink link, boolean markAsCompleted, int subItemIndex) {
273         Label l = null;
274         ArrayList JavaDoc list = null;
275         SubItemCompositeHolder sich = null;
276         CoreItem ciws = null;
277
278         currentItem = (ViewItem) link.getData();
279
280         if (currentItem instanceof CoreItem)
281             ciws = (CoreItem) currentItem;
282
283         if (ciws != null) {
284             list = ciws.getListOfSubItemCompositeHolders();
285             sich = (SubItemCompositeHolder) list.get(subItemIndex);
286             l = sich.getCheckDoneLabel();
287         }
288
289         if (l != null) {
290             if (markAsCompleted) {
291                 sich.setCompleted(true);
292                 sich.setSkipped(false);
293                 /* LP-subitem event */
294                 // fireManagerSubItemEvent(ICheatSheetItemEvent.ITEM_COMPLETED, ciws, subItemID);
295
} else {
296                 sich.setSkipped(true);
297                 sich.setCompleted(false);
298                 /* LP-subitem event */
299                 // fireManagerSubItemEvent(ICheatSheetItemEvent.ITEM_SKIPPED, ciws, subItemID);
300
}
301             ciws.refreshItem();
302         }
303
304         boolean allAttempted = checkAllAttempted(list);
305         boolean anySkipped = checkContainsSkipped(list);
306
307         if (allAttempted && !anySkipped) {
308             advanceItem(link, true);
309             return;
310         } else if (allAttempted && anySkipped) {
311             advanceItem(link, false);
312             return;
313         }
314         
315         setFocus();
316         saveCurrentSheet();
317     }
318
319     private boolean checkAllAttempted(ArrayList JavaDoc list) {
320         for (int i = 0; i < list.size(); i++) {
321             SubItemCompositeHolder s = (SubItemCompositeHolder) list.get(i);
322             if (s.isCompleted() || s.isSkipped()) {
323                 continue;
324             }
325             return false;
326         }
327         return true;
328     }
329
330     private boolean checkContainsSkipped(ArrayList JavaDoc list) {
331         for (int i = 0; i < list.size(); i++) {
332             SubItemCompositeHolder s = (SubItemCompositeHolder) list.get(i);
333             if (s.isSkipped()) {
334                 return true;
335             }
336         }
337         return false;
338     }
339
340     private boolean loadState() {
341         try {
342             Properties JavaDoc props = stateManager.getProperties();
343
344             manager = stateManager.getCheatSheetManager();
345     
346             // There is a bug which causes the background of the buttons to
347
// remain white, even though the color is set. So instead of calling
348
// clearBackgrounds() only the following line should be needed. D'oh!
349
// ((ViewItem) viewItemList.get(0)).setOriginalColor();
350
clearBackgrounds();
351     
352             if (props == null) {
353                 getViewItemAtIndex(0).setAsCurrentActiveItem();
354                 /* LP-item event */
355                 // fireManagerItemEvent(ICheatSheetItemEvent.ITEM_ACTIVATED, items[0]);
356
return true;
357             }
358     
359             boolean buttonIsDown = (Integer.parseInt((String JavaDoc) props.get(IParserTags.BUTTON)) == 0) ? false : true;
360             int itemNum = Integer.parseInt((String JavaDoc) props.get(IParserTags.CURRENT));
361             ArrayList JavaDoc completedStatesList = (ArrayList JavaDoc) props.get(IParserTags.COMPLETED);
362             ArrayList JavaDoc expandedStatesList = (ArrayList JavaDoc) props.get(IParserTags.EXPANDED);
363             expandRestoreList = (ArrayList JavaDoc) props.get(IParserTags.EXPANDRESTORE);
364             String JavaDoc cid = (String JavaDoc) props.get(IParserTags.ID);
365             Hashtable JavaDoc completedSubItems = (Hashtable JavaDoc) props.get(IParserTags.SUBITEMCOMPLETED);
366             Hashtable JavaDoc skippedSubItems = (Hashtable JavaDoc) props.get(IParserTags.SUBITEMSKIPPED);
367     
368             ArrayList JavaDoc completedSubItemsItemList = new ArrayList JavaDoc();
369             ArrayList JavaDoc skippedSubItemsItemList = new ArrayList JavaDoc();
370     
371             Enumeration JavaDoc e = completedSubItems.keys();
372             while (e.hasMoreElements())
373                 completedSubItemsItemList.add(e.nextElement());
374     
375             Enumeration JavaDoc e2 = skippedSubItems.keys();
376             while (e2.hasMoreElements())
377                 skippedSubItemsItemList.add(e2.nextElement());
378     
379             if (cid != null)
380                 currentID = cid;
381     
382             if (itemNum >= 0) {
383                 currentItemNum = itemNum;
384                 
385                 currentItem = getViewItemAtIndex(itemNum);
386     
387                 CheatSheetStopWatch.startStopWatch("CheatSheetViewer.checkSavedState()"); //$NON-NLS-1$
388
for (int i = 0; i < viewItemList.size(); i++) {
389     
390                     ViewItem item = getViewItemAtIndex(i);
391                     if (i > 0 && item.item.isDynamic() && i <= currentItemNum) {
392                          item.handleButtons();
393                          item.setOriginalColor();
394                     }
395     
396                     if (completedStatesList.contains(Integer.toString(i))) {
397                         item.setComplete();
398                         item.setRestartImage();
399                     } else {
400                         if (i < currentItemNum) {
401                             item.setSkipped();
402                         }
403                     }
404                     if (expandedStatesList.contains(Integer.toString(i))) {
405                         item.setExpanded();
406                     } else {
407                         item.setCollapsed();
408                     }
409                     if (i > currentItemNum) {
410                         item.setButtonsVisible(false);
411                         item.setCompletionMessageCollapsed();
412                     } else {
413                         item.setButtonsVisible(true);
414                         if (i >currentItemNum || item.isCompleted()) {
415                             item.setCompletionMessageExpanded(i + 1 >= viewItemList.size());
416                         } else {
417                             item.setCompletionMessageCollapsed();
418                         }
419                     }
420                     if (expandRestoreList.contains(Integer.toString(i))) {
421                         item.setCollapsed();
422                     }
423                     if (completedSubItemsItemList.contains(Integer.toString(i))) {
424                         String JavaDoc subItemNumbers = (String JavaDoc) completedSubItems.get(Integer.toString(i));
425                         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(subItemNumbers, ","); //$NON-NLS-1$
426
if (item instanceof CoreItem) {
427                             CoreItem coreitemws = (CoreItem) item;
428                             ArrayList JavaDoc subItemCompositeHolders = coreitemws.getListOfSubItemCompositeHolders();
429                             if (subItemCompositeHolders != null) {
430                                 while (st.hasMoreTokens()) {
431                                     String JavaDoc token = st.nextToken();
432                                     ((SubItemCompositeHolder) subItemCompositeHolders.get(Integer.parseInt(token))).setCompleted(true);
433                                     ArrayList JavaDoc l = subItemCompositeHolders;
434                                     SubItemCompositeHolder s = (SubItemCompositeHolder) l.get(Integer.parseInt(token));
435                                     if (s != null && s.getStartButton() != null) {
436                                         s.getStartButton().setImage(CheatSheetPlugin.getPlugin().getImage(ICheatSheetResource.CHEATSHEET_ITEM_BUTTON_RESTART));
437                                         s.getStartButton().setToolTipText(Messages.RESTART_TASK_TOOLTIP);
438                                     }
439         
440                                 }
441                             }
442                         }
443                     }
444                     if (skippedSubItemsItemList.contains(Integer.toString(i))) {
445                         String JavaDoc subItemNumbers = (String JavaDoc) skippedSubItems.get(Integer.toString(i));
446                         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(subItemNumbers, ","); //$NON-NLS-1$
447
if (item instanceof CoreItem) {
448                             CoreItem coreitemws = (CoreItem) item;
449                             while (st.hasMoreTokens()) {
450                                 String JavaDoc token = st.nextToken();
451                                 ((SubItemCompositeHolder) coreitemws.getListOfSubItemCompositeHolders().get(Integer.parseInt(token))).setSkipped(true);
452                             }
453                         }
454                     }
455                     CheatSheetStopWatch.printLapTime("CheatSheetViewer.checkSavedState()", "Time in CheatSheetViewer.checkSavedState() after loop #"+i+": "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
456
}
457                 CheatSheetStopWatch.printLapTime("CheatSheetViewer.checkSavedState()", "Time in CheatSheetViewer.checkSavedState() after loop: "); //$NON-NLS-1$ //$NON-NLS-2$
458

459                 if (buttonIsDown) {
460                     if(expandRestoreAction != null)
461                         expandRestoreAction.setCollapsed(true);
462                 }
463                 
464                 // If the last item is the current one and it is complete then
465
// we should collapse the last item and set the focus on intro.
466
// For all other cases, set the current item as the active item.
467
if(viewItemList.size()-1 == itemNum && currentItem.isCompleted()) {
468                     currentItem.setCollapsed();
469                     getViewItemAtIndex(0).getMainItemComposite().setFocus();
470                     
471                     // The cheat sheet has been restored but is also completed so fire both events
472
getManager().fireEvent(ICheatSheetEvent.CHEATSHEET_RESTORED);
473                     getManager().fireEvent(ICheatSheetEvent.CHEATSHEET_COMPLETED);
474                 } else {
475                     currentItem.setAsCurrentActiveItem();
476     
477                     // If the intro item is completed, than the cheat sheet has been restored.
478
if(getViewItemAtIndex(0).isCompleted())
479                         getManager().fireEvent(ICheatSheetEvent.CHEATSHEET_RESTORED);
480                 }
481     
482                 /* LP-item event */
483                 // fireManagerItemEvent(ICheatSheetItemEvent.ITEM_ACTIVATED, currentItem);
484
} else {
485                 getViewItemAtIndex(0).setAsCurrentActiveItem();
486                 /* LP-item event */
487                 // fireManagerItemEvent(ICheatSheetItemEvent.ITEM_ACTIVATED, items[0]);
488
}
489     
490             return true;
491         } catch(Exception JavaDoc e) {
492             // An exception while restoring the saved state data usually only occurs if
493
// the cheat sheet has been modified since this previous execution. This most
494
// often occurs during development of cheat sheets and as such an end user is
495
// not as likely to encounter this.
496

497             boolean reset = MessageDialog.openConfirm(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
498                     Messages.CHEATSHEET_STATE_RESTORE_FAIL_TITLE,
499                     Messages.CHEATSHEET_STATE_RESET_CONFIRM);
500
501             if (reset) {
502                 restart();
503                 return true;
504             }
505             
506             // Log the exception
507
String JavaDoc stateFile = saveHelper.getStateFile(currentID).toOSString();
508             String JavaDoc message = NLS.bind(Messages.ERROR_APPLYING_STATE_DATA_LOG, (new Object JavaDoc[] {stateFile, currentID}));
509             IStatus status = new Status(IStatus.ERROR, ICheatSheetResource.CHEAT_SHEET_PLUGIN_ID, IStatus.OK, message, e);
510             CheatSheetPlugin.getPlugin().getLog().log(status);
511
512             // Set the currentID to null so it is not saved during internalDispose()
513
currentID = null;
514
515             internalDispose();
516
517             // Reinitialize a few variables because there is no currentItem or currentPage now
518
parserInput = null;
519             currentItem = null;
520             currentItemNum = -1;
521             currentPage = null;
522             expandRestoreList = new ArrayList JavaDoc();
523             viewItemList = new ArrayList JavaDoc();
524             
525             // Create the errorpage to show the user
526
createErrorPage(Messages.ERROR_APPLYING_STATE_DATA);
527
528             return false;
529         }
530     }
531
532     private void clearBackgrounds() {
533         for (Iterator JavaDoc iter = viewItemList.iterator(); iter.hasNext();) {
534             ViewItem item = (ViewItem) iter.next();
535             item.setOriginalColor();
536         }
537     }
538
539     private void clearIcons() {
540         for (Iterator JavaDoc iter = viewItemList.iterator(); iter.hasNext();) {
541             ViewItem item = (ViewItem) iter.next();
542             item.setOriginalColor();
543             if (item.isCompleted() || item.isExpanded() || item.isSkipped())
544                     item.setIncomplete();
545         }
546     }
547
548     private void collapseAllButCurrent(boolean fromAction) {
549         expandRestoreList = new ArrayList JavaDoc();
550         try {
551             ViewItem current = getViewItemAtIndex(currentItemNum);
552             for (ListIterator JavaDoc iter = viewItemList.listIterator(viewItemList.size()); iter.hasPrevious();) {
553                 ViewItem item = (ViewItem) iter.previous();
554                 if (item != current && item.isExpanded()) {
555                     item.setCollapsed();
556                     if (fromAction)
557                         expandRestoreList.add(Integer.toString(getIndexOfItem(item)));
558                 }
559             }
560         } catch (Exception JavaDoc e) {
561         }
562     }
563
564     private void collapseAllButtons() {
565         for (Iterator JavaDoc iter = viewItemList.listIterator(1); iter.hasNext();) {
566             ViewItem item = (ViewItem) iter.next();
567             item.setButtonsVisible(false);
568             item.setCompletionMessageCollapsed();
569         }
570     }
571
572     private void createErrorPage(String JavaDoc message) {
573         setCollapseExpandButtonEnabled(false);
574         if(message != null) {
575             currentPage = new ErrorPage(message);
576         } else {
577             currentPage = new ErrorPage();
578         }
579         currentPage.createPart(control);
580         control.layout(true);
581     }
582     
583     private void showStartPage() {
584         setCollapseExpandButtonEnabled(false);
585         internalDispose();
586
587         howToBegin = new Label(control, SWT.WRAP);
588         howToBegin.setText(Messages.INITIAL_VIEW_DIRECTIONS);
589         howToBegin.setLayoutData(new GridData(GridData.FILL_BOTH));
590         currentPage = null;
591         control.layout(true);
592     }
593     
594     private void createErrorPage(IStatus status) {
595         setCollapseExpandButtonEnabled(false);
596         currentPage = new ErrorPage(status);
597         currentPage.createPart(control);
598         control.layout(true);
599     }
600
601     /**
602      * Creates the SWT controls for this workbench part.
603      * <p>
604      * Clients should not call this method (the workbench calls this method at
605      * appropriate times).
606      * </p>
607      * <p>
608      * For implementors this is a multi-step process:
609      * <ol>
610      * <li>Create one or more controls within the parent.</li>
611      * <li>Set the parent layout as needed.</li>
612      * <li>Register any global actions with the <code>IActionService</code>.</li>
613      * <li>Register any popup menus with the <code>IActionService</code>.</li>
614      * <li>Register a selection provider with the <code>ISelectionService</code>
615      * (optional). </li>
616      * </ol>
617      * </p>
618      *
619      * @param parent the parent control
620      */

621     public void createPartControl(Composite parent) {
622         control = new Composite(parent, SWT.NONE);
623         GridLayout layout = new GridLayout();
624         layout.marginHeight = 0;
625         layout.marginWidth = 0;
626         layout.verticalSpacing = 0;
627         layout.horizontalSpacing = 0;
628         layout.numColumns = 1;
629         control.setLayout(layout);
630
631         control.addDisposeListener(new DisposeListener(){
632             public void widgetDisposed(DisposeEvent e) {
633                 dispose();
634             }
635         });
636         
637         showStartPage();
638
639         Display display = parent.getDisplay();
640
641         busyCursor = new Cursor(display, SWT.CURSOR_WAIT);
642
643         if(contentElement != null) {
644             initCheatSheetView();
645         }
646     }
647
648     /**
649      * Called when any TrayDialog is opened. The viewer must react by disabling
650      * itself and moving the cheat sheet to the dialog's tray if the current item
651      * was flagged as one that opens a modal dialog.
652      *
653      * @param dialog the dialog that was opened
654      */

655     private void dialogOpened(final TrayDialog dialog) {
656         if (isActive()) {
657             HelpTray tray = (HelpTray)dialog.getTray();
658             if (tray == null) {
659                 tray = new HelpTray();
660                 dialog.openTray(tray);
661             }
662             ReusableHelpPart helpPart = tray.getHelpPart();
663             IHelpPartPage page = helpPart.createPage(CheatSheetHelpPart.ID, null, null);
664             page.setVerticalSpacing(0);
665             page.setHorizontalMargin(0);
666             ICheatSheetStateManager trayManager = new TrayStateManager();
667             preTrayManager = stateManager;
668             stateManager = trayManager;
669             saveCurrentSheet(); // Save the state into the tray manager
670
helpPart.addPart(CheatSheetHelpPart.ID, new CheatSheetHelpPart(helpPart.getForm().getForm().getBody(), helpPart.getForm().getToolkit(), page.getToolBarManager(), contentElement, trayManager));
671             page.addPart(CheatSheetHelpPart.ID, true);
672             helpPart.addPage(page);
673             helpPart.showPage(CheatSheetHelpPart.ID);
674             
675             /*
676              * Disable the viewer until the tray is closed, then show it again.
677              */

678             control.setVisible(false);
679             Display.getCurrent().removeFilter(SWT.Show, listener);
680
681             helpPart.getControl().addListener(SWT.Dispose, new Listener() {
682                 public void handleEvent(Event event) {
683                     control.setVisible(true);
684                     Display.getCurrent().addFilter(SWT.Show, listener);
685                     if (preTrayManager != null) {
686                         loadState(); // Load from the tray manager
687
stateManager = preTrayManager;
688                         preTrayManager = null;
689                     }
690                     dialogReturnCode = dialog.getReturnCode();
691                 }
692             });
693         }
694     }
695
696     /**
697      * Disposes of this cheat sheet viewer.
698      */

699     private void dispose() {
700         internalDispose();
701         if (busyCursor != null)
702             busyCursor.dispose();
703     }
704
705     /*
706      * Returns the cheat sheet being viewed.
707      */

708     public ICheatSheet getCheatSheet() {
709         return model;
710     }
711     
712     /* (non-Javadoc)
713      * @see org.eclipse.ui.cheatsheets.ICheatSheetViewer#getCheatSheetID()
714      */

715     public String JavaDoc getCheatSheetID() {
716         if(getContent() != null) {
717             return getContent().getID();
718         }
719         
720         return null;
721     }
722
723     /**
724      * Returns the current content.
725      *
726      * @return CheatSheetElement
727      */

728     /*package*/ CheatSheetElement getContent() {
729         return contentElement;
730     }
731
732     /* (non-Javadoc)
733      * @see org.eclipse.ui.cheatsheets.ICheatSheetViewer#getControl()
734      */

735     public Control getControl() {
736         return control;
737     }
738
739     private int getIndexOfItem(ViewItem item) {
740         int index = viewItemList.indexOf(item);
741         if(index != -1) {
742             return index;
743         }
744         return 0;
745     }
746
747     /*package*/ CheatSheetManager getManager() {
748         if (manager == null) {
749             getNewManager();
750         }
751         return manager;
752     }
753
754     private CheatSheetManager getNewManager(){
755         manager = new CheatSheetManager(contentElement);
756         return manager;
757     }
758     
759     private CheatSheetManager initManager(){
760         CheatSheetManager csManager = getManager();
761         csManager.setData(new Hashtable JavaDoc());
762         return csManager;
763     }
764
765     private ViewItem getViewItemAtIndex(int index) {
766         if (viewItemList != null && !viewItemList.isEmpty()) {
767             return (ViewItem) viewItemList.get(index);
768         }
769         return null;
770     }
771     
772     /**
773      * Returns whether or not this viewer contains the given Control, which
774      * is currently in focus.
775      *
776      * @param control the Control currently in focus
777      * @return whether this viewer contains the given Control or not
778      */

779     public boolean hasFocusControl(Control control) {
780         return (control == this.control) || (currentPage.getControl() == control);
781     }
782     
783     /**
784      * If in a dialog-opening step, will add the appropriate listener for
785      * the cheatsheet to jump into the dialog's tray once opened.
786      *
787      * Should be called before executing any action.
788      */

789     private void hookDialogListener() {
790         /*
791          * org.eclipse.help.ui is an optional dependency; only perform this
792          * step is this plugin is present.
793          */

794         if (!inDialog && isInDialogItem() && (Platform.getBundle("org.eclipse.help.ui") != null)) { //$NON-NLS-1$
795
listener = new Listener() {
796                 public void handleEvent(Event event) {
797                     if (isTrayDialog(event.widget)) {
798                         dialogOpened((TrayDialog)((Shell)event.widget).getData());
799                     }
800                 }
801             };
802             Display.getCurrent().addFilter(SWT.Show, listener);
803         }
804     }
805     
806     /**
807      * Removes the dialog-opening listener, if it was added.
808      *
809      * Should be called after executing any action.
810      */

811     private void unhookDialogListener() {
812         if (listener != null) {
813             Display.getCurrent().removeFilter(SWT.Show, listener);
814         }
815     }
816     
817     /*
818      * return true if a cheat sheet was opened successfully
819      */

820     private boolean initCheatSheetView() {
821         CheatSheetStopWatch.startStopWatch("CheatSheetViewer.initCheatSheetView()"); //$NON-NLS-1$
822
//Re-initialize list to store items collapsed by expand/restore action on c.s. toolbar.
823
expandRestoreList = new ArrayList JavaDoc();
824
825         // re set that action to turned off.
826
if(expandRestoreAction != null)
827             expandRestoreAction.setCollapsed(false);
828
829         //reset current item to be null; next item too.
830
currentItem = null;
831         currentItemNum = 0;
832         viewItemList = new ArrayList JavaDoc();
833
834         // Reset the page variable
835
currentPage = null;
836         
837         if(howToBegin != null) {
838             howToBegin.dispose();
839             howToBegin = null;
840         }
841         
842         // If a null cheat sheet id was specified, return leaving the cheat sheet empty.
843
if(nullCheatSheetId) {
844             return false;
845         }
846         
847         if(invalidCheatSheetId) {
848             createErrorPage(Messages.ERROR_CHEATSHEET_DOESNOT_EXIST);
849             return false;
850         }
851         
852         // read our contents, if there are problems reading the file an error page should be created.
853
CheatSheetStopWatch.printLapTime("CheatSheetViewer.initCheatSheetView()", "Time in CheatSheetViewer.initCheatSheetView() before readFile() call: "); //$NON-NLS-1$ //$NON-NLS-2$
854
IStatus parseStatus = readFile();
855         CheatSheetStopWatch.printLapTime("CheatSheetViewer.initCheatSheetView()", "Time in CheatSheetViewer.initCheatSheetView() after readFile() call: "); //$NON-NLS-1$ //$NON-NLS-2$
856
if (!parseStatus.isOK()) {
857             CheatSheetPlugin.getPlugin().getLog().log(parseStatus);
858         }
859         if(parseStatus.getSeverity() == Status.ERROR){
860
861             // Error during parsing.
862
// Something is wrong with the Cheat sheet content file at the xml level.
863

864             createErrorPage(parseStatus);
865             return false;
866         }
867         
868         control.setRedraw(false);
869         if (model instanceof CheatSheet) {
870             CheatSheet cheatSheetModel = (CheatSheet)model;
871
872             if (isRestricted && cheatSheetModel.isContainsCommandOrAction()) {
873                 boolean isOK = MessageDialog.openConfirm(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
874                         Messages.CHEATSHEET_FROM_URL_WITH_EXEC_TITLE,
875                         Messages.CHEATSHEET_FROM_URL_WITH_EXEC);
876
877                 if (!isOK) {
878                     control.setRedraw(true);
879                     showStartPage();
880                     return true;
881                 }
882             }
883             
884             currentPage = new CheatSheetPage(cheatSheetModel, viewItemList, this);
885             setCollapseExpandButtonEnabled(true);
886         } else if (model instanceof CompositeCheatSheetModel) {
887             CompositeCheatSheetModel compositeCheatSheetModel = ((CompositeCheatSheetModel)model);
888             compositeCheatSheetModel.setId(currentID);
889             currentPage = new CompositeCheatSheetPage(compositeCheatSheetModel, stateManager);
890             compositeCheatSheetModel.setCheatSheetManager(initManager());
891             setCollapseExpandButtonEnabled(false);
892         }
893         CheatSheetStopWatch.printLapTime("CheatSheetViewer.initCheatSheetView()", "Time in CheatSheetViewer.initCheatSheetView() after CheatSheetPage() call: "); //$NON-NLS-1$ //$NON-NLS-2$
894
currentPage.createPart(control);
895         CheatSheetStopWatch.printLapTime("CheatSheetViewer.initCheatSheetView()", "Time in CheatSheetViewer.initCheatSheetView() after CheatSheetPage.createPart() call: "); //$NON-NLS-1$ //$NON-NLS-2$
896

897         if (model instanceof CheatSheet) {
898             CheatSheetStopWatch.printLapTime("CheatSheetViewer.initCheatSheetView()", "Time in CheatSheetViewer.initCheatSheetView() after fireEvent() call: "); //$NON-NLS-1$ //$NON-NLS-2$
899

900             if(!loadState()) {
901                 // An error occurred when apply the saved state data.
902
control.setRedraw(true);
903                 control.layout();
904                 return true;
905             }
906
907             getManager().fireEvent(ICheatSheetEvent.CHEATSHEET_OPENED);
908         }
909         CheatSheetStopWatch.printLapTime("CheatSheetViewer.initCheatSheetView()", "Time in CheatSheetViewer.initCheatSheetView() after checkSavedState() call: "); //$NON-NLS-1$ //$NON-NLS-2$
910

911         currentPage.initialized();
912         control.setRedraw(true);
913         control.layout();
914         CheatSheetStopWatch.printLapTime("CheatSheetViewer.initCheatSheetView()", "Time in CheatSheetViewer.initCheatSheetView() after layout() call: "); //$NON-NLS-1$ //$NON-NLS-2$
915

916         if (currentItem != null && !currentItem.isCompleted())
917             currentItem.setFocus();
918         CheatSheetStopWatch.printLapTime("CheatSheetViewer.initCheatSheetView()", "Time in CheatSheetViewer.initCheatSheetView() at end of method: "); //$NON-NLS-1$ //$NON-NLS-2$
919
return true;
920     }
921
922     private void internalDispose() {
923         if(manager != null)
924             manager.fireEvent(ICheatSheetEvent.CHEATSHEET_CLOSED);
925        
926         saveCurrentSheet();
927
928         for (Iterator JavaDoc iter = viewItemList.iterator(); iter.hasNext();) {
929             ViewItem item = (ViewItem) iter.next();
930             item.dispose();
931         }
932
933         if(currentPage != null) {
934             currentPage.dispose();
935         }
936     }
937
938     /**
939      * Returns whether or not the cheat sheet viewer is currently active. This
940      * means it is visible to the user and enabled.
941      *
942      * @return whether or not this viewer is active
943      */

944     private boolean isActive() {
945         Control control = getControl();
946         if (control != null && !control.isDisposed()) {
947             Control parent = control.getParent();
948             return (parent != null && !parent.isDisposed() && parent.isVisible() && parent.isEnabled());
949         }
950         return false;
951     }
952     
953     /*
954      * Show the collapse/expand button if we have access to the toolbar
955      */

956     private void setCollapseExpandButtonEnabled(boolean enable) {
957         if (expandRestoreAction != null) {
958             expandRestoreAction.setEnabled(enable);
959         }
960     }
961
962     /**
963      * Returns whether or not the currently active item requires opening a
964      * modal dialog.
965      *
966      * @return whether the current item opens a modal dialog
967      */

968     private boolean isInDialogItem() {
969         ViewItem item = getViewItemAtIndex(currentItemNum);
970         if (item != null) {
971             return item.getItem().isDialog();
972         }
973         return false;
974     }
975     
976     /**
977      * Returns whether or not this cheat sheet viewer is inside a modal
978      * dialog.
979      *
980      * @return whether this viewer is inside a modal dialog
981      */

982     public boolean isInDialogMode() {
983         return inDialog;
984     }
985     
986     /**
987      * Returns whether the given widget is a TrayDialog.
988      *
989      * @param widget the widget to check
990      * @return whether or not the widget is a TrayDialog
991      */

992     private boolean isTrayDialog(Widget widget) {
993         return (widget instanceof Shell && ((Shell)widget).getData() instanceof TrayDialog);
994     }
995
996     /**
997     * Read the contents of the cheat sheet file
998     * @return true if the file was read and parsed without error
999     */

1000    private IStatus readFile() {
1001        if(parser == null)
1002            parser = new CheatSheetParser();
1003        // If the cheat sheet was registered then
1004
// search for a specific type - composite or simple
1005
int cheatSheetKind = CheatSheetParser.ANY;
1006        if (contentElement.isRegistered()) {
1007            if (contentElement.isComposite()) {
1008                cheatSheetKind = CheatSheetParser.COMPOSITE_ONLY;
1009            } else {
1010                cheatSheetKind = CheatSheetParser.SIMPLE_ONLY;
1011            }
1012        }
1013    
1014        model = parser.parse(parserInput, cheatSheetKind);
1015        return parser.getStatus();
1016    }
1017
1018    private void restoreExpandStates() {
1019        try {
1020            for (int i = 0; i < expandRestoreList.size(); i++) {
1021                int index = Integer.parseInt(((String JavaDoc) expandRestoreList.get(i)));
1022                ViewItem item = getViewItemAtIndex(index);
1023                if (!item.isExpanded()) {
1024                    item.setExpanded();
1025                }
1026            }
1027            expandRestoreList = null;
1028        } catch (Exception JavaDoc e) {
1029        }
1030    }
1031    
1032    /*package*/ void runPerformExecutable(ImageHyperlink link) {
1033        link.setCursor(busyCursor);
1034        currentItem = (ViewItem) link.getData();
1035        CoreItem coreItem = (CoreItem) currentItem;
1036
1037        if (coreItem != null) {
1038            try {
1039                hookDialogListener();
1040                dialogReturnCode = -1;
1041                IStatus status = coreItem.runExecutable(getManager());
1042                if (status.isOK() && dialogReturnCode != Window.CANCEL) {
1043                    coreItem.setRestartImage();
1044                    if (!coreItem.hasConfirm()) {
1045                        //set that item as complete.
1046
advanceItem(link, true);
1047                        saveCurrentSheet();
1048                    }
1049                }
1050                if ( status.getSeverity() == IStatus.ERROR) {
1051                    CheatSheetPlugin.getPlugin().getLog().log(status);
1052                    org.eclipse.jface.dialogs.ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), null, null, status);
1053                }
1054            }
1055            finally {
1056                unhookDialogListener();
1057            }
1058        }
1059
1060        link.setCursor(null);
1061    }
1062
1063    /*package*/ void runSubItemPerformExecutable(ImageHyperlink link, int subItemIndex) {
1064        CoreItem coreItem = null;
1065        link.setCursor(busyCursor);
1066        currentItem = (ViewItem) link.getData();
1067        coreItem = (CoreItem) currentItem;
1068
1069        try {
1070            if (coreItem != null) {
1071                hookDialogListener();
1072                if (coreItem.runSubItemExecutable(getManager(), subItemIndex) == ViewItem.VIEWITEM_ADVANCE && !coreItem.hasConfirm(subItemIndex)) {
1073                    ArrayList JavaDoc l = coreItem.getListOfSubItemCompositeHolders();
1074                    SubItemCompositeHolder s = (SubItemCompositeHolder) l.get(subItemIndex);
1075                    s.getStartButton().setImage(CheatSheetPlugin.getPlugin().getImage(ICheatSheetResource.CHEATSHEET_ITEM_BUTTON_RESTART));
1076                    s.getStartButton().setToolTipText(Messages.RESTART_TASK_TOOLTIP);
1077                    advanceSubItem(link, true, subItemIndex);
1078                    saveCurrentSheet();
1079                }
1080            }
1081        } catch (RuntimeException JavaDoc e) {
1082            IStatus status = new Status(IStatus.ERROR, ICheatSheetResource.CHEAT_SHEET_PLUGIN_ID, IStatus.OK, Messages.ERROR_RUNNING_ACTION, e);
1083            CheatSheetPlugin.getPlugin().getLog().log(status);
1084            org.eclipse.jface.dialogs.ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), null, null, status);
1085        } finally {
1086            unhookDialogListener();
1087            link.setCursor(null);
1088        }
1089    }
1090
1091    /*package*/ void saveCurrentSheet() {
1092        if(currentID != null) {
1093            if (currentPage instanceof CheatSheetPage) {
1094                Properties JavaDoc properties = saveHelper.createProperties(currentItemNum, viewItemList, getExpandRestoreActionState(), expandRestoreList, currentID, restorePath);
1095                IStatus status = stateManager.saveState(properties, getManager());
1096                if (!status.isOK()) {
1097                    CheatSheetPlugin.getPlugin().getLog().log(status);
1098                }
1099            } else if (currentPage instanceof CompositeCheatSheetPage) {
1100                ((CompositeCheatSheetPage)currentPage).saveState();
1101            }
1102        }
1103    }
1104    
1105    private boolean getExpandRestoreActionState() {
1106        boolean expandRestoreActionState = false;
1107        if(expandRestoreAction != null)
1108            expandRestoreActionState = expandRestoreAction.isCollapsed();
1109        return expandRestoreActionState;
1110    }
1111
1112    /*package*/ void setContent(CheatSheetElement element, ICheatSheetStateManager inputStateManager) {
1113        CheatSheetStopWatch.startStopWatch("CheatSheetViewer.setContent(CheatSheetElement element)"); //$NON-NLS-1$
1114

1115        // Cleanup previous contents
1116
internalDispose();
1117
1118        // Set the current content to new content
1119
contentElement = element;
1120        stateManager = inputStateManager;
1121        stateManager.setElement(element);
1122
1123        currentID = null;
1124        parserInput = null;
1125        if (element != null) {
1126            initInputFields(element);
1127        }
1128
1129        CheatSheetStopWatch.printLapTime("CheatSheetViewer.setContent(CheatSheetElement element)", "Time in CheatSheetViewer.setContent() before initCheatSheetView() call: "); //$NON-NLS-1$ //$NON-NLS-2$
1130
// Initialize the view with the new contents
1131
boolean cheatSheetOpened = false;
1132        if (control != null) {
1133            cheatSheetOpened = initCheatSheetView();
1134        }
1135        if (!cheatSheetOpened) {
1136            contentElement = null;
1137            stateManager = null;
1138        }
1139        // If the cheat sheet failed to open clear the content element so we don't see an
1140
CheatSheetStopWatch.printLapTime("CheatSheetViewer.setContent(CheatSheetElement element)", "Time in CheatSheetViewer.setContent() after initCheatSheetView() call: "); //$NON-NLS-1$ //$NON-NLS-2$
1141
}
1142
1143    private void initInputFields(CheatSheetElement element) {
1144        currentID = element.getID();
1145        String JavaDoc contentXml = element.getContentXml();
1146        URL JavaDoc contentURL = null;
1147        restorePath = element.getRestorePath();
1148        
1149        if (contentXml != null) {
1150            parserInput = new ParserInput(contentXml, element.getHref());
1151            return;
1152        }
1153
1154        // The input was not an XML string, find the content URL
1155
Bundle bundle = null;
1156        if(element != null && element.getConfigurationElement() != null)
1157            try{
1158                String JavaDoc pluginId = element.getConfigurationElement().getContributor().getName();
1159                bundle = Platform.getBundle(pluginId);
1160            } catch (Exception JavaDoc e) {
1161                // do nothing
1162
}
1163        if (bundle != null) {
1164            contentURL = FileLocator.find(bundle, new Path(element.getContentFile()), null);
1165        }
1166
1167        if (contentURL == null) {
1168            try {
1169                contentURL = new URL JavaDoc(element.getHref());
1170            } catch (MalformedURLException JavaDoc mue) {
1171            }
1172        }
1173        parserInput = new ParserInput(contentURL, bundle != null ? bundle.getSymbolicName() : null);
1174    }
1175    
1176    
1177    /*package*/ void setExpandRestoreAction(CheatSheetExpandRestoreAction action) {
1178        expandRestoreAction = action;
1179    }
1180
1181    /**
1182     * Passing the focus request to the viewer's control.
1183     */

1184    public void setFocus() {
1185        //need this to have current item selected. (Assumes that when you reactivate the view you will work with current item.)
1186
if (currentItem != null) {
1187            currentItem.setFocus();
1188        } else {
1189            getControl().setFocus();
1190        }
1191    }
1192    
1193
1194    /* (non-Javadoc)
1195     * @see org.eclipse.ui.cheatsheets.ICheatSheetViewer#setInput(java.lang.String)
1196     */

1197    public void setInput(String JavaDoc id) {
1198        setInput(id, new DefaultStateManager());
1199    }
1200
1201    public void setInput(String JavaDoc id, ICheatSheetStateManager inputStateManager) {
1202        CheatSheetStopWatch.startStopWatch("CheatSheetViewer.setInput(String id)"); //$NON-NLS-1$
1203

1204        CheatSheetElement element = null;
1205
1206        if(id == null) {
1207            nullCheatSheetId = true;
1208        } else {
1209            nullCheatSheetId = false;
1210
1211            element = CheatSheetRegistryReader.getInstance().findCheatSheet(id);
1212            if(element == null) {
1213                String JavaDoc message = NLS.bind(Messages.ERROR_INVALID_CHEATSHEET_ID, (new Object JavaDoc[] {id}));
1214                IStatus status = new Status(IStatus.ERROR, ICheatSheetResource.CHEAT_SHEET_PLUGIN_ID, IStatus.OK, message, null);
1215                CheatSheetPlugin.getPlugin().getLog().log(status);
1216                invalidCheatSheetId = true;
1217            } else {
1218                invalidCheatSheetId = false;
1219                this.isRestricted = false;
1220            }
1221        }
1222
1223        CheatSheetStopWatch.printLapTime("CheatSheetViewer.setInput(String id)", "Time in CheatSheetViewer.setInput(String id) before setContent() call: "); //$NON-NLS-1$ //$NON-NLS-2$
1224
setContent(element, inputStateManager);
1225        CheatSheetStopWatch.printLapTime("CheatSheetViewer.setInput(String id)", "Time in CheatSheetViewer.setInput(String id) after setContent() call: "); //$NON-NLS-1$ //$NON-NLS-2$
1226

1227        // Update most recently used cheat sheets list.
1228
CheatSheetPlugin.getPlugin().getCheatSheetHistory().add(element);
1229        CheatSheetStopWatch.printLapTime("CheatSheetViewer.setInput(String id)", "Time in CheatSheetViewer.setInput(String id) after getCheatSheetHistory() call: "); //$NON-NLS-1$ //$NON-NLS-2$
1230
}
1231
1232    /* (non-Javadoc)
1233     * @see org.eclipse.ui.cheatsheets.ICheatSheetViewer#setInput(java.lang.String, java.lang.String, java.net.URL)
1234     */

1235    public void setInput(String JavaDoc id, String JavaDoc name, URL JavaDoc url) {
1236        setInput(id, name, url, new DefaultStateManager(), false);
1237    }
1238    
1239    public void setInputFromXml(String JavaDoc id, String JavaDoc name, String JavaDoc xml, String JavaDoc basePath) {
1240        if (id == null || name == null || xml == null) {
1241            throw new IllegalArgumentException JavaDoc();
1242        }
1243        CheatSheetElement element = new CheatSheetElement(name);
1244        element.setID(id);
1245        element.setContentXml(xml);
1246        element.setHref(basePath);
1247
1248        nullCheatSheetId = false;
1249        invalidCheatSheetId = false;
1250        isRestricted = false;
1251        setContent(element, new NoSaveStateManager());
1252    }
1253
1254    public void setInput(String JavaDoc id, String JavaDoc name, URL JavaDoc url,
1255            ICheatSheetStateManager inputStateManager, boolean isRestricted) {
1256        if (id == null || name == null || url == null) {
1257            throw new IllegalArgumentException JavaDoc();
1258        }
1259        CheatSheetElement element = new CheatSheetElement(name);
1260        element.setID(id);
1261        element.setHref(url.toString());
1262
1263        nullCheatSheetId = false;
1264        invalidCheatSheetId = false;
1265        this.isRestricted = isRestricted;
1266        setContent(element, inputStateManager);
1267    }
1268    
1269    /*package*/ void toggleExpandRestore() {
1270        if(expandRestoreAction == null)
1271            return;
1272
1273        if (expandRestoreAction.isCollapsed()) {
1274            restoreExpandStates();
1275            expandRestoreAction.setCollapsed(false);
1276        } else {
1277            collapseAllButCurrent(true);
1278            expandRestoreAction.setCollapsed(true);
1279        }
1280
1281    }
1282
1283    public Action getCopyAction() {
1284        return copyAction;
1285    }
1286
1287    public void setCopyAction(Action copyAction) {
1288        this.copyAction = copyAction;
1289    }
1290    
1291    public void copy() {
1292        if (currentItem!=null)
1293            currentItem.copy();
1294    }
1295
1296    public void addListener(CheatSheetListener listener) {
1297        if (contentElement != null ) {
1298            getManager().addListener(listener);
1299        }
1300    }
1301
1302    public int contributeToViewMenu(Menu menu, int index) {
1303        if (currentPage instanceof IMenuContributor) {
1304            return ((IMenuContributor)currentPage).contributeToViewMenu(menu, index);
1305        }
1306        return index;
1307    }
1308    
1309    public void restart() {
1310        resetItemState();
1311        currentItemNum = 0;
1312        collapseAllButCurrent(false);
1313        IntroItem introItem = (IntroItem) getViewItemAtIndex(0);
1314        introItem.setIncomplete();
1315        showIntroItem();
1316    }
1317
1318    public void saveState(IMemento memento) {
1319        if (currentPage instanceof CheatSheetPage) {
1320            Properties JavaDoc properties = saveHelper.createProperties(currentItemNum, viewItemList, getExpandRestoreActionState(), expandRestoreList, currentID, restorePath);
1321            saveHelper.saveToMemento(properties, getManager(), memento);
1322        }
1323    }
1324
1325    public void reset(Map JavaDoc cheatSheetData) {
1326        if (currentPage instanceof CheatSheetPage) {
1327            restart();
1328            getManager().setData(cheatSheetData);
1329        } else if (currentPage instanceof CompositeCheatSheetPage) {
1330            ((CompositeCheatSheetPage)currentPage).restart(cheatSheetData);
1331        }
1332    }
1333    
1334    public void showError(String JavaDoc message) {
1335        internalDispose();
1336        if(howToBegin != null) {
1337            howToBegin.dispose();
1338            howToBegin = null;
1339        }
1340        createErrorPage(message);
1341    }
1342
1343}
Popular Tags