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;
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;
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.
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.
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.
66 public class PHPManualView extends ViewPart implements INullSelectionListener, ISelectionListenerWithAST {
69 * The ViewPart's browser
71 private Browser browser;
74 * A reference to store last active editor to know when we've
75 * got a new instance of the PHPEditor
77 private PHPEditor lastEditor;
80 * String that stores the last selected word
82 private String lastOccurrence = null;
85 * The path to the doc.zip file containing the PHP Manual
88 private final Path docPath = new Path("doc.zip");
93 public PHPManualView() {
97 * This method initializes the ViewPart. It instantiates components
100 * @param parent The parent control
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];
120 if ((lastEditor = getJavaEditor()) != null) {
121 SelectionListenerWithASTManager.getDefault().addListener(lastEditor, this);
123 getSite().getWorkbenchWindow().getSelectionService()
124 .addPostSelectionListener(PHPeclipsePlugin.EDITOR_ID, this);
127 * Cleanup to remove the selection listener
129 public void dispose() {
130 getSite().getWorkbenchWindow().getSelectionService()
131 .removePostSelectionListener(PHPeclipsePlugin.EDITOR_ID, this);
135 * Passing the focus request to the viewer's control.
137 public void setFocus() {
142 * Treats selection changes from the PHPEditor
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) {
150 final String wordStr = document.get(iRegion.getOffset(),
151 iRegion.getLength());
152 if (!wordStr.equalsIgnoreCase(lastOccurrence)) {
153 showReference(wordStr);
154 lastOccurrence = wordStr;
156 } catch (Exception e) {
163 * Treats selection changes from the workbench. When part is new
164 * instance of PHPEditor it gets a listener attached
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;
171 System.out.println(part);
176 * Updates the browser with the reference page for a given function
178 * @param funcName Function name
180 private void showReference(final String funcName) {
181 new Thread(new Runnable() {
183 Display.getDefault().asyncExec(new Runnable() {
185 String html = getHtmlSource(funcName);
186 browser.setText(html);
194 * Filters the function's reference page extracting only parts of it
196 * @param source HTML source of the reference page
197 * @return HTML source of reference page
199 private String filterHtmlSource(String source) {
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());
220 return output.toString().replaceAll("—", "-");
221 //.replace("<h3 class=\"title\">Description</h3>", " ");
222 } catch (ParserException e) {
228 * Reads the template that defines the style of the reference page
229 * shown inside the view's browser
231 * @return HTML source of the template
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;
239 URL resolve = FileLocator.resolve(fileURL);
240 input = new BufferedReader(new FileReader(resolve.getPath()+"/refpage.html"));
242 while ((line = input.readLine()) != null){
243 contents.append(line);
246 catch (FileNotFoundException e) {
248 } catch (IOException e) {
257 catch (IOException ex) {
258 ex.printStackTrace();
261 return contents.toString();
265 * Replaces each substring of source string that matches the
266 * given pattern string with the given replace string
268 * @param source The source string
269 * @param pattern The pattern string
270 * @param replace The replace string
271 * @return The resulting String
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();
279 while ((found = source.indexOf(pattern, start)) != -1) {
280 sb.append(source.substring(start, found));
284 sb.append(source.substring(start));
285 return sb.toString();
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
297 * @return HTML source of reference page
299 public String getHtmlSource(String funcName) {
300 if (funcName.length() == 0) {
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" };
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('.'));
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());
328 String reference = filterHtmlSource(new String(b));
329 String refPageTpl = getRefPageTemplate();
330 refPageTpl = refPageTpl.replaceAll("%title%", funcName);
331 refPageTpl = replace(refPageTpl, "%reference%", reference);
336 } catch (IOException e) {
337 return "<html>" + PHPManualUIPlugin.getString("LookupException") + "</html>";
338 } catch (Exception e) {
341 return "<html>" + PHPManualUIPlugin.getString("LookupMiss") + "</html>";
345 * Returns the currently active java editor, or <code>null</code> if it
346 * cannot be determined.
348 * @return the currently active java editor, or <code>null</code>
350 private PHPEditor getJavaEditor() {
352 IEditorPart part = PHPeclipsePlugin.getActivePage().getActiveEditor();
353 if (part instanceof PHPEditor)
354 return (PHPEditor) part;
357 } catch (Exception e) {