893e0c18e75daf1aeca01cb3a638ebad103a7ce5
[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
18 import net.sourceforge.phpdt.internal.corext.template.ContextType;
19 import net.sourceforge.phpdt.internal.corext.template.ContextTypeRegistry;
20 import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal;
21 import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator;
22 import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine;
23 import net.sourceforge.phpdt.internal.ui.text.template.IdentifierEngine;
24 import net.sourceforge.phpdt.internal.ui.text.template.TemplateEngine;
25 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
26 import net.sourceforge.phpeclipse.phpeditor.PHPContentOutlinePage;
27 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
28
29 import org.eclipse.jface.text.IDocument;
30 import org.eclipse.jface.text.ITextViewer;
31 import org.eclipse.jface.text.TextPresentation;
32 import org.eclipse.jface.text.contentassist.ICompletionProposal;
33 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
34 import org.eclipse.jface.text.contentassist.IContextInformation;
35 import org.eclipse.jface.text.contentassist.IContextInformationExtension;
36 import org.eclipse.jface.text.contentassist.IContextInformationPresenter;
37 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
38 import org.eclipse.swt.graphics.Image;
39 import org.eclipse.ui.IEditorPart;
40
41 /**
42  * Example PHP completion processor.
43  */
44 public class PHPCompletionProcessor implements IContentAssistProcessor {
45
46   /**
47    * Simple content assist tip closer. The tip is valid in a range
48    * of 5 characters around its popup location.
49    */
50   protected static class Validator implements IContextInformationValidator, IContextInformationPresenter {
51
52     protected int fInstallOffset;
53
54     /*
55      * @see IContextInformationValidator#isContextInformationValid(int)
56      */
57     public boolean isContextInformationValid(int offset) {
58       return Math.abs(fInstallOffset - offset) < 5;
59     }
60
61     /*
62      * @see IContextInformationValidator#install(IContextInformation, ITextViewer, int)
63      */
64     public void install(IContextInformation info, ITextViewer viewer, int offset) {
65       fInstallOffset = offset;
66     }
67
68     /*
69      * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int, TextPresentation)
70      */
71     public boolean updatePresentation(int documentPosition, TextPresentation presentation) {
72       return false;
73     }
74   };
75
76   private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension {
77
78     private final IContextInformation fContextInformation;
79     private int fPosition;
80
81     public ContextInformationWrapper(IContextInformation contextInformation) {
82       fContextInformation = contextInformation;
83     }
84
85     /*
86      * @see IContextInformation#getContextDisplayString()
87      */
88     public String getContextDisplayString() {
89       return fContextInformation.getContextDisplayString();
90     }
91
92     /*
93     * @see IContextInformation#getImage()
94     */
95     public Image getImage() {
96       return fContextInformation.getImage();
97     }
98
99     /*
100      * @see IContextInformation#getInformationDisplayString()
101      */
102     public String getInformationDisplayString() {
103       return fContextInformation.getInformationDisplayString();
104     }
105
106     /*
107      * @see IContextInformationExtension#getContextInformationPosition()
108      */
109     public int getContextInformationPosition() {
110       return fPosition;
111     }
112
113     public void setContextInformationPosition(int position) {
114       fPosition = position;
115     }
116   };
117
118   //  public final class VariablesCompletionProposal implements IJavaCompletionProposal {
119   //    private String fDisplayString;
120   //    private String fReplacementString;
121   //    private int fReplacementOffset;
122   //    private int fReplacementLength;
123   //    private int fCursorPosition;
124   //    private Image fImage;
125   //    private IContextInformation fContextInformation;
126   //    private String fAdditionalProposalInfo;
127   //
128   //    /**
129   //     * Creates a new completion proposal based on the provided information.  The replacement string is
130   //     * considered being the display string too. All remaining fields are set to <code>null</code>.
131   //     *
132   //     * @param replacementString the actual string to be inserted into the document
133   //     * @param replacementOffset the offset of the text to be replaced
134   //     * @param replacementLength the length of the text to be replaced
135   //     * @param cursorPosition the position of the cursor following the insert relative to replacementOffset
136   //     */
137   //    public VariablesCompletionProposal(
138   //      String replacementString,
139   //      int replacementOffset,
140   //      int replacementLength,
141   //      int cursorPosition) {
142   //      this(replacementString, replacementOffset, replacementLength, cursorPosition, null, null, null, null);
143   //    }
144   //
145   //    /**
146   //     * Creates a new completion proposal. All fields are initialized based on the provided information.
147   //     *
148   //     * @param replacementString the actual string to be inserted into the document
149   //     * @param replacementOffset the offset of the text to be replaced
150   //     * @param replacementLength the length of the text to be replaced
151   //     * @param cursorPosition the position of the cursor following the insert relative to replacementOffset
152   //     * @param image the image to display for this proposal
153   //     * @param displayString the string to be displayed for the proposal
154   //     * @param contentInformation the context information associated with this proposal
155   //     * @param additionalProposalInfo the additional information associated with this proposal
156   //     */
157   //    public VariablesCompletionProposal(
158   //      String replacementString,
159   //      int replacementOffset,
160   //      int replacementLength,
161   //      int cursorPosition,
162   //      Image image,
163   //      String displayString,
164   //      IContextInformation contextInformation,
165   //      String additionalProposalInfo) {
166   //      //      Assert.isNotNull(replacementString);
167   //      //      Assert.isTrue(replacementOffset >= 0);
168   //      //      Assert.isTrue(replacementLength >= 0);
169   //      //      Assert.isTrue(cursorPosition >= 0);
170   //
171   //      fReplacementString = replacementString;
172   //      fReplacementOffset = replacementOffset;
173   //      fReplacementLength = replacementLength;
174   //      fCursorPosition = cursorPosition;
175   //      fImage = image;
176   //      fDisplayString = displayString;
177   //      fContextInformation = contextInformation;
178   //      fAdditionalProposalInfo = additionalProposalInfo;
179   //    }
180   //
181   //    /*
182   //     * @see ICompletionProposal#apply
183   //     */
184   //    public void apply(IDocument document) {
185   //      try {
186   //        document.replace(fReplacementOffset, fReplacementLength, fReplacementString);
187   //      } catch (BadLocationException x) {
188   //        // ignore
189   //      }
190   //    }
191   //
192   //    /*
193   //     * @see ICompletionProposal#getSelection
194   //     */
195   //    public Point getSelection(IDocument document) {
196   //      return new Point(fReplacementOffset + fCursorPosition, 0);
197   //    }
198   //
199   //    /*
200   //     * @see ICompletionProposal#getContextInformation()
201   //     */
202   //    public IContextInformation getContextInformation() {
203   //      return fContextInformation;
204   //    }
205   //
206   //    /*
207   //     * @see ICompletionProposal#getImage()
208   //     */
209   //    public Image getImage() {
210   //      return fImage;
211   //    }
212   //
213   //    /*
214   //     * @see ICompletionProposal#getDisplayString()
215   //     */
216   //    public String getDisplayString() {
217   //      if (fDisplayString != null)
218   //        return fDisplayString;
219   //      return fReplacementString;
220   //    }
221   //
222   //    /*
223   //     * @see ICompletionProposal#getAdditionalProposalInfo()
224   //     */
225   //    public String getAdditionalProposalInfo() {
226   //      return fAdditionalProposalInfo;
227   //    }
228   //    /**
229   //    * Returns the relevance of the proposal.
230   //    */
231   //    public int getRelevance() {
232   //      return 0;
233   //    }
234   //  }
235
236   protected final static String[] fgProposals = PHPFunctionNames.FUNCTION_NAMES;
237
238   private char[] fProposalAutoActivationSet;
239   protected IContextInformationValidator fValidator = new Validator();
240   private TemplateEngine fTemplateEngine;
241   private PHPCompletionProposalComparator fComparator;
242   private int fNumberOfComputedResults = 0;
243
244   public PHPCompletionProcessor() {
245
246     ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
247     if (contextType != null)
248       fTemplateEngine = new TemplateEngine(contextType);
249
250     fComparator = new PHPCompletionProposalComparator();
251   }
252   
253   /**
254    * Sets this processor's set of characters triggering the activation of the
255    * completion proposal computation.
256    * 
257    * @param activationSet the activation set
258    */
259   public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
260     fProposalAutoActivationSet= activationSet;
261   }
262   /* (non-Javadoc)
263    * Method declared on IContentAssistProcessor
264    */
265   public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
266     //    IDocument document = viewer.getDocument();
267     //    if (documentOffset > 0) {
268     //      try {
269     //        ICompletionProposal[] result;
270     //        char character = document.getChar(documentOffset - 1);
271     //        if (character == '$') {
272     ////viewer.  .getActivePage().getActiveEditor();
273     //          result = new ICompletionProposal[fgProposals.length];
274     //          for (int i = 0; i < fgProposals.length; i++) {
275     //            IContextInformation info = new ContextInformation(fgProposals[i], MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.ContextInfo.pattern"), new Object[] { fgProposals[i] })); //$NON-NLS-1$
276     //            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$
277     //          }
278     //          return result;
279     //        }
280     //      } catch (BadLocationException e) {
281     //        return new ICompletionProposal[0];
282     //      }
283     //    }
284     //
285     //    ICompletionProposal[] result = new ICompletionProposal[fgProposals.length];
286     //    for (int i = 0; i < fgProposals.length; i++) {
287     //      IContextInformation info = new ContextInformation(fgProposals[i], MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.ContextInfo.pattern"), new Object[] { fgProposals[i] })); //$NON-NLS-1$
288     //      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$
289     //    }
290     //    return result;
291     int contextInformationPosition = guessContextInformationPosition(viewer, documentOffset);
292     return internalComputeCompletionProposals(viewer, documentOffset, contextInformationPosition);
293
294   }
295
296   private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) {
297     IDocument document = viewer.getDocument();
298     Object[] identifiers = null;
299     if (offset > 0) {
300
301       PHPEditor editor = null;
302       PHPContentOutlinePage outlinePage = null;
303
304       IEditorPart targetEditor = PHPeclipsePlugin.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
305       if (targetEditor != null && (targetEditor instanceof PHPEditor)) {
306         editor = (PHPEditor) targetEditor;
307         outlinePage = editor.getfOutlinePage();
308         identifiers = outlinePage.getVariables();
309       }
310     }
311
312     if (fTemplateEngine != null) {
313       ICompletionProposal[] results;
314       //      try {
315       fTemplateEngine.reset();
316       fTemplateEngine.complete(viewer, offset); //, unit);
317       //      } catch (JavaModelException x) {
318       //        Shell shell= viewer.getTextWidget().getShell();
319       //        ErrorDialog.openError(shell, JavaTextMessages.getString("CompletionProcessor.error.accessing.title"), JavaTextMessages.getString("CompletionProcessor.error.accessing.message"), x.getStatus()); //$NON-NLS-2$ //$NON-NLS-1$
320       //      }       
321
322       IPHPCompletionProposal[] templateResults = fTemplateEngine.getResults();
323
324       IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
325       if (identifiers != null) {
326         IdentifierEngine identifierEngine;
327         String proposal;
328         // int j = 0;
329         //        for (int i = templateResults.length; i < templateResults.length + variables.length; i++) {
330         //          proposal = (String) variables[j++];
331         //          IContextInformation info = new ContextInformation(proposal, MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.ContextInfo.pattern"), new Object[] { proposal })); //$NON-NLS-1$
332         //          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$
333         //        }
334
335         ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
336         if (contextType != null) {
337           identifierEngine = new IdentifierEngine(contextType);
338           identifierEngine.complete(viewer, offset, identifiers);
339           identifierResults = identifierEngine.getResults();
340         }
341       }
342
343       IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
344       if (PHPFunctionNames.FUNCTION_NAMES != null) {
345         BuiltInEngine builtinEngine;
346         String proposal;
347
348         ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
349         if (contextType != null) {
350           builtinEngine = new BuiltInEngine(contextType);
351           builtinEngine.complete(viewer, offset, PHPFunctionNames.FUNCTION_NAMES);
352           builtinResults = builtinEngine.getResults();
353         }
354       }
355
356       // concatenate arrays
357       IPHPCompletionProposal[] total;
358       total = new IPHPCompletionProposal[templateResults.length + identifierResults.length + builtinResults.length];
359       System.arraycopy(templateResults, 0, total, 0, templateResults.length);
360       System.arraycopy(identifierResults, 0, total, templateResults.length, identifierResults.length);
361       System.arraycopy(builtinResults, 0, total, templateResults.length + identifierResults.length, builtinResults.length);
362       results = total;
363
364       fNumberOfComputedResults = (results == null ? 0 : results.length);
365       /*
366        * Order here and not in result collector to make sure that the order
367        * applies to all proposals and not just those of the compilation unit. 
368        */
369       return order(results);
370     }
371     return new IPHPCompletionProposal[0];
372   }
373
374   private int guessContextInformationPosition(ITextViewer viewer, int offset) {
375     int contextPosition = offset;
376
377     IDocument document = viewer.getDocument();
378
379     //    try {
380     //
381     //      PHPCodeReader reader= new PHPCodeReader();
382     //      reader.configureBackwardReader(document, offset, true, true);
383     //  
384     //      int nestingLevel= 0;
385     //
386     //      int curr= reader.read();    
387     //      while (curr != PHPCodeReader.EOF) {
388     //
389     //        if (')' == (char) curr)
390     //          ++ nestingLevel;
391     //
392     //        else if ('(' == (char) curr) {
393     //          -- nestingLevel;
394     //        
395     //          if (nestingLevel < 0) {
396     //            int start= reader.getOffset();
397     //            if (looksLikeMethod(reader))
398     //              return start + 1;
399     //          } 
400     //        }
401     //
402     //        curr= reader.read();          
403     //      }
404     //    } catch (IOException e) {
405     //    }
406
407     return contextPosition;
408   }
409
410   /* (non-Javadoc)
411    * Method declared on IContentAssistProcessor
412    */
413   //  public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
414   //    IContextInformation[] result = new IContextInformation[5];
415   //    for (int i = 0; i < result.length; i++)
416   //      result[i] = new ContextInformation(MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.display.pattern"), new Object[] { new Integer(i), new Integer(documentOffset)}), //$NON-NLS-1$
417   //      MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.value.pattern"), new Object[] { new Integer(i), new Integer(documentOffset - 5), new Integer(documentOffset + 5)})); //$NON-NLS-1$
418   //    return result;
419   //  }
420   /**
421    * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
422    */
423   public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
424     int contextInformationPosition = guessContextInformationPosition(viewer, offset);
425     List result = addContextInformations(viewer, contextInformationPosition);
426     return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]);
427   }
428
429   private List addContextInformations(ITextViewer viewer, int offset) {
430     ICompletionProposal[] proposals = internalComputeCompletionProposals(viewer, offset, -1);
431
432     List result = new ArrayList();
433     for (int i = 0; i < proposals.length; i++) {
434       IContextInformation contextInformation = proposals[i].getContextInformation();
435       if (contextInformation != null) {
436         ContextInformationWrapper wrapper = new ContextInformationWrapper(contextInformation);
437         wrapper.setContextInformationPosition(offset);
438         result.add(wrapper);
439       }
440     }
441     return result;
442   }
443
444   /**
445    * Order the given proposals.
446    */
447   private ICompletionProposal[] order(ICompletionProposal[] proposals) {
448     Arrays.sort(proposals, fComparator);
449     return proposals;
450   }
451
452   /* (non-Javadoc)
453    * Method declared on IContentAssistProcessor
454    */
455   public char[] getCompletionProposalAutoActivationCharacters() {
456     return fProposalAutoActivationSet;
457 //    return null; // new char[] { '$' };
458   }
459
460   /* (non-Javadoc)
461    * Method declared on IContentAssistProcessor
462    */
463   public char[] getContextInformationAutoActivationCharacters() {
464     return new char[] {
465     };
466   }
467
468   /* (non-Javadoc)
469    * Method declared on IContentAssistProcessor
470    */
471   public IContextInformationValidator getContextInformationValidator() {
472     return fValidator;
473   }
474
475   /* (non-Javadoc)
476    * Method declared on IContentAssistProcessor
477    */
478   public String getErrorMessage() {
479     return null;
480   }
481 }