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