Truly prevents the location update and the display of the "location not found" dialog box
[phpeclipse.git] / net.sourceforge.phpeclipse.phpmanual / src / net / sourceforge / phpeclipse / phpmanual / views / PHPManualView.java
index fe2cace..ed0ef3e 100644 (file)
@@ -1,6 +1,5 @@
 package net.sourceforge.phpeclipse.phpmanual.views;
 
-
 import java.io.BufferedReader;
 import java.io.FileNotFoundException;
 import java.io.FileReader;
@@ -19,33 +18,22 @@ import net.sourceforge.phpeclipse.PHPeclipsePlugin;
 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
 import net.sourceforge.phpeclipse.phpmanual.PHPManualUIPlugin;
 
+import org.eclipse.core.runtime.FileLocator;
 import org.eclipse.core.runtime.Path;
 import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.dialogs.MessageDialog;
 import org.eclipse.jface.text.IDocument;
 import org.eclipse.jface.text.IRegion;
 import org.eclipse.jface.text.ITextSelection;
 import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
 import org.eclipse.swt.SWT;
+import org.eclipse.swt.browser.Browser;
+import org.eclipse.swt.browser.LocationAdapter;
+import org.eclipse.swt.browser.LocationEvent;
 import org.eclipse.swt.widgets.Composite;
 import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.browser.Browser;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Menu;
 import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbenchActionConstants;
-import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.INullSelectionListener;
+import org.eclipse.ui.IWorkbenchPart;
 import org.eclipse.ui.part.ViewPart;
 import org.htmlparser.Node;
 import org.htmlparser.Parser;
@@ -55,28 +43,45 @@ import org.htmlparser.visitors.TagFindingVisitor;
 import org.osgi.framework.Bundle;
 
 /**
- * This sample class demonstrates how to plug-in a new
- * workbench view. The view shows data obtained from the
- * model. The sample creates a dummy model on the fly,
- * but a real implementation would connect to the model
- * available either in this or another plug-in (e.g. the workspace).
- * The view is connected to the model using a content provider.
+ * This ViewPart is the implementation of the idea of having the 
+ * PHP Manual easily accessible while coding. It shows the
+ * under-cursor function's reference inside a browser.
  * <p>
- * The view uses a label provider to define how model
- * objects should be presented in the view. Each
- * view can present the same model objects using
- * different labels and icons, if needed. Alternatively,
- * a single label provider can be shared between views
- * in order to ensure that objects of the same type are
- * presented in the same way everywhere.
+ * The view listens to selection changes both in the (1)workbench, to
+ * know when the user changes between the instances of the PHPEditor
+ * or when a new instance is created; and in the (2)PHPEditor, to know
+ * when the user changes the cursor position. This explains the need
+ * to implement both ISelectionListener and ISelectionListenerWithAST.
  * <p>
+ * Up to now, the ViewPart show reference pages from HTML stored in the
+ * doc.zip file from the net.sourceforge.phpeclipse.phphelp plugin. It
+ * also depends on net.sourceforge.phpeclipse.phpmanual.htmlparser to
+ * parse these HTML files.
+ * <p>
+ * @author scorphus
  */
+public class PHPManualView extends ViewPart implements INullSelectionListener, ISelectionListenerWithAST {
 
-public class PHPManualView extends ViewPart implements ISelectionListenerWithAST {
+       /**
+        * The ViewPart's browser
+        */
        private Browser browser;
-       private Action action1;
-       private Action action2;
-       private PHPEditor phpEditor;
+
+       /**
+        * A reference to store last active editor to know when we've
+        * got a new instance of the PHPEditor
+        */
+       private PHPEditor lastEditor;
+
+       /**
+        * String that stores the last selected word
+        */
+       private String lastOccurrence = null;
+
+       /**
+        * The path to the doc.zip file containing the PHP Manual
+        * in HTML format
+        */
        private final Path docPath = new Path("doc.zip"); 
 
        /**
@@ -86,117 +91,246 @@ public class PHPManualView extends ViewPart implements ISelectionListenerWithAST
        }
 
        /**
-        * This is a callback that will allow us
-        * to create the viewer and initialize it.
+        * This method initializes the ViewPart. It instantiates components
+        * and add listeners
+        * 
+        * @param parent The parent control
         */
        public void createPartControl(Composite parent) {
                browser = new Browser(parent, SWT.NONE);
+               browser.addLocationListener(new LocationAdapter() {
+                       public void changing(LocationEvent event) {
+                               String loc = event.location.toString();
+                               if(!loc.equalsIgnoreCase("about:blank") && !loc.startsWith("jar:")) {
+                                       String func = loc.replaceAll("file:///", "");
+                                       func = func.replaceAll("#.+$", "");
+                                       String[] afunc = loc.split("\\.");
+                                       if(!afunc[1].equalsIgnoreCase(lastOccurrence)) {
+                                               lastOccurrence = afunc[1];
+                                               showLinkReference(func);
+                                               event.doit = false;
+                                       }
+                               } else if (loc.startsWith("jar:")) {
+                                       // TODO find a better way of not showing the location error page. This is a cheap trick
+                                       // to keep the page from showing.
+                                       // ed_mann
+                                       browser.setText("<html></html>");
+                               }
+                       }
+               });
                parent.pack();
-               phpEditor = getJavaEditor();
-               makeActions();
-               hookContextMenu();
-               SelectionListenerWithASTManager.getDefault().addListener(phpEditor, this);
-               if (phpEditor.getSelectionProvider() != null) {
-                       ISelection its = phpEditor.getSelectionProvider().getSelection();
-                       SelectionListenerWithASTManager.getDefault().forceSelectionChange(
-                                       phpEditor, (ITextSelection) its);
+               if ((lastEditor = getJavaEditor()) != null) {
+                       SelectionListenerWithASTManager.getDefault().addListener(lastEditor, this);
                }
+               getSite().getWorkbenchWindow().getSelectionService()
+                               .addPostSelectionListener(PHPeclipsePlugin.EDITOR_ID, this);
        }
 
-       /* (non-Javadoc)
-        * @see net.sourceforge.phpdt.internal.ui.viewsupport.ISelectionListenerWithAST#selectionChanged()
+       /**
+        * Cleanup to remove the selection listener
+        */
+       public void dispose() {
+               getSite().getWorkbenchWindow().getSelectionService()
+                               .removePostSelectionListener(PHPeclipsePlugin.EDITOR_ID, this);
+       }
+
+       /**
+        * Passing the focus request to the viewer's control.
+        */
+       public void setFocus() {
+               browser.setFocus();
+       }
+
+       /**
+        * Treats selection changes from the PHPEditor
         */
        public void selectionChanged(IEditorPart part, ITextSelection selection) {
-               if (getJavaEditor() != null) {
-                       phpEditor = getJavaEditor();
-               }
-               IDocument document = phpEditor.getViewer().getDocument();
+               IDocument document = ((PHPEditor)part).getViewer().getDocument();
                int offset = selection.getOffset();
                IRegion iRegion = JavaWordFinder.findWord(document, offset);
-               try {
-                       final String wordStr = document.get(iRegion.getOffset(),
-                                       iRegion.getLength());
-                       showReference(wordStr);
-               } catch (Exception e) {
-                       // TODO Auto-generated catch block
-                       e.printStackTrace();
+               if (document != null && iRegion != null) {
+                       try {
+                               final String wordStr = document.get(iRegion.getOffset(),
+                                               iRegion.getLength());
+                               if (!wordStr.equalsIgnoreCase(lastOccurrence)) {
+                                       showReference(wordStr);                         
+                                       lastOccurrence = wordStr;
+                               }
+                       } catch (Exception e) {
+                               e.printStackTrace();
+                       }
                }
        }
 
-       private void showReference(final String occurrence) {
-               System.out.println("Show reference for " + occurrence);
+       /**
+        * Treats selection changes from the workbench. When part is new
+        * instance of PHPEditor it gets a listener attached
+        */
+       public void selectionChanged(IWorkbenchPart part, ISelection selection) {
+               if (part != null && !((PHPEditor)part).equals(lastEditor)) {
+                       SelectionListenerWithASTManager.getDefault().addListener((PHPEditor)part, this);
+                       lastEditor = (PHPEditor)part;
+               } else {
+                       System.out.println(part);
+               }
+       }
+
+       /**
+        * Updates the browser with the reference page for a given function
+        * 
+        * @param funcName Function name
+        */
+       private void showReference(final String funcName) {
                new Thread(new Runnable() {
                        public void run() {
                                Display.getDefault().asyncExec(new Runnable() {
                                        public void run() {
-                                               String html = getHtmlSource(occurrence);
+                                               String html = getHtmlSource(funcName);
                                                browser.setText(html);
                                        }
                                });
                        }
                }).start();
        }
-
-       private void hookContextMenu() {
-               MenuManager menuMgr = new MenuManager("#PopupMenu");
-               menuMgr.setRemoveAllWhenShown(true);
-               menuMgr.addMenuListener(new IMenuListener() {
-                       public void menuAboutToShow(IMenuManager manager) {
-                               PHPManualView.this.fillContextMenu(manager);
+       
+       /**
+        * Updates the browser with the reference page for a given function
+        * 
+        * @param funcName Function name
+        */
+       private void showLinkReference(final String funcName) {
+               new Thread(new Runnable() {
+                       public void run() {
+                               Display.getDefault().asyncExec(new Runnable() {
+                                       public void run() {
+                                               String html = getLinkHtmlSource(funcName);
+                                               browser.setText(html);
+                                       }
+                               });
                        }
-               });
-//             Menu menu = menuMgr.createContextMenu(viewer.getControl());
-//             viewer.getControl().setMenu(menu);
-//             getSite().registerContextMenu(menuMgr, viewer);
-       }
-
-       private void fillContextMenu(IMenuManager manager) {
-               manager.add(action1);
-               manager.add(action2);
-               // Other plug-ins can contribute there actions here
-               manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
+               }).start();
        }
 
-       private void makeActions() {
-               action1 = new Action() {
-                       public void run() {
-                               showMessage("Action 1 executed");
+       /**
+        * Filters the function's reference page extracting only parts of it
+        * 
+        * @param source HTML source of the reference page
+        * @return HTML source of reference page
+        */
+       private String filterIniHtmlSource(String source) {
+               try {
+                       Parser parser = new Parser(source);
+                       String [] tagsToBeFound = {"DIV"};
+                       ArrayList classList = new ArrayList(8);
+                       classList.add("section");
+                       classList.add("title");
+                       classList.add("refsect1 parameters");
+                       classList.add("refsect1 returnvalues");
+                       classList.add("refsect1 examples");
+                       classList.add("refsect1 seealso");
+                       classList.add("refsect1 u");
+                       TagFindingVisitor visitor = new TagFindingVisitor(tagsToBeFound);
+                       parser.visitAllNodesWith(visitor);
+                       Node [] allPTags = visitor.getTags(0);
+                       StringBuffer output = new StringBuffer();
+                       for (int i = 0; i < allPTags.length; i++) {
+                               String tagClass = ((Div)allPTags[i]).getAttribute("class");
+                               if (classList.contains(tagClass)) {
+                                       output.append(allPTags[i].toHtml());
+                               }
                        }
-               };
-               action1.setText("Action 1");
-               action1.setToolTipText("Action 1 tooltip");
-               action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
-                       getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
-               
-               action2 = new Action() {
-                       public void run() {
-                               showMessage("Action 2 executed");
+                       return output.toString().replaceAll("—", "-");
+                       //.replace("<h3 class=\"title\">Description</h3>", " ");
+               } catch (ParserException e) {
+                       e.printStackTrace();
+               }
+               return "";
+       }
+       
+       /**
+        * Filters the function's reference page extracting only parts of it
+        * 
+        * @param source HTML source of the reference page
+        * @return HTML source of reference page
+        */
+       private String filterLangHtmlSource(String source) {
+               try {
+                       Parser parser = new Parser(source);
+                       String [] tagsToBeFound = {"DIV"};
+                       ArrayList classList = new ArrayList(8);
+                       classList.add("sect1");
+                       classList.add("title");
+                       classList.add("refsect1 parameters");
+                       classList.add("refsect1 returnvalues");
+                       classList.add("refsect1 examples");
+                       classList.add("refsect1 seealso");
+                       classList.add("refsect1 u");
+                       TagFindingVisitor visitor = new TagFindingVisitor(tagsToBeFound);
+                       parser.visitAllNodesWith(visitor);
+                       Node [] allPTags = visitor.getTags(0);
+                       StringBuffer output = new StringBuffer();
+                       for (int i = 0; i < allPTags.length; i++) {
+                               String tagClass = ((Div)allPTags[i]).getAttribute("class");
+                               if (classList.contains(tagClass)) {
+                                       output.append(allPTags[i].toHtml());
+                               }
                        }
-               };
-               action2.setText("Action 2");
-               action2.setToolTipText("Action 2 tooltip");
-               action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
-                               getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
+                       return output.toString().replaceAll("—", "-");
+                       //.replace("<h3 class=\"title\">Description</h3>", " ");
+               } catch (ParserException e) {
+                       e.printStackTrace();
+               }
+               return "";
        }
-
-       private void showMessage(String message) {
-//             MessageDialog.openInformation(
-//                     viewer.getControl().getShell(),
-//                     "%phpManualView",
-//                     message);
+       
+       /**
+        * Filters the function's reference page extracting only parts of it
+        * 
+        * @param source HTML source of the reference page
+        * @return HTML source of reference page
+        */
+       private String filterRefHtmlSource(String source) {
+               try {
+                       Parser parser = new Parser(source);
+                       String [] tagsToBeFound = {"DIV"};
+                       ArrayList classList = new ArrayList(8);
+                       classList.add("partintro");
+                       classList.add("section");
+                       classList.add("title");
+                       classList.add("refsect1 parameters");
+                       classList.add("refsect1 returnvalues");
+                       classList.add("refsect1 examples");
+                       classList.add("refsect1 seealso");
+                       classList.add("refsect1 u");
+                       TagFindingVisitor visitor = new TagFindingVisitor(tagsToBeFound);
+                       parser.visitAllNodesWith(visitor);
+                       Node [] allPTags = visitor.getTags(0);
+                       StringBuffer output = new StringBuffer();
+                       for (int i = 0; i < allPTags.length; i++) {
+                               String tagClass = ((Div)allPTags[i]).getAttribute("class");
+                               if (classList.contains(tagClass)) {
+                                       output.append(allPTags[i].toHtml());
+                               }
+                       }
+                       return output.toString().replaceAll("—", "-");
+                       //.replace("<h3 class=\"title\">Description</h3>", " ");
+               } catch (ParserException e) {
+                       e.printStackTrace();
+               }
+               return "";
        }
-
+       
        /**
-        * Looks for the function's reference page inside the doc.zip file and
-        * returns a filtered HTML source of it
-        * @param funcName Function name
+        * Filters the function's reference page extracting only parts of it
+        * 
+        * @param source HTML source of the reference page
         * @return HTML source of reference page
         */
        private String filterHtmlSource(String source) {
                try {
                        Parser parser = new Parser(source);
                        String [] tagsToBeFound = {"DIV"};
-                       ArrayList<String> classList = new ArrayList<String>(6);
+                       ArrayList classList = new ArrayList(8);
                        classList.add("refnamediv");
                        classList.add("refsect1 description");
                        classList.add("refsect1 parameters");
@@ -207,35 +341,33 @@ public class PHPManualView extends ViewPart implements ISelectionListenerWithAST
                        TagFindingVisitor visitor = new TagFindingVisitor(tagsToBeFound);
                        parser.visitAllNodesWith(visitor);
                        Node [] allPTags = visitor.getTags(0);
-                       StringBuilder output = new StringBuilder();
+                       StringBuffer output = new StringBuffer();
                        for (int i = 0; i < allPTags.length; i++) {
                                String tagClass = ((Div)allPTags[i]).getAttribute("class");
                                if (classList.contains(tagClass)) {
                                        output.append(allPTags[i].toHtml());
                                }
                        }
-                       return output.toString().replace("—", "-");
+                       return output.toString().replaceAll("—", "-");
                        //.replace("<h3 class=\"title\">Description</h3>", " ");
                } catch (ParserException e) {
-                       // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                return "";
        }
-
        /**
-        * Looks for the function's reference page inside the doc.zip file and
-        * returns a filtered HTML source of it
-        * @param funcName Function name
-        * @return HTML source of reference page
+        * Reads the template that defines the style of the reference page
+        * shown inside the view's browser
+        * 
+        * @return HTML source of the template
         */
        public String getRefPageTemplate() {
                Bundle bundle = Platform.getBundle(PHPManualUIPlugin.PLUGIN_ID);
-               URL fileURL = Platform.find(bundle, new Path("templates"));
+               URL fileURL = FileLocator.find(bundle, new Path("templates"), null);
                StringBuffer contents = new StringBuffer();
                BufferedReader input = null;
                try {
-                       URL resolve = Platform.resolve(fileURL);
+                       URL resolve = FileLocator.resolve(fileURL);
                        input = new BufferedReader(new FileReader(resolve.getPath()+"/refpage.html"));
                        String line = null;
                        while ((line = input.readLine()) != null){
@@ -261,42 +393,116 @@ public class PHPManualView extends ViewPart implements ISelectionListenerWithAST
        }
 
        /**
+        * Replaces each substring of source string that matches the
+        * given pattern string with the given replace string
+        * 
+        * @param source The source string
+        * @param pattern The pattern string
+        * @param replace The replace string
+        * @return The resulting String
+        */
+       public static String replace(String source, String pattern, String replace) {
+               if (source != null) {
+                       final int len = pattern.length();
+                       StringBuffer sb = new StringBuffer();
+                       int found = -1;
+                       int start = 0;
+                       while ((found = source.indexOf(pattern, start)) != -1) {
+                               sb.append(source.substring(start, found));
+                               sb.append(replace);
+                               start = found + len;
+                       }
+                       sb.append(source.substring(start));
+                       return sb.toString();
+               } else {
+                       return "";
+               }
+       }
+
+       /**
         * Looks for the function's reference page inside the doc.zip file and
-        * returns a filtered HTML source of it
-        * @param funcName Function name
+        * returns a filtered HTML source of it embedded in the template
+        * 
+        * @param funcName
+        *            Function name
         * @return HTML source of reference page
         */
        public String getHtmlSource(String funcName) {
                Bundle bundle = Platform.getBundle(PHPHelpPlugin.PLUGIN_ID);
-               URL fileURL = Platform.find(bundle, docPath);
+               URL fileURL = FileLocator.find(bundle, docPath, null);
+               ZipEntry entry;
                byte[] b = null;
                try {
-                       URL resolve = Platform.resolve(fileURL);
+                       URL resolve = FileLocator.resolve(fileURL);
                        ZipFile docFile = new ZipFile(resolve.getPath());
-                       ZipEntry entry = docFile.getEntry("doc/function."+funcName.replace('_', '-')+".html");
+                       entry = docFile.getEntry("doc/function."+funcName.replace('_', '-')+".html");
+                       if(entry == null){
+                               entry = docFile.getEntry("doc/ini."+funcName.replace('_', '-')+".html");
+                       }
                        InputStream ref = docFile.getInputStream(entry);
                        b = new byte[(int)entry.getSize()];
                        ref.read(b, 0, (int)entry.getSize());
+                       if (b != null) {
+                               String reference = filterHtmlSource(new String(b));
+                               String refPageTpl = getRefPageTemplate();
+                               refPageTpl = refPageTpl.replaceAll("%title%", funcName);
+                               refPageTpl = replace(refPageTpl, "%reference%", reference);
+                               return refPageTpl;
+                       }
                } catch (IOException e) {
                        return "<html></html>";
-               }
-               if (b != null) {
-                       String reference = filterHtmlSource(new String(b));
-                       String refPageTpl = getRefPageTemplate();
-                       refPageTpl = refPageTpl.replace("{title}", funcName);
-                       refPageTpl = refPageTpl.replace("{reference}", reference);
-                       return refPageTpl;
+               } catch (Exception e) {
+                       return null;
                }
                return "<html></html>";
        }
 
        /**
-        * Passing the focus request to the viewer's control.
+        * Looks for the function's reference page inside the doc.zip file and
+        * returns a filtered HTML source of it embedded in the template
+        * 
+        * @param funcName
+        *            Function name
+        * @return HTML source of reference page
         */
-       public void setFocus() {
-//             viewer.getControl().setFocus();
+       public String getLinkHtmlSource(String funcName) {
+               Bundle bundle = Platform.getBundle(PHPHelpPlugin.PLUGIN_ID);
+               URL fileURL = FileLocator.find(bundle, docPath, null);
+               ZipEntry entry;
+               byte[] b = null;
+               try {
+                       URL resolve = FileLocator.resolve(fileURL);
+                       ZipFile docFile = new ZipFile(resolve.getPath());
+                       entry = docFile.getEntry("doc/"+funcName);
+                       InputStream ref = docFile.getInputStream(entry);
+                       b = new byte[(int)entry.getSize()];
+                       ref.read(b, 0, (int)entry.getSize());
+                       if (b != null) {
+                               String reference = null;
+                               String aFuncName = funcName.toString();
+                               if(aFuncName.startsWith("function")){
+                                       reference = filterHtmlSource(new String(b));
+                               } else if (aFuncName.startsWith("ini")){
+                                       reference = filterIniHtmlSource(new String(b));
+                               } else if (aFuncName.startsWith("install")){
+                                       reference = filterIniHtmlSource(new String(b));
+                               } else if (aFuncName.startsWith("language")){
+                                       reference = filterLangHtmlSource(new String(b));
+                               } else if (aFuncName.startsWith("ref")){
+                                       reference = filterRefHtmlSource(new String(b));
+                               }
+                               String refPageTpl = getRefPageTemplate();
+                               refPageTpl = refPageTpl.replaceAll("%title%", funcName);
+                               refPageTpl = replace(refPageTpl, "%reference%", reference);
+                               return refPageTpl;
+                       }
+               } catch (IOException e) {
+                       return "<html></html>";
+               } catch (Exception e) {
+                       return null;
+               }
+               return "<html></html>";
        }
-
        /**
         * Returns the currently active java editor, or <code>null</code> if it
         * cannot be determined.
@@ -311,7 +517,6 @@ public class PHPManualView extends ViewPart implements ISelectionListenerWithAST
                        else
                                return null;
                } catch (Exception e) {
-                       e.printStackTrace();
                        return null;
                }
        }