1 package net.sourceforge.phpeclipse.phpmanual.views;
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;
9 import java.util.Arrays;
10 import java.util.ArrayList;
11 import java.util.zip.ZipEntry;
12 import java.util.zip.ZipFile;
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;
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;
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.
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.
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.
67 public class PHPManualView extends ViewPart implements INullSelectionListener, ISelectionListenerWithAST {
70 * The ViewPart's browser
72 private Browser browser;
75 * A reference to store last active editor to know when we've
76 * got a new instance of the PHPEditor
78 private PHPEditor lastEditor;
81 * String that stores the last selected word
83 private String lastOccurrence = null;
86 * The path to the doc.zip file containing the PHP Manual
89 private final Path docPath = new Path("doc.zip");
94 public PHPManualView() {
98 * This method initializes the ViewPart. It instantiates components
101 * @param parent The parent control
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];
121 if ((lastEditor = getJavaEditor()) != null) {
122 SelectionListenerWithASTManager.getDefault().addListener(lastEditor, this);
124 getSite().getWorkbenchWindow().getSelectionService()
125 .addPostSelectionListener(PHPeclipsePlugin.EDITOR_ID, this);
128 * Cleanup to remove the selection listener
130 public void dispose() {
131 getSite().getWorkbenchWindow().getSelectionService()
132 .removePostSelectionListener(PHPeclipsePlugin.EDITOR_ID, this);
136 * Passing the focus request to the viewer's control.
138 public void setFocus() {
143 * Treats selection changes from the PHPEditor
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) {
151 final String wordStr = document.get(iRegion.getOffset(),
152 iRegion.getLength());
153 if (!wordStr.equalsIgnoreCase(lastOccurrence)) {
154 showReference(wordStr);
155 lastOccurrence = wordStr;
157 } catch (Exception e) {
164 * Treats selection changes from the workbench. When part is new
165 * instance of PHPEditor it gets a listener attached
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;
175 * Updates the browser with the reference page for a given function
177 * @param funcName Function name
179 private void showReference(final String funcName) {
180 new Thread(new Runnable() {
182 Display.getDefault().asyncExec(new Runnable() {
184 String html = getHtmlSource(funcName);
185 browser.setText(html);
193 * Filters the function's reference page extracting only parts of it
195 * @param source HTML source of the reference page
196 * @return HTML source of reference page
198 private String filterHtmlSource(String source) {
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());
219 return output.toString().replaceAll("—", "-");
220 //.replace("<h3 class=\"title\">Description</h3>", " ");
221 } catch (ParserException e) {
227 * Reads the template that defines the style of the reference page
228 * shown inside the view's browser
230 * @return HTML source of the template
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;
238 URL resolve = FileLocator.resolve(fileURL);
239 input = new BufferedReader(new FileReader(resolve.getPath()+"/refpage.html"));
241 while ((line = input.readLine()) != null){
242 contents.append(line);
245 catch (FileNotFoundException e) {
247 } catch (IOException e) {
256 catch (IOException ex) {
257 ex.printStackTrace();
260 return contents.toString();
264 * Replaces each substring of source string that matches the
265 * given pattern string with the given replace string
267 * @param source The source string
268 * @param pattern The pattern string
269 * @param replace The replace string
270 * @return The resulting String
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();
278 while ((found = source.indexOf(pattern, start)) != -1) {
279 sb.append(source.substring(start, found));
283 sb.append(source.substring(start));
284 return sb.toString();
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
296 * @return HTML source of reference page
298 public String getHtmlSource(String funcName) {
299 if (funcName.length() == 0) {
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" };
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('.'));
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());
327 String reference = filterHtmlSource(new String(b));
328 String refPageTpl = getRefPageTemplate();
329 refPageTpl = refPageTpl.replaceAll("%title%", funcName);
330 refPageTpl = replace(refPageTpl, "%reference%", reference);
335 } catch (IOException e) {
336 return "<html>" + PHPManualUIPlugin.getString("LookupException") + "</html>";
337 } catch (Exception e) {
340 return null; // Keeps the last reference
344 * Returns the currently active java editor, or <code>null</code> if it
345 * cannot be determined.
347 * @return the currently active java editor, or <code>null</code>
349 private PHPEditor getJavaEditor() {
351 IEditorPart part = /*PHPeclipsePlugin*/WebUI.getActivePage().getActiveEditor();
352 if (part instanceof PHPEditor)
353 return (PHPEditor) part;
356 } catch (Exception e) {