KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > browser > BrowserViewer


1 /*******************************************************************************
2  * Copyright (c) 2004, 2006 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.browser;
12
13 import java.beans.PropertyChangeEvent JavaDoc;
14 import java.beans.PropertyChangeListener JavaDoc;
15 import java.io.File JavaDoc;
16 import java.util.ArrayList JavaDoc;
17 import java.util.List JavaDoc;
18
19 import org.eclipse.core.runtime.IProgressMonitor;
20 import org.eclipse.jface.action.IStatusLineManager;
21 import org.eclipse.swt.SWT;
22 import org.eclipse.swt.SWTError;
23 import org.eclipse.swt.SWTException;
24 import org.eclipse.swt.browser.Browser;
25 import org.eclipse.swt.browser.CloseWindowListener;
26 import org.eclipse.swt.browser.LocationEvent;
27 import org.eclipse.swt.browser.LocationListener;
28 import org.eclipse.swt.browser.OpenWindowListener;
29 import org.eclipse.swt.browser.ProgressEvent;
30 import org.eclipse.swt.browser.ProgressListener;
31 import org.eclipse.swt.browser.StatusTextEvent;
32 import org.eclipse.swt.browser.StatusTextListener;
33 import org.eclipse.swt.browser.TitleEvent;
34 import org.eclipse.swt.browser.TitleListener;
35 import org.eclipse.swt.browser.VisibilityWindowListener;
36 import org.eclipse.swt.browser.WindowEvent;
37 import org.eclipse.swt.dnd.Clipboard;
38 import org.eclipse.swt.events.MouseEvent;
39 import org.eclipse.swt.events.MouseListener;
40 import org.eclipse.swt.events.SelectionAdapter;
41 import org.eclipse.swt.events.SelectionEvent;
42 import org.eclipse.swt.layout.FillLayout;
43 import org.eclipse.swt.layout.GridData;
44 import org.eclipse.swt.layout.GridLayout;
45 import org.eclipse.swt.widgets.Combo;
46 import org.eclipse.swt.widgets.Composite;
47 import org.eclipse.swt.widgets.Display;
48 import org.eclipse.swt.widgets.Event;
49 import org.eclipse.swt.widgets.Listener;
50 import org.eclipse.swt.widgets.Shell;
51 import org.eclipse.swt.widgets.ToolBar;
52 import org.eclipse.swt.widgets.ToolItem;
53 import org.eclipse.ui.PlatformUI;
54
55 /**
56  * A Web browser widget. It extends the Eclipse SWT Browser widget by adding an
57  * optional toolbar complete with a URL combo box, history, back & forward, and
58  * refresh buttons.
59  * <p>
60  * Use the style bits to choose which toolbars are available within the browser
61  * composite. You can access the embedded SWT Browser directly using the
62  * getBrowser() method.
63  * </p>
64  * <p>
65  * Additional capabilities are available when used as the internal Web browser,
66  * including status text and progress on the Eclipse window's status line, or
67  * moving the toolbar capabilities up into the main toolbar.
68  * </p>
69  * <dl>
70  * <dt><b>Styles:</b></dt>
71  * <dd>LOCATION_BAR, BUTTON_BAR</dd>
72  * <dt><b>Events:</b></dt>
73  * <dd>None</dd>
74  * </dl>
75  *
76  * @since 1.0
77  */

78 public class BrowserViewer extends Composite {
79     /**
80      * Style parameter (value 1) indicating that the URL and Go button will be
81      * on the local toolbar.
82      */

83     public static final int LOCATION_BAR = 1 << 1;
84
85     /**
86      * Style parameter (value 2) indicating that the toolbar will be available
87      * on the web browser. This style parameter cannot be used without the
88      * LOCATION_BAR style.
89      */

90     public static final int BUTTON_BAR = 1 << 2;
91      
92      protected static final String JavaDoc PROPERTY_TITLE = "title"; //$NON-NLS-1$
93

94     private static final int MAX_HISTORY = 50;
95
96     public Clipboard clipboard;
97
98     public Combo combo;
99
100     protected boolean showToolbar;
101
102     protected boolean showURLbar;
103
104     protected ToolItem back;
105
106     protected ToolItem forward;
107
108     protected BusyIndicator busy;
109
110     protected boolean loading;
111
112     protected static java.util.List JavaDoc history;
113
114     protected Browser browser;
115     
116     protected BrowserText text;
117
118     protected boolean newWindow;
119
120     protected IBrowserViewerContainer container;
121
122     protected String JavaDoc title;
123
124     protected int progressWorked = 0;
125      
126      protected List JavaDoc propertyListeners;
127
128     /**
129      * Under development - do not use
130      */

131     public static interface ILocationListener {
132         public void locationChanged(String JavaDoc url);
133
134         public void historyChanged(String JavaDoc[] history2);
135     }
136
137     public ILocationListener locationListener;
138
139     /**
140      * Under development - do not use
141      */

142     public static interface IBackNextListener {
143         public void updateBackNextBusy();
144     }
145
146     public IBackNextListener backNextListener;
147
148     /**
149      * Creates a new Web browser given its parent and a style value describing
150      * its behavior and appearance.
151      * <p>
152      * The style value is either one of the style constants defined in the class
153      * header or class <code>SWT</code> which is applicable to instances of
154      * this class, or must be built by <em>bitwise OR</em>'ing together (that
155      * is, using the <code>int</code> "|" operator) two or more of those
156      * <code>SWT</code> style constants. The class description lists the style
157      * constants that are applicable to the class. Style bits are also inherited
158      * from superclasses.
159      * </p>
160      *
161      * @param parent
162      * a composite control which will be the parent of the new
163      * instance (cannot be null)
164      * @param style
165      * the style of control to construct
166      */

167     public BrowserViewer(Composite parent, int style) {
168         super(parent, SWT.NONE);
169           
170         if ((style & LOCATION_BAR) != 0)
171             showURLbar = true;
172
173         if ((style & BUTTON_BAR) != 0)
174             showToolbar = true;
175
176         GridLayout layout = new GridLayout();
177         layout.marginHeight = 0;
178         layout.marginWidth = 0;
179         layout.horizontalSpacing = 0;
180         layout.verticalSpacing = 0;
181         layout.numColumns = 1;
182         setLayout(layout);
183         setLayoutData(new GridData(GridData.FILL_BOTH));
184         clipboard = new Clipboard(parent.getDisplay());
185         
186         if (showToolbar || showURLbar) {
187             Composite toolbarComp = new Composite(this, SWT.NONE);
188             toolbarComp.setLayout(new ToolbarLayout());
189             toolbarComp.setLayoutData(new GridData(
190                   GridData.VERTICAL_ALIGN_BEGINNING
191                   | GridData.FILL_HORIZONTAL));
192
193             if (showToolbar)
194                 createToolbar(toolbarComp);
195             
196                 if (showURLbar)
197                 createLocationBar(toolbarComp);
198
199                 if (showToolbar | showURLbar) {
200                     busy = new BusyIndicator(toolbarComp, SWT.NONE);
201                     busy.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
202                     busy.addMouseListener(new MouseListener() {
203                         public void mouseDoubleClick(MouseEvent e) {
204                             // ignore
205
}
206
207                         public void mouseDown(MouseEvent e) {
208                             setURL("http://www.eclipse.org"); //$NON-NLS-1$
209
}
210
211                         public void mouseUp(MouseEvent e) {
212                             // ignore
213
}
214                     });
215                 }
216                 PlatformUI.getWorkbench().getHelpSystem().setHelp(this,
217                   ContextIds.WEB_BROWSER);
218         }
219
220         // create a new SWT Web browser widget, checking once again to make sure
221
// we can use it in this environment
222
//if (WebBrowserUtil.canUseInternalWebBrowser())
223
try {
224             this.browser = new Browser(this, SWT.NONE);
225         }
226         catch (SWTError e) {
227             if (e.code!=SWT.ERROR_NO_HANDLES) {
228                 WebBrowserUtil.openError(Messages.errorCouldNotLaunchInternalWebBrowser);
229                 return;
230             }
231             text = new BrowserText(this, this, e);
232         }
233
234         if (showURLbar)
235             updateHistory();
236         if (showToolbar)
237             updateBackNextBusy();
238
239          if (browser!=null) {
240             browser.setLayoutData(new GridData(GridData.FILL_BOTH));
241             PlatformUI.getWorkbench().getHelpSystem().setHelp(browser,
242                     ContextIds.WEB_BROWSER);
243         }
244         else
245             text.getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
246
247         addBrowserListeners();
248         //listen();
249
}
250
251     /**
252      * Returns the underlying SWT browser widget.
253      *
254      * @return the underlying browser
255      */

256     public Browser getBrowser() {
257         return browser;
258     }
259
260     /**
261      * Navigate to the home URL.
262      */

263     public void home() {
264      browser.setText(""); //$NON-NLS-1$
265
}
266
267     /**
268      * Loads a URL.
269      *
270      * @param url
271      * the URL to be loaded
272      * @return true if the operation was successful and false otherwise.
273      * @exception IllegalArgumentException
274      * <ul>
275      * <li>ERROR_NULL_ARGUMENT - if the url is null</li>
276      * </ul>
277      * @exception SWTException
278      * <ul>
279      * <li>ERROR_THREAD_INVALID_ACCESS when called from the
280      * wrong thread</li>
281      * <li>ERROR_WIDGET_DISPOSED when the widget has been
282      * disposed</li>
283      * </ul>
284      * @see #getURL()
285      */

286     public void setURL(String JavaDoc url) {
287        setURL(url, true);
288     }
289
290     protected void updateBackNextBusy() {
291         back.setEnabled(isBackEnabled());
292         forward.setEnabled(isForwardEnabled());
293         busy.setBusy(loading);
294
295         if (backNextListener != null)
296             backNextListener.updateBackNextBusy();
297     }
298
299     protected void updateLocation() {
300         if (locationListener != null)
301             locationListener.historyChanged(null);
302
303         if (locationListener != null)
304             locationListener.locationChanged(null);
305     }
306
307     /**
308      *
309      */

310     private void addBrowserListeners() {
311         if (browser==null) return;
312         // respond to ExternalBrowserInstance StatusTextEvents events by
313
// updating the status line
314
browser.addStatusTextListener(new StatusTextListener() {
315             public void changed(StatusTextEvent event) {
316                     //System.out.println("status: " + event.text); //$NON-NLS-1$
317
if (container != null) {
318                     IStatusLineManager status = container.getActionBars()
319                             .getStatusLineManager();
320                     status.setMessage(event.text);
321                 }
322             }
323         });
324
325         // Add listener for new window creation so that we can instead of
326
// opening a separate
327
// new window in which the session is lost, we can instead open a new
328
// window in a new
329
// shell within the browser area thereby maintaining the session.
330
browser.addOpenWindowListener(new OpenWindowListener() {
331             public void open(WindowEvent event) {
332                 Shell shell2 = new Shell(getShell());
333                 shell2.setLayout(new FillLayout());
334                 shell2.setText(Messages.viewWebBrowserTitle);
335                 shell2.setImage(getShell().getImage());
336                 if (event.location != null)
337                     shell2.setLocation(event.location);
338                 if (event.size != null)
339                     shell2.setSize(event.size);
340                      int style = 0;
341                      if (event.addressBar)
342                          style += LOCATION_BAR;
343                      if (event.toolBar)
344                          style += BUTTON_BAR;
345                 BrowserViewer browser2 = new BrowserViewer(shell2, 0);
346                 browser2.newWindow = true;
347                 event.browser = browser2.browser;
348             }
349         });
350           
351           browser.addVisibilityWindowListener(new VisibilityWindowListener() {
352                 public void hide(WindowEvent e) {
353                     // ignore
354
}
355                 
356                 public void show(WindowEvent e) {
357                     Browser browser2 = (Browser)e.widget;
358                     if (browser2.getParent().getParent() instanceof Shell) {
359                         Shell shell = (Shell) browser2.getParent().getParent();
360                         if (e.location != null)
361                             shell.setLocation(e.location);
362                         if (e.size != null)
363                             shell.setSize(shell.computeSize(e.size.x, e.size.y));
364                         shell.open();
365                     }
366                 }
367             });
368
369         browser.addCloseWindowListener(new CloseWindowListener() {
370             public void close(WindowEvent event) {
371                 // if shell is not null, it must be a secondary popup window,
372
// else its an editor window
373
if (newWindow)
374                     getShell().dispose();
375                 else
376                     container.close();
377             }
378         });
379
380         browser.addProgressListener(new ProgressListener() {
381             public void changed(ProgressEvent event) {
382                     //System.out.println("progress: " + event.current + ", " + event.total); //$NON-NLS-1$ //$NON-NLS-2$
383
if (event.total == 0)
384                     return;
385
386                 boolean done = (event.current == event.total);
387
388                 int percentProgress = event.current * 100 / event.total;
389                 if (container != null) {
390                     IProgressMonitor monitor = container.getActionBars()
391                             .getStatusLineManager().getProgressMonitor();
392                     if (done) {
393                         monitor.done();
394                         progressWorked = 0;
395                     } else if (progressWorked == 0) {
396                         monitor.beginTask("", event.total); //$NON-NLS-1$
397
progressWorked = percentProgress;
398                     } else {
399                         monitor.worked(event.current - progressWorked);
400                         progressWorked = event.current;
401                     }
402                 }
403
404                 if (showToolbar) {
405                     if (!busy.isBusy() && !done)
406                         loading = true;
407                     else if (busy.isBusy() && done) // once the progress hits
408
// 100 percent, done, set
409
// busy to false
410
loading = false;
411
412                           //System.out.println("loading: " + loading); //$NON-NLS-1$
413
updateBackNextBusy();
414                     updateHistory();
415                 }
416             }
417
418             public void completed(ProgressEvent event) {
419                 if (container != null) {
420                     IProgressMonitor monitor = container.getActionBars()
421                             .getStatusLineManager().getProgressMonitor();
422                     monitor.done();
423                 }
424                 if (showToolbar) {
425                     loading = false;
426                     updateBackNextBusy();
427                     updateHistory();
428                 }
429             }
430         });
431
432         if (showToolbar) {
433             browser.addLocationListener(new LocationListener() {
434                 public void changed(LocationEvent event) {
435                     if (!event.top)
436                         return;
437                     if (combo != null) {
438                         if (!"about:blank".equals(event.location)) { //$NON-NLS-1$
439
combo.setText(event.location);
440                             addToHistory(event.location);
441                             updateHistory();
442                         }// else
443
// combo.setText(""); //$NON-NLS-1$
444
}
445                 }
446
447                 public void changing(LocationEvent event) {
448                     // do nothing
449
}
450             });
451         }
452
453         browser.addTitleListener(new TitleListener() {
454             public void changed(TitleEvent event) {
455                      String JavaDoc oldTitle = title;
456                 title = event.title;
457                      firePropertyChangeEvent(PROPERTY_TITLE, oldTitle, title);
458             }
459         });
460     }
461      
462      /**
463          * Add a property change listener to this instance.
464          *
465          * @param listener java.beans.PropertyChangeListener
466          */

467         public void addPropertyChangeListener(PropertyChangeListener JavaDoc listener) {
468             if (propertyListeners == null)
469                 propertyListeners = new ArrayList JavaDoc();
470             propertyListeners.add(listener);
471         }
472
473         /**
474          * Remove a property change listener from this instance.
475          *
476          * @param listener java.beans.PropertyChangeListener
477          */

478         public void removePropertyChangeListener(PropertyChangeListener JavaDoc listener) {
479             if (propertyListeners != null)
480                 propertyListeners.remove(listener);
481         }
482
483         /**
484          * Fire a property change event.
485          */

486         protected void firePropertyChangeEvent(String JavaDoc propertyName, Object JavaDoc oldValue, Object JavaDoc newValue) {
487             if (propertyListeners == null)
488                 return;
489
490             PropertyChangeEvent JavaDoc event = new PropertyChangeEvent JavaDoc(this, propertyName, oldValue, newValue);
491             //Trace.trace("Firing: " + event + " " + oldValue);
492
try {
493                 int size = propertyListeners.size();
494                 PropertyChangeListener JavaDoc[] pcl = new PropertyChangeListener JavaDoc[size];
495                 propertyListeners.toArray(pcl);
496                 
497                 for (int i = 0; i < size; i++)
498                     try {
499                         pcl[i].propertyChange(event);
500                     } catch (Exception JavaDoc e) {
501                         // ignore
502
}
503             } catch (Exception JavaDoc e) {
504                 // ignore
505
}
506         }
507
508     /**
509      * Navigate to the next session history item. Convenience method that calls
510      * the underlying SWT browser.
511      *
512      * @return <code>true</code> if the operation was successful and
513      * <code>false</code> otherwise
514      * @exception SWTException
515      * <ul>
516      * <li>ERROR_THREAD_INVALID_ACCESS when called from the
517      * wrong thread</li>
518      * <li>ERROR_WIDGET_DISPOSED when the widget has been
519      * disposed</li>
520      * </ul>
521      * @see #back
522      */

523     public boolean forward() {
524         if (browser==null)
525             return false;
526         return browser.forward();
527     }
528
529     /**
530      * Navigate to the previous session history item. Convenience method that
531      * calls the underlying SWT browser.
532      *
533      * @return <code>true</code> if the operation was successful and
534      * <code>false</code> otherwise
535      * @exception SWTException
536      * <ul>
537      * <li>ERROR_THREAD_INVALID_ACCESS when called from the
538      * wrong thread</li>
539      * <li>ERROR_WIDGET_DISPOSED when the widget has been
540      * disposed</li>
541      * </ul>
542      * @see #forward
543      */

544     public boolean back() {
545         if (browser==null)
546             return false;
547         return browser.back();
548     }
549
550     /**
551      * Returns <code>true</code> if the receiver can navigate to the previous
552      * session history item, and <code>false</code> otherwise. Convenience
553      * method that calls the underlying SWT browser.
554      *
555      * @return the receiver's back command enabled state
556      * @exception SWTException
557      * <ul>
558      * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
559      * disposed</li>
560      * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
561      * thread that created the receiver</li>
562      * </ul>
563      * @see #back
564      */

565     public boolean isBackEnabled() {
566         if (browser==null)
567             return false;
568         return browser.isBackEnabled();
569     }
570
571     /**
572      * Returns <code>true</code> if the receiver can navigate to the next
573      * session history item, and <code>false</code> otherwise. Convenience
574      * method that calls the underlying SWT browser.
575      *
576      * @return the receiver's forward command enabled state
577      * @exception SWTException
578      * <ul>
579      * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
580      * disposed</li>
581      * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
582      * thread that created the receiver</li>
583      * </ul>
584      * @see #forward
585      */

586     public boolean isForwardEnabled() {
587         if (browser==null)
588             return false;
589         return browser.isForwardEnabled();
590     }
591
592     /**
593      * Stop any loading and rendering activity. Convenience method that calls
594      * the underlying SWT browser.
595      *
596      * @exception SWTException
597      * <ul>
598      * <li>ERROR_THREAD_INVALID_ACCESS when called from the
599      * wrong thread</li>
600      * <li>ERROR_WIDGET_DISPOSED when the widget has been
601      * disposed</li>
602      * </ul>
603      */

604     public void stop() {
605         if (browser!=null)
606             browser.stop();
607     }
608
609     /**
610      *
611      */

612     private boolean navigate(String JavaDoc url) {
613         Trace.trace(Trace.FINER, "Navigate: " + url); //$NON-NLS-1$
614
if (url != null && url.equals(getURL())) {
615             refresh();
616             return true;
617         }
618         if (browser!=null)
619             return browser.setUrl(url);
620         return text.setUrl(url);
621     }
622  
623     /**
624      * Refresh the current page. Convenience method that calls the underlying
625      * SWT browser.
626      *
627      * @exception SWTException
628      * <ul>
629      * <li>ERROR_THREAD_INVALID_ACCESS when called from the
630      * wrong thread</li>
631      * <li>ERROR_WIDGET_DISPOSED when the widget has been
632      * disposed</li>
633      * </ul>
634      */

635     public void refresh() {
636         if (browser!=null)
637             browser.refresh();
638         else
639             text.refresh();
640           try {
641               Thread.sleep(50);
642           } catch (Exception JavaDoc e) {
643               // ignore
644
}
645     }
646
647     private void setURL(String JavaDoc url, boolean browse) {
648         Trace.trace(Trace.FINEST, "setURL: " + url + " " + browse); //$NON-NLS-1$ //$NON-NLS-2$
649
if (url == null) {
650             home();
651             return;
652         }
653
654         if ("eclipse".equalsIgnoreCase(url)) //$NON-NLS-1$
655
url = "http://www.eclipse.org"; //$NON-NLS-1$
656
else if ("wtp".equalsIgnoreCase(url)) //$NON-NLS-1$
657
url = "http://www.eclipse.org/webtools/"; //$NON-NLS-1$
658

659         if (browse)
660             navigate(url);
661
662         addToHistory(url);
663         updateHistory();
664     }
665
666     protected void addToHistory(String JavaDoc url) {
667         if (history == null)
668             history = WebBrowserPreference.getInternalWebBrowserHistory();
669         int found = -1;
670         int size = history.size();
671         for (int i = 0; i < size; i++) {
672             String JavaDoc s = (String JavaDoc) history.get(i);
673             if (s.equals(url)) {
674                 found = i;
675                 break;
676             }
677         }
678
679         if (found == -1) {
680             if (size >= MAX_HISTORY)
681                 history.remove(size - 1);
682             history.add(0, url);
683             WebBrowserPreference.setInternalWebBrowserHistory(history);
684         } else if (found != 0) {
685             history.remove(found);
686             history.add(0, url);
687             WebBrowserPreference.setInternalWebBrowserHistory(history);
688         }
689     }
690
691     /**
692      *
693      */

694     public void dispose() {
695         super.dispose();
696
697         showToolbar = false;
698
699         if (busy != null)
700             busy.dispose();
701         busy = null;
702
703         browser = null;
704         text = null;
705         if (clipboard!=null)
706             clipboard.dispose();
707         clipboard=null;
708
709         removeSynchronizationListener();
710     }
711
712     private ToolBar createLocationBar(Composite parent) {
713         combo = new Combo(parent, SWT.DROP_DOWN);
714
715         updateHistory();
716
717         combo.addSelectionListener(new SelectionAdapter() {
718             public void widgetSelected(SelectionEvent we) {
719                 try {
720                     if (combo.getSelectionIndex() != -1)
721                         setURL(combo.getItem(combo.getSelectionIndex()));
722                 } catch (Exception JavaDoc e) {
723                     // ignore
724
}
725             }
726         });
727         combo.addListener(SWT.DefaultSelection, new Listener JavaDoc() {
728             public void handleEvent(Event JavaDoc e) {
729                 setURL(combo.getText());
730             }
731         });
732         
733         ToolBar toolbar = new ToolBar(parent, SWT.FLAT);
734
735         ToolItem go = new ToolItem(toolbar, SWT.NONE);
736         go.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_GO));
737         go.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_GO));
738         go.setDisabledImage(ImageResource
739                 .getImage(ImageResource.IMG_DLCL_NAV_GO));
740         go.setToolTipText(Messages.actionWebBrowserGo);
741         go.addSelectionListener(new SelectionAdapter() {
742             public void widgetSelected(SelectionEvent event) {
743                 setURL(combo.getText());
744             }
745         });
746           
747           return toolbar;
748     }
749
750     private ToolBar createToolbar(Composite parent) {
751           ToolBar toolbar = new ToolBar(parent, SWT.FLAT);
752           
753         // create back and forward actions
754
back = new ToolItem(toolbar, SWT.NONE);
755         back.setImage(ImageResource
756                 .getImage(ImageResource.IMG_ELCL_NAV_BACKWARD));
757         back.setHotImage(ImageResource
758                 .getImage(ImageResource.IMG_CLCL_NAV_BACKWARD));
759         back.setDisabledImage(ImageResource
760                 .getImage(ImageResource.IMG_DLCL_NAV_BACKWARD));
761         back.setToolTipText(Messages.actionWebBrowserBack);
762         back.addSelectionListener(new SelectionAdapter() {
763             public void widgetSelected(SelectionEvent event) {
764                 back();
765             }
766         });
767
768         forward = new ToolItem(toolbar, SWT.NONE);
769         forward.setImage(ImageResource
770                 .getImage(ImageResource.IMG_ELCL_NAV_FORWARD));
771         forward.setHotImage(ImageResource
772                 .getImage(ImageResource.IMG_CLCL_NAV_FORWARD));
773         forward.setDisabledImage(ImageResource
774                 .getImage(ImageResource.IMG_DLCL_NAV_FORWARD));
775         forward.setToolTipText(Messages.actionWebBrowserForward);
776         forward.addSelectionListener(new SelectionAdapter() {
777             public void widgetSelected(SelectionEvent event) {
778                 forward();
779             }
780         });
781
782         // create refresh, stop, and print actions
783
ToolItem stop = new ToolItem(toolbar, SWT.NONE);
784         stop.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_STOP));
785         stop.setHotImage(ImageResource
786                 .getImage(ImageResource.IMG_CLCL_NAV_STOP));
787         stop.setDisabledImage(ImageResource
788                 .getImage(ImageResource.IMG_DLCL_NAV_STOP));
789         stop.setToolTipText(Messages.actionWebBrowserStop);
790         stop.addSelectionListener(new SelectionAdapter() {
791             public void widgetSelected(SelectionEvent event) {
792                 stop();
793             }
794         });
795
796         ToolItem refresh = new ToolItem(toolbar, SWT.NONE);
797         refresh.setImage(ImageResource
798                 .getImage(ImageResource.IMG_ELCL_NAV_REFRESH));
799         refresh.setHotImage(ImageResource
800                 .getImage(ImageResource.IMG_CLCL_NAV_REFRESH));
801         refresh.setDisabledImage(ImageResource
802                 .getImage(ImageResource.IMG_DLCL_NAV_REFRESH));
803         refresh.setToolTipText(Messages.actionWebBrowserRefresh);
804         refresh.addSelectionListener(new SelectionAdapter() {
805             public void widgetSelected(SelectionEvent event) {
806                 refresh();
807             }
808         });
809           
810           return toolbar;
811     }
812
813     /**
814      * Returns the current URL. Convenience method that calls the underlying SWT
815      * browser.
816      *
817      * @return the current URL or an empty <code>String</code> if there is no
818      * current URL
819      * @exception SWTException
820      * <ul>
821      * <li>ERROR_THREAD_INVALID_ACCESS when called from the
822      * wrong thread</li>
823      * <li>ERROR_WIDGET_DISPOSED when the widget has been
824      * disposed</li>
825      * </ul>
826      * @see #setURL(String)
827      */

828     public String JavaDoc getURL() {
829         if (browser!=null)
830             return browser.getUrl();
831         return text.getUrl();
832     }
833
834     public boolean setFocus() {
835         if (browser!=null) {
836             browser.setFocus();
837             updateHistory();
838             return true;
839         }
840         return super.setFocus();
841     }
842
843     /**
844      * Update the history list to the global/shared copy.
845      */

846     protected void updateHistory() {
847         if (combo == null)
848             return;
849
850         String JavaDoc temp = combo.getText();
851         if (history == null)
852             history = WebBrowserPreference.getInternalWebBrowserHistory();
853
854         String JavaDoc[] historyList = new String JavaDoc[history.size()];
855         history.toArray(historyList);
856         combo.setItems(historyList);
857
858         combo.setText(temp);
859     }
860
861     public IBrowserViewerContainer getContainer() {
862         return container;
863     }
864
865     public void setContainer(IBrowserViewerContainer container) {
866         if (container==null && this.container!=null) {
867             IStatusLineManager manager = this.container.getActionBars().getStatusLineManager();
868             if (manager!=null)
869                 manager.getProgressMonitor().done();
870         }
871         this.container = container;
872     }
873
874     protected File JavaDoc file;
875     protected long timestamp;
876     protected Thread JavaDoc fileListenerThread;
877     protected LocationListener locationListener2;
878     protected Object JavaDoc syncObject = new Object JavaDoc();
879     
880     protected void addSynchronizationListener() {
881      if (fileListenerThread != null)
882          return;
883      
884      fileListenerThread = new Thread JavaDoc("Browser file synchronization") { //$NON-NLS-1$
885
public void run() {
886              while (fileListenerThread != null) {
887                  try {
888                      Thread.sleep(2000);
889                  } catch (Exception JavaDoc e) {
890                      // ignore
891
}
892                  synchronized (syncObject) {
893                          if (file != null && file.lastModified() != timestamp) {
894                          timestamp = file.lastModified();
895                          Display.getDefault().syncExec(new Runnable JavaDoc() {
896                                 public void run() {
897                                     refresh();
898                                 }
899                          });
900                          }
901                       }
902              }
903          }
904      };
905      fileListenerThread.setDaemon(true);
906      fileListenerThread.setPriority(Thread.MIN_PRIORITY);
907      
908      locationListener2 = new LocationListener() {
909           public void changed(LocationEvent event) {
910              File JavaDoc temp = getFile(event.location);
911              if (temp != null && temp.exists()) {
912                  synchronized (syncObject) {
913                      file = temp;
914                      timestamp = file.lastModified();
915                      }
916              } else
917                  file = null;
918           }
919           
920           public void changing(LocationEvent event) {
921              // do nothing
922
}
923        };
924        browser.addLocationListener(locationListener2);
925        
926        File JavaDoc temp = getFile(browser.getUrl());
927      if (temp != null && temp.exists()) {
928         file = temp;
929         timestamp = file.lastModified();
930      }
931      fileListenerThread.start();
932     }
933
934     protected static File JavaDoc getFile(String JavaDoc location) {
935      if (location == null)
936          return null;
937      if (location.startsWith("file:/")) //$NON-NLS-1$
938
location = location.substring(6);
939      
940      return new File JavaDoc(location);
941     }
942
943     protected void removeSynchronizationListener() {
944      if (fileListenerThread == null)
945          return;
946      
947      fileListenerThread = null;
948      browser.removeLocationListener(locationListener2);
949      locationListener2 = null;
950     }
951 }
952
Popular Tags