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;
174 * Updates the browser with the reference page for a given function
176 * @param funcName Function name
178 private void showReference(final String funcName) {
179 new Thread(new Runnable() {
181 Display.getDefault().asyncExec(new Runnable() {
183 String html = getHtmlSource(funcName);
184 browser.setText(html);
192 * Filters the function's reference page extracting only parts of it
194 * @param source HTML source of the reference page
195 * @return HTML source of reference page
197 private String filterHtmlSource(String source) {
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());
218 return output.toString().replaceAll("—", "-");
219 //.replace("<h3 class=\"title\">Description</h3>", " ");
220 } catch (ParserException e) {
226 * Reads the template that defines the style of the reference page
227 * shown inside the view's browser
229 * @return HTML source of the template
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;
237 URL resolve = FileLocator.resolve(fileURL);
238 input = new BufferedReader(new FileReader(resolve.getPath()+"/refpage.html"));
240 while ((line = input.readLine()) != null){
241 contents.append(line);
244 catch (FileNotFoundException e) {
246 } catch (IOException e) {
255 catch (IOException ex) {
256 ex.printStackTrace();
259 return contents.toString();
263 * Replaces each substring of source string that matches the
264 * given pattern string with the given replace string
266 * @param source The source string
267 * @param pattern The pattern string
268 * @param replace The replace string
269 * @return The resulting String
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();
277 while ((found = source.indexOf(pattern, start)) != -1) {
278 sb.append(source.substring(start, found));
282 sb.append(source.substring(start));
283 return sb.toString();
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
295 * @return HTML source of reference page
297 public String getHtmlSource(String funcName) {
298 if (funcName.length() == 0) {
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" };
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('.'));
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());
326 String reference = filterHtmlSource(new String(b));
327 String refPageTpl = getRefPageTemplate();
328 refPageTpl = refPageTpl.replaceAll("%title%", funcName);
329 refPageTpl = replace(refPageTpl, "%reference%", reference);
334 } catch (IOException e) {
335 return "<html>" + PHPManualUIPlugin.getString("LookupException") + "</html>";
336 } catch (Exception e) {
339 return null; // Keeps the last reference
343 * Returns the currently active java editor, or <code>null</code> if it
344 * cannot be determined.
346 * @return the currently active java editor, or <code>null</code>
348 private PHPEditor getJavaEditor() {
350 IEditorPart part = PHPeclipsePlugin.getActivePage().getActiveEditor();
351 if (part instanceof PHPEditor)
352 return (PHPEditor) part;
355 } catch (Exception e) {