PHP Manual View now keeps the last reference page (closes #691)
[phpeclipse.git] / net.sourceforge.phpeclipse.phpmanual / src / net / sourceforge / phpeclipse / phpmanual / views / PHPManualView.java
1 package net.sourceforge.phpeclipse.phpmanual.views;
2
3 import java.io.BufferedReader;
4 import java.io.FileNotFoundException;
5 import java.io.FileReader;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.net.URL;
9 import java.util.Arrays;
10 import java.util.ArrayList;
11 import java.util.zip.ZipEntry;
12 import java.util.zip.ZipFile;
13
14 import net.sourceforge.phpeclipse.phpmanual.PHPManualUiMessages;
15 //import net.sourceforge.phpdt.internal.debug.ui.PHPDebugUiMessages;
16 import net.sourceforge.phpdt.internal.ui.text.JavaWordFinder;
17 import net.sourceforge.phpdt.internal.ui.viewsupport.ISelectionListenerWithAST;
18 import net.sourceforge.phpdt.internal.ui.viewsupport.SelectionListenerWithASTManager;
19 import net.sourceforge.phpdt.phphelp.PHPHelpPlugin;
20 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
21 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
22 import net.sourceforge.phpeclipse.phpmanual.PHPManualUIPlugin;
23
24 import org.eclipse.core.runtime.FileLocator;
25 import org.eclipse.core.runtime.Path;
26 import org.eclipse.core.runtime.Platform;
27 import org.eclipse.jface.text.IDocument;
28 import org.eclipse.jface.text.IRegion;
29 import org.eclipse.jface.text.ITextSelection;
30 import org.eclipse.jface.viewers.ISelection;
31 import org.eclipse.swt.SWT;
32 import org.eclipse.swt.browser.Browser;
33 import org.eclipse.swt.browser.LocationAdapter;
34 import org.eclipse.swt.browser.LocationEvent;
35 import org.eclipse.swt.widgets.Composite;
36 import org.eclipse.swt.widgets.Display;
37 import org.eclipse.ui.IEditorPart;
38 import org.eclipse.ui.INullSelectionListener;
39 import org.eclipse.ui.IWorkbenchPart;
40 import org.eclipse.ui.part.ViewPart;
41 import org.htmlparser.Node;
42 import org.htmlparser.Parser;
43 import org.htmlparser.tags.Div;
44 import org.htmlparser.util.ParserException;
45 import org.htmlparser.visitors.TagFindingVisitor;
46 import org.osgi.framework.Bundle;
47
48 /**
49  * This ViewPart is the implementation of the idea of having the 
50  * PHP Manual easily accessible while coding. It shows the
51  * under-cursor function's reference inside a browser.
52  * <p>
53  * The view listens to selection changes both in the (1)workbench, to
54  * know when the user changes between the instances of the PHPEditor
55  * or when a new instance is created; and in the (2)PHPEditor, to know
56  * when the user changes the cursor position. This explains the need
57  * to implement both ISelectionListener and ISelectionListenerWithAST.
58  * <p>
59  * Up to now, the ViewPart show reference pages from HTML stored in the
60  * doc.zip file from the net.sourceforge.phpeclipse.phphelp plugin. It
61  * also depends on net.sourceforge.phpeclipse.phpmanual.htmlparser to
62  * parse these HTML files.
63  * <p>
64  * @author scorphus
65  */
66 public class PHPManualView extends ViewPart implements INullSelectionListener, ISelectionListenerWithAST {
67
68         /**
69          * The ViewPart's browser
70          */
71         private Browser browser;
72
73         /**
74          * A reference to store last active editor to know when we've
75          * got a new instance of the PHPEditor
76          */
77         private PHPEditor lastEditor;
78
79         /**
80          * String that stores the last selected word
81          */
82         private String lastOccurrence = null;
83
84         /**
85          * The path to the doc.zip file containing the PHP Manual
86          * in HTML format
87          */
88         private final Path docPath = new Path("doc.zip"); 
89
90         /**
91          * The constructor.
92          */
93         public PHPManualView() {
94         }
95
96         /**
97          * This method initializes the ViewPart. It instantiates components
98          * and add listeners
99          * 
100          * @param parent The parent control
101          */
102         public void createPartControl(Composite parent) {
103                 browser = new Browser(parent, SWT.NONE);
104                 browser.addLocationListener(new LocationAdapter() {
105                         public void changing(LocationEvent event) {
106                                 String loc = event.location.toString();
107                                 if(!loc.equalsIgnoreCase("about:blank") && !loc.startsWith("jar:")) {
108                                         String func = loc.replaceAll("file:///", "");
109                                         func = func.replaceAll("#.+$", "");
110                                         String[] afunc = loc.split("\\.");
111                                         if(!afunc[1].equalsIgnoreCase(lastOccurrence)) {
112                                                 lastOccurrence = afunc[1];
113                                                 showReference(func);
114                                                 event.doit = false;
115                                         }
116                                 }
117                         }
118                 });
119                 parent.pack();
120                 if ((lastEditor = getJavaEditor()) != null) {
121                         SelectionListenerWithASTManager.getDefault().addListener(lastEditor, this);
122                 }
123                 getSite().getWorkbenchWindow().getSelectionService()
124                                 .addPostSelectionListener(PHPeclipsePlugin.EDITOR_ID, this);
125         }
126         /**
127          * Cleanup to remove the selection listener
128          */
129         public void dispose() {
130                 getSite().getWorkbenchWindow().getSelectionService()
131                                 .removePostSelectionListener(PHPeclipsePlugin.EDITOR_ID, this);
132         }
133
134         /**
135          * Passing the focus request to the viewer's control.
136          */
137         public void setFocus() {
138                 browser.setFocus();
139         }
140
141         /**
142          * Treats selection changes from the PHPEditor
143          */
144         public void selectionChanged(IEditorPart part, ITextSelection selection) {
145                 IDocument document = ((PHPEditor)part).getViewer().getDocument();
146                 int offset = selection.getOffset();
147                 IRegion iRegion = JavaWordFinder.findWord(document, offset);
148                 if (document != null && iRegion != null) {
149                         try {
150                                 final String wordStr = document.get(iRegion.getOffset(),
151                                                 iRegion.getLength());
152                                 if (!wordStr.equalsIgnoreCase(lastOccurrence)) {
153                                         showReference(wordStr);                         
154                                         lastOccurrence = wordStr;
155                                 }
156                         } catch (Exception e) {
157                                 e.printStackTrace();
158                         }
159                 }
160         }
161
162         /**
163          * Treats selection changes from the workbench. When part is new
164          * instance of PHPEditor it gets a listener attached
165          */
166         public void selectionChanged(IWorkbenchPart part, ISelection selection) {
167                 if (part != null && !((PHPEditor)part).equals(lastEditor)) {
168                         SelectionListenerWithASTManager.getDefault().addListener((PHPEditor)part, this);
169                         lastEditor = (PHPEditor)part;
170                 } else {
171                         System.out.println(part);
172                 }
173         }
174
175         /**
176          * Updates the browser with the reference page for a given function
177          * 
178          * @param funcName Function name
179          */
180         private void showReference(final String funcName) {
181                 new Thread(new Runnable() {
182                         public void run() {
183                                 Display.getDefault().asyncExec(new Runnable() {
184                                         public void run() {
185                                                 String html = getHtmlSource(funcName);
186                                                 browser.setText(html);
187                                         }
188                                 });
189                         }
190                 }).start();
191         }
192         
193         /**
194          * Filters the function's reference page extracting only parts of it
195          * 
196          * @param source HTML source of the reference page
197          * @return HTML source of reference page
198          */
199         private String filterHtmlSource(String source) {
200                 try {
201                         Parser parser = new Parser(source);
202                         String[] tagsToBeFound = { "DIV" };
203                         // Common classes to be included for all page types
204                         ArrayList classList = new ArrayList(Arrays.asList(new String[] {
205                                         "section", "sect1", "title", "partintro", "refnamediv",
206                                         "refsect1 description", "refsect1 parameters",
207                                         "refsect1 returnvalues", "refsect1 examples",
208                                         "refsect1 seealso", "refsect1 u", "example-contents" }));
209                         // Grab all the tags for processing
210                         TagFindingVisitor visitor = new TagFindingVisitor(tagsToBeFound);
211                         parser.visitAllNodesWith(visitor);
212                         Node [] allPTags = visitor.getTags(0);
213                         StringBuffer output = new StringBuffer();
214                         for (int i = 0; i < allPTags.length; i++) {
215                                 String tagClass = ((Div)allPTags[i]).getAttribute("class");
216                                 if (classList.contains(tagClass)) {
217                                         output.append(allPTags[i].toHtml());
218                                 }
219                         }
220                         return output.toString().replaceAll("—", "-");
221                         //.replace("<h3 class=\"title\">Description</h3>", " ");
222                 } catch (ParserException e) {
223                         e.printStackTrace();
224                 }
225                 return "";
226         }
227         /**
228          * Reads the template that defines the style of the reference page
229          * shown inside the view's browser
230          * 
231          * @return HTML source of the template
232          */
233         public String getRefPageTemplate() {
234                 Bundle bundle = Platform.getBundle(PHPManualUIPlugin.PLUGIN_ID);
235                 URL fileURL = FileLocator.find(bundle, new Path("templates"), null);
236                 StringBuffer contents = new StringBuffer();
237                 BufferedReader input = null;
238                 try {
239                         URL resolve = FileLocator.resolve(fileURL);
240                         input = new BufferedReader(new FileReader(resolve.getPath()+"/refpage.html"));
241                         String line = null;
242                         while ((line = input.readLine()) != null){
243                                 contents.append(line);
244                         }
245                 }
246                 catch (FileNotFoundException e) {
247                         e.printStackTrace();
248                 } catch (IOException e) {
249                         e.printStackTrace();
250                 }
251                 finally {
252                         try {
253                                 if (input!= null) {
254                                         input.close();
255                                 }
256                         }
257                         catch (IOException ex) {
258                                 ex.printStackTrace();
259                         }
260                 }
261                 return contents.toString();
262         }
263
264         /**
265          * Replaces each substring of source string that matches the
266          * given pattern string with the given replace string
267          * 
268          * @param source The source string
269          * @param pattern The pattern string
270          * @param replace The replace string
271          * @return The resulting String
272          */
273         public static String replace(String source, String pattern, String replace) {
274                 if (source != null) {
275                         final int len = pattern.length();
276                         StringBuffer sb = new StringBuffer();
277                         int found = -1;
278                         int start = 0;
279                         while ((found = source.indexOf(pattern, start)) != -1) {
280                                 sb.append(source.substring(start, found));
281                                 sb.append(replace);
282                                 start = found + len;
283                         }
284                         sb.append(source.substring(start));
285                         return sb.toString();
286                 } else {
287                         return "";
288                 }
289         }
290
291         /**
292          * Looks for the function's reference page inside the doc.zip file and
293          * returns a filtered HTML source of it embedded in the template
294          * 
295          * @param funcName
296          *            Function name
297          * @return HTML source of reference page
298          */
299         public String getHtmlSource(String funcName) {
300                 if (funcName.length() == 0) {
301                         // Don't bother ;-) 
302                         return null;
303                 }
304                 Bundle bundle = Platform.getBundle(PHPHelpPlugin.PLUGIN_ID);
305                 URL fileURL = FileLocator.find(bundle, docPath, null);
306                 ZipEntry entry = null;
307                 // List of prefixes to lookup HTML files by, ordered so that looping
308                 // is as minimal as possible.  The empty value matches links passed,
309                 // rather than function 
310                 String[] prefixes = { "", "function", "control-structures", "ref", "http", "imagick", "ming" };
311                 byte[] b = null;
312                 if (funcName.matches("^[a-z-]+\\.[a-z-0-9]+\\.html$")) {
313                         // funcName is actually a page reference, strip the prefix and suffix
314                         funcName = funcName.substring(0, funcName.lastIndexOf('.'));
315                 }
316                 try {
317                         URL resolve = FileLocator.resolve(fileURL);
318                         ZipFile docFile = new ZipFile(resolve.getPath());
319                         for (int i = 0; i < prefixes.length; i++) {
320                                 if ((entry = docFile.getEntry("doc/" + prefixes[i] +
321                                                 (prefixes[i].length() == 0 ? "" : ".") +
322                                                 funcName.replace('_', '-') + ".html")) != null) {
323                                         // Document was matched
324                                         InputStream ref = docFile.getInputStream(entry);
325                                         b = new byte[(int)entry.getSize()];
326                                         ref.read(b, 0, (int)entry.getSize());
327                                         if (b != null) {
328                                                 String reference = filterHtmlSource(new String(b));
329                                                 String refPageTpl = getRefPageTemplate();
330                                                 refPageTpl = refPageTpl.replaceAll("%title%", funcName);
331                                                 refPageTpl = replace(refPageTpl, "%reference%", reference);
332                                                 return refPageTpl;
333                                         }
334                                 }
335                         }
336                 } catch (IOException e) {
337                         return "<html>" + PHPManualUIPlugin.getString("LookupException") + "</html>";
338                 } catch (Exception e) {
339                         return null;
340                 }
341                 return null; // Keeps the last reference
342         }
343
344         /**
345          * Returns the currently active java editor, or <code>null</code> if it
346          * cannot be determined.
347          * 
348          * @return the currently active java editor, or <code>null</code>
349          */
350         private PHPEditor getJavaEditor() {
351                 try {
352                         IEditorPart part = PHPeclipsePlugin.getActivePage().getActiveEditor();
353                         if (part instanceof PHPEditor)
354                                 return (PHPEditor) part;
355                         else
356                                 return null;
357                 } catch (Exception e) {
358                         return null;
359                 }
360         }
361
362 }