KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > help > ui > internal > views > ReusableHelpPart


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.help.ui.internal.views;
12
13 import java.io.UnsupportedEncodingException JavaDoc;
14 import java.net.MalformedURLException JavaDoc;
15 import java.net.URL JavaDoc;
16 import java.net.URLDecoder JavaDoc;
17 import java.util.ArrayList JavaDoc;
18 import java.util.HashMap JavaDoc;
19 import java.util.Iterator JavaDoc;
20 import java.util.Map JavaDoc;
21 import java.util.Set JavaDoc;
22
23 import org.eclipse.core.runtime.Preferences;
24 import org.eclipse.core.runtime.jobs.Job;
25 import org.eclipse.help.IContext;
26 import org.eclipse.help.IContextProvider;
27 import org.eclipse.help.IHelpResource;
28 import org.eclipse.help.IIndexEntry;
29 import org.eclipse.help.IToc;
30 import org.eclipse.help.ITopic;
31 import org.eclipse.help.UAContentFilter;
32 import org.eclipse.help.internal.base.BaseHelpSystem;
33 import org.eclipse.help.internal.base.HelpBasePlugin;
34 import org.eclipse.help.internal.base.HelpEvaluationContext;
35 import org.eclipse.help.internal.base.IHelpBaseConstants;
36 import org.eclipse.help.internal.base.util.LinkUtil;
37 import org.eclipse.help.internal.protocols.HelpURLConnection;
38 import org.eclipse.help.internal.search.federated.IndexerJob;
39 import org.eclipse.help.internal.util.ProductPreferences;
40 import org.eclipse.help.search.ISearchEngine2;
41 import org.eclipse.help.ui.internal.DefaultHelpUI;
42 import org.eclipse.help.ui.internal.HelpUIPlugin;
43 import org.eclipse.help.ui.internal.HelpUIResources;
44 import org.eclipse.help.ui.internal.IHelpUIConstants;
45 import org.eclipse.help.ui.internal.Messages;
46 import org.eclipse.jface.action.Action;
47 import org.eclipse.jface.action.IAction;
48 import org.eclipse.jface.action.IContributionManager;
49 import org.eclipse.jface.action.IMenuListener;
50 import org.eclipse.jface.action.IMenuManager;
51 import org.eclipse.jface.action.IStatusLineManager;
52 import org.eclipse.jface.action.IToolBarManager;
53 import org.eclipse.jface.action.MenuManager;
54 import org.eclipse.jface.action.Separator;
55 import org.eclipse.jface.action.SubStatusLineManager;
56 import org.eclipse.jface.action.SubToolBarManager;
57 import org.eclipse.jface.dialogs.MessageDialogWithToggle;
58 import org.eclipse.jface.operation.IRunnableContext;
59 import org.eclipse.jface.preference.IPreferenceStore;
60 import org.eclipse.jface.viewers.ISelectionProvider;
61 import org.eclipse.jface.viewers.IStructuredSelection;
62 import org.eclipse.jface.viewers.Viewer;
63 import org.eclipse.jface.viewers.ViewerFilter;
64 import org.eclipse.osgi.util.NLS;
65 import org.eclipse.swt.SWT;
66 import org.eclipse.swt.SWTError;
67 import org.eclipse.swt.custom.BusyIndicator;
68 import org.eclipse.swt.events.FocusEvent;
69 import org.eclipse.swt.events.FocusListener;
70 import org.eclipse.swt.events.SelectionEvent;
71 import org.eclipse.swt.events.SelectionListener;
72 import org.eclipse.swt.graphics.Image;
73 import org.eclipse.swt.graphics.Point;
74 import org.eclipse.swt.graphics.Rectangle;
75 import org.eclipse.swt.widgets.Composite;
76 import org.eclipse.swt.widgets.Control;
77 import org.eclipse.swt.widgets.Event;
78 import org.eclipse.swt.widgets.Layout;
79 import org.eclipse.swt.widgets.Listener;
80 import org.eclipse.swt.widgets.Menu;
81 import org.eclipse.swt.widgets.Shell;
82 import org.eclipse.ui.IActionBars;
83 import org.eclipse.ui.IMemento;
84 import org.eclipse.ui.ISharedImages;
85 import org.eclipse.ui.IWorkbenchPart;
86 import org.eclipse.ui.IWorkbenchWindow;
87 import org.eclipse.ui.PlatformUI;
88 import org.eclipse.ui.SubActionBars;
89 import org.eclipse.ui.actions.ActionFactory;
90 import org.eclipse.ui.activities.ActivityManagerEvent;
91 import org.eclipse.ui.activities.IActivityManagerListener;
92 import org.eclipse.ui.forms.IFormPart;
93 import org.eclipse.ui.forms.ManagedForm;
94 import org.eclipse.ui.forms.events.HyperlinkEvent;
95 import org.eclipse.ui.forms.widgets.FormText;
96 import org.eclipse.ui.forms.widgets.FormToolkit;
97 import org.eclipse.ui.forms.widgets.ILayoutExtension;
98 import org.eclipse.ui.forms.widgets.ScrolledForm;
99
100 import com.ibm.icu.text.Collator;
101
102 public class ReusableHelpPart implements IHelpUIConstants,
103         IActivityManagerListener {
104     public static final int ALL_TOPICS = 1 << 1;
105
106     public static final int CONTEXT_HELP = 1 << 2;
107
108     public static final int SEARCH = 1 << 3;
109
110     public static final int BOOKMARKS = 1 << 4;
111
112     public static final int INDEX = 1 << 5;
113
114     public static final Collator SHARED_COLLATOR = Collator.getInstance();
115
116     private static final String JavaDoc PROMPT_KEY = "askShowAll"; //$NON-NLS-1$
117

118     private static final int STATE_START = 1;
119
120     private static final int STATE_LT = 2;
121
122     private static final int STATE_LT_B = 3;
123
124     private static final int STATE_LT_BR = 4;
125     
126     /*
127      * Used as a bridge from live help actions back (e.g. breadcrumb links)
128      * to the originating help part.
129      */

130     private static ReusableHelpPart lastActiveInstance;
131
132     private RoleFilter roleFilter;
133
134     private UAFilter uaFilter;
135
136     private ManagedForm mform;
137
138     private int verticalSpacing = 15;
139
140     private int bmargin = 5;
141
142     private String JavaDoc defaultContextHelpText;
143
144     private ArrayList JavaDoc pages;
145
146     private Action backAction;
147
148     private Action nextAction;
149
150     private CopyAction copyAction;
151
152     private Action openInfoCenterAction;
153
154     private OpenHrefAction openAction;
155
156     private OpenHrefAction openInHelpAction;
157
158     private OpenHrefAction bookmarkAction;
159
160     private Action showAllAction;
161
162     private ReusableHelpPartHistory history;
163
164     private HelpPartPage currentPage;
165
166     private int style;
167
168     private IMemento memento;
169
170     private boolean showDocumentsInPlace = true;
171
172     private int numberOfInPlaceHits = 8;
173
174     private IRunnableContext runnableContext;
175
176     private IToolBarManager toolBarManager;
177
178     private IStatusLineManager statusLineManager;
179
180     private IActionBars actionBars;
181     
182     private EngineDescriptorManager engineManager;
183
184     private abstract class BusyRunAction extends Action {
185         public BusyRunAction(String JavaDoc name) {
186             super(name);
187         }
188
189         public void run() {
190             BusyIndicator.showWhile(getControl().getDisplay(), new Runnable JavaDoc() {
191                 public void run() {
192                     busyRun();
193                 }
194             });
195         }
196
197         protected abstract void busyRun();
198     }
199
200     private abstract class OpenHrefAction extends BusyRunAction {
201         private Object JavaDoc target;
202
203         public OpenHrefAction(String JavaDoc name) {
204             super(name);
205         }
206
207         public void setTarget(Object JavaDoc target) {
208             this.target = target;
209         }
210
211         public Object JavaDoc getTarget() {
212             return target;
213         }
214     }
215
216     private class CopyAction extends Action implements FocusListener,
217             SelectionListener {
218         private FormText target;
219
220         public CopyAction() {
221             super("copy"); //$NON-NLS-1$
222
}
223
224         public void hook(final FormText text) {
225             text.addFocusListener(this);
226         }
227
228         public void unhook(FormText text) {
229             text.removeFocusListener(this);
230             if (target == text)
231                 setTarget(null);
232         }
233
234         public void focusGained(FocusEvent e) {
235             FormText text = (FormText) e.widget;
236             text.addSelectionListener(this);
237             setTarget(text);
238         }
239
240         public void focusLost(FocusEvent e) {
241             FormText text = (FormText) e.widget;
242             text.removeSelectionListener(this);
243             setTarget(null);
244         }
245
246         public void setTarget(FormText target) {
247             this.target = target;
248             updateState();
249         }
250
251         private void updateState() {
252             setEnabled(target != null && target.canCopy());
253         }
254
255         public void run() {
256             if (target != null)
257                 target.copy();
258         }
259
260         public void widgetSelected(SelectionEvent e) {
261             FormText text = (FormText) e.widget;
262             if (text == target) {
263                 updateState();
264             }
265         }
266
267         public void widgetDefaultSelected(SelectionEvent e) {
268         }
269     }
270
271     private static class PartRec {
272         String JavaDoc id;
273
274         boolean flexible;
275
276         boolean grabVertical;
277
278         IHelpPart part;
279
280         PartRec(String JavaDoc id, boolean flexible, boolean grabVertical) {
281             this.id = id;
282             this.flexible = flexible;
283             this.grabVertical = grabVertical;
284         }
285     }
286
287     private class HelpPartPage implements IHelpPartPage {
288         private String JavaDoc id;
289
290         private String JavaDoc iconId;
291
292         Action pageAction;
293
294         private int vspacing = verticalSpacing;
295
296         private int horizontalMargin = 0;
297
298         private String JavaDoc text;
299
300         private SubActionBars bars;
301
302         private IToolBarManager toolBarManager;
303
304         protected ArrayList JavaDoc partRecs;
305
306         private int nflexible;
307
308         private Control focusControl;
309
310         public HelpPartPage(String JavaDoc id, String JavaDoc text) {
311             this.id = id;
312             this.text = text;
313             partRecs = new ArrayList JavaDoc();
314             if (ReusableHelpPart.this.actionBars != null) {
315                 bars = new SubActionBars(ReusableHelpPart.this.actionBars);
316                 toolBarManager = bars.getToolBarManager();
317             } else
318                 toolBarManager = new SubToolBarManager(
319                         ReusableHelpPart.this.toolBarManager);
320         }
321
322         public HelpPartPage(String JavaDoc id, String JavaDoc text, String JavaDoc iconId) {
323             this(id, text);
324             this.iconId = iconId;
325         }
326
327         public void dispose() {
328             if (bars != null) {
329                 bars.dispose();
330                 bars = null;
331                 toolBarManager = null;
332             } else
333                 ((SubToolBarManager) toolBarManager).disposeManager();
334             partRecs = null;
335         }
336
337         public void setVerticalSpacing(int value) {
338             this.vspacing = value;
339         }
340
341         public int getVerticalSpacing() {
342             return vspacing;
343         }
344
345         public void setHorizontalMargin(int value) {
346             this.horizontalMargin = value;
347         }
348
349         public int getHorizontalMargin() {
350             return horizontalMargin;
351         }
352
353         public IToolBarManager getToolBarManager() {
354             return toolBarManager;
355         }
356
357         public String JavaDoc getId() {
358             return id;
359         }
360
361         public String JavaDoc getText() {
362             return text;
363         }
364
365         public String JavaDoc getIconId() {
366             return iconId;
367         }
368
369         public void addPart(String JavaDoc id, boolean flexible) {
370             addPart(id, flexible, false);
371         }
372
373         public void addPart(String JavaDoc id, boolean flexible, boolean grabVertical) {
374             partRecs.add(new PartRec(id, flexible, grabVertical));
375             if (flexible)
376                 nflexible++;
377         }
378
379         public PartRec[] getParts() {
380             return (PartRec[]) partRecs.toArray(new PartRec[partRecs.size()]);
381         }
382
383         public int getNumberOfFlexibleParts() {
384             return nflexible;
385         }
386
387         public boolean canOpen() {
388             for (int i = 0; i < partRecs.size(); i++) {
389                 PartRec rec = (PartRec) partRecs.get(i);
390
391                 if (rec.id.equals(IHelpUIConstants.HV_BROWSER)) {
392                     // Try to create a browser and watch
393
// for 'no-handle' error - it means
394
// that the embedded browser is not
395
// available
396
try {
397                         createRecPart(rec);
398                         rec.part.setVisible(false);
399                     } catch (SWTError error) {
400                         // cannot create a browser
401
return false;
402                     }
403                 }
404             }
405             return true;
406         }
407
408         public void stop() {
409             for (int i = 0; i < partRecs.size(); i++) {
410                 PartRec rec = (PartRec) partRecs.get(i);
411                 if (rec.part!=null)
412                     rec.part.stop();
413             }
414         }
415         
416         public void saveState(IMemento memento) {
417             for (int i = 0; i < partRecs.size(); i++) {
418                 PartRec rec = (PartRec) partRecs.get(i);
419                 if (rec.part!=null)
420                     rec.part.saveState(memento);
421             }
422         }
423
424         public void toggleRoleFilter() {
425             for (int i = 0; i < partRecs.size(); i++) {
426                 PartRec rec = (PartRec) partRecs.get(i);
427                 if (rec.part != null)
428                     rec.part.toggleRoleFilter();
429             }
430         }
431
432         public void refilter() {
433             for (int i = 0; i < partRecs.size(); i++) {
434                 PartRec rec = (PartRec) partRecs.get(i);
435                 if (rec.part != null)
436                     rec.part.refilter();
437             }
438         }
439
440         public void setVisible(boolean visible) {
441             if (bars != null)
442                 bars.clearGlobalActionHandlers();
443             ArrayList JavaDoc tabList = new ArrayList JavaDoc();
444             Control originalFocusControl = focusControl;
445             for (int i = 0; i < partRecs.size(); i++) {
446                 PartRec rec = (PartRec) partRecs.get(i);
447                 if (visible) {
448                     createRecPart(rec);
449                     hookGlobalAction(ActionFactory.PRINT.getId(), rec.part);
450                     hookGlobalAction(ActionFactory.COPY.getId(), rec.part);
451                     hookGlobalAction(ActionFactory.DELETE.getId(), rec.part);
452                     tabList.add(rec.part.getControl());
453                 }
454                 rec.part.setVisible(visible);
455             }
456             focusControl = originalFocusControl;
457             Composite parent = mform.getForm().getBody();
458             parent.setTabList((Control[]) tabList.toArray(new Control[tabList
459                     .size()]));
460
461             if (actionBars != null) {
462                 actionBars.clearGlobalActionHandlers();
463                 if (visible) {
464                     Map JavaDoc handlers = bars.getGlobalActionHandlers();
465                     if (handlers != null) {
466                         Set JavaDoc keys = handlers.keySet();
467                         for (Iterator JavaDoc iter = keys.iterator(); iter.hasNext();) {
468                             String JavaDoc key = (String JavaDoc) iter.next();
469                             actionBars.setGlobalActionHandler(key,
470                                     (IAction) handlers.get(key));
471                         }
472                     }
473                 }
474                 if (pageAction != null)
475                     pageAction.setChecked(visible);
476             }
477             
478             if (bars != null) {
479                 if (visible)
480                     bars.activate();
481                 else
482                     bars.deactivate();
483                 bars.updateActionBars();
484             } else {
485                 ((SubToolBarManager) toolBarManager).setVisible(visible);
486                 ReusableHelpPart.this.toolBarManager.update(true);
487                 getControl().getParent().layout();
488             }
489             
490         }
491
492         private void hookGlobalAction(String JavaDoc id, IHelpPart part) {
493             if (bars == null)
494                 return;
495             IAction action = part.getGlobalAction(id);
496             if (action != null)
497                 bars.setGlobalActionHandler(id, action);
498         }
499
500         private void createRecPart(PartRec rec) throws SWTError {
501             if (rec.part == null) {
502                 rec.part = createPart(rec.id, toolBarManager);
503                 rec.part.getControl().addListener(SWT.Activate, new Listener() {
504                     public void handleEvent(Event e) {
505                         focusControl = e.widget.getDisplay().getFocusControl();
506                     }
507                 });
508             }
509         }
510
511         public IHelpPart findPart(String JavaDoc id) {
512             for (int i = 0; i < partRecs.size(); i++) {
513                 PartRec rec = (PartRec) partRecs.get(i);
514                 if (rec.id.equals(id))
515                     return rec.part;
516             }
517             return null;
518         }
519
520         public void setFocus() {
521             // set focus on the control that had
522
// focus when this page was active
523
if (focusControl != null && focusControl.isDisposed())
524                 focusControl = null;
525             if (focusControl!=null && focusControl.setFocus())
526                 return;
527             if (partRecs.size() == 0)
528                 return;
529             PartRec rec = (PartRec) partRecs.get(0);
530             rec.part.setFocus();
531         }
532     }
533
534     class HelpPartLayout extends Layout implements ILayoutExtension {
535         public int computeMaximumWidth(Composite parent, boolean changed) {
536             return computeSize(parent, SWT.DEFAULT, SWT.DEFAULT, changed).x;
537         }
538
539         public int computeMinimumWidth(Composite parent, boolean changed) {
540             return computeSize(parent, 0, SWT.DEFAULT, changed).x;
541         }
542
543         protected Point computeSize(Composite composite, int wHint, int hHint,
544                 boolean flushCache) {
545             if (currentPage == null)
546                 return new Point(0, 0);
547             PartRec[] parts = currentPage.getParts();
548             int hmargin = currentPage.getHorizontalMargin();
549             int innerWhint = wHint != SWT.DEFAULT ? wHint - 2 * hmargin : wHint;
550             Point result = new Point(0, 0);
551             for (int i = 0; i < parts.length; i++) {
552                 PartRec partRec = parts[i];
553                 if (!partRec.flexible) {
554                     Control c = partRec.part.getControl();
555                     Point size = c.computeSize(innerWhint, SWT.DEFAULT,
556                             flushCache);
557                     result.x = Math.max(result.x, size.x);
558                     result.y += size.y;
559                 }
560                 if (i < parts.length - 1)
561                     result.y += currentPage.getVerticalSpacing();
562             }
563             result.x += hmargin * 2;
564             result.y += bmargin;
565             return result;
566         }
567
568         protected void layout(Composite composite, boolean flushCache) {
569             if (currentPage == null)
570                 return;
571
572             Rectangle clientArea = composite.getClientArea();
573
574             PartRec[] parts = currentPage.getParts();
575             int hmargin = currentPage.getHorizontalMargin();
576             int nfixedParts = parts.length
577                     - currentPage.getNumberOfFlexibleParts();
578             Point[] fixedSizes = new Point[nfixedParts];
579             int fixedHeight = 0;
580             int index = 0;
581             int innerWidth = clientArea.width - hmargin * 2;
582             for (int i = 0; i < parts.length; i++) {
583                 PartRec partRec = parts[i];
584                 if (!partRec.flexible) {
585                     Control c = partRec.part.getControl();
586                     Point size = c.computeSize(innerWidth, SWT.DEFAULT, false);
587                     fixedSizes[index++] = size;
588                     if (!partRec.grabVertical)
589                         fixedHeight += size.y;
590                 }
591                 if (i < parts.length - 1)
592                     fixedHeight += currentPage.getVerticalSpacing();
593             }
594             fixedHeight += bmargin;
595             int flexHeight = clientArea.height - fixedHeight;
596             int flexPortion = 0;
597             if (currentPage.getNumberOfFlexibleParts() > 0)
598                 flexPortion = flexHeight
599                         / currentPage.getNumberOfFlexibleParts();
600
601             int usedFlexHeight = 0;
602             int y = 0;
603             index = 0;
604             int nflexParts = 0;
605             for (int i = 0; i < parts.length; i++) {
606                 PartRec partRec = parts[i];
607                 Control c = partRec.part.getControl();
608
609                 if (partRec.flexible) {
610                     int height;
611                     if (++nflexParts == currentPage.getNumberOfFlexibleParts())
612                         height = flexHeight - usedFlexHeight;
613                     else {
614                         height = flexPortion;
615                         usedFlexHeight += height;
616                     }
617                     c.setBounds(0, y, clientArea.width, height);
618                 } else {
619                     Point fixedSize = fixedSizes[index++];
620                     if (fixedSize.y < flexHeight && partRec.grabVertical)
621                         c.setBounds(hmargin, y, innerWidth, flexHeight);
622                     else
623                         c.setBounds(hmargin, y, innerWidth, fixedSize.y);
624                 }
625                 if (i < parts.length - 1)
626                     y += c.getSize().y + currentPage.getVerticalSpacing();
627             }
628         }
629     }
630
631     class RoleFilter extends ViewerFilter {
632         public boolean select(Viewer viewer, Object JavaDoc parentElement,
633                 Object JavaDoc element) {
634             IHelpResource res = (IHelpResource) element;
635             String JavaDoc href = res.getHref();
636             if (href == null)
637                 return true;
638             return HelpBasePlugin.getActivitySupport().isEnabled(href);
639         }
640     }
641     
642     class UAFilter extends ViewerFilter {
643         public boolean select(Viewer viewer, Object JavaDoc parentElement,
644                 Object JavaDoc element) {
645             return !UAContentFilter.isFiltered(element, HelpEvaluationContext.getContext());
646         }
647     }
648
649     public ReusableHelpPart(IRunnableContext runnableContext) {
650         this(runnableContext, getDefaultStyle());
651     }
652
653     public ReusableHelpPart(IRunnableContext runnableContext, int style) {
654         this.runnableContext = runnableContext;
655         history = new ReusableHelpPartHistory();
656         this.style = style;
657         ensureHelpIndexed();
658         PlatformUI.getWorkbench().getActivitySupport().getActivityManager()
659                 .addActivityManagerListener(this);
660     }
661
662     /*
663      * Used as a bridge from live help actions back (e.g. breadcrumb links)
664      * to the originating help part.
665      */

666     public static ReusableHelpPart getLastActiveInstance() {
667         return lastActiveInstance;
668     }
669     
670     private void ensureHelpIndexed() {
671         // make sure we have the index but
672
// don't schedule the indexer job if one is
673
// already running
674
Job[] jobs = Job.getJobManager().find(IndexerJob.FAMILY);
675         if (jobs.length == 0) {
676             IndexerJob indexerJob = new IndexerJob();
677             indexerJob.schedule();
678         }
679     }
680     
681     /**
682      * Adds the given page to this part.
683      *
684      * @param page the page to add
685      */

686     public void addPage(IHelpPartPage page) {
687         pages.add(page);
688     }
689     
690     /**
691      * Adds the given part to this one. The part can then be used inside
692      * any page and referred to by id.
693      *
694      * @param id the part's unique id
695      * @param part the part to add
696      */

697     public void addPart(String JavaDoc id, IHelpPart part) {
698         part.init(this, id, memento);
699         mform.addPart(part);
700     }
701     
702     /**
703      * Creates a new page for this part.
704      *
705      * @param id the page's unique id
706      * @param text the page's heading, or null for none
707      * @param iconId the page's icon
708      * @return the newly created page
709      */

710     public IHelpPartPage createPage(String JavaDoc id, String JavaDoc text, String JavaDoc iconId) {
711         return new HelpPartPage(id, text, iconId);
712     }
713     
714     private void definePages() {
715         pages = new ArrayList JavaDoc();
716         // federated search page
717
HelpPartPage page = new HelpPartPage(HV_FSEARCH_PAGE,
718                 Messages.ReusableHelpPart_searchPage_name,
719                 IHelpUIConstants.IMAGE_HELP_SEARCH);
720         page.setVerticalSpacing(0);
721         page.addPart(HV_FSEARCH, false);
722         page.addPart(HV_FSEARCH_RESULT, true);
723         page.addPart(HV_SEE_ALSO, false);
724         pages.add(page);
725
726         // all topics page
727
page = new HelpPartPage(HV_ALL_TOPICS_PAGE,
728                 Messages.ReusableHelpPart_allTopicsPage_name,
729                 IHelpUIConstants.IMAGE_ALL_TOPICS);
730         page.setVerticalSpacing(0);
731         page.setHorizontalMargin(0);
732         page.addPart(HV_TOPIC_TREE, true);
733         page.addPart(HV_SEE_ALSO, false);
734         pages.add(page);
735
736         // bookmarks page
737
page = new HelpPartPage(HV_BOOKMARKS_PAGE,
738                 Messages.ReusableHelpPart_bookmarksPage_name,
739                 IHelpUIConstants.IMAGE_BOOKMARKS);
740         page.setVerticalSpacing(0);
741         page.setHorizontalMargin(0);
742         page.addPart(HV_BOOKMARKS_TREE, true);
743         page.addPart(HV_SEE_ALSO, false);
744         pages.add(page);
745         // browser page
746
page = new HelpPartPage(HV_BROWSER_PAGE, null);
747         page.setVerticalSpacing(0);
748         page.addPart(HV_BROWSER, true);
749         page.addPart(HV_SEE_ALSO, false);
750         pages.add(page);
751
752         // context help page
753
page = new HelpPartPage(HV_CONTEXT_HELP_PAGE,
754                 Messages.ReusableHelpPart_contextHelpPage_name,
755                 IHelpUIConstants.IMAGE_RELATED_TOPICS);
756         // page.addPart(HV_CONTEXT_HELP, false);
757
// page.addPart(HV_SEARCH_RESULT, false, true);
758
page.setVerticalSpacing(0);
759         page.setHorizontalMargin(0);
760         page.addPart(HV_RELATED_TOPICS, true);
761         page.addPart(HV_SEE_ALSO, false);
762         pages.add(page);
763
764         // index page
765
page = new HelpPartPage(HV_INDEX_PAGE,
766                 Messages.ReusableHelpPart_indexPage_name,
767                 IHelpUIConstants.IMAGE_INDEX);
768         page.setVerticalSpacing(0);
769         page.addPart(HV_INDEX_TYPEIN, false);
770         page.addPart(HV_INDEX, true);
771         page.addPart(HV_SEE_ALSO, false);
772         pages.add(page);
773     }
774
775     public void init(IActionBars bars, IToolBarManager toolBarManager,
776             IStatusLineManager statusLineManager, IMemento memento) {
777         this.memento = memento;
778         this.actionBars = bars;
779         this.toolBarManager = toolBarManager;
780         this.statusLineManager = statusLineManager;
781         definePages();
782         makeActions();
783     }
784
785     private void makeActions() {
786         backAction = new Action("back") { //$NON-NLS-1$
787
public void run() {
788                 doBack();
789             }
790         };
791         backAction.setImageDescriptor(PlatformUI.getWorkbench()
792                 .getSharedImages().getImageDescriptor(
793                         ISharedImages.IMG_TOOL_BACK));
794         backAction.setDisabledImageDescriptor(PlatformUI.getWorkbench()
795                 .getSharedImages().getImageDescriptor(
796                         ISharedImages.IMG_TOOL_BACK_DISABLED));
797         backAction.setEnabled(false);
798         backAction.setText(Messages.ReusableHelpPart_back_label);
799         backAction.setToolTipText(Messages.ReusableHelpPart_back_tooltip);
800         backAction.setId("back"); //$NON-NLS-1$
801

802         nextAction = new Action("next") { //$NON-NLS-1$
803
public void run() {
804                 doNext();
805             }
806         };
807         nextAction.setText(Messages.ReusableHelpPart_forward_label);
808         nextAction.setImageDescriptor(PlatformUI.getWorkbench()
809                 .getSharedImages().getImageDescriptor(
810                         ISharedImages.IMG_TOOL_FORWARD));
811         nextAction.setDisabledImageDescriptor(PlatformUI.getWorkbench()
812                 .getSharedImages().getImageDescriptor(
813                         ISharedImages.IMG_TOOL_FORWARD_DISABLED));
814         nextAction.setEnabled(false);
815         nextAction.setToolTipText(Messages.ReusableHelpPart_forward_tooltip);
816         nextAction.setId("next"); //$NON-NLS-1$
817
toolBarManager.add(backAction);
818         toolBarManager.add(nextAction);
819
820         openInfoCenterAction = new BusyRunAction("openInfoCenter") { //$NON-NLS-1$
821
protected void busyRun() {
822                 PlatformUI.getWorkbench().getHelpSystem().displayHelp();
823             }
824         };
825         openInfoCenterAction
826                 .setText(Messages.ReusableHelpPart_openInfoCenterAction_label);
827         openAction = new OpenHrefAction("open") { //$NON-NLS-1$
828
protected void busyRun() {
829                 doOpen(getTarget(), getShowDocumentsInPlace());
830             }
831         };
832         openAction.setText(Messages.ReusableHelpPart_openAction_label);
833         openInHelpAction = new OpenHrefAction("") {//$NON-NLS-1$
834
protected void busyRun() {
835                 doOpenInHelp(getTarget());
836             }
837         };
838         openInHelpAction
839                 .setText(Messages.ReusableHelpPart_openInHelpContentsAction_label);
840         copyAction = new CopyAction();
841         copyAction.setText(Messages.ReusableHelpPart_copyAction_label);
842         bookmarkAction = new OpenHrefAction("bookmark") { //$NON-NLS-1$
843
protected void busyRun() {
844                 doBookmark(getTarget());
845             }
846         };
847         bookmarkAction.setText(Messages.ReusableHelpPart_bookmarkAction_label);
848         bookmarkAction.setImageDescriptor(HelpUIResources
849                 .getImageDescriptor(IHelpUIConstants.IMAGE_ADD_BOOKMARK));
850         if (actionBars != null && actionBars.getMenuManager() != null)
851             contributeToDropDownMenu(actionBars.getMenuManager());
852         
853         roleFilter = new RoleFilter();
854         uaFilter = new UAFilter();
855         if (HelpBasePlugin.getActivitySupport().isUserCanToggleFiltering()) {
856             showAllAction = new Action() {
857                 public void run() {
858                     BusyIndicator.showWhile(getControl().getDisplay(),
859                             new Runnable JavaDoc() {
860                                 public void run() {
861                                     toggleShowAll(showAllAction.isChecked());
862                                 }
863                             });
864                 }
865             };
866             showAllAction.setImageDescriptor(HelpUIResources
867                     .getImageDescriptor(IHelpUIConstants.IMAGE_SHOW_ALL));
868             showAllAction
869                     .setToolTipText(Messages.AllTopicsPart_showAll_tooltip);
870             toolBarManager.insertBefore("back", showAllAction); //$NON-NLS-1$
871
toolBarManager.insertBefore("back", new Separator()); //$NON-NLS-1$
872
showAllAction.setChecked(!HelpBasePlugin.getActivitySupport()
873                     .isFilteringEnabled());
874         }
875     }
876
877     ViewerFilter getRoleFilter() {
878         return roleFilter;
879     }
880
881     ViewerFilter getUAFilter() {
882         return uaFilter;
883     }
884
885     public void activityManagerChanged(ActivityManagerEvent activityManagerEvent) {
886         for (int i = 0; i < pages.size(); i++) {
887             HelpPartPage page = (HelpPartPage) pages.get(i);
888             page.refilter();
889         }
890     }
891
892     boolean isFilteredByRoles() {
893         return HelpBasePlugin.getActivitySupport().isFilteringEnabled();
894     }
895
896     private void doBack() {
897         String JavaDoc id = getCurrentPageId();
898         if (id.equals(IHelpUIConstants.HV_BROWSER_PAGE)) {
899             // stop the browser
900
BrowserPart part = (BrowserPart) findPart(IHelpUIConstants.HV_BROWSER);
901             part.stop();
902         }
903         HistoryEntry entry = history.prev();
904         if (entry != null)
905             executeHistoryEntry(entry);
906     }
907
908     private void doNext() {
909         HistoryEntry entry = history.next();
910         if (entry != null)
911             executeHistoryEntry(entry);
912     }
913
914     private void executeHistoryEntry(HistoryEntry entry) {
915         history.setBlocked(true);
916         if (entry.getType() == HistoryEntry.PAGE) {
917             showPage(entry.getTarget(), true);
918             mform.setInput(entry.getData());
919         } else if (entry.getType() == HistoryEntry.URL) {
920             String JavaDoc relativeUrl = (String JavaDoc) entry.getData();
921             showURL(relativeUrl != null ? relativeUrl : entry.getTarget(), true);
922         }
923     }
924
925     public void createControl(Composite parent, FormToolkit toolkit) {
926         ScrolledForm form = toolkit.createScrolledForm(parent);
927         form.getBody().setLayout(new HelpPartLayout());
928         mform = new ManagedForm(toolkit, form);
929         mform.getForm().setDelayedReflow(false);
930         toolkit.decorateFormHeading(mform.getForm().getForm());
931         MenuManager manager = new MenuManager();
932         IMenuListener listener = new IMenuListener() {
933             public void menuAboutToShow(IMenuManager manager) {
934                 contextMenuAboutToShow(manager);
935             }
936         };
937         manager.setRemoveAllWhenShown(true);
938         manager.addMenuListener(listener);
939         Menu contextMenu = manager.createContextMenu(form.getForm());
940         form.getForm().setMenu(contextMenu);
941         form.addListener(SWT.Activate, new Listener() {
942             public void handleEvent(Event event) {
943                 lastActiveInstance = ReusableHelpPart.this;
944             }
945         });
946         //contributeToDropDownMenu(mform.getForm().getForm().getMenuManager());
947
}
948
949     public HelpPartPage showPage(String JavaDoc id) {
950         if (currentPage != null && currentPage.getId().equals(id))
951             return currentPage;
952         HelpPartPage page = findPage(id);
953         if (page != null) {
954             boolean success = flipPages(currentPage, page);
955             return success ? page : null;
956         }
957         return null;
958     }
959
960     public HelpPartPage showPage(String JavaDoc id, boolean setFocus) {
961         HelpPartPage page = this.showPage(id);
962         if (page != null && setFocus)
963             page.setFocus();
964         return page;
965     }
966
967     public void startSearch(String JavaDoc phrase) {
968         showPage(IHelpUIConstants.HV_FSEARCH_PAGE, true);
969         SearchPart part = (SearchPart) findPart(IHelpUIConstants.HV_FSEARCH);
970         if (part != null && phrase != null)
971             part.startSearch(phrase);
972     }
973
974     public void showDynamicHelp(IWorkbenchPart wpart, Control c) {
975         showPage(IHelpUIConstants.HV_CONTEXT_HELP_PAGE, true);
976         RelatedTopicsPart part = (RelatedTopicsPart) findPart(IHelpUIConstants.HV_RELATED_TOPICS);
977         if (part != null) {
978             part.handleActivation(c, wpart);
979         }
980     }
981
982     private boolean flipPages(HelpPartPage oldPage, HelpPartPage newPage) {
983         if (newPage.canOpen() == false)
984             return false;
985         if (oldPage != null) {
986             oldPage.stop();
987             oldPage.setVisible(false);
988         }
989         mform.getForm().setText(newPage.getText());
990         mform.getForm().getForm().setSeparatorVisible(newPage.getText()!=null);
991         Image newImage=null;
992         String JavaDoc iconId = newPage.getIconId();
993         if (iconId != null)
994             newImage = HelpUIResources.getImage(iconId);
995         mform.getForm().setImage(newImage);
996         newPage.setVisible(true);
997         toolBarManager.update(true);
998         currentPage = newPage;
999         if (mform.isStale())
1000            mform.refresh();
1001        mform.getForm().getBody().layout(true);
1002        mform.reflow(true);
1003        if (newPage.getId().equals(IHelpUIConstants.HV_BROWSER_PAGE) == false) {
1004            if (!history.isBlocked()) {
1005                history.addEntry(new HistoryEntry(HistoryEntry.PAGE, newPage
1006                        .getId(), null));
1007            }
1008            updateNavigation();
1009        }
1010        return true;
1011    }
1012
1013    /*
1014     * void addPageHistoryEntry(String id, Object data) { if
1015     * (!history.isBlocked()) { history.addEntry(new
1016     * HistoryEntry(HistoryEntry.PAGE, id, data)); } updateNavigation(); }
1017     */

1018    public HelpPartPage getCurrentPage() {
1019        return currentPage;
1020    }
1021
1022    public String JavaDoc getCurrentPageId() {
1023        return currentPage != null ? currentPage.getId() : null;
1024    }
1025
1026    void browserChanged(String JavaDoc url) {
1027        if (!history.isBlocked()) {
1028            try {
1029                history.addEntry(new HistoryEntry(HistoryEntry.URL, url,
1030                        BaseHelpSystem.unresolve(new URL JavaDoc(url))));
1031            } catch (MalformedURLException JavaDoc e) {
1032                HelpUIPlugin.logError("Malformed URL: " + url, e); //$NON-NLS-1$
1033
}
1034        }
1035        updateNavigation();
1036    }
1037
1038    private void updateNavigation() {
1039        backAction.setEnabled(history.hasPrev());
1040        nextAction.setEnabled(history.hasNext());
1041        history.setBlocked(false);
1042    }
1043
1044    public boolean isMonitoringContextHelp() {
1045        return currentPage != null
1046                && currentPage.getId().equals(HV_CONTEXT_HELP_PAGE);
1047    }
1048
1049    public Control getControl() {
1050        return mform.getForm();
1051    }
1052
1053    public ManagedForm getForm() {
1054        return mform;
1055    }
1056
1057    public void reflow() {
1058        mform.getForm().getBody().layout();
1059        mform.reflow(true);
1060    }
1061
1062    public void dispose() {
1063        if (lastActiveInstance == this) {
1064            lastActiveInstance = null;
1065        }
1066        for (int i = 0; i < pages.size(); i++) {
1067            HelpPartPage page = (HelpPartPage) pages.get(i);
1068            page.dispose();
1069        }
1070        pages = null;
1071        if (mform != null) {
1072            mform.dispose();
1073            mform = null;
1074        }
1075        PlatformUI.getWorkbench().getActivitySupport().getActivityManager()
1076                .removeActivityManagerListener(this);
1077    }
1078
1079    /*
1080     * (non-Javadoc)
1081     *
1082     * @see org.eclipse.ui.internal.intro.impl.parts.IStandbyContentPart#setFocus()
1083     */

1084    public void setFocus() {
1085        if (currentPage != null)
1086            currentPage.setFocus();
1087        else
1088            mform.setFocus();
1089    }
1090
1091    public void update(IWorkbenchPart part, Control control) {
1092        mform.setInput(new ContextHelpProviderInput(null, null, control, part));
1093    }
1094
1095    public void update(IContextProvider provider, IContext context, IWorkbenchPart part,
1096            Control control) {
1097        mform.setInput(new ContextHelpProviderInput(provider, context, control, part));
1098    }
1099
1100    public void update(IContext context, IWorkbenchPart part, Control control) {
1101        mform.setInput(new ContextHelpProviderInput(null, context, control, part));
1102    }
1103
1104    private IHelpPart createPart(String JavaDoc id, IToolBarManager tbm) {
1105        IHelpPart part = null;
1106        Composite parent = mform.getForm().getBody();
1107
1108        part = findPart(id);
1109        if (part != null)
1110            return part;
1111
1112        if (id.equals(HV_TOPIC_TREE)) {
1113            part = new AllTopicsPart(parent, mform.getToolkit(), tbm);
1114        } else if (id.equals(HV_CONTEXT_HELP)) {
1115            part = new ContextHelpPart(parent, mform.getToolkit());
1116            ((ContextHelpPart) part)
1117                    .setDefaultText(getDefaultContextHelpText());
1118        } else if (id.equals(HV_RELATED_TOPICS)) {
1119            part = new RelatedTopicsPart(parent, mform.getToolkit());
1120            ((RelatedTopicsPart) part)
1121                    .setDefaultText(getDefaultContextHelpText());
1122        } else if (id.equals(HV_BROWSER)) {
1123            part = new BrowserPart(parent, mform.getToolkit(), tbm);
1124        } else if (id.equals(HV_SEARCH_RESULT)) {
1125            part = new DynamicHelpPart(parent, mform.getToolkit());
1126        } else if (id.equals(HV_FSEARCH_RESULT)) {
1127            part = new SearchResultsPart(parent, mform.getToolkit(), tbm);
1128        } else if (id.equals(HV_SEE_ALSO)) {
1129            part = new SeeAlsoPart(parent, mform.getToolkit());
1130        } else if (id.equals(HV_FSEARCH)) {
1131            part = new SearchPart(parent, mform.getToolkit());
1132        } else if (id.equals(HV_BOOKMARKS_TREE)) {
1133            part = new BookmarksPart(parent, mform.getToolkit(), tbm);
1134        } else if (id.equals(HV_INDEX)) {
1135            part = new IndexPart(parent, mform.getToolkit(), tbm);
1136        } else if (id.equals(HV_INDEX_TYPEIN)) {
1137            part = new IndexTypeinPart(parent, mform.getToolkit(), tbm);
1138        }
1139        if (part != null) {
1140            mform.addPart(part);
1141            part.init(this, id, memento);
1142        }
1143        return part;
1144    }
1145
1146    /**
1147     * @return Returns the runnableContext.
1148     */

1149    public IRunnableContext getRunnableContext() {
1150        return runnableContext;
1151    }
1152
1153    public boolean isInWorkbenchWindow() {
1154        return runnableContext instanceof IWorkbenchWindow;
1155    }
1156
1157    /**
1158     * @return Returns the defaultContextHelpText.
1159     */

1160    public String JavaDoc getDefaultContextHelpText() {
1161        return defaultContextHelpText;
1162    }
1163
1164    /**
1165     * @param defaultContextHelpText
1166     * The defaultContextHelpText to set.
1167     */

1168    public void setDefaultContextHelpText(String JavaDoc defaultContextHelpText) {
1169        this.defaultContextHelpText = defaultContextHelpText;
1170    }
1171
1172    public void showURL(final String JavaDoc url) {
1173        BusyIndicator.showWhile(getControl().getDisplay(), new Runnable JavaDoc() {
1174            public void run() {
1175                showURL(url, getShowDocumentsInPlace());
1176            }
1177        });
1178    }
1179
1180    public void showURL(String JavaDoc url, boolean replace) {
1181        if (url == null)
1182            return;
1183        if (url.startsWith("nw:")) { //$NON-NLS-1$
1184
replace = false;
1185            url = url.substring(3);
1186        }
1187        else if (url.startsWith("open:")) { //$NON-NLS-1$
1188
int col = url.indexOf(':');
1189            int qloc = url.indexOf('?');
1190            String JavaDoc engineId = url.substring(col+1, qloc);
1191            EngineDescriptor desc = getEngineManager().findEngine(engineId);
1192            if (desc==null)
1193                return;
1194            HashMap JavaDoc args = new HashMap JavaDoc();
1195            HelpURLConnection.parseQuery(url.substring(qloc+1), args);
1196            ((ISearchEngine2)desc.getEngine()).open((String JavaDoc)args.get("id")); //$NON-NLS-1$
1197
return;
1198        }
1199        if (replace) {
1200            if (openInternalBrowser(url))
1201                return;
1202        }
1203        showExternalURL(url);
1204    }
1205
1206    private boolean openInternalBrowser(String JavaDoc url) {
1207        Preferences pref = HelpBasePlugin.getDefault().getPluginPreferences();
1208        boolean openInEditor = pref.getBoolean(IHelpBaseConstants.P_KEY_OPEN_IN_EDITOR);
1209        Shell windowShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1210        Shell helpShell = mform.getForm().getShell();
1211        boolean isDialog = (helpShell != windowShell);
1212        if (!isDialog && openInEditor) {
1213            return DefaultHelpUI.showInWorkbenchBrowser(url, true);
1214        }
1215        showPage(IHelpUIConstants.HV_BROWSER_PAGE);
1216        BrowserPart bpart = (BrowserPart) findPart(IHelpUIConstants.HV_BROWSER);
1217        if (bpart != null) {
1218            bpart.showURL(BaseHelpSystem
1219                    .resolve(url, "/help/ntopic").toString()); //$NON-NLS-1$
1220
return true;
1221        }
1222        return false;
1223    }
1224
1225    public void showExternalURL(String JavaDoc url) {
1226        if (isHelpResource(url))
1227            PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(url);
1228        else {
1229            try {
1230                String JavaDoc aurl = BaseHelpSystem.resolve(url, true).toString();
1231                if (aurl.endsWith("&noframes=true") || aurl.endsWith("?noframes=true")) //$NON-NLS-1$ //$NON-NLS-2$
1232
aurl = aurl.substring(0, aurl.length() - 14);
1233                DefaultHelpUI.showInWorkbenchBrowser(aurl, false);
1234            } catch (Exception JavaDoc e) {
1235                HelpUIPlugin.logError("Error opening browser", e); //$NON-NLS-1$
1236
}
1237        }
1238    }
1239
1240    public IHelpPart findPart(String JavaDoc id) {
1241        if (mform == null)
1242            return null;
1243        IFormPart[] parts = mform.getParts();
1244        for (int i = 0; i < parts.length; i++) {
1245            IHelpPart part = (IHelpPart) parts[i];
1246            if (part.getId().equals(id))
1247                return part;
1248        }
1249        return null;
1250    }
1251
1252    public boolean isHelpResource(String JavaDoc url) {
1253        if (url == null || url.indexOf("://") == -1) //$NON-NLS-1$
1254
return true;
1255        return false;
1256    }
1257
1258    private void contextMenuAboutToShow(IMenuManager manager) {
1259        IFormPart[] parts = mform.getParts();
1260        boolean hasContext = false;
1261        Control focusControl = getControl().getDisplay().getFocusControl();
1262        for (int i = 0; i < parts.length; i++) {
1263            IHelpPart part = (IHelpPart) parts[i];
1264            if (part.hasFocusControl(focusControl)) {
1265                hasContext = part.fillContextMenu(manager);
1266                break;
1267            }
1268        }
1269        if (hasContext)
1270            manager.add(new Separator());
1271        manager.add(backAction);
1272        manager.add(nextAction);
1273        manager.add(new Separator());
1274        manager.add(openInfoCenterAction);
1275    }
1276
1277    private void contributeToDropDownMenu(IMenuManager manager) {
1278        addPageAction(manager, IHelpUIConstants.HV_CONTEXT_HELP_PAGE);
1279        addPageAction(manager, IHelpUIConstants.HV_ALL_TOPICS_PAGE);
1280        addPageAction(manager, IHelpUIConstants.HV_INDEX_PAGE);
1281        addPageAction(manager, IHelpUIConstants.HV_FSEARCH_PAGE);
1282        addPageAction(manager, IHelpUIConstants.HV_BOOKMARKS_PAGE);
1283    }
1284
1285    private void addPageAction(IMenuManager manager, final String JavaDoc pageId) {
1286        // String cid = getCurrentPageId();
1287
HelpPartPage page = findPage(pageId);
1288        if (page == null)
1289            return;
1290        Action action = new Action(pageId, IAction.AS_CHECK_BOX) {
1291            public void run() {
1292                BusyIndicator.showWhile(mform.getForm().getDisplay(),
1293                        new Runnable JavaDoc() {
1294                            public void run() {
1295                                showPage(pageId);
1296                            }
1297                        });
1298            }
1299        };
1300        action.setText(page.getText());
1301        String JavaDoc iconId = page.getIconId();
1302        if (iconId != null)
1303            action.setImageDescriptor(HelpUIResources
1304                    .getImageDescriptor(iconId));
1305        manager.add(action);
1306        page.pageAction = action;
1307    }
1308
1309    private HelpPartPage findPage(String JavaDoc id) {
1310        for (int i = 0; i < pages.size(); i++) {
1311            HelpPartPage page = (HelpPartPage) pages.get(i);
1312            if (page.getId().equals(id)) {
1313                return page;
1314            }
1315        }
1316        return null;
1317    }
1318
1319    boolean fillSelectionProviderMenu(ISelectionProvider provider,
1320            IMenuManager manager, boolean addBookmarks) {
1321        boolean value = fillOpenActions(provider, manager);
1322        if (value && addBookmarks) {
1323            manager.add(new Separator());
1324            bookmarkAction.setTarget(provider);
1325            manager.add(bookmarkAction);
1326        }
1327        return true;
1328    }
1329
1330    private boolean fillOpenActions(Object JavaDoc target, IMenuManager manager) {
1331        String JavaDoc href = getHref(target);
1332        if (href != null && !href.startsWith("__")) { //$NON-NLS-1$
1333
openAction.setTarget(target);
1334            openInHelpAction.setTarget(target);
1335            manager.add(openAction);
1336            if (!href.startsWith("nw:")) //$NON-NLS-1$
1337
manager.add(openInHelpAction);
1338            return true;
1339        }
1340        return false;
1341    }
1342
1343    void hookFormText(FormText text) {
1344        copyAction.hook(text);
1345    }
1346
1347    void unhookFormText(FormText text) {
1348        copyAction.unhook(text);
1349    }
1350
1351    boolean fillFormContextMenu(FormText text, IMenuManager manager) {
1352        if (fillOpenActions(text, manager))
1353            manager.add(new Separator());
1354        manager.add(copyAction);
1355        copyAction.setTarget(text);
1356        if (text.getSelectedLinkHref() != null) {
1357            manager.add(new Separator());
1358            manager.add(bookmarkAction);
1359            bookmarkAction.setTarget(getResource(text));
1360        }
1361        return true;
1362    }
1363
1364    IAction getCopyAction() {
1365        return copyAction;
1366    }
1367
1368    private String JavaDoc getHref(Object JavaDoc target) {
1369        if (target instanceof ISelectionProvider) {
1370            ISelectionProvider provider = (ISelectionProvider) target;
1371            IStructuredSelection ssel = (IStructuredSelection) provider
1372                    .getSelection();
1373            Object JavaDoc obj = ssel.getFirstElement();
1374            if (obj instanceof IToc)
1375                return null;
1376            if (obj instanceof IHelpResource) {
1377                IHelpResource res = (IHelpResource) obj;
1378                return res.getHref();
1379            }
1380            if (obj instanceof IIndexEntry) {
1381                /*
1382                 * if index entry has single topic
1383                 * it represents the topic by itself
1384                 */

1385                IHelpResource[] topics = ((IIndexEntry) obj).getTopics();
1386                if (topics.length == 1)
1387                    return topics[0].getHref();
1388                return null;
1389            }
1390        } else if (target instanceof FormText) {
1391            FormText text = (FormText) target;
1392            Object JavaDoc href = text.getSelectedLinkHref();
1393            if (href != null)
1394                return href.toString();
1395        }
1396        return null;
1397    }
1398
1399    private IHelpResource getResource(Object JavaDoc target) {
1400        if (target instanceof ISelectionProvider) {
1401            ISelectionProvider provider = (ISelectionProvider) target;
1402            IStructuredSelection ssel = (IStructuredSelection) provider
1403                    .getSelection();
1404            Object JavaDoc obj = ssel.getFirstElement();
1405            if (obj instanceof ITopic) {
1406                return (ITopic) obj;
1407            } else if (obj instanceof IIndexEntry) {
1408                /*
1409                 * if index entry has single topic
1410                 * it represents the topic by itself
1411                 */

1412                IIndexEntry entry = (IIndexEntry) obj;
1413                IHelpResource[] topics = entry.getTopics();
1414                if (topics.length == 1) {
1415                    final String JavaDoc href = topics[0].getHref();
1416                    final String JavaDoc label = entry.getKeyword();
1417                    return new IHelpResource() {
1418                        public String JavaDoc getHref() {
1419                            return href;
1420                        }
1421
1422                        public String JavaDoc getLabel() {
1423                            return label;
1424                        }
1425                    };
1426                }
1427                return null;
1428            } else if (obj instanceof IHelpResource) {
1429                return (IHelpResource) obj;
1430            }
1431        } else if (target instanceof FormText) {
1432            FormText text = (FormText) target;
1433            final String JavaDoc href = LinkUtil.stripParams(text.getSelectedLinkHref().toString());
1434            final String JavaDoc label = text.getSelectedLinkText();
1435            if (href != null) {
1436                return new IHelpResource() {
1437                    public String JavaDoc getHref() {
1438                        return href;
1439                    }
1440
1441                    public String JavaDoc getLabel() {
1442                        return label;
1443                    }
1444                };
1445            }
1446        }
1447        return null;
1448    }
1449
1450    private void doBookmark(Object JavaDoc target) {
1451        IHelpResource res = null;
1452        if (target instanceof IHelpResource) {
1453            res = (IHelpResource)target;
1454        }
1455        else {
1456            res = getResource(target);
1457        }
1458        if (res != null) {
1459            BaseHelpSystem.getBookmarkManager().addBookmark(res.getHref(),
1460                    res.getLabel());
1461        }
1462    }
1463
1464    /*
1465     * private void doOpen(Object target) { String href = getHref(target); if
1466     * (href != null) showURL(href, getShowDocumentsInPlace()); }
1467     */

1468
1469    private void doOpen(Object JavaDoc target, boolean replace) {
1470        String JavaDoc href = getHref(target);
1471        if (href != null)
1472            showURL(href, replace);
1473    }
1474
1475    private void doOpenInHelp(Object JavaDoc target) {
1476        String JavaDoc href = getHref(target);
1477        if (href != null)
1478            // WorkbenchHelp.displayHelpResource(href);
1479
showURL(href, false);
1480    }
1481
1482    /**
1483     * @return Returns the statusLineManager.
1484     */

1485    public IStatusLineManager getStatusLineManager() {
1486        return statusLineManager;
1487    }
1488
1489    /**
1490     * @return Returns the showDocumentsInPlace.
1491     */

1492    public boolean getShowDocumentsInPlace() {
1493        return showDocumentsInPlace;
1494    }
1495
1496    /**
1497     * @param showDocumentsInPlace
1498     * The showDocumentsInPlace to set.
1499     */

1500    public void setShowDocumentsInPlace(boolean showDocumentsInPlace) {
1501        this.showDocumentsInPlace = showDocumentsInPlace;
1502    }
1503
1504    /**
1505     * @return Returns the style.
1506     */

1507    public int getStyle() {
1508        return style;
1509    }
1510
1511    public int getNumberOfInPlaceHits() {
1512        return numberOfInPlaceHits;
1513    }
1514
1515    public void setNumberOfInPlaceHits(int numberOfInPlaceHits) {
1516        this.numberOfInPlaceHits = numberOfInPlaceHits;
1517    }
1518
1519    void handleLinkEntered(HyperlinkEvent e) {
1520        IStatusLineManager mng = getRoot(getStatusLineManager());
1521        if (mng != null) {
1522            String JavaDoc label = e.getLabel();
1523            String JavaDoc href = (String JavaDoc) e.getHref();
1524            if (href != null && href.startsWith("__")) //$NON-NLS-1$
1525
href = null;
1526            if (href != null) {
1527                try {
1528                    href = URLDecoder.decode(href, "UTF-8"); //$NON-NLS-1$
1529
} catch (UnsupportedEncodingException JavaDoc ex) {
1530                }
1531                href = href.replaceAll("&", "&&"); //$NON-NLS-1$ //$NON-NLS-2$
1532
}
1533            if (label != null && href != null) {
1534                String JavaDoc message = NLS.bind(Messages.ReusableHelpPart_status,
1535                        label, href);
1536                mng.setMessage(message);
1537            } else if (label != null)
1538                mng.setMessage(label);
1539            else
1540                mng.setMessage(href);
1541        }
1542    }
1543
1544    private IStatusLineManager getRoot(IStatusLineManager mng) {
1545        while (mng != null) {
1546            if (mng instanceof SubStatusLineManager) {
1547                SubStatusLineManager smng = (SubStatusLineManager) mng;
1548                IContributionManager parent = smng.getParent();
1549                if (parent == null)
1550                    return smng;
1551                if (!(parent instanceof IStatusLineManager))
1552                    return smng;
1553                mng = (IStatusLineManager) parent;
1554            } else
1555                break;
1556        }
1557        return mng;
1558    }
1559
1560    void handleLinkExited(HyperlinkEvent e) {
1561        IStatusLineManager mng = getRoot(getStatusLineManager());
1562        if (mng != null)
1563            mng.setMessage(null);
1564    }
1565
1566    String JavaDoc escapeSpecialChars(String JavaDoc value) {
1567        return escapeSpecialChars(value, false);
1568    }
1569
1570    String JavaDoc escapeSpecialChars(String JavaDoc value, boolean leaveBold) {
1571        StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
1572        for (int i = 0; i < value.length(); i++) {
1573            char c = value.charAt(i);
1574
1575            switch (c) {
1576            case '&':
1577                buf.append("&amp;"); //$NON-NLS-1$
1578
break;
1579            case '<':
1580                if (leaveBold) {
1581                    int length = value.length();
1582                    if (i + 6 < length) {
1583                        String JavaDoc tag = value.substring(i, i+7);
1584                        if (tag.equalsIgnoreCase("</code>")) { //$NON-NLS-1$
1585
buf.append("</span>"); //$NON-NLS-1$
1586
i+= 6;
1587                            continue;
1588                        }
1589                    }
1590                    if (i + 5 < length) {
1591                        String JavaDoc tag = value.substring(i, i+6);
1592                        if (tag.equalsIgnoreCase("<code>")) { //$NON-NLS-1$
1593
buf.append("<span font=\"code\">"); //$NON-NLS-1$
1594
i+= 5;
1595                            continue;
1596                        }
1597                    }
1598                    if (i + 3 < length) {
1599                        String JavaDoc tag = value.substring(i, i + 4);
1600                        if (tag.equalsIgnoreCase("</b>")) { //$NON-NLS-1$
1601
buf.append(tag);
1602                            i += 3;
1603                            continue;
1604                        }
1605                        if (tag.equalsIgnoreCase("<br>")) { //$NON-NLS-1$
1606
buf.append("<br/>"); //$NON-NLS-1$
1607
i+= 3;
1608                            continue;
1609                        }
1610                    }
1611                    if (i + 2 < length) {
1612                        String JavaDoc tag = value.substring(i, i + 3);
1613                        if (tag.equalsIgnoreCase("<b>")) { //$NON-NLS-1$
1614
buf.append(tag);
1615                            i += 2;
1616                            continue;
1617                        }
1618                    }
1619                }
1620                buf.append("&lt;"); //$NON-NLS-1$
1621
break;
1622            case '>':
1623                buf.append("&gt;"); //$NON-NLS-1$
1624
break;
1625            case '\'':
1626                buf.append("&apos;"); //$NON-NLS-1$
1627
break;
1628            case '\"':
1629                buf.append("&quot;"); //$NON-NLS-1$
1630
break;
1631            case 160:
1632                buf.append(" "); //$NON-NLS-1$
1633
break;
1634            default:
1635                buf.append(c);
1636                break;
1637            }
1638        }
1639        return buf.toString();
1640    }
1641
1642    private void toggleShowAll(boolean checked) {
1643        if (checked) {
1644            IPreferenceStore store = HelpUIPlugin.getDefault()
1645                    .getPreferenceStore();
1646            String JavaDoc value = store.getString(PROMPT_KEY);
1647            if (value.length() == 0) {
1648                MessageDialogWithToggle dialog = MessageDialogWithToggle
1649                        .openOkCancelConfirm(null,
1650                                Messages.AskShowAll_dialogTitle,
1651                                getShowAllMessage(),
1652                                Messages.AskShowAll_toggleMessage, false,
1653                                store, PROMPT_KEY);
1654                if (dialog.getReturnCode() != MessageDialogWithToggle.OK) {
1655                    showAllAction.setChecked(false);
1656                    return;
1657                }
1658            }
1659        }
1660        HelpBasePlugin.getActivitySupport().setFilteringEnabled(!checked);
1661        for (int i = 0; i < pages.size(); i++) {
1662            HelpPartPage page = (HelpPartPage) pages.get(i);
1663            page.toggleRoleFilter();
1664        }
1665    }
1666    
1667    public void saveState(IMemento memento) {
1668        for (int i = 0; i < pages.size(); i++) {
1669            HelpPartPage page = (HelpPartPage) pages.get(i);
1670            page.saveState(memento);
1671        }
1672    }
1673
1674    private String JavaDoc getShowAllMessage() {
1675        String JavaDoc message = HelpBasePlugin.getActivitySupport()
1676                .getShowAllMessage();
1677        if (message == null)
1678            return Messages.AskShowAll_message;
1679        StringBuffer JavaDoc buff = new StringBuffer JavaDoc();
1680        int state = STATE_START;
1681
1682        for (int i = 0; i < message.length(); i++) {
1683            char c = message.charAt(i);
1684            switch (state) {
1685            case STATE_START:
1686                if (c == '<')
1687                    state = STATE_LT;
1688                else
1689                    buff.append(c);
1690                break;
1691            case STATE_LT:
1692                if (c == 'b' || c == 'B')
1693                    state = STATE_LT_B;
1694                break;
1695            case STATE_LT_B:
1696                if (c == 'r' || c == 'R')
1697                    state = STATE_LT_BR;
1698                break;
1699            case STATE_LT_BR:
1700                if (c == '>') {
1701                    buff.append('\n');
1702                }
1703                state = STATE_START;
1704                break;
1705            default:
1706                buff.append(c);
1707            }
1708        }
1709        return buff.toString();
1710    }
1711    
1712    EngineDescriptorManager getEngineManager() {
1713        if (engineManager==null) {
1714            engineManager = new EngineDescriptorManager();
1715        }
1716        return engineManager;
1717    }
1718
1719    static public int getDefaultStyle() {
1720        int style = ALL_TOPICS | CONTEXT_HELP | SEARCH;
1721        if (ProductPreferences.getBoolean(HelpBasePlugin.getDefault(), "indexView")) { //$NON-NLS-1$
1722
style |= INDEX;
1723        }
1724        if (ProductPreferences.getBoolean(HelpBasePlugin.getDefault(), "bookmarksView")) { //$NON-NLS-1$
1725
style |= BOOKMARKS;
1726        }
1727        return style;
1728    }
1729}
1730
1731
Popular Tags