misc 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 import java.sql.Connection;
14 import java.sql.DatabaseMetaData;
15 import java.sql.ResultSet;
16 import java.sql.SQLException;
17 import java.util.ArrayList;
18 import java.util.Arrays;
19 import java.util.List;
20 import java.util.SortedMap;
21 import net.sourceforge.phpdt.core.ToolFactory;
22 import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
23 import net.sourceforge.phpdt.core.compiler.InvalidInputException;
24 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
25 import net.sourceforge.phpdt.internal.corext.template.ContextType;
26 import net.sourceforge.phpdt.internal.corext.template.ContextTypeRegistry;
27 import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContextType;
28 import net.sourceforge.phpdt.internal.corext.template.php.PHPUnitContext;
29 import net.sourceforge.phpdt.internal.ui.PHPUiImages;
30 import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal;
31 import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator;
32 import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine;
33 import net.sourceforge.phpdt.internal.ui.text.template.DeclarationEngine;
34 import net.sourceforge.phpdt.internal.ui.text.template.IdentifierEngine;
35 import net.sourceforge.phpdt.internal.ui.text.template.IdentifierProposal;
36 import net.sourceforge.phpdt.internal.ui.text.template.TemplateEngine;
37 import net.sourceforge.phpeclipse.IPreferenceConstants;
38 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
39 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
40 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
41 import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr;
42 import org.eclipse.core.resources.IFile;
43 import org.eclipse.core.resources.IProject;
44 import org.eclipse.jface.text.BadLocationException;
45 import org.eclipse.jface.text.IDocument;
46 import org.eclipse.jface.text.IRegion;
47 import org.eclipse.jface.text.ITextViewer;
48 import org.eclipse.jface.text.Region;
49 import org.eclipse.jface.text.TextPresentation;
50 import org.eclipse.jface.text.contentassist.ICompletionProposal;
51 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
52 import org.eclipse.jface.text.contentassist.IContextInformation;
53 import org.eclipse.jface.text.contentassist.IContextInformationExtension;
54 import org.eclipse.jface.text.contentassist.IContextInformationPresenter;
55 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
56 import org.eclipse.swt.graphics.Image;
57 import org.eclipse.ui.IEditorPart;
58 import org.eclipse.ui.IFileEditorInput;
59 import net.sourceforge.phpeclipse.overlaypages.Util;
60 import com.quantum.model.Bookmark;
61 import com.quantum.model.BookmarkCollection;
62 import com.quantum.model.NotConnectedException;
63 import com.quantum.util.connection.ConnectionUtil;
64 /**
65  * Example PHP completion processor.
66  */
67 public class PHPCompletionProcessor implements IContentAssistProcessor {
68   /**
69    * Simple content assist tip closer. The tip is valid in a range of 5
70    * characters around its popup location.
71    */
72   protected static class Validator
73       implements
74         IContextInformationValidator,
75         IContextInformationPresenter {
76     protected int fInstallOffset;
77     /*
78      * @see IContextInformationValidator#isContextInformationValid(int)
79      */
80     public boolean isContextInformationValid(int offset) {
81       return Math.abs(fInstallOffset - offset) < 5;
82     }
83     /*
84      * @see IContextInformationValidator#install(IContextInformation,
85      *      ITextViewer, int)
86      */
87     public void install(IContextInformation info, ITextViewer viewer, int offset) {
88       fInstallOffset = offset;
89     }
90     /*
91      * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int,
92      *      TextPresentation)
93      */
94     public boolean updatePresentation(int documentPosition,
95         TextPresentation presentation) {
96       return false;
97     }
98   };
99   private static class ContextInformationWrapper
100       implements
101         IContextInformation,
102         IContextInformationExtension {
103     private final IContextInformation fContextInformation;
104     private int fPosition;
105     public ContextInformationWrapper(IContextInformation contextInformation) {
106       fContextInformation = contextInformation;
107     }
108     /*
109      * @see IContextInformation#getContextDisplayString()
110      */
111     public String getContextDisplayString() {
112       return fContextInformation.getContextDisplayString();
113     }
114     /*
115      * @see IContextInformation#getImage()
116      */
117     public Image getImage() {
118       return fContextInformation.getImage();
119     }
120     /*
121      * @see IContextInformation#getInformationDisplayString()
122      */
123     public String getInformationDisplayString() {
124       return fContextInformation.getInformationDisplayString();
125     }
126     /*
127      * @see IContextInformationExtension#getContextInformationPosition()
128      */
129     public int getContextInformationPosition() {
130       return fPosition;
131     }
132     public void setContextInformationPosition(int position) {
133       fPosition = position;
134     }
135   };
136   private char[] fProposalAutoActivationSet;
137   protected IContextInformationValidator fValidator = new Validator();
138   private TemplateEngine fTemplateEngine;
139   private PHPCompletionProposalComparator fComparator;
140   private int fNumberOfComputedResults = 0;
141   public PHPCompletionProcessor() {
142     ContextType contextType = ContextTypeRegistry.getInstance().getContextType(
143         "php"); //$NON-NLS-1$
144     if (contextType != null)
145       fTemplateEngine = new TemplateEngine(contextType);
146     fComparator = new PHPCompletionProposalComparator();
147   }
148   /**
149    * Tells this processor to order the proposals alphabetically.
150    * 
151    * @param order
152    *            <code>true</code> if proposals should be ordered.
153    */
154   public void orderProposalsAlphabetically(boolean order) {
155     fComparator.setOrderAlphabetically(order);
156   }
157   /**
158    * Sets this processor's set of characters triggering the activation of the
159    * completion proposal computation.
160    * 
161    * @param activationSet
162    *            the activation set
163    */
164   public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
165     fProposalAutoActivationSet = activationSet;
166   }
167   /*
168    * (non-Javadoc) Method declared on IContentAssistProcessor
169    */
170   public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
171       int documentOffset) {
172     int contextInformationPosition = guessContextInformationPosition(viewer,
173         documentOffset);
174     return internalComputeCompletionProposals(viewer, documentOffset,
175         contextInformationPosition);
176   }
177   private int getLastToken(ITextViewer viewer, int completionPosition,
178       PHPUnitContext context) {
179     IDocument document = viewer.getDocument();
180     int start = context.getStart();
181     int end = context.getEnd();
182     String startText;
183     int lastSignificantToken = ITerminalSymbols.TokenNameEOF;
184     try {
185       // begin search 2 lines behind of this
186       int j = start;
187       if (j != 0) {
188         char ch;
189         while (j-- > 0) {
190           ch = document.getChar(j);
191           if (ch == '\n') {
192             break;
193           }
194         }
195         while (j-- > 0) {
196           ch = document.getChar(j);
197           if (ch == '\n') {
198             break;
199           }
200         }
201       }
202       if (j != start) {
203         // scan the line for the dereferencing operator '->'
204         startText = document.get(j, start - j);
205         if (Scanner.DEBUG) {
206           System.out.println(startText);
207         }
208         int token = ITerminalSymbols.TokenNameEOF;
209         
210         token = getLastSQLToken(startText);
211         
212         Scanner scanner = ToolFactory.createScanner(false, false, false);
213         scanner.setSource(startText.toCharArray());
214         scanner.setPHPMode(true);
215         
216         int beforeLastToken = ITerminalSymbols.TokenNameEOF;
217         int lastToken = ITerminalSymbols.TokenNameEOF;
218         try {
219           token = scanner.getNextToken();
220           lastToken = token;
221           while (token != ITerminalSymbols.TokenNameERROR
222               && token != ITerminalSymbols.TokenNameEOF) {
223             beforeLastToken = lastToken;
224             lastToken = token;
225             //                                                          System.out.println(scanner.toStringAction(lastToken));
226             token = scanner.getNextToken();
227           }
228         } catch (InvalidInputException e1) {
229         }
230         switch (lastToken) {
231           case ITerminalSymbols.TokenNameMINUS_GREATER :
232             // dereferencing operator '->' found
233             lastSignificantToken = ITerminalSymbols.TokenNameMINUS_GREATER;
234             if (beforeLastToken == ITerminalSymbols.TokenNameVariable) {
235               lastSignificantToken = ITerminalSymbols.TokenNameVariable;
236             }
237             break;
238           case ITerminalSymbols.TokenNamenew :
239             lastSignificantToken = ITerminalSymbols.TokenNamenew;
240             break;
241         }
242       }
243     } catch (BadLocationException e) {
244     }
245     return lastSignificantToken;
246   }
247   
248   /**
249    * Detect the last significant SQL token in the text before the completion
250    * 
251    * @param startText
252    */
253   private int getLastSQLToken(String startText) {
254     int token;
255     // scan for sql identifiers
256     char ch = ' ';
257     int currentSQLPosition = startText.length();
258     int identEnd = -1;
259     String ident = null;
260     boolean whiteSpace = true;
261     try {
262       while (true) {
263         ch = startText.charAt(--currentSQLPosition);
264         if (ch >= 'A' && ch <= 'Z') {
265           if (identEnd < 0) {
266             identEnd = currentSQLPosition + 1;
267           }
268         } else if (ch >= 'a' && ch <= 'z') {
269           if (identEnd < 0) {
270             identEnd = currentSQLPosition + 1;
271           }
272         } else if (identEnd >= 0) {
273           ident = startText.substring(currentSQLPosition + 1, identEnd);
274           // select -- from -- where --
275           // update -- set -- where --
276           // insert into -- ( -- ) values ( -- )
277           if (ident.length() >= 3 && ident.length() <= 6) {
278             ident = ident.toLowerCase();
279             switch (ident.length()) {
280               case 3 :
281                 if (ident.equals("set")) {
282 //                  System.out.println("set");
283                   token = ITerminalSymbols.TokenNameSQLset;
284                   return token;
285                 }
286                 break;
287               case 4 :
288                 if (ident.equals("from")) {
289 //                  System.out.println("from");
290                   token = ITerminalSymbols.TokenNameSQLfrom;
291                   return token;
292                 } else if (ident.equals("into")) {
293 //                System.out.println("into");
294                   token = ITerminalSymbols.TokenNameSQLinto;
295                   return token;
296                 }
297                 break;
298               case 5 :
299                 if (ident.equals("where")) {
300 //                  System.out.println("where");
301                   token = ITerminalSymbols.TokenNameSQLwhere;
302                   return token;
303                 }
304                 break;
305               case 6 :
306                 if (ident.equals("select")) {
307 //                  System.out.println("select");
308                   token = ITerminalSymbols.TokenNameSQLselect;
309                   return token;
310                 } else if (ident.equals("insert")) {
311 //                  System.out.println("insert");
312                   token = ITerminalSymbols.TokenNameSQLinsert;
313                   return token;
314                 } else if (ident.equals("update")) {
315 //                  System.out.println("update");
316                   token = ITerminalSymbols.TokenNameSQLupdate;
317                   return token;
318                 } else if (ident.equals("values")) {
319 //                System.out.println("values");
320                   token = ITerminalSymbols.TokenNameSQLvalues;
321                   return token;
322                 }
323                 break;
324             }
325           }
326           whiteSpace = false;
327           identEnd = -1;
328         } else if (Character.isWhitespace(ch)) {
329         } else {
330           whiteSpace = false;
331         }
332       }
333     } catch (IndexOutOfBoundsException e) {
334     }
335     return ITerminalSymbols.TokenNameEOF;
336   }
337   
338   private ICompletionProposal[] internalComputeCompletionProposals(
339       ITextViewer viewer, int offset, int contextOffset) {
340     IDocument document = viewer.getDocument();
341     Object[] identifiers = null;
342     IFile file = null;
343     IProject project = null;
344     if (offset > 0) {
345       PHPEditor editor = null;
346       //      JavaOutlinePage outlinePage = null;
347       IEditorPart targetEditor = PHPeclipsePlugin.getActiveWorkbenchWindow()
348           .getActivePage().getActiveEditor();
349       if (targetEditor != null && (targetEditor instanceof PHPEditor)) {
350         editor = (PHPEditor) targetEditor;
351         file = ((IFileEditorInput) editor.getEditorInput()).getFile();
352         project = file.getProject();
353         //        outlinePage = editor.getfOutlinePage();
354         // TODO: get the identifiers from the new model
355         //        if (outlinePage instanceof PHPContentOutlinePage) {
356         //          identifiers = ((PHPContentOutlinePage) outlinePage).getVariables();
357         //        }
358       }
359     }
360     ContextType phpContextType = ContextTypeRegistry.getInstance()
361         .getContextType("php"); //$NON-NLS-1$
362     ((CompilationUnitContextType) phpContextType).setContextParameters(
363         document, offset, 0);
364     PHPUnitContext context = (PHPUnitContext) phpContextType.createContext();
365     String prefix = context.getKey();
366     int lastSignificantToken = getLastToken(viewer, offset, context);
367     boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER)
368         || (lastSignificantToken == ITerminalSymbols.TokenNameVariable)
369         || (lastSignificantToken == ITerminalSymbols.TokenNamenew);
370     boolean emptyPrefix = prefix == null || prefix.equals("");
371     if (fTemplateEngine != null) {
372       IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0];
373       ICompletionProposal[] results;
374       if (!emptyPrefix) {
375         fTemplateEngine.reset();
376         fTemplateEngine.complete(viewer, offset); //, unit);
377         templateResults = fTemplateEngine.getResults();
378       }
379       IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
380       if ((!useClassMembers) && identifiers != null) {
381         IdentifierEngine identifierEngine;
382         ContextType contextType = ContextTypeRegistry.getInstance()
383             .getContextType("php"); //$NON-NLS-1$
384         if (contextType != null) {
385           identifierEngine = new IdentifierEngine(contextType);
386           identifierEngine.complete(viewer, offset, identifiers);
387           identifierResults = identifierEngine.getResults();
388         }
389       }
390       // declarations stored in file project.index on project level
391       IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0];
392       if (project != null) {
393         DeclarationEngine declarationEngine;
394         ContextType contextType = ContextTypeRegistry.getInstance()
395             .getContextType("php"); //$NON-NLS-1$
396         if (contextType != null) {
397           IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault()
398               .getIndexManager(project);
399           SortedMap sortedMap = indexManager.getIdentifierMap();
400           declarationEngine = new DeclarationEngine(contextType,
401               lastSignificantToken, file);
402           declarationEngine.complete(viewer, offset, sortedMap);
403           declarationResults = declarationEngine.getResults();
404         }
405       }
406       // built in function names from phpsyntax.xml
407       ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData();
408       IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
409       if ((!useClassMembers) && syntaxbuffer != null) {
410         BuiltInEngine builtinEngine;
411         String proposal;
412         ContextType contextType = ContextTypeRegistry.getInstance()
413             .getContextType("php"); //$NON-NLS-1$
414         if (contextType != null) {
415           builtinEngine = new BuiltInEngine(contextType);
416           builtinEngine.complete(viewer, offset, syntaxbuffer);
417           builtinResults = builtinEngine.getResults();
418         }
419       }
420       IPHPCompletionProposal[] sqlResults = new IPHPCompletionProposal[0];
421       if (project != null) {
422         // Get The Database bookmark from the Quantum SQL plugin:
423         BookmarkCollection sqlBookMarks = BookmarkCollection.getInstance();
424         if (sqlBookMarks != null) {
425           String bookmarkString = Util.getMiscProjectsPreferenceValue(project,
426               IPreferenceConstants.PHP_BOOKMARK_DEFAULT);
427           if (bookmarkString != null && !bookmarkString.equals("")) {
428             Bookmark bookmark = sqlBookMarks.find(bookmarkString);
429             ArrayList list = new ArrayList();
430             if (bookmark != null && !bookmark.isConnected()) {
431               new ConnectionUtil().connect(bookmark, null);
432             }
433             if (bookmark != null && bookmark.isConnected()) {
434               try {
435                 Connection connection = bookmark.getConnection();
436                 DatabaseMetaData metaData = connection.getMetaData();
437                 if (metaData != null) {
438                   int start = context.getStart();
439                   int end = context.getEnd();
440                   IRegion region = new Region(start, end - start);
441                   ResultSet set = metaData.getTables(null, null, prefix + "%",
442                       null);
443                   while (set.next()) {
444                     //                  String tempSchema = set.getString("TABLE_SCHEM");
445                     //                  tempSchema = (tempSchema == null) ? "" :
446                     // tempSchema.trim();
447                     String tableName = set.getString("TABLE_NAME");
448                     tableName = (tableName == null) ? "" : tableName.trim();
449                     if (tableName != null && tableName.length() > 0) {
450                       list.add(tableName);
451                     }
452                   }
453                   set.close();
454                   set = metaData.getColumns(null, null, "%", prefix + "%");
455                   while (set.next()) {
456                     String tableName = set.getString("COLUMN_NAME");
457                     tableName = (tableName == null) ? "" : tableName.trim();
458                     if (tableName != null && tableName.length() > 0) {
459                       list.add(tableName);
460                     }
461                     tableName = set.getString("TABLE_NAME");
462                     tableName = (tableName == null) ? "" : tableName.trim();
463                     if (tableName != null && tableName.length() > 0) {
464                       list.add(tableName);
465                     }
466                   }
467                   set.close();
468                   sqlResults = new IPHPCompletionProposal[list.size()];
469                   for (int i = 0; i < list.size(); i++) {
470                     sqlResults[i] = new IdentifierProposal(
471                         (String) list.get(i), context, region, viewer,
472                         PHPUiImages.get(PHPUiImages.IMG_FUN), PHPUiImages
473                             .get(PHPUiImages.IMG_VAR));
474                   }
475                 }
476               } catch (NotConnectedException e) {
477                 // ignore this - not mission critical
478               } catch (SQLException e) {
479                 e.printStackTrace();
480               }
481             }
482           }
483         }
484       }
485       // concatenate the result arrays
486       IPHPCompletionProposal[] total;
487       total = new IPHPCompletionProposal[templateResults.length
488           + identifierResults.length + builtinResults.length
489           + declarationResults.length + sqlResults.length];
490       System.arraycopy(templateResults, 0, total, 0, templateResults.length);
491       System.arraycopy(identifierResults, 0, total, templateResults.length,
492           identifierResults.length);
493       System.arraycopy(builtinResults, 0, total, templateResults.length
494           + identifierResults.length, builtinResults.length);
495       System.arraycopy(declarationResults, 0, total, templateResults.length
496           + identifierResults.length + builtinResults.length,
497           declarationResults.length);
498       System.arraycopy(sqlResults, 0, total, templateResults.length
499           + identifierResults.length + builtinResults.length
500           + declarationResults.length, sqlResults.length);
501       results = total;
502       fNumberOfComputedResults = (results == null ? 0 : results.length);
503       /*
504        * Order here and not in result collector to make sure that the order
505        * applies to all proposals and not just those of the compilation unit.
506        */
507       return order(results);
508     }
509     return new IPHPCompletionProposal[0];
510   }
511   private int guessContextInformationPosition(ITextViewer viewer, int offset) {
512     int contextPosition = offset;
513     IDocument document = viewer.getDocument();
514     //    try {
515     //
516     //      PHPCodeReader reader= new PHPCodeReader();
517     //      reader.configureBackwardReader(document, offset, true, true);
518     //  
519     //      int nestingLevel= 0;
520     //
521     //      int curr= reader.read();
522     //      while (curr != PHPCodeReader.EOF) {
523     //
524     //        if (')' == (char) curr)
525     //          ++ nestingLevel;
526     //
527     //        else if ('(' == (char) curr) {
528     //          -- nestingLevel;
529     //        
530     //          if (nestingLevel < 0) {
531     //            int start= reader.getOffset();
532     //            if (looksLikeMethod(reader))
533     //              return start + 1;
534     //          }
535     //        }
536     //
537     //        curr= reader.read();
538     //      }
539     //    } catch (IOException e) {
540     //    }
541     return contextPosition;
542   }
543   /*
544    * (non-Javadoc) Method declared on IContentAssistProcessor
545    */
546   //  public IContextInformation[] computeContextInformation(ITextViewer viewer,
547   // int documentOffset) {
548   //    IContextInformation[] result = new IContextInformation[5];
549   //    for (int i = 0; i < result.length; i++)
550   //      result[i] = new
551   // ContextInformation(MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.display.pattern"),
552   // new Object[] { new Integer(i), new Integer(documentOffset)}),
553   // //$NON-NLS-1$
554   //      MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.value.pattern"),
555   // new Object[] { new Integer(i), new Integer(documentOffset - 5), new
556   // Integer(documentOffset + 5)})); //$NON-NLS-1$
557   //    return result;
558   //  }
559   /**
560    * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
561    */
562   public IContextInformation[] computeContextInformation(ITextViewer viewer,
563       int offset) {
564     int contextInformationPosition = guessContextInformationPosition(viewer,
565         offset);
566     List result = addContextInformations(viewer, contextInformationPosition);
567     return (IContextInformation[]) result
568         .toArray(new IContextInformation[result.size()]);
569   }
570   private List addContextInformations(ITextViewer viewer, int offset) {
571     ICompletionProposal[] proposals = internalComputeCompletionProposals(
572         viewer, offset, -1);
573     List result = new ArrayList();
574     for (int i = 0; i < proposals.length; i++) {
575       IContextInformation contextInformation = proposals[i]
576           .getContextInformation();
577       if (contextInformation != null) {
578         ContextInformationWrapper wrapper = new ContextInformationWrapper(
579             contextInformation);
580         wrapper.setContextInformationPosition(offset);
581         result.add(wrapper);
582       }
583     }
584     return result;
585   }
586   /**
587    * Order the given proposals.
588    */
589   private ICompletionProposal[] order(ICompletionProposal[] proposals) {
590     Arrays.sort(proposals, fComparator);
591     return proposals;
592   }
593   /*
594    * (non-Javadoc) Method declared on IContentAssistProcessor
595    */
596   public char[] getCompletionProposalAutoActivationCharacters() {
597     return fProposalAutoActivationSet;
598     //    return null; // new char[] { '$' };
599   }
600   /*
601    * (non-Javadoc) Method declared on IContentAssistProcessor
602    */
603   public char[] getContextInformationAutoActivationCharacters() {
604     return new char[]{};
605   }
606   /*
607    * (non-Javadoc) Method declared on IContentAssistProcessor
608    */
609   public IContextInformationValidator getContextInformationValidator() {
610     return fValidator;
611   }
612   /*
613    * (non-Javadoc) Method declared on IContentAssistProcessor
614    */
615   public String getErrorMessage() {
616     return null;
617   }
618 }