source: josm/trunk/src/org/openstreetmap/josm/gui/help/HelpBrowser.java@ 3128

Last change on this file since 3128 was 3083, checked in by bastiK, 14 years ago

added svn:eol-style=native to source files

  • Property svn:eol-style set to native
File size: 20.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.help;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.buildAbsoluteHelpTopic;
5import static org.openstreetmap.josm.gui.help.HelpUtil.getHelpTopicEditUrl;
6import static org.openstreetmap.josm.tools.I18n.tr;
7
8import java.awt.BorderLayout;
9import java.awt.Dimension;
10import java.awt.Rectangle;
11import java.awt.event.ActionEvent;
12import java.awt.event.KeyEvent;
13import java.awt.event.WindowAdapter;
14import java.awt.event.WindowEvent;
15import java.io.BufferedReader;
16import java.io.IOException;
17import java.io.InputStreamReader;
18import java.util.Locale;
19import java.util.Observable;
20import java.util.Observer;
21import java.util.logging.Logger;
22
23import javax.swing.AbstractAction;
24import javax.swing.JButton;
25import javax.swing.JComponent;
26import javax.swing.JEditorPane;
27import javax.swing.JFrame;
28import javax.swing.JOptionPane;
29import javax.swing.JPanel;
30import javax.swing.JScrollBar;
31import javax.swing.JScrollPane;
32import javax.swing.JSeparator;
33import javax.swing.JToolBar;
34import javax.swing.KeyStroke;
35import javax.swing.SwingUtilities;
36import javax.swing.event.HyperlinkEvent;
37import javax.swing.event.HyperlinkListener;
38import javax.swing.text.AttributeSet;
39import javax.swing.text.BadLocationException;
40import javax.swing.text.Document;
41import javax.swing.text.Element;
42import javax.swing.text.SimpleAttributeSet;
43import javax.swing.text.html.HTMLDocument;
44import javax.swing.text.html.HTMLEditorKit;
45import javax.swing.text.html.StyleSheet;
46import javax.swing.text.html.HTML.Tag;
47
48import org.openstreetmap.josm.Main;
49import org.openstreetmap.josm.gui.HelpAwareOptionPane;
50import org.openstreetmap.josm.tools.ImageProvider;
51import org.openstreetmap.josm.tools.OpenBrowser;
52import org.openstreetmap.josm.tools.WindowGeometry;
53
54public class HelpBrowser extends JFrame {
55 static private final Logger logger = Logger.getLogger(HelpBrowser.class.getName());
56
57 /** the unique instance */
58 private static HelpBrowser instance;
59
60 /**
61 * Replies the unique instance of the help browser
62 *
63 * @return the unique instance of the help browser
64 */
65 static public HelpBrowser getInstance() {
66 if (instance == null) {
67 instance = new HelpBrowser();
68 }
69 return instance;
70 }
71
72 /**
73 * Show the help page for help topic <code>helpTopic</code>.
74 *
75 * @param helpTopic the help topic
76 */
77 public static void setUrlForHelpTopic(final String helpTopic) {
78 final HelpBrowser browser = getInstance();
79 Runnable r = new Runnable() {
80 public void run() {
81 browser.openHelpTopic(helpTopic);
82 browser.setVisible(true);
83 browser.toFront();
84 }
85 };
86 SwingUtilities.invokeLater(r);
87 }
88
89 /**
90 * Launches the internal help browser and directs it to the help page for
91 * <code>helpTopic</code>.
92 *
93 * @param helpTopic the help topic
94 */
95 static public void launchBrowser(String helpTopic) {
96 HelpBrowser browser = getInstance();
97 browser.openHelpTopic(helpTopic);
98 browser.setVisible(true);
99 browser.toFront();
100 }
101
102 /** the help browser */
103 private JEditorPane help;
104 private JScrollPane spHelp;
105
106 /** the help browser history */
107 private HelpBrowserHistory history;
108
109 /** the currently displayed URL */
110 private String url;
111
112 private HelpContentReader reader;
113
114 /**
115 * Builds the style sheet used in the internal help browser
116 *
117 * @return the style sheet
118 */
119 protected StyleSheet buildStyleSheet() {
120 StyleSheet ss = new StyleSheet();
121 BufferedReader reader = new BufferedReader(
122 new InputStreamReader(
123 getClass().getResourceAsStream("/data/help-browser.css")
124 )
125 );
126 StringBuffer css = new StringBuffer();
127 try {
128 String line = null;
129 while ((line = reader.readLine()) != null) {
130 css.append(line);
131 css.append("\n");
132 }
133 reader.close();
134 } catch(Exception e) {
135 System.err.println(tr("Failed to read CSS file ''help-browser.css''. Exception is: {0}", e.toString()));
136 e.printStackTrace();
137 return ss;
138 }
139 ss.addRule(css.toString());
140 return ss;
141 }
142
143 protected JToolBar buildToolBar() {
144 JToolBar tb = new JToolBar();
145 tb.add(new JButton(new HomeAction()));
146 tb.add(new JButton(new BackAction(history)));
147 tb.add(new JButton(new ForwardAction(history)));
148 tb.add(new JButton(new ReloadAction()));
149 tb.add(new JSeparator());
150 tb.add(new JButton(new OpenInBrowserAction()));
151 tb.add(new JButton(new EditAction()));
152 return tb;
153 }
154
155 protected void build() {
156 help = new JEditorPane();
157 HTMLEditorKit kit = new HTMLEditorKit();
158 kit.setStyleSheet(buildStyleSheet());
159 help.setEditorKit(kit);
160 help.setEditable(false);
161 help.addHyperlinkListener(new HyperlinkHandler());
162 help.setContentType("text/html");
163 history = new HelpBrowserHistory(this);
164
165 JPanel p = new JPanel(new BorderLayout());
166 setContentPane(p);
167
168 p.add(spHelp = new JScrollPane(help), BorderLayout.CENTER);
169
170 addWindowListener(new WindowAdapter(){
171 @Override public void windowClosing(WindowEvent e) {
172 setVisible(false);
173 }
174 });
175
176 p.add(buildToolBar(), BorderLayout.NORTH);
177 help.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Close");
178 help.getActionMap().put("Close", new AbstractAction(){
179 public void actionPerformed(ActionEvent e) {
180 setVisible(false);
181 }
182 });
183
184 setMinimumSize(new Dimension(400, 200));
185 setTitle(tr("JOSM Help Browser"));
186 }
187
188 @Override
189 public void setVisible(boolean visible) {
190 if (visible) {
191 new WindowGeometry(
192 getClass().getName() + ".geometry",
193 WindowGeometry.centerInWindow(
194 getParent(),
195 new Dimension(600,400)
196 )
197 ).applySafe(this);
198 } else if (!visible && isShowing()){
199 new WindowGeometry(this).remember(getClass().getName() + ".geometry");
200 }
201 super.setVisible(visible);
202 }
203
204 public HelpBrowser() {
205 reader = new HelpContentReader(HelpUtil.getWikiBaseUrl());
206 build();
207 }
208
209 /**
210 * Replies the current URL
211 *
212 * @return the current URL
213 */
214
215 public String getUrl() {
216 return url;
217 }
218
219 /**
220 * Displays a warning page when a help topic doesn't exist yet.
221 *
222 * @param relativeHelpTopic the help topic
223 */
224 protected void handleMissingHelpContent(String relativeHelpTopic) {
225 String message = tr("<html><p class=\"warning-header\">Help content for help topic missing</p>"
226 + "<p class=\"warning-body\">Help content for the help topic <strong>{0}</strong> is "
227 + "not available yet. It is missing both in your local language ({1}) and in english.<br><br>"
228 + "Please help to improve the JOSM help system and fill in the missing information. "
229 + "You can both edit the <a href=\"{2}\">help topic in your local language ({1})</a> and "
230 + "the <a href=\"{3}\">help topic in english</a>."
231 + "</p></html>",
232 relativeHelpTopic,
233 Locale.getDefault().getDisplayName(),
234 getHelpTopicEditUrl(buildAbsoluteHelpTopic(relativeHelpTopic)),
235 getHelpTopicEditUrl(buildAbsoluteHelpTopic(relativeHelpTopic, Locale.ENGLISH))
236 );
237 help.setText(message);
238 }
239
240 /**
241 * Displays a error page if a help topic couldn't be loaded because of network or IO error.
242 *
243 * @param relativeHelpTopic the help topic
244 * @param e the exception
245 */
246 protected void handleHelpContentReaderException(String relativeHelpTopic, HelpContentReaderException e) {
247 String message = tr("<html><p class=\"error-header\">Error when retrieving help information</p>"
248 + "<p class=\"error-body\">The content for the help topic <strong>{0}</strong> could "
249 + "not be loaded. The error message is (untranslated):<br>"
250 + "<tt>{1}</tt>"
251 + "</p></html>",
252 relativeHelpTopic,
253 e.toString()
254 );
255 help.setText(message);
256 }
257
258 protected void scrollToTop() {
259 JScrollBar sb = spHelp.getVerticalScrollBar();
260 sb.setValue(sb.getMinimum());
261 }
262
263 /**
264 * Loads a help topic given by a relative help topic name (i.e. "/Action/New")
265 *
266 * First tries to load the language specific help topic. If it is missing, tries to
267 * load the topic in english.
268 *
269 * @param relativeHelpTopic the relative help topic
270 */
271 protected void loadRelativeHelpTopic(String relativeHelpTopic) {
272 String url = HelpUtil.getHelpTopicUrl(HelpUtil.buildAbsoluteHelpTopic(relativeHelpTopic));
273 String content = null;
274 try {
275 content = reader.fetchHelpTopicContent(url, true);
276 } catch(MissingHelpContentException e) {
277 url = HelpUtil.getHelpTopicUrl(HelpUtil.buildAbsoluteHelpTopic(relativeHelpTopic, Locale.ENGLISH));
278 try {
279 logger.info("fetching url: " + url);
280 content = reader.fetchHelpTopicContent(url, true);
281 } catch(MissingHelpContentException e1) {
282 this.url = url;
283 handleMissingHelpContent(relativeHelpTopic);
284 return;
285 } catch(HelpContentReaderException e1) {
286 e1.printStackTrace();
287 handleHelpContentReaderException(relativeHelpTopic,e1);
288 return;
289 }
290 } catch(HelpContentReaderException e) {
291 e.printStackTrace();
292 handleHelpContentReaderException(relativeHelpTopic, e);
293 return;
294 }
295 help.setText(content);
296 history.setCurrentUrl(url);
297 this.url = url;
298 scrollToTop();
299 }
300
301 /**
302 * Loads a help topic given by an absolute help topic name, i.e.
303 * "/De:Help/Action/New"
304 *
305 * @param absoluteHelpTopic the absolute help topic name
306 */
307 protected void loadAbsoluteHelpTopic(String absoluteHelpTopic) {
308 String url = HelpUtil.getHelpTopicUrl(absoluteHelpTopic);
309 String content = null;
310 try {
311 content = reader.fetchHelpTopicContent(url, true);
312 } catch(MissingHelpContentException e) {
313 this.url = url;
314 handleMissingHelpContent(absoluteHelpTopic);
315 return;
316 } catch(HelpContentReaderException e) {
317 e.printStackTrace();
318 handleHelpContentReaderException(absoluteHelpTopic, e);
319 return;
320 }
321 help.setText(content);
322 history.setCurrentUrl(url);
323 this.url = url;
324 scrollToTop();
325 }
326
327 /**
328 * Opens an URL and displays the content.
329 *
330 * If the URL is the locator of an absolute help topic, help content is loaded from
331 * the JOSM wiki. Otherwise, the help browser loads the page from the given URL
332 *
333 * @param url the url
334 */
335 public void openUrl(String url) {
336 if (!isVisible()) {
337 setVisible(true);
338 toFront();
339 } else {
340 toFront();
341 }
342 String helpTopic = HelpUtil.extractAbsoluteHelpTopic(url);
343 if (helpTopic == null) {
344 try {
345 this.url = url;
346 String content = reader.fetchHelpTopicContent(url, false);
347 help.setText(content);
348 history.setCurrentUrl(url);
349 this.url = url;
350 scrollToTop();
351 } catch(Exception e) {
352 HelpAwareOptionPane.showOptionDialog(
353 Main.parent,
354 tr(
355 "<html>Failed to open help page for url {0}.<br>"
356 + "This is most likely due to a network problem, please check<br>"
357 + "your internet connection</html>",
358 url.toString()
359 ),
360 tr("Failed to open URL"),
361 JOptionPane.ERROR_MESSAGE,
362 null, /* no icon */
363 null, /* standard options, just OK button */
364 null, /* default is standard */
365 null /* no help context */
366 );
367 }
368 history.setCurrentUrl(url);
369 } else {
370 loadAbsoluteHelpTopic(helpTopic);
371 }
372 }
373
374 /**
375 * Loads and displays the help information for a help topic given
376 * by a relative help topic name, i.e. "/Action/New"
377 *
378 * @param relativeHelpTopic the relative help topic
379 */
380 public void openHelpTopic(String relativeHelpTopic) {
381 if (!isVisible()) {
382 setVisible(true);
383 toFront();
384 } else {
385 toFront();
386 }
387 loadRelativeHelpTopic(relativeHelpTopic);
388 }
389
390 class OpenInBrowserAction extends AbstractAction {
391 public OpenInBrowserAction() {
392 //putValue(NAME, tr("Open in Browser"));
393 putValue(SHORT_DESCRIPTION, tr("Open the current help page in an external browser"));
394 putValue(SMALL_ICON, ImageProvider.get("help", "internet"));
395 }
396
397 public void actionPerformed(ActionEvent e) {
398 OpenBrowser.displayUrl(getUrl());
399 }
400 }
401
402 class EditAction extends AbstractAction {
403 public EditAction() {
404 // putValue(NAME, tr("Edit"));
405 putValue(SHORT_DESCRIPTION, tr("Edit the current help page"));
406 putValue(SMALL_ICON,ImageProvider.get("dialogs", "edit"));
407 }
408
409 public void actionPerformed(ActionEvent e) {
410 String url = getUrl();
411 if(url == null)
412 return;
413 if (!url.startsWith(HelpUtil.getWikiBaseHelpUrl())) {
414 String message = tr(
415 "<html>The current URL <tt>{0}</tt><br>"
416 + "is an external URL. Editing is only possible for help topics<br>"
417 + "on the help server <tt>{1}</tt>.</html>",
418 getUrl(),
419 HelpUtil.getWikiBaseUrl()
420 );
421 JOptionPane.showMessageDialog(
422 Main.parent,
423 message,
424 tr("Warning"),
425 JOptionPane.WARNING_MESSAGE
426 );
427 return;
428 }
429 url = url.replaceAll("#[^#]*$", "");
430 OpenBrowser.displayUrl(url+"?action=edit");
431 }
432 }
433
434 class ReloadAction extends AbstractAction {
435 public ReloadAction() {
436 //putValue(NAME, tr("Reload"));
437 putValue(SHORT_DESCRIPTION, tr("Reload the current help page"));
438 putValue(SMALL_ICON, ImageProvider.get("dialogs", "refresh"));
439 }
440
441 public void actionPerformed(ActionEvent e) {
442 openUrl(getUrl());
443 }
444 }
445
446 static class BackAction extends AbstractAction implements Observer {
447 private HelpBrowserHistory history;
448 public BackAction(HelpBrowserHistory history) {
449 this.history = history;
450 history.addObserver(this);
451 //putValue(NAME, tr("Back"));
452 putValue(SHORT_DESCRIPTION, tr("Go to the previous page"));
453 putValue(SMALL_ICON, ImageProvider.get("help", "previous"));
454 setEnabled(history.canGoBack());
455 }
456
457 public void actionPerformed(ActionEvent e) {
458 history.back();
459 }
460 public void update(Observable o, Object arg) {
461 //System.out.println("BackAction: canGoBoack=" + history.canGoBack() );
462 setEnabled(history.canGoBack());
463 }
464 }
465
466 static class ForwardAction extends AbstractAction implements Observer {
467 private HelpBrowserHistory history;
468 public ForwardAction(HelpBrowserHistory history) {
469 this.history = history;
470 history.addObserver(this);
471 //putValue(NAME, tr("Forward"));
472 putValue(SHORT_DESCRIPTION, tr("Go to the next page"));
473 putValue(SMALL_ICON, ImageProvider.get("help", "next"));
474 setEnabled(history.canGoForward());
475 }
476
477 public void actionPerformed(ActionEvent e) {
478 history.forward();
479 }
480 public void update(Observable o, Object arg) {
481 setEnabled(history.canGoForward());
482 }
483 }
484
485 class HomeAction extends AbstractAction {
486 public HomeAction() {
487 //putValue(NAME, tr("Home"));
488 putValue(SHORT_DESCRIPTION, tr("Go to the JOSM help home page"));
489 putValue(SMALL_ICON, ImageProvider.get("help", "home"));
490 }
491
492 public void actionPerformed(ActionEvent e) {
493 openHelpTopic("/");
494 }
495 }
496
497 class HyperlinkHandler implements HyperlinkListener {
498
499 /**
500 * Scrolls the help browser to the element with id <code>id</code>
501 *
502 * @param id the id
503 * @return true, if an element with this id was found and scrolling was successful; false, otherwise
504 */
505 protected boolean scrollToElementWithId(String id) {
506 Document d = help.getDocument();
507 if (d instanceof HTMLDocument) {
508 HTMLDocument doc = (HTMLDocument) d;
509 Element element = doc.getElement(id);
510 try {
511 Rectangle r = help.modelToView(element.getStartOffset());
512 if (r != null) {
513 Rectangle vis = help.getVisibleRect();
514 r.height = vis.height;
515 help.scrollRectToVisible(r);
516 return true;
517 }
518 } catch(BadLocationException e) {
519 System.err.println(tr("Warning: bad location in HTML document. Exception was: {0}", e.toString()));
520 e.printStackTrace();
521 }
522 }
523 return false;
524 }
525
526 /**
527 * Checks whether the hyperlink event originated on a <a ...> element with
528 * a relative href consisting of a URL fragment only, i.e.
529 * <a href="#thisIsALocalFragment">. If so, replies the fragment, i.e.
530 * "thisIsALocalFragment".
531 *
532 * Otherwise, replies null
533 *
534 * @param e the hyperlink event
535 * @return the local fragment
536 */
537 protected String getUrlFragment(HyperlinkEvent e) {
538 AttributeSet set = e.getSourceElement().getAttributes();
539 Object value = set.getAttribute(Tag.A);
540 if (value == null || ! (value instanceof SimpleAttributeSet)) return null;
541 SimpleAttributeSet atts = (SimpleAttributeSet)value;
542 value = atts.getAttribute(javax.swing.text.html.HTML.Attribute.HREF);
543 if (value == null) return null;
544 String s = (String)value;
545 if (s.matches("#.*"))
546 return s.substring(1);
547 return null;
548 }
549
550 public void hyperlinkUpdate(HyperlinkEvent e) {
551 if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED)
552 return;
553 if (e.getURL() == null) {
554 // Probably hyperlink event on a an A-element with a href consisting of
555 // a fragment only, i.e. "#ALocalFragment".
556 //
557 String fragment = getUrlFragment(e);
558 if (fragment != null) {
559 // first try to scroll to an element with id==fragment. This is the way
560 // table of contents are built in the JOSM wiki. If this fails, try to
561 // scroll to a <A name="..."> element.
562 //
563 if (!scrollToElementWithId(fragment)) {
564 help.scrollToReference(fragment);
565 }
566 } else {
567 HelpAwareOptionPane.showOptionDialog(
568 Main.parent,
569 tr("Failed to open help page. The target URL is empty."),
570 tr("Failed to open help page"),
571 JOptionPane.ERROR_MESSAGE,
572 null, /* no icon */
573 null, /* standard options, just OK button */
574 null, /* default is standard */
575 null /* no help context */
576 );
577 }
578 } else if (e.getURL().toString().endsWith("action=edit")) {
579 OpenBrowser.displayUrl(e.getURL().toString());
580 } else {
581 url = e.getURL().toString();
582 openUrl(e.getURL().toString());
583 }
584 }
585 }
586}
Note: See TracBrowser for help on using the repository browser.