Changes:
[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.ITextViewer;
45 import org.eclipse.jface.text.TextPresentation;
46 import org.eclipse.jface.text.contentassist.ICompletionProposal;
47 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
48 import org.eclipse.jface.text.contentassist.IContextInformation;
49 import org.eclipse.jface.text.contentassist.IContextInformationExtension;
50 import org.eclipse.jface.text.contentassist.IContextInformationPresenter;
51 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
52 import org.eclipse.swt.graphics.Image;
53 import org.eclipse.ui.IEditorPart;
54 import org.eclipse.ui.IFileEditorInput;
55
56 /**
57  * Example PHP completion processor.
58  */
59 public class PHPCompletionProcessor implements IContentAssistProcessor {
60
61   /**
62    * Simple content assist tip closer. The tip is valid in a range
63    * of 5 characters around its popup location.
64    */
65   protected static class Validator implements IContextInformationValidator, IContextInformationPresenter {
66
67     protected int fInstallOffset;
68
69     /*
70      * @see IContextInformationValidator#isContextInformationValid(int)
71      */
72     public boolean isContextInformationValid(int offset) {
73       return Math.abs(fInstallOffset - offset) < 5;
74     }
75
76     /*
77      * @see IContextInformationValidator#install(IContextInformation, ITextViewer, int)
78      */
79     public void install(IContextInformation info, ITextViewer viewer, int offset) {
80       fInstallOffset = offset;
81     }
82
83     /*
84      * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int, TextPresentation)
85      */
86     public boolean updatePresentation(int documentPosition, TextPresentation presentation) {
87       return false;
88     }
89   };
90
91   private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension {
92
93     private final IContextInformation fContextInformation;
94     private int fPosition;
95
96     public ContextInformationWrapper(IContextInformation contextInformation) {
97       fContextInformation = contextInformation;
98     }
99
100     /*
101      * @see IContextInformation#getContextDisplayString()
102      */
103     public String getContextDisplayString() {
104       return fContextInformation.getContextDisplayString();
105     }
106
107     /*
108     * @see IContextInformation#getImage()
109     */
110     public Image getImage() {
111       return fContextInformation.getImage();
112     }
113
114     /*
115      * @see IContextInformation#getInformationDisplayString()
116      */
117     public String getInformationDisplayString() {
118       return fContextInformation.getInformationDisplayString();
119     }
120
121     /*
122      * @see IContextInformationExtension#getContextInformationPosition()
123      */
124     public int getContextInformationPosition() {
125       return fPosition;
126     }
127
128     public void setContextInformationPosition(int position) {
129       fPosition = position;
130     }
131   };
132
133   private char[] fProposalAutoActivationSet;
134   protected IContextInformationValidator fValidator = new Validator();
135   private TemplateEngine fTemplateEngine;
136   private PHPCompletionProposalComparator fComparator;
137   private int fNumberOfComputedResults = 0;
138
139   public PHPCompletionProcessor() {
140
141     ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
142     if (contextType != null)
143       fTemplateEngine = new TemplateEngine(contextType);
144
145     fComparator = new PHPCompletionProposalComparator();
146   }
147
148   /**
149    * Tells this processor to order the proposals alphabetically.
150    * 
151    * @param order <code>true</code> if proposals should be ordered.
152    */
153   public void orderProposalsAlphabetically(boolean order) {
154     fComparator.setOrderAlphabetically(order);
155   }
156
157   /**
158    * Sets this processor's set of characters triggering the activation of the
159    * completion proposal computation.
160    * 
161    * @param activationSet the activation set
162    */
163   public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
164     fProposalAutoActivationSet = activationSet;
165   }
166
167   /* (non-Javadoc)
168    * Method declared on IContentAssistProcessor
169    */
170   public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
171     int contextInformationPosition = guessContextInformationPosition(viewer, documentOffset);
172     return internalComputeCompletionProposals(viewer, documentOffset, contextInformationPosition);
173   }
174
175   private int getLastToken(ITextViewer viewer, int completionPosition, PHPUnitContext context) {
176     IDocument document = viewer.getDocument();
177     int start = context.getStart();
178     int end = context.getEnd();
179
180     String startText;
181     int lastSignificantToken = ITerminalSymbols.TokenNameEOF;
182
183     try {
184       // begin search 2 lines behind of this
185       int j = start;
186       if (j != 0) {
187         char ch;
188         while (j-- > 0) {
189           ch = document.getChar(j);
190           if (ch == '\n') {
191             break;
192           }
193         }
194         while (j-- > 0) {
195           ch = document.getChar(j);
196           if (ch == '\n') {
197             break;
198           }
199         }
200       }
201       if (j != start) {
202         // scan the line for the dereferencing operator '->'
203         startText = document.get(j, start - j);
204         //                                              System.out.println(startText);
205         Scanner scanner = ToolFactory.createScanner(false, false, false);
206         scanner.setSource(startText.toCharArray());
207         scanner.setPHPMode(true);
208         int token = ITerminalSymbols.TokenNameEOF;
209         int beforeLastToken = ITerminalSymbols.TokenNameEOF;
210         int lastToken = ITerminalSymbols.TokenNameEOF;
211
212         try {
213           token = scanner.getNextToken();
214           lastToken = token;
215           while (token != ITerminalSymbols.TokenNameERROR && token != ITerminalSymbols.TokenNameEOF) {
216             beforeLastToken = lastToken;
217             lastToken = token;
218             //                                                          System.out.println(scanner.toStringAction(lastToken));
219             token = scanner.getNextToken();
220           }
221         } catch (InvalidInputException e1) {
222         }
223         switch (lastToken) {
224           case ITerminalSymbols.TokenNameMINUS_GREATER :
225             // dereferencing operator '->' found
226             lastSignificantToken = ITerminalSymbols.TokenNameMINUS_GREATER;
227             if (beforeLastToken == ITerminalSymbols.TokenNamethis) {
228               lastSignificantToken = ITerminalSymbols.TokenNamethis;
229             }
230             break;
231           case ITerminalSymbols.TokenNamenew :
232             lastSignificantToken = ITerminalSymbols.TokenNamenew;
233             break;
234         }
235       }
236     } catch (BadLocationException e) {
237     }
238     return lastSignificantToken;
239   }
240
241   private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) {
242     IDocument document = viewer.getDocument();
243     Object[] identifiers = null;
244     IFile file = null;
245     IProject project = null;
246     if (offset > 0) {
247
248       PHPEditor editor = null;
249       AbstractContentOutlinePage outlinePage = null;
250
251       IEditorPart targetEditor = PHPeclipsePlugin.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
252       if (targetEditor != null && (targetEditor instanceof PHPEditor)) {
253         editor = (PHPEditor) targetEditor;
254         file = ((IFileEditorInput) editor.getEditorInput()).getFile();
255         project = file.getProject();
256         outlinePage = editor.getfOutlinePage();
257         if (outlinePage instanceof PHPContentOutlinePage) {
258           identifiers = ((PHPContentOutlinePage) outlinePage).getVariables();
259         }
260       }
261     }
262
263     ContextType phpContextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
264      ((CompilationUnitContextType) phpContextType).setContextParameters(document, offset, 0);
265
266     PHPUnitContext context = (PHPUnitContext) phpContextType.createContext();
267     String prefix = context.getKey();
268
269     int lastSignificantToken = getLastToken(viewer, offset, context);
270     boolean useClassMembers =
271       (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER) || 
272       (lastSignificantToken == ITerminalSymbols.TokenNamethis) ||
273                   (lastSignificantToken == ITerminalSymbols.TokenNamenew);
274     boolean emptyPrefix = prefix == null || prefix.equals("");
275
276     if (fTemplateEngine != null) {
277       IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0];
278
279       ICompletionProposal[] results;
280       if (!emptyPrefix) {
281         fTemplateEngine.reset();
282         fTemplateEngine.complete(viewer, offset); //, unit);
283         templateResults = fTemplateEngine.getResults();
284       }
285
286       IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
287       if ((!useClassMembers) && identifiers != null) {
288         IdentifierEngine identifierEngine;
289
290         ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
291         if (contextType != null) {
292           identifierEngine = new IdentifierEngine(contextType);
293           identifierEngine.complete(viewer, offset, identifiers);
294           identifierResults = identifierEngine.getResults();
295         }
296       }
297
298       // declarations stored in file project.index on project level
299       IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0];
300       if (project != null) {
301         DeclarationEngine declarationEngine;
302
303         ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
304         if (contextType != null) {
305           IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(project);
306           SortedMap sortedMap = indexManager.getIdentifierMap();
307
308           declarationEngine = new DeclarationEngine(contextType, lastSignificantToken, file);
309           declarationEngine.complete(viewer, offset, sortedMap);
310           declarationResults = declarationEngine.getResults();
311         }
312       }
313
314       // built in function names from phpsyntax.xml
315       ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData();
316       IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
317       if ((!useClassMembers) && syntaxbuffer != null) {
318         BuiltInEngine builtinEngine;
319         String proposal;
320
321         ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
322         if (contextType != null) {
323           builtinEngine = new BuiltInEngine(contextType);
324           builtinEngine.complete(viewer, offset, syntaxbuffer);
325           builtinResults = builtinEngine.getResults();
326         }
327       }
328
329       // concatenate the result arrays
330       IPHPCompletionProposal[] total;
331       total =
332         new IPHPCompletionProposal[templateResults.length
333           + identifierResults.length
334           + builtinResults.length
335           + declarationResults.length];
336       System.arraycopy(templateResults, 0, total, 0, templateResults.length);
337       System.arraycopy(identifierResults, 0, total, templateResults.length, identifierResults.length);
338       System.arraycopy(builtinResults, 0, total, templateResults.length + identifierResults.length, builtinResults.length);
339       System.arraycopy(
340         declarationResults,
341         0,
342         total,
343         templateResults.length + identifierResults.length + builtinResults.length,
344         declarationResults.length);
345
346       results = total;
347
348       fNumberOfComputedResults = (results == null ? 0 : results.length);
349       /*
350        * Order here and not in result collector to make sure that the order
351        * applies to all proposals and not just those of the compilation unit. 
352        */
353       return order(results);
354     }
355     return new IPHPCompletionProposal[0];
356   }
357
358   private int guessContextInformationPosition(ITextViewer viewer, int offset) {
359     int contextPosition = offset;
360
361     IDocument document = viewer.getDocument();
362
363     //    try {
364     //
365     //      PHPCodeReader reader= new PHPCodeReader();
366     //      reader.configureBackwardReader(document, offset, true, true);
367     //  
368     //      int nestingLevel= 0;
369     //
370     //      int curr= reader.read();    
371     //      while (curr != PHPCodeReader.EOF) {
372     //
373     //        if (')' == (char) curr)
374     //          ++ nestingLevel;
375     //
376     //        else if ('(' == (char) curr) {
377     //          -- nestingLevel;
378     //        
379     //          if (nestingLevel < 0) {
380     //            int start= reader.getOffset();
381     //            if (looksLikeMethod(reader))
382     //              return start + 1;
383     //          } 
384     //        }
385     //
386     //        curr= reader.read();          
387     //      }
388     //    } catch (IOException e) {
389     //    }
390
391     return contextPosition;
392   }
393
394   /* (non-Javadoc)
395    * Method declared on IContentAssistProcessor
396    */
397   //  public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
398   //    IContextInformation[] result = new IContextInformation[5];
399   //    for (int i = 0; i < result.length; i++)
400   //      result[i] = new ContextInformation(MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.display.pattern"), new Object[] { new Integer(i), new Integer(documentOffset)}), //$NON-NLS-1$
401   //      MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.value.pattern"), new Object[] { new Integer(i), new Integer(documentOffset - 5), new Integer(documentOffset + 5)})); //$NON-NLS-1$
402   //    return result;
403   //  }
404   /**
405    * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
406    */
407   public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
408     int contextInformationPosition = guessContextInformationPosition(viewer, offset);
409     List result = addContextInformations(viewer, contextInformationPosition);
410     return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]);
411   }
412
413   private List addContextInformations(ITextViewer viewer, int offset) {
414     ICompletionProposal[] proposals = internalComputeCompletionProposals(viewer, offset, -1);
415
416     List result = new ArrayList();
417     for (int i = 0; i < proposals.length; i++) {
418       IContextInformation contextInformation = proposals[i].getContextInformation();
419       if (contextInformation != null) {
420         ContextInformationWrapper wrapper = new ContextInformationWrapper(contextInformation);
421         wrapper.setContextInformationPosition(offset);
422         result.add(wrapper);
423       }
424     }
425     return result;
426   }
427
428   /**
429    * Order the given proposals.
430    */
431   private ICompletionProposal[] order(ICompletionProposal[] proposals) {
432     Arrays.sort(proposals, fComparator);
433     return proposals;
434   }
435
436   /* (non-Javadoc)
437    * Method declared on IContentAssistProcessor
438    */
439   public char[] getCompletionProposalAutoActivationCharacters() {
440     return fProposalAutoActivationSet;
441     //    return null; // new char[] { '$' };
442   }
443
444   /* (non-Javadoc)
445    * Method declared on IContentAssistProcessor
446    */
447   public char[] getContextInformationAutoActivationCharacters() {
448     return new char[] {
449     };
450   }
451
452   /* (non-Javadoc)
453    * Method declared on IContentAssistProcessor
454    */
455   public IContextInformationValidator getContextInformationValidator() {
456     return fValidator;
457   }
458
459   /* (non-Javadoc)
460    * Method declared on IContentAssistProcessor
461    */
462   public String getErrorMessage() {
463     return null;
464   }
465 }