Merging code from trunk that fixes #774, this work was done by incastrix
[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                 }
171         }
172
173         /**
174          * Updates the browser with the reference page for a given function
175          * 
176          * @param funcName Function name
177          */
178         private void showReference(final String funcName) {
179                 new Thread(new Runnable() {
180                         public void run() {
181                                 Display.getDefault().asyncExec(new Runnable() {
182                                         public void run() {
183                                                 String html = getHtmlSource(funcName);
184                                                 browser.setText(html);
185                                         }
186                                 });
187                         }
188                 }).start();
189         }
190         
191         /**
192          * Filters the function's reference page extracting only parts of it
193          * 
194          * @param source HTML source of the reference page
195          * @return HTML source of reference page
196          */
197         private String filterHtmlSource(String source) {
198                 try {
199                         Parser parser = new Parser(source);
200                         String[] tagsToBeFound = { "DIV" };
201                         // Common classes to be included for all page types
202                         ArrayList classList = new ArrayList(Arrays.asList(new String[] {
203                                         "section", "sect1", "title", "partintro", "refnamediv",
204                                         "refsect1 description", "refsect1 parameters",
205                                         "refsect1 returnvalues", "refsect1 examples",
206                                         "refsect1 seealso", "refsect1 u", "example-contents" }));
207                         // Grab all the tags for processing
208                         TagFindingVisitor visitor = new TagFindingVisitor(tagsToBeFound);
209                         parser.visitAllNodesWith(visitor);
210                         Node [] allPTags = visitor.getTags(0);
211                         StringBuffer output = new StringBuffer();
212                         for (int i = 0; i < allPTags.length; i++) {
213                                 String tagClass = ((Div)allPTags[i]).getAttribute("class");
214                                 if (classList.contains(tagClass)) {
215                                         output.append(allPTags[i].toHtml());
216                                 }
217                         }
218                         return output.toString().replaceAll("—", "-");
219                         //.replace("<h3 class=\"title\">Description</h3>", " ");
220                 } catch (ParserException e) {
221                         e.printStackTrace();
222                 }
223                 return "";
224         }
225         /**
226          * Reads the template that defines the style of the reference page
227          * shown inside the view's browser
228          * 
229          * @return HTML source of the template
230          */
231         public String getRefPageTemplate() {
232                 Bundle bundle = Platform.getBundle(PHPManualUIPlugin.PLUGIN_ID);
233                 URL fileURL = FileLocator.find(bundle, new Path("templates"), null);
234                 StringBuffer contents = new StringBuffer();
235                 BufferedReader input = null;
236                 try {
237                         URL resolve = FileLocator.resolve(fileURL);
238                         input = new BufferedReader(new FileReader(resolve.getPath()+"/refpage.html"));
239                         String line = null;
240                         while ((line = input.readLine()) != null){
241                                 contents.append(line);
242                         }
243                 }
244                 catch (FileNotFoundException e) {
245                         e.printStackTrace();
246                 } catch (IOException e) {
247                         e.printStackTrace();
248                 }
249                 finally {
250                         try {
251                                 if (input!= null) {
252                                         input.close();
253                                 }
254                         }
255                         catch (IOException ex) {
256                                 ex.printStackTrace();
257                         }
258                 }
259                 return contents.toString();
260         }
261
262         /**
263          * Replaces each substring of source string that matches the
264          * given pattern string with the given replace string
265          * 
266          * @param source The source string
267          * @param pattern The pattern string
268          * @param replace The replace string
269          * @return The resulting String
270          */
271         public static String replace(String source, String pattern, String replace) {
272                 if (source != null) {
273                         final int len = pattern.length();
274                         StringBuffer sb = new StringBuffer();
275                         int found = -1;
276                         int start = 0;
277                         while ((found = source.indexOf(pattern, start)) != -1) {
278                                 sb.append(source.substring(start, found));
279                                 sb.append(replace);
280                                 start = found + len;
281                         }
282                         sb.append(source.substring(start));
283                         return sb.toString();
284                 } else {
285                         return "";
286                 }
287         }
288
289         /**
290          * Looks for the function's reference page inside the doc.zip file and
291          * returns a filtered HTML source of it embedded in the template
292          * 
293          * @param funcName
294          *            Function name
295          * @return HTML source of reference page
296          */
297         public String getHtmlSource(String funcName) {
298                 if (funcName.length() == 0) {
299                         // Don't bother ;-) 
300                         return null;
301                 }
302                 Bundle bundle = Platform.getBundle(PHPHelpPlugin.PLUGIN_ID);
303                 URL fileURL = FileLocator.find(bundle, docPath, null);
304                 ZipEntry entry = null;
305                 // List of prefixes to lookup HTML files by, ordered so that looping
306                 // is as minimal as possible.  The empty value matches links passed,
307                 // rather than function 
308                 String[] prefixes = { "", "function", "control-structures", "ref", "http", "imagick", "ming" };
309                 byte[] b = null;
310                 if (funcName.matches("^[a-z-]+\\.[a-z-0-9]+\\.html$")) {
311                         // funcName is actually a page reference, strip the prefix and suffix
312                         funcName = funcName.substring(0, funcName.lastIndexOf('.'));
313                 }
314                 try {
315                         URL resolve = FileLocator.resolve(fileURL);
316                         ZipFile docFile = new ZipFile(resolve.getPath());
317                         for (int i = 0; i < prefixes.length; i++) {
318                                 if ((entry = docFile.getEntry("doc/" + prefixes[i] +
319                                                 (prefixes[i].length() == 0 ? "" : ".") +
320                                                 funcName.replace('_', '-') + ".html")) != null) {
321                                         // Document was matched
322                                         InputStream ref = docFile.getInputStream(entry);
323                                         b = new byte[(int)entry.getSize()];
324                                         ref.read(b, 0, (int)entry.getSize());
325                                         if (b != null) {
326                                                 String reference = filterHtmlSource(new String(b));
327                                                 String refPageTpl = getRefPageTemplate();
328                                                 refPageTpl = refPageTpl.replaceAll("%title%", funcName);
329                                                 refPageTpl = replace(refPageTpl, "%reference%", reference);
330                                                 return refPageTpl;
331                                         }
332                                 }
333                         }
334                 } catch (IOException e) {
335                         return "<html>" + PHPManualUIPlugin.getString("LookupException") + "</html>";
336                 } catch (Exception e) {
337                         return null;
338                 }
339                 return null; // Keeps the last reference
340         }
341
342         /**
343          * Returns the currently active java editor, or <code>null</code> if it
344          * cannot be determined.
345          * 
346          * @return the currently active java editor, or <code>null</code>
347          */
348         private PHPEditor getJavaEditor() {
349                 try {
350                         IEditorPart part = PHPeclipsePlugin.getActivePage().getActiveEditor();
351                         if (part instanceof PHPEditor)
352                                 return (PHPEditor) part;
353                         else
354                                 return null;
355                 } catch (Exception e) {
356                         return null;
357                 }
358         }
359
360 }