1 package winterwell.markdown.views;
7 import org.eclipse.core.runtime.IPath;
8 import org.eclipse.swt.SWT;
9 import org.eclipse.swt.browser.Browser;
10 import org.eclipse.swt.widgets.Composite;
11 import org.eclipse.ui.IEditorPart;
12 import org.eclipse.ui.IPathEditorInput;
13 import org.eclipse.ui.part.ViewPart;
15 import winterwell.markdown.editors.ActionBarContributor;
16 import winterwell.markdown.editors.MarkdownEditor;
17 import winterwell.markdown.pagemodel.MarkdownPage;
22 public class MarkdownPreview extends ViewPart {
24 public static MarkdownPreview preview = null;
26 private Browser viewer = null;
31 public MarkdownPreview() {
36 * This is a callback that will allow us
37 * to create the viewer and initialize it.
40 public void createPartControl(Composite parent) {
41 viewer = new Browser(parent, SWT.MULTI); // | SWT.H_SCROLL | SWT.V_SCROLL
48 * Passing the focus request to the viewer's control.
51 public void setFocus() {
52 if (viewer==null) return;
57 public void update() {
58 if (viewer==null) return;
60 IEditorPart editor = ActionBarContributor.getActiveEditor();
61 if (!(editor instanceof MarkdownEditor)) {
65 MarkdownEditor ed = (MarkdownEditor) editor;
66 MarkdownPage page = ed.getMarkdownPage();
67 String html = page.html();
68 html = addBaseURL(editor, html);
69 if (page != null) viewer.setText(html);
70 else viewer.setText("");
71 } catch (Exception ex) {
73 System.out.println(ex);
75 if (viewer != null && !viewer.isDisposed())
76 viewer.setText(ex.getMessage());
81 * Adjust the URL base to be the file's directory.
86 private String addBaseURL(IEditorPart editor, String html) {
88 IPathEditorInput input = (IPathEditorInput) editor.getEditorInput();
89 IPath path = input.getPath();
90 path = path.removeLastSegments(1);
91 File f = path.toFile();
92 URI fileURI = f.toURI();
93 String html2 = "<html><head><base href='"+fileURI+"' /></head><body>\r\n"+html
94 +"\r\n</body></html>";
96 } catch (Exception ex) {