d0d7f9295505347c6bc3b4fa0dd28968f0f46902
[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.sql.Connection;
15 import java.sql.DatabaseMetaData;
16 import java.sql.ResultSet;
17 import java.sql.SQLException;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.SortedMap;
23
24 import net.sourceforge.phpdt.core.IBuffer;
25 import net.sourceforge.phpdt.core.ICompilationUnit;
26 import net.sourceforge.phpdt.core.IJavaProject;
27 import net.sourceforge.phpdt.core.JavaModelException;
28 import net.sourceforge.phpdt.core.ToolFactory;
29 import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
30 import net.sourceforge.phpdt.core.compiler.InvalidInputException;
31 import net.sourceforge.phpdt.internal.compiler.IProblemFactory;
32 import net.sourceforge.phpdt.internal.compiler.SourceElementParser;
33 import net.sourceforge.phpdt.internal.compiler.impl.CompilerOptions;
34 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
35 import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory;
36 import net.sourceforge.phpdt.internal.core.CompilationUnit;
37 import net.sourceforge.phpdt.internal.core.CompilationUnitStructureRequestor;
38 import net.sourceforge.phpdt.internal.core.JavaModelManager;
39 import net.sourceforge.phpdt.internal.core.JavaProject;
40 import net.sourceforge.phpdt.internal.corext.template.ContextType;
41 import net.sourceforge.phpdt.internal.corext.template.ContextTypeRegistry;
42 import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContextType;
43 import net.sourceforge.phpdt.internal.corext.template.php.PHPUnitContext;
44 import net.sourceforge.phpdt.internal.ui.PHPUiImages;
45 import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal;
46 import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator;
47 import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine;
48 import net.sourceforge.phpdt.internal.ui.text.template.DeclarationEngine;
49 import net.sourceforge.phpdt.internal.ui.text.template.IdentifierEngine;
50 import net.sourceforge.phpdt.internal.ui.text.template.SQLProposal;
51 import net.sourceforge.phpdt.internal.ui.text.template.TemplateEngine;
52 import net.sourceforge.phpdt.ui.IWorkingCopyManager;
53 import net.sourceforge.phpeclipse.IPreferenceConstants;
54 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
55 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
56 import net.sourceforge.phpeclipse.internal.compiler.ast.CompilationUnitDeclaration;
57 import net.sourceforge.phpeclipse.overlaypages.Util;
58 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
59 import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr;
60
61 import org.eclipse.core.resources.IFile;
62 import org.eclipse.core.resources.IProject;
63 import org.eclipse.jface.text.BadLocationException;
64 import org.eclipse.jface.text.IDocument;
65 import org.eclipse.jface.text.IRegion;
66 import org.eclipse.jface.text.ITextViewer;
67 import org.eclipse.jface.text.Region;
68 import org.eclipse.jface.text.TextPresentation;
69 import org.eclipse.jface.text.contentassist.ICompletionProposal;
70 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
71 import org.eclipse.jface.text.contentassist.IContextInformation;
72 import org.eclipse.jface.text.contentassist.IContextInformationExtension;
73 import org.eclipse.jface.text.contentassist.IContextInformationPresenter;
74 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
75 import org.eclipse.swt.graphics.Image;
76 import org.eclipse.ui.IEditorPart;
77 import org.eclipse.ui.IFileEditorInput;
78
79 import com.quantum.model.Bookmark;
80 import com.quantum.model.BookmarkCollection;
81 import com.quantum.model.NotConnectedException;
82 import com.quantum.util.connection.ConnectionUtil;
83
84 /**
85  * Example PHP completion processor.
86  */
87 public class PHPCompletionProcessor implements IContentAssistProcessor {
88   /**
89    * Simple content assist tip closer. The tip is valid in a range of 5
90    * characters around its popup location.
91    */
92   protected static class Validator implements IContextInformationValidator,
93       IContextInformationPresenter {
94     protected int fInstallOffset;
95
96     /*
97      * @see IContextInformationValidator#isContextInformationValid(int)
98      */
99     public boolean isContextInformationValid(int offset) {
100       return Math.abs(fInstallOffset - offset) < 5;
101     }
102
103     /*
104      * @see IContextInformationValidator#install(IContextInformation,
105      *      ITextViewer, int)
106      */
107     public void install(IContextInformation info, ITextViewer viewer, int offset) {
108       fInstallOffset = offset;
109     }
110
111     /*
112      * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int,
113      *      TextPresentation)
114      */
115     public boolean updatePresentation(int documentPosition,
116         TextPresentation presentation) {
117       return false;
118     }
119   };
120
121   private static class ContextInformationWrapper implements
122       IContextInformation, IContextInformationExtension {
123     private final IContextInformation fContextInformation;
124
125     private int fPosition;
126
127     public ContextInformationWrapper(IContextInformation contextInformation) {
128       fContextInformation = contextInformation;
129     }
130
131     /*
132      * @see IContextInformation#getContextDisplayString()
133      */
134     public String getContextDisplayString() {
135       return fContextInformation.getContextDisplayString();
136     }
137
138     /*
139      * @see IContextInformation#getImage()
140      */
141     public Image getImage() {
142       return fContextInformation.getImage();
143     }
144
145     /*
146      * @see IContextInformation#getInformationDisplayString()
147      */
148     public String getInformationDisplayString() {
149       return fContextInformation.getInformationDisplayString();
150     }
151
152     /*
153      * @see IContextInformationExtension#getContextInformationPosition()
154      */
155     public int getContextInformationPosition() {
156       return fPosition;
157     }
158
159     public void setContextInformationPosition(int position) {
160       fPosition = position;
161     }
162   };
163
164   private class TableName {
165     String fTableName;
166
167     TableName() {
168       fTableName = null;
169     }
170
171     /**
172      * @return Returns the tableName.
173      */
174     public String getTableName() {
175       if (fTableName == null) {
176         return "<!--no-table-->";
177       }
178       return fTableName;
179     }
180
181     /**
182      * @param tableName
183      *          The tableName to set.
184      */
185     public void setTableName(String tableName) {
186       fTableName = tableName;
187     }
188   }
189
190   private char[] fProposalAutoActivationSet;
191
192   protected IContextInformationValidator fValidator = new Validator();
193
194   private TemplateEngine fTemplateEngine;
195
196   private PHPCompletionProposalComparator fComparator;
197
198   private int fNumberOfComputedResults = 0;
199
200   private IEditorPart fEditor;
201
202   protected IWorkingCopyManager fManager;
203
204   public PHPCompletionProcessor(IEditorPart editor) {
205     fEditor = editor;
206     fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager();
207     ContextType contextType = ContextTypeRegistry.getInstance().getContextType(
208         "php"); //$NON-NLS-1$
209     if (contextType != null)
210       fTemplateEngine = new TemplateEngine(contextType);
211     fComparator = new PHPCompletionProposalComparator();
212   }
213
214   /**
215    * Tells this processor to order the proposals alphabetically.
216    * 
217    * @param order
218    *          <code>true</code> if proposals should be ordered.
219    */
220   public void orderProposalsAlphabetically(boolean order) {
221     fComparator.setOrderAlphabetically(order);
222   }
223
224   /**
225    * Sets this processor's set of characters triggering the activation of the
226    * completion proposal computation.
227    * 
228    * @param activationSet
229    *          the activation set
230    */
231   public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
232     fProposalAutoActivationSet = activationSet;
233   }
234
235   /*
236    * (non-Javadoc) Method declared on IContentAssistProcessor
237    */
238   public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
239       int documentOffset) {
240     int contextInformationPosition = guessContextInformationPosition(viewer,
241         documentOffset);
242     return internalComputeCompletionProposals(viewer, documentOffset,
243         contextInformationPosition);
244   }
245
246   private int getLastToken(ITextViewer viewer, int completionPosition,
247       PHPUnitContext context, TableName tableName) {
248     IDocument document = viewer.getDocument();
249     int start = context.getStart();
250     int end = context.getEnd();
251     String startText;
252     int lastSignificantToken = ITerminalSymbols.TokenNameEOF;
253     try {
254       // begin search 2 lines behind of this
255       int j = start;
256       if (j != 0) {
257         char ch;
258         while (j-- > 0) {
259           ch = document.getChar(j);
260           if (ch == '\n') {
261             break;
262           }
263         }
264         while (j-- > 0) {
265           ch = document.getChar(j);
266           if (ch == '\n') {
267             break;
268           }
269         }
270       }
271       if (j != start) {
272         // scan the line for the dereferencing operator '->'
273         startText = document.get(j, start - j);
274         if (Scanner.DEBUG) {
275           System.out.println(startText);
276         }
277         int token = ITerminalSymbols.TokenNameEOF;
278         //        token = getLastSQLToken(startText);
279         tableName.setTableName(getLastSQLTableName(startText));
280         Scanner scanner = ToolFactory.createScanner(false, false, false);
281         scanner.setSource(startText.toCharArray());
282         scanner.setPHPMode(true);
283         int beforeLastToken = ITerminalSymbols.TokenNameEOF;
284         int lastToken = ITerminalSymbols.TokenNameEOF;
285         char[] ident;
286         try {
287           token = scanner.getNextToken();
288           lastToken = token;
289           while (token != ITerminalSymbols.TokenNameERROR
290               && token != ITerminalSymbols.TokenNameEOF) {
291             beforeLastToken = lastToken;
292             if (lastToken==ITerminalSymbols.TokenNameVariable) {
293               ident = scanner.getCurrentTokenSource();
294               if (ident[0]=='$' &&
295                   ident[0]=='t' &&
296                   ident[0]=='h' &&
297                   ident[0]=='i' &&
298                   ident[0]=='s') {
299                 beforeLastToken = ITerminalSymbols.TokenNamethis_PHP_COMPLETION;
300               }
301             }
302             lastToken = token;
303             //                                                          System.out.println(scanner.toStringAction(lastToken));
304             token = scanner.getNextToken();
305           }
306         } catch (InvalidInputException e1) {
307         }
308         switch (lastToken) {
309         case ITerminalSymbols.TokenNameMINUS_GREATER:
310           // dereferencing operator '->' found
311           lastSignificantToken = ITerminalSymbols.TokenNameMINUS_GREATER;
312           if (beforeLastToken == ITerminalSymbols.TokenNameVariable) {
313             lastSignificantToken = ITerminalSymbols.TokenNameVariable;
314           }
315           break;
316         case ITerminalSymbols.TokenNamenew:
317           lastSignificantToken = ITerminalSymbols.TokenNamenew;
318           break;
319         }
320       }
321     } catch (BadLocationException e) {
322     }
323     return lastSignificantToken;
324   }
325
326   String getSQLTableName(String sqlText, int start) {
327     int tableNameStart = -1;
328     int currentCharacterPosition = start + 1;
329     char ch;
330     try {
331       while (true) {
332         ch = sqlText.charAt(currentCharacterPosition++);
333         if (tableNameStart == -1 && Character.isJavaIdentifierStart(ch)) {
334           tableNameStart = currentCharacterPosition - 1;
335         } else {
336           if (!Character.isJavaIdentifierPart(ch)) {
337             return sqlText.substring(tableNameStart,
338                 currentCharacterPosition - 1);
339           }
340         }
341       }
342     } catch (IndexOutOfBoundsException e) {
343       if (tableNameStart >= 0) {
344         return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
345       }
346     }
347     return "";
348   }
349
350   private String getLastSQLTableName(String startText) {
351     int token;
352     // scan for sql identifiers
353     char ch = ' ';
354     int currentSQLPosition = startText.length();
355     int identEnd = -1;
356     String ident = null;
357     boolean whiteSpace = true;
358     try {
359       while (true) {
360         ch = startText.charAt(--currentSQLPosition);
361         if (ch >= 'A' && ch <= 'Z') {
362           if (identEnd < 0) {
363             identEnd = currentSQLPosition + 1;
364           }
365         } else if (ch >= 'a' && ch <= 'z') {
366           if (identEnd < 0) {
367             identEnd = currentSQLPosition + 1;
368           }
369         } else if (identEnd >= 0) {
370           ident = startText.substring(currentSQLPosition + 1, identEnd);
371           // select -- from -- where --
372           // update -- set -- where --
373           // insert into -- ( -- ) values ( -- )
374           if (ident.length() >= 4 && ident.length() <= 6) {
375             ident = ident.toLowerCase();
376             switch (ident.length()) {
377             //              case 3 :
378             //                if (ident.equals("set")) {
379             //                  // System.out.println("set");
380             //                  token = ITerminalSymbols.TokenNameSQLset;
381             //                  return token;
382             //                }
383             //                break;
384             case 4:
385               if (ident.equals("from")) {
386                 //                  System.out.println("from");
387                 token = ITerminalSymbols.TokenNameSQLfrom;
388                 return getSQLTableName(startText, identEnd);
389               } else if (ident.equals("into")) {
390                 //                System.out.println("into");
391                 token = ITerminalSymbols.TokenNameSQLinto;
392                 return getSQLTableName(startText, identEnd);
393               }
394               break;
395             //              case 5 :
396             //                if (ident.equals("where")) {
397             //                  // System.out.println("where");
398             //                  token = ITerminalSymbols.TokenNameSQLwhere;
399             //                  return token;
400             //                }
401             //                break;
402             case 6:
403               //                if (ident.equals("select")) {
404               //                  // System.out.println("select");
405               //                  token = ITerminalSymbols.TokenNameSQLselect;
406               //                  return token;
407               //                } else if (ident.equals("insert")) {
408               //                  // System.out.println("insert");
409               //                  token = ITerminalSymbols.TokenNameSQLinsert;
410               //                  return token;
411               //                } else
412               if (ident.equals("update")) {
413                 //                  System.out.println("update");
414                 token = ITerminalSymbols.TokenNameSQLupdate;
415                 return getSQLTableName(startText, identEnd);
416               }
417               //                else if (ident.equals("values")) {
418               //                  // System.out.println("values");
419               //                  token = ITerminalSymbols.TokenNameSQLvalues;
420               //                  return token;
421               //                }
422               break;
423             }
424           }
425           whiteSpace = false;
426           identEnd = -1;
427         } else if (Character.isWhitespace(ch)) {
428         } else {
429           whiteSpace = false;
430         }
431       }
432     } catch (IndexOutOfBoundsException e) {
433     }
434     return "<!--no-table-->";
435   }
436
437   /**
438    * Detect the last significant SQL token in the text before the completion
439    * 
440    * @param startText
441    */
442   private int getLastSQLToken(String startText) {
443     int token;
444     // scan for sql identifiers
445     char ch = ' ';
446     int currentSQLPosition = startText.length();
447     int identEnd = -1;
448     String ident = null;
449     boolean whiteSpace = true;
450     try {
451       while (true) {
452         ch = startText.charAt(--currentSQLPosition);
453         if (ch >= 'A' && ch <= 'Z') {
454           if (identEnd < 0) {
455             identEnd = currentSQLPosition + 1;
456           }
457         } else if (ch >= 'a' && ch <= 'z') {
458           if (identEnd < 0) {
459             identEnd = currentSQLPosition + 1;
460           }
461         } else if (identEnd >= 0) {
462           ident = startText.substring(currentSQLPosition + 1, identEnd);
463           // select -- from -- where --
464           // update -- set -- where --
465           // insert into -- ( -- ) values ( -- )
466           if (ident.length() >= 3 && ident.length() <= 6) {
467             ident = ident.toLowerCase();
468             switch (ident.length()) {
469             case 3:
470               if (ident.equals("set")) {
471                 //                  System.out.println("set");
472                 token = ITerminalSymbols.TokenNameSQLset;
473                 return token;
474               }
475               break;
476             case 4:
477               if (ident.equals("from")) {
478                 //                  System.out.println("from");
479                 token = ITerminalSymbols.TokenNameSQLfrom;
480                 //getSQLTableName();
481                 return token;
482               } else if (ident.equals("into")) {
483                 //                System.out.println("into");
484                 token = ITerminalSymbols.TokenNameSQLinto;
485                 return token;
486               }
487               break;
488             case 5:
489               if (ident.equals("where")) {
490                 //                  System.out.println("where");
491                 token = ITerminalSymbols.TokenNameSQLwhere;
492                 return token;
493               }
494               break;
495             case 6:
496               if (ident.equals("select")) {
497                 //                  System.out.println("select");
498                 token = ITerminalSymbols.TokenNameSQLselect;
499                 return token;
500               } else if (ident.equals("insert")) {
501                 //                  System.out.println("insert");
502                 token = ITerminalSymbols.TokenNameSQLinsert;
503                 return token;
504               } else if (ident.equals("update")) {
505                 //                  System.out.println("update");
506                 token = ITerminalSymbols.TokenNameSQLupdate;
507                 return token;
508               } else if (ident.equals("values")) {
509                 //                System.out.println("values");
510                 token = ITerminalSymbols.TokenNameSQLvalues;
511                 return token;
512               }
513               break;
514             }
515           }
516           whiteSpace = false;
517           identEnd = -1;
518         } else if (Character.isWhitespace(ch)) {
519         } else {
520           whiteSpace = false;
521         }
522       }
523     } catch (IndexOutOfBoundsException e) {
524     }
525     return ITerminalSymbols.TokenNameEOF;
526   }
527
528   private ICompletionProposal[] internalComputeCompletionProposals(
529       ITextViewer viewer, int offset, int contextOffset) {
530
531     IDocument document = viewer.getDocument();
532     Object[] identifiers = null;
533     IFile file = null;
534     IProject project = null;
535     if (offset > 0) {
536       PHPEditor editor = null;
537       if (fEditor != null && (fEditor instanceof PHPEditor)) {
538         editor = (PHPEditor) fEditor;
539         file = ((IFileEditorInput) editor.getEditorInput()).getFile();
540         project = file.getProject();
541         //        outlinePage = editor.getfOutlinePage();
542         // TODO: get the identifiers from the new model
543         //        if (outlinePage instanceof PHPContentOutlinePage) {
544         //          identifiers = ((PHPContentOutlinePage) outlinePage).getVariables();
545         //        }
546       }
547     }
548     
549     ContextType phpContextType = ContextTypeRegistry.getInstance()
550         .getContextType("php"); //$NON-NLS-1$
551     ((CompilationUnitContextType) phpContextType).setContextParameters(
552         document, offset, 0);
553     PHPUnitContext context = (PHPUnitContext) phpContextType.createContext();
554     String prefix = context.getKey();
555     TableName sqlTable = new TableName();
556     int lastSignificantToken = getLastToken(viewer, offset, context, sqlTable);
557     boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER)
558         || (lastSignificantToken == ITerminalSymbols.TokenNameVariable)
559         || (lastSignificantToken == ITerminalSymbols.TokenNamenew)
560         || (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION);
561     boolean emptyPrefix = prefix == null || prefix.equals("");
562     if (fTemplateEngine != null) {
563       IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0];
564       ICompletionProposal[] results;
565       if (!emptyPrefix) {
566         fTemplateEngine.reset();
567         fTemplateEngine.complete(viewer, offset); //, unit);
568         templateResults = fTemplateEngine.getResults();
569       }
570       IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
571       if ((!useClassMembers) && identifiers != null) {
572         IdentifierEngine identifierEngine;
573         ContextType contextType = ContextTypeRegistry.getInstance()
574             .getContextType("php"); //$NON-NLS-1$
575         if (contextType != null) {
576           identifierEngine = new IdentifierEngine(contextType);
577           identifierEngine.complete(viewer, offset, identifiers);
578           identifierResults = identifierEngine.getResults();
579         }
580       }
581       // declarations stored in file project.index on project level
582       IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0];
583       if (project != null) {
584         DeclarationEngine declarationEngine;
585         ContextType contextType = ContextTypeRegistry.getInstance()
586             .getContextType("php"); //$NON-NLS-1$
587         if (contextType != null) {
588           IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault()
589               .getIndexManager(project);
590           SortedMap sortedMap = indexManager.getIdentifierMap();
591           declarationEngine = new DeclarationEngine(contextType,
592               lastSignificantToken, file);
593           declarationEngine.complete(viewer, offset, sortedMap);
594           declarationResults = declarationEngine.getResults();
595         }
596       }
597       // built in function names from phpsyntax.xml
598       ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData();
599       IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
600       if ((!useClassMembers) && syntaxbuffer != null) {
601         BuiltInEngine builtinEngine;
602         String proposal;
603         ContextType contextType = ContextTypeRegistry.getInstance()
604             .getContextType("php"); //$NON-NLS-1$
605         if (contextType != null) {
606           builtinEngine = new BuiltInEngine(contextType);
607           builtinEngine.complete(viewer, offset, syntaxbuffer);
608           builtinResults = builtinEngine.getResults();
609         }
610       }
611       IPHPCompletionProposal[] sqlResults = new IPHPCompletionProposal[0];
612       if (project != null) {
613         // Get The Database bookmark from the Quantum SQL plugin:
614         BookmarkCollection sqlBookMarks = BookmarkCollection.getInstance();
615         if (sqlBookMarks != null) {
616           String bookmarkString = Util.getMiscProjectsPreferenceValue(project,
617               IPreferenceConstants.PHP_BOOKMARK_DEFAULT);
618           if (bookmarkString != null && !bookmarkString.equals("")) {
619             Bookmark bookmark = sqlBookMarks.find(bookmarkString);
620             ArrayList sqlList = new ArrayList();
621             if (bookmark != null && !bookmark.isConnected()) {
622               new ConnectionUtil().connect(bookmark, null);
623             }
624             if (bookmark != null && bookmark.isConnected()) {
625               try {
626                 Connection connection = bookmark.getConnection();
627                 DatabaseMetaData metaData = connection.getMetaData();
628
629                 if (metaData != null) {
630                   int start = context.getStart();
631                   int end = context.getEnd();
632                   String foundSQLTableName = sqlTable.getTableName();
633                   String tableName;
634                   String columnName;
635                   String prefixWithoutDollar = prefix;
636                   boolean isDollarPrefix = false;
637                   if (prefix.length() > 0 && prefix.charAt(0) == '$') {
638                     prefixWithoutDollar = prefix.substring(1);
639                     isDollarPrefix = true;
640                   }
641                   IRegion region = new Region(start, end - start);
642                   ResultSet set;
643                   if (!isDollarPrefix) {
644                     set = metaData.getTables(null, null, prefixWithoutDollar
645                         + "%", null);
646                     while (set.next()) {
647                       //                  String tempSchema = set.getString("TABLE_SCHEM");
648                       //                  tempSchema = (tempSchema == null) ? "" :
649                       // tempSchema.trim();
650                       tableName = set.getString("TABLE_NAME");
651                       tableName = (tableName == null) ? "" : tableName.trim();
652                       if (tableName != null && tableName.length() > 0) {
653                         sqlList.add(new SQLProposal(tableName, context, region,
654                             viewer, PHPUiImages.get(PHPUiImages.IMG_TABLE)));
655                       }
656                     }
657                     set.close();
658                   }
659                   set = metaData.getColumns(null, null, "%",
660                       prefixWithoutDollar + "%");
661                   SQLProposal sqlProposal;
662                   while (set.next()) {
663                     columnName = set.getString("COLUMN_NAME");
664                     columnName = (columnName == null) ? "" : columnName.trim();
665                     tableName = set.getString("TABLE_NAME");
666                     tableName = (tableName == null) ? "" : tableName.trim();
667                     if (tableName != null && tableName.length() > 0
668                         && columnName != null && columnName.length() > 0) {
669                       if (isDollarPrefix) {
670                         sqlProposal = new SQLProposal(tableName, "$"
671                             + columnName, context, region, viewer, PHPUiImages
672                             .get(PHPUiImages.IMG_COLUMN));
673                       } else {
674                         sqlProposal = new SQLProposal(tableName, columnName,
675                             context, region, viewer, PHPUiImages
676                                 .get(PHPUiImages.IMG_COLUMN));
677                       }
678                       if (tableName.equals(foundSQLTableName)) {
679                         sqlProposal.setRelevance(90);
680                       } else if (tableName.indexOf(foundSQLTableName) >= 0) {
681                         sqlProposal.setRelevance(75);
682                       }
683                       sqlList.add(sqlProposal);
684                     }
685                   }
686                   set.close();
687                   sqlResults = new IPHPCompletionProposal[sqlList.size()];
688                   for (int i = 0; i < sqlList.size(); i++) {
689                     sqlResults[i] = (SQLProposal) sqlList.get(i);
690                   }
691                 }
692               } catch (NotConnectedException e) {
693                 // ignore this - not mission critical
694               } catch (SQLException e) {
695                 e.printStackTrace();
696               }
697             }
698           }
699         }
700       }
701       // concatenate the result arrays
702       IPHPCompletionProposal[] total;
703       total = new IPHPCompletionProposal[templateResults.length
704           + identifierResults.length + builtinResults.length
705           + declarationResults.length + sqlResults.length];
706       System.arraycopy(templateResults, 0, total, 0, templateResults.length);
707       System.arraycopy(identifierResults, 0, total, templateResults.length,
708           identifierResults.length);
709       System.arraycopy(builtinResults, 0, total, templateResults.length
710           + identifierResults.length, builtinResults.length);
711       System.arraycopy(declarationResults, 0, total, templateResults.length
712           + identifierResults.length + builtinResults.length,
713           declarationResults.length);
714       System.arraycopy(sqlResults, 0, total, templateResults.length
715           + identifierResults.length + builtinResults.length
716           + declarationResults.length, sqlResults.length);
717       results = total;
718       fNumberOfComputedResults = (results == null ? 0 : results.length);
719       /*
720        * Order here and not in result collector to make sure that the order
721        * applies to all proposals and not just those of the compilation unit.
722        */
723       return order(results);
724     }
725     return new IPHPCompletionProposal[0];
726   }
727
728   private int guessContextInformationPosition(ITextViewer viewer, int offset) {
729     int contextPosition = offset;
730     IDocument document = viewer.getDocument();
731     //    try {
732     //
733     //      PHPCodeReader reader= new PHPCodeReader();
734     //      reader.configureBackwardReader(document, offset, true, true);
735     //  
736     //      int nestingLevel= 0;
737     //
738     //      int curr= reader.read();
739     //      while (curr != PHPCodeReader.EOF) {
740     //
741     //        if (')' == (char) curr)
742     //          ++ nestingLevel;
743     //
744     //        else if ('(' == (char) curr) {
745     //          -- nestingLevel;
746     //        
747     //          if (nestingLevel < 0) {
748     //            int start= reader.getOffset();
749     //            if (looksLikeMethod(reader))
750     //              return start + 1;
751     //          }
752     //        }
753     //
754     //        curr= reader.read();
755     //      }
756     //    } catch (IOException e) {
757     //    }
758     return contextPosition;
759   }
760
761   /*
762    * (non-Javadoc) Method declared on IContentAssistProcessor
763    */
764   //  public IContextInformation[] computeContextInformation(ITextViewer viewer,
765   // int documentOffset) {
766   //    IContextInformation[] result = new IContextInformation[5];
767   //    for (int i = 0; i < result.length; i++)
768   //      result[i] = new
769   // ContextInformation(MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.display.pattern"),
770   // new Object[] { new Integer(i), new Integer(documentOffset)}),
771   // //$NON-NLS-1$
772   //      MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.value.pattern"),
773   // new Object[] { new Integer(i), new Integer(documentOffset - 5), new
774   // Integer(documentOffset + 5)})); //$NON-NLS-1$
775   //    return result;
776   //  }
777   /**
778    * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
779    */
780   public IContextInformation[] computeContextInformation(ITextViewer viewer,
781       int offset) {
782     int contextInformationPosition = guessContextInformationPosition(viewer,
783         offset);
784     List result = addContextInformations(viewer, contextInformationPosition);
785     return (IContextInformation[]) result
786         .toArray(new IContextInformation[result.size()]);
787   }
788
789   private List addContextInformations(ITextViewer viewer, int offset) {
790     ICompletionProposal[] proposals = internalComputeCompletionProposals(
791         viewer, offset, -1);
792     List result = new ArrayList();
793     for (int i = 0; i < proposals.length; i++) {
794       IContextInformation contextInformation = proposals[i]
795           .getContextInformation();
796       if (contextInformation != null) {
797         ContextInformationWrapper wrapper = new ContextInformationWrapper(
798             contextInformation);
799         wrapper.setContextInformationPosition(offset);
800         result.add(wrapper);
801       }
802     }
803     return result;
804   }
805
806   /**
807    * Order the given proposals.
808    */
809   private ICompletionProposal[] order(ICompletionProposal[] proposals) {
810     Arrays.sort(proposals, fComparator);
811     return proposals;
812   }
813
814   /*
815    * (non-Javadoc) Method declared on IContentAssistProcessor
816    */
817   public char[] getCompletionProposalAutoActivationCharacters() {
818     return fProposalAutoActivationSet;
819     //    return null; // new char[] { '$' };
820   }
821
822   /*
823    * (non-Javadoc) Method declared on IContentAssistProcessor
824    */
825   public char[] getContextInformationAutoActivationCharacters() {
826     return new char[] {};
827   }
828
829   /*
830    * (non-Javadoc) Method declared on IContentAssistProcessor
831    */
832   public IContextInformationValidator getContextInformationValidator() {
833     return fValidator;
834   }
835
836   /*
837    * (non-Javadoc) Method declared on IContentAssistProcessor
838    */
839   public String getErrorMessage() {
840     return null;
841   }
842 }