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