976f38536e29d543d444cb9419101e482a785f71
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / phpeditor / php / PHPCompletionProcessor.java
1 /**********************************************************************
2 Copyright (c) 2000, 2002 IBM Corp. and others.
3 All rights reserved. This program and the accompanying materials
4 are made available under the terms of the Common Public License v1.0
5 which accompanies this distribution, and is available at
6 http://www.eclipse.org/legal/cpl-v10.html
7
8 Contributors:
9     IBM Corporation - Initial implementation
10     Klaus Hartlage - www.eclipseproject.de
11 **********************************************************************/
12 package net.sourceforge.phpeclipse.phpeditor.php;
13
14 import java.util.ArrayList;
15 import java.util.Arrays;
16 import java.util.List;
17 import java.util.SortedMap;
18
19 import net.sourceforge.phpdt.core.ToolFactory;
20 import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
21 import net.sourceforge.phpdt.core.compiler.InvalidInputException;
22 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
23 import net.sourceforge.phpdt.internal.corext.template.ContextType;
24 import net.sourceforge.phpdt.internal.corext.template.ContextTypeRegistry;
25 import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContextType;
26 import net.sourceforge.phpdt.internal.corext.template.php.PHPUnitContext;
27 import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal;
28 import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator;
29 import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine;
30 import net.sourceforge.phpdt.internal.ui.text.template.DeclarationEngine;
31 import net.sourceforge.phpdt.internal.ui.text.template.IdentifierEngine;
32 import net.sourceforge.phpdt.internal.ui.text.template.TemplateEngine;
33 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
34 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
35 import net.sourceforge.phpeclipse.phpeditor.AbstractContentOutlinePage;
36 import net.sourceforge.phpeclipse.phpeditor.PHPContentOutlinePage;
37 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
38 import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr;
39
40 import org.eclipse.core.resources.IFile;
41 import org.eclipse.core.resources.IProject;
42 import org.eclipse.jface.text.BadLocationException;
43 import org.eclipse.jface.text.IDocument;
44 import org.eclipse.jface.text.IRegion;
45 import org.eclipse.jface.text.ITextViewer;
46 import org.eclipse.jface.text.Region;
47 import org.eclipse.jface.text.TextPresentation;
48 import org.eclipse.jface.text.contentassist.ICompletionProposal;
49 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
50 import org.eclipse.jface.text.contentassist.IContextInformation;
51 import org.eclipse.jface.text.contentassist.IContextInformationExtension;
52 import org.eclipse.jface.text.contentassist.IContextInformationPresenter;
53 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
54 import org.eclipse.swt.graphics.Image;
55 import org.eclipse.ui.IEditorPart;
56 import org.eclipse.ui.IFileEditorInput;
57
58 /**
59  * Example PHP completion processor.
60  */
61 public class PHPCompletionProcessor implements IContentAssistProcessor {
62
63   /**
64    * Simple content assist tip closer. The tip is valid in a range
65    * of 5 characters around its popup location.
66    */
67   protected static class Validator implements IContextInformationValidator, IContextInformationPresenter {
68
69     protected int fInstallOffset;
70
71     /*
72      * @see IContextInformationValidator#isContextInformationValid(int)
73      */
74     public boolean isContextInformationValid(int offset) {
75       return Math.abs(fInstallOffset - offset) < 5;
76     }
77
78     /*
79      * @see IContextInformationValidator#install(IContextInformation, ITextViewer, int)
80      */
81     public void install(IContextInformation info, ITextViewer viewer, int offset) {
82       fInstallOffset = offset;
83     }
84
85     /*
86      * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int, TextPresentation)
87      */
88     public boolean updatePresentation(int documentPosition, TextPresentation presentation) {
89       return false;
90     }
91   };
92
93   private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension {
94
95     private final IContextInformation fContextInformation;
96     private int fPosition;
97
98     public ContextInformationWrapper(IContextInformation contextInformation) {
99       fContextInformation = contextInformation;
100     }
101
102     /*
103      * @see IContextInformation#getContextDisplayString()
104      */
105     public String getContextDisplayString() {
106       return fContextInformation.getContextDisplayString();
107     }
108
109     /*
110     * @see IContextInformation#getImage()
111     */
112     public Image getImage() {
113       return fContextInformation.getImage();
114     }
115
116     /*
117      * @see IContextInformation#getInformationDisplayString()
118      */
119     public String getInformationDisplayString() {
120       return fContextInformation.getInformationDisplayString();
121     }
122
123     /*
124      * @see IContextInformationExtension#getContextInformationPosition()
125      */
126     public int getContextInformationPosition() {
127       return fPosition;
128     }
129
130     public void setContextInformationPosition(int position) {
131       fPosition = position;
132     }
133   };
134
135   //  public final class VariablesCompletionProposal implements IJavaCompletionProposal {
136   //    private String fDisplayString;
137   //    private String fReplacementString;
138   //    private int fReplacementOffset;
139   //    private int fReplacementLength;
140   //    private int fCursorPosition;
141   //    private Image fImage;
142   //    private IContextInformation fContextInformation;
143   //    private String fAdditionalProposalInfo;
144   //
145   //    /**
146   //     * Creates a new completion proposal based on the provided information.  The replacement string is
147   //     * considered being the display string too. All remaining fields are set to <code>null</code>.
148   //     *
149   //     * @param replacementString the actual string to be inserted into the document
150   //     * @param replacementOffset the offset of the text to be replaced
151   //     * @param replacementLength the length of the text to be replaced
152   //     * @param cursorPosition the position of the cursor following the insert relative to replacementOffset
153   //     */
154   //    public VariablesCompletionProposal(
155   //      String replacementString,
156   //      int replacementOffset,
157   //      int replacementLength,
158   //      int cursorPosition) {
159   //      this(replacementString, replacementOffset, replacementLength, cursorPosition, null, null, null, null);
160   //    }
161   //
162   //    /**
163   //     * Creates a new completion proposal. All fields are initialized based on the provided information.
164   //     *
165   //     * @param replacementString the actual string to be inserted into the document
166   //     * @param replacementOffset the offset of the text to be replaced
167   //     * @param replacementLength the length of the text to be replaced
168   //     * @param cursorPosition the position of the cursor following the insert relative to replacementOffset
169   //     * @param image the image to display for this proposal
170   //     * @param displayString the string to be displayed for the proposal
171   //     * @param contentInformation the context information associated with this proposal
172   //     * @param additionalProposalInfo the additional information associated with this proposal
173   //     */
174   //    public VariablesCompletionProposal(
175   //      String replacementString,
176   //      int replacementOffset,
177   //      int replacementLength,
178   //      int cursorPosition,
179   //      Image image,
180   //      String displayString,
181   //      IContextInformation contextInformation,
182   //      String additionalProposalInfo) {
183   //      //      Assert.isNotNull(replacementString);
184   //      //      Assert.isTrue(replacementOffset >= 0);
185   //      //      Assert.isTrue(replacementLength >= 0);
186   //      //      Assert.isTrue(cursorPosition >= 0);
187   //
188   //      fReplacementString = replacementString;
189   //      fReplacementOffset = replacementOffset;
190   //      fReplacementLength = replacementLength;
191   //      fCursorPosition = cursorPosition;
192   //      fImage = image;
193   //      fDisplayString = displayString;
194   //      fContextInformation = contextInformation;
195   //      fAdditionalProposalInfo = additionalProposalInfo;
196   //    }
197   //
198   //    /*
199   //     * @see ICompletionProposal#apply
200   //     */
201   //    public void apply(IDocument document) {
202   //      try {
203   //        document.replace(fReplacementOffset, fReplacementLength, fReplacementString);
204   //      } catch (BadLocationException x) {
205   //        // ignore
206   //      }
207   //    }
208   //
209   //    /*
210   //     * @see ICompletionProposal#getSelection
211   //     */
212   //    public Point getSelection(IDocument document) {
213   //      return new Point(fReplacementOffset + fCursorPosition, 0);
214   //    }
215   //
216   //    /*
217   //     * @see ICompletionProposal#getContextInformation()
218   //     */
219   //    public IContextInformation getContextInformation() {
220   //      return fContextInformation;
221   //    }
222   //
223   //    /*
224   //     * @see ICompletionProposal#getImage()
225   //     */
226   //    public Image getImage() {
227   //      return fImage;
228   //    }
229   //
230   //    /*
231   //     * @see ICompletionProposal#getDisplayString()
232   //     */
233   //    public String getDisplayString() {
234   //      if (fDisplayString != null)
235   //        return fDisplayString;
236   //      return fReplacementString;
237   //    }
238   //
239   //    /*
240   //     * @see ICompletionProposal#getAdditionalProposalInfo()
241   //     */
242   //    public String getAdditionalProposalInfo() {
243   //      return fAdditionalProposalInfo;
244   //    }
245   //    /**
246   //    * Returns the relevance of the proposal.
247   //    */
248   //    public int getRelevance() {
249   //      return 0;
250   //    }
251   //  }
252
253 //  protected final static String[] fgProposals = PHPFunctionNames.FUNCTION_NAMES;
254
255   private char[] fProposalAutoActivationSet;
256   protected IContextInformationValidator fValidator = new Validator();
257   private TemplateEngine fTemplateEngine;
258   private PHPCompletionProposalComparator fComparator;
259   private int fNumberOfComputedResults = 0;
260
261   public PHPCompletionProcessor() {
262
263     ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
264     if (contextType != null)
265       fTemplateEngine = new TemplateEngine(contextType);
266
267     fComparator = new PHPCompletionProposalComparator();
268   }
269
270   /**
271    * Tells this processor to order the proposals alphabetically.
272    * 
273    * @param order <code>true</code> if proposals should be ordered.
274    */
275   public void orderProposalsAlphabetically(boolean order) {
276     fComparator.setOrderAlphabetically(order);
277   }
278
279   /**
280    * Sets this processor's set of characters triggering the activation of the
281    * completion proposal computation.
282    * 
283    * @param activationSet the activation set
284    */
285   public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
286     fProposalAutoActivationSet = activationSet;
287   }
288   /* (non-Javadoc)
289    * Method declared on IContentAssistProcessor
290    */
291   public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
292     //    IDocument document = viewer.getDocument();
293     //    if (documentOffset > 0) {
294     //      try {
295     //        ICompletionProposal[] result;
296     //        char character = document.getChar(documentOffset - 1);
297     //        if (character == '$') {
298     ////viewer.  .getActivePage().getActiveEditor();
299     //          result = new ICompletionProposal[fgProposals.length];
300     //          for (int i = 0; i < fgProposals.length; i++) {
301     //            IContextInformation info = new ContextInformation(fgProposals[i], MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.ContextInfo.pattern"), new Object[] { fgProposals[i] })); //$NON-NLS-1$
302     //            result[i] = new CompletionProposal(fgProposals[i], documentOffset, 0, fgProposals[i].length(), null, fgProposals[i], info, MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.hoverinfo.pattern"), new Object[] { fgProposals[i] })); //$NON-NLS-1$
303     //          }
304     //          return result;
305     //        }
306     //      } catch (BadLocationException e) {
307     //        return new ICompletionProposal[0];
308     //      }
309     //    }
310     //
311     //    ICompletionProposal[] result = new ICompletionProposal[fgProposals.length];
312     //    for (int i = 0; i < fgProposals.length; i++) {
313     //      IContextInformation info = new ContextInformation(fgProposals[i], MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.ContextInfo.pattern"), new Object[] { fgProposals[i] })); //$NON-NLS-1$
314     //      result[i] = new CompletionProposal(fgProposals[i], documentOffset, 0, fgProposals[i].length(), null, fgProposals[i], info, MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.hoverinfo.pattern"), new Object[] { fgProposals[i] })); //$NON-NLS-1$
315     //    }
316     //    return result;
317     int contextInformationPosition = guessContextInformationPosition(viewer, documentOffset);
318     return internalComputeCompletionProposals(viewer, documentOffset, contextInformationPosition);
319
320   }
321
322   private boolean isReference(ITextViewer viewer, int completionPosition) {
323     IDocument document = viewer.getDocument();
324     ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
325     ((CompilationUnitContextType) contextType).setContextParameters(document, completionPosition, 0);
326
327     PHPUnitContext context = (PHPUnitContext) contextType.createContext();
328     int start = context.getStart();
329     int end = context.getEnd();
330     String prefix = context.getKey();
331     IRegion region = new Region(start, end - start);
332
333     String startText;
334     boolean useClassEntries = false;
335     try {
336       // search begin of 2 lines behind this
337       int j = start;
338       if (j != 0) {
339         char ch;
340         while (j-- > 0) {
341           ch = document.getChar(j);
342           if (ch == '\n') {
343             break;
344           }
345         }
346         while (j-- > 0) {
347           ch = document.getChar(j);
348           if (ch == '\n') {
349             break;
350           }
351         }
352       }
353       if (j != start) {
354         // scan the line for the dereferencing operator '->'
355         startText = document.get(j, start - j);
356         //                                              System.out.println(startText);
357         Scanner scanner = ToolFactory.createScanner(false, false, false);
358         scanner.setSource(startText.toCharArray());
359         scanner.setPHPMode(true);
360         int token = ITerminalSymbols.TokenNameEOF;
361         int lastToken = ITerminalSymbols.TokenNameEOF;
362
363         try {
364           token = scanner.getNextToken();
365           lastToken = token;
366           while (token != ITerminalSymbols.TokenNameERROR && token != ITerminalSymbols.TokenNameEOF) {
367             lastToken = token;
368             //                                                          System.out.println(scanner.toStringAction(lastToken));
369             token = scanner.getNextToken();
370           }
371         } catch (InvalidInputException e1) {
372         }
373         if (lastToken == ITerminalSymbols.TokenNameMINUS_GREATER) {
374           // dereferencing operator '->' found
375           useClassEntries = true;
376           //                                                    System.out.println("useClassEntries = true");
377         }
378       }
379     } catch (BadLocationException e) {
380     }
381     return useClassEntries;
382   }
383   
384   private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) {
385     IDocument document = viewer.getDocument();
386     Object[] identifiers = null;
387     IProject project = null;
388     if (offset > 0) {
389
390       PHPEditor editor = null;
391       AbstractContentOutlinePage outlinePage = null;
392
393       IEditorPart targetEditor = PHPeclipsePlugin.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
394       if (targetEditor != null && (targetEditor instanceof PHPEditor)) {
395         editor = (PHPEditor) targetEditor;
396         IFile f = ((IFileEditorInput) editor.getEditorInput()).getFile();
397         project = f.getProject();
398         outlinePage = editor.getfOutlinePage();
399         if (outlinePage instanceof PHPContentOutlinePage) {
400           identifiers = ((PHPContentOutlinePage) outlinePage).getVariables();
401         }
402       }
403     }
404
405     if (fTemplateEngine != null) {
406       ICompletionProposal[] results;
407       //      try {
408       fTemplateEngine.reset();
409       fTemplateEngine.complete(viewer, offset); //, unit);
410       //      } catch (JavaModelException x) {
411       //        Shell shell= viewer.getTextWidget().getShell();
412       //        ErrorDialog.openError(shell, JavaTextMessages.getString("CompletionProcessor.error.accessing.title"), JavaTextMessages.getString("CompletionProcessor.error.accessing.message"), x.getStatus()); //$NON-NLS-2$ //$NON-NLS-1$
413       //      }       
414
415       IPHPCompletionProposal[] templateResults = fTemplateEngine.getResults();
416
417       IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
418       if (identifiers != null) {
419         IdentifierEngine identifierEngine;
420         String proposal;
421         // int j = 0;
422         //        for (int i = templateResults.length; i < templateResults.length + variables.length; i++) {
423         //          proposal = (String) variables[j++];
424         //          IContextInformation info = new ContextInformation(proposal, MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.ContextInfo.pattern"), new Object[] { proposal })); //$NON-NLS-1$
425         //          results[i] = new VariablesCompletionProposal(proposal, offset, 0, proposal.length(), null, proposal, info, MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.hoverinfo.pattern"), new Object[] { proposal })); //$NON-NLS-1$
426         //        }
427
428         ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
429         if (contextType != null) {
430           identifierEngine = new IdentifierEngine(contextType);
431           identifierEngine.complete(viewer, offset, identifiers);
432           identifierResults = identifierEngine.getResults();
433         }
434       }
435
436       boolean useClassEntries = isReference(viewer, offset);
437       IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0];
438       if (project != null) {
439         DeclarationEngine identifierEngine;
440         String proposal;
441
442         ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
443         if (contextType != null) {
444           IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(project);
445           SortedMap sortedMap = indexManager.getIdentifierMap();
446
447           identifierEngine = new DeclarationEngine(contextType, useClassEntries);
448           identifierEngine.complete(viewer, offset, sortedMap);
449           identifierResults = identifierEngine.getResults();
450         }
451       }
452
453       // built in function names from phpsyntax.xml
454                         ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData();
455       IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
456       if ((!useClassEntries)&&syntaxbuffer != null) {
457         BuiltInEngine builtinEngine;
458         String proposal;
459
460         ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
461         if (contextType != null) {
462           builtinEngine = new BuiltInEngine(contextType);
463           builtinEngine.complete(viewer, offset, syntaxbuffer);
464           builtinResults = builtinEngine.getResults();
465         }
466       }
467
468       // concatenate arrays
469       IPHPCompletionProposal[] total;
470       total =
471         new IPHPCompletionProposal[templateResults.length
472           + identifierResults.length
473           + builtinResults.length
474           + declarationResults.length];
475       System.arraycopy(templateResults, 0, total, 0, templateResults.length);
476       System.arraycopy(identifierResults, 0, total, templateResults.length, identifierResults.length);
477       System.arraycopy(builtinResults, 0, total, templateResults.length + identifierResults.length, builtinResults.length);
478       System.arraycopy(
479         declarationResults,
480         0,
481         total,
482         templateResults.length + identifierResults.length + builtinResults.length,
483         declarationResults.length);
484
485       results = total;
486
487       fNumberOfComputedResults = (results == null ? 0 : results.length);
488       /*
489        * Order here and not in result collector to make sure that the order
490        * applies to all proposals and not just those of the compilation unit. 
491        */
492       return order(results);
493     }
494     return new IPHPCompletionProposal[0];
495   }
496
497   private int guessContextInformationPosition(ITextViewer viewer, int offset) {
498     int contextPosition = offset;
499
500     IDocument document = viewer.getDocument();
501
502     //    try {
503     //
504     //      PHPCodeReader reader= new PHPCodeReader();
505     //      reader.configureBackwardReader(document, offset, true, true);
506     //  
507     //      int nestingLevel= 0;
508     //
509     //      int curr= reader.read();    
510     //      while (curr != PHPCodeReader.EOF) {
511     //
512     //        if (')' == (char) curr)
513     //          ++ nestingLevel;
514     //
515     //        else if ('(' == (char) curr) {
516     //          -- nestingLevel;
517     //        
518     //          if (nestingLevel < 0) {
519     //            int start= reader.getOffset();
520     //            if (looksLikeMethod(reader))
521     //              return start + 1;
522     //          } 
523     //        }
524     //
525     //        curr= reader.read();          
526     //      }
527     //    } catch (IOException e) {
528     //    }
529
530     return contextPosition;
531   }
532
533   /* (non-Javadoc)
534    * Method declared on IContentAssistProcessor
535    */
536   //  public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
537   //    IContextInformation[] result = new IContextInformation[5];
538   //    for (int i = 0; i < result.length; i++)
539   //      result[i] = new ContextInformation(MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.display.pattern"), new Object[] { new Integer(i), new Integer(documentOffset)}), //$NON-NLS-1$
540   //      MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.value.pattern"), new Object[] { new Integer(i), new Integer(documentOffset - 5), new Integer(documentOffset + 5)})); //$NON-NLS-1$
541   //    return result;
542   //  }
543   /**
544    * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
545    */
546   public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
547     int contextInformationPosition = guessContextInformationPosition(viewer, offset);
548     List result = addContextInformations(viewer, contextInformationPosition);
549     return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]);
550   }
551
552   private List addContextInformations(ITextViewer viewer, int offset) {
553     ICompletionProposal[] proposals = internalComputeCompletionProposals(viewer, offset, -1);
554
555     List result = new ArrayList();
556     for (int i = 0; i < proposals.length; i++) {
557       IContextInformation contextInformation = proposals[i].getContextInformation();
558       if (contextInformation != null) {
559         ContextInformationWrapper wrapper = new ContextInformationWrapper(contextInformation);
560         wrapper.setContextInformationPosition(offset);
561         result.add(wrapper);
562       }
563     }
564     return result;
565   }
566
567   /**
568    * Order the given proposals.
569    */
570   private ICompletionProposal[] order(ICompletionProposal[] proposals) {
571     Arrays.sort(proposals, fComparator);
572     return proposals;
573   }
574
575   /* (non-Javadoc)
576    * Method declared on IContentAssistProcessor
577    */
578   public char[] getCompletionProposalAutoActivationCharacters() {
579     return fProposalAutoActivationSet;
580     //    return null; // new char[] { '$' };
581   }
582
583   /* (non-Javadoc)
584    * Method declared on IContentAssistProcessor
585    */
586   public char[] getContextInformationAutoActivationCharacters() {
587     return new char[] {
588     };
589   }
590
591   /* (non-Javadoc)
592    * Method declared on IContentAssistProcessor
593    */
594   public IContextInformationValidator getContextInformationValidator() {
595     return fValidator;
596   }
597
598   /* (non-Javadoc)
599    * Method declared on IContentAssistProcessor
600    */
601   public String getErrorMessage() {
602     return null;
603   }
604 }