69f3124448180a951b46ac3dc237c644ec85d09f
[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         try {
286           token = scanner.getNextToken();
287           lastToken = token;
288           while (token != ITerminalSymbols.TokenNameERROR
289               && token != ITerminalSymbols.TokenNameEOF) {
290             beforeLastToken = lastToken;
291             lastToken = token;
292             //                                                          System.out.println(scanner.toStringAction(lastToken));
293             token = scanner.getNextToken();
294           }
295         } catch (InvalidInputException e1) {
296         }
297         switch (lastToken) {
298         case ITerminalSymbols.TokenNameMINUS_GREATER:
299           // dereferencing operator '->' found
300           lastSignificantToken = ITerminalSymbols.TokenNameMINUS_GREATER;
301           if (beforeLastToken == ITerminalSymbols.TokenNameVariable) {
302             lastSignificantToken = ITerminalSymbols.TokenNameVariable;
303           }
304           break;
305         case ITerminalSymbols.TokenNamenew:
306           lastSignificantToken = ITerminalSymbols.TokenNamenew;
307           break;
308         }
309       }
310     } catch (BadLocationException e) {
311     }
312     return lastSignificantToken;
313   }
314
315   String getSQLTableName(String sqlText, int start) {
316     int tableNameStart = -1;
317     int currentCharacterPosition = start + 1;
318     char ch;
319     try {
320       while (true) {
321         ch = sqlText.charAt(currentCharacterPosition++);
322         if (tableNameStart == -1 && Character.isJavaIdentifierStart(ch)) {
323           tableNameStart = currentCharacterPosition - 1;
324         } else {
325           if (!Character.isJavaIdentifierPart(ch)) {
326             return sqlText.substring(tableNameStart,
327                 currentCharacterPosition - 1);
328           }
329         }
330       }
331     } catch (IndexOutOfBoundsException e) {
332       if (tableNameStart >= 0) {
333         return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
334       }
335     }
336     return "";
337   }
338
339   private String getLastSQLTableName(String startText) {
340     int token;
341     // scan for sql identifiers
342     char ch = ' ';
343     int currentSQLPosition = startText.length();
344     int identEnd = -1;
345     String ident = null;
346     boolean whiteSpace = true;
347     try {
348       while (true) {
349         ch = startText.charAt(--currentSQLPosition);
350         if (ch >= 'A' && ch <= 'Z') {
351           if (identEnd < 0) {
352             identEnd = currentSQLPosition + 1;
353           }
354         } else if (ch >= 'a' && ch <= 'z') {
355           if (identEnd < 0) {
356             identEnd = currentSQLPosition + 1;
357           }
358         } else if (identEnd >= 0) {
359           ident = startText.substring(currentSQLPosition + 1, identEnd);
360           // select -- from -- where --
361           // update -- set -- where --
362           // insert into -- ( -- ) values ( -- )
363           if (ident.length() >= 4 && ident.length() <= 6) {
364             ident = ident.toLowerCase();
365             switch (ident.length()) {
366             //              case 3 :
367             //                if (ident.equals("set")) {
368             //                  // System.out.println("set");
369             //                  token = ITerminalSymbols.TokenNameSQLset;
370             //                  return token;
371             //                }
372             //                break;
373             case 4:
374               if (ident.equals("from")) {
375                 //                  System.out.println("from");
376                 token = ITerminalSymbols.TokenNameSQLfrom;
377                 return getSQLTableName(startText, identEnd);
378               } else if (ident.equals("into")) {
379                 //                System.out.println("into");
380                 token = ITerminalSymbols.TokenNameSQLinto;
381                 return getSQLTableName(startText, identEnd);
382               }
383               break;
384             //              case 5 :
385             //                if (ident.equals("where")) {
386             //                  // System.out.println("where");
387             //                  token = ITerminalSymbols.TokenNameSQLwhere;
388             //                  return token;
389             //                }
390             //                break;
391             case 6:
392               //                if (ident.equals("select")) {
393               //                  // System.out.println("select");
394               //                  token = ITerminalSymbols.TokenNameSQLselect;
395               //                  return token;
396               //                } else if (ident.equals("insert")) {
397               //                  // System.out.println("insert");
398               //                  token = ITerminalSymbols.TokenNameSQLinsert;
399               //                  return token;
400               //                } else
401               if (ident.equals("update")) {
402                 //                  System.out.println("update");
403                 token = ITerminalSymbols.TokenNameSQLupdate;
404                 return getSQLTableName(startText, identEnd);
405               }
406               //                else if (ident.equals("values")) {
407               //                  // System.out.println("values");
408               //                  token = ITerminalSymbols.TokenNameSQLvalues;
409               //                  return token;
410               //                }
411               break;
412             }
413           }
414           whiteSpace = false;
415           identEnd = -1;
416         } else if (Character.isWhitespace(ch)) {
417         } else {
418           whiteSpace = false;
419         }
420       }
421     } catch (IndexOutOfBoundsException e) {
422     }
423     return "<!--no-table-->";
424   }
425
426   /**
427    * Detect the last significant SQL token in the text before the completion
428    * 
429    * @param startText
430    */
431   private int getLastSQLToken(String startText) {
432     int token;
433     // scan for sql identifiers
434     char ch = ' ';
435     int currentSQLPosition = startText.length();
436     int identEnd = -1;
437     String ident = null;
438     boolean whiteSpace = true;
439     try {
440       while (true) {
441         ch = startText.charAt(--currentSQLPosition);
442         if (ch >= 'A' && ch <= 'Z') {
443           if (identEnd < 0) {
444             identEnd = currentSQLPosition + 1;
445           }
446         } else if (ch >= 'a' && ch <= 'z') {
447           if (identEnd < 0) {
448             identEnd = currentSQLPosition + 1;
449           }
450         } else if (identEnd >= 0) {
451           ident = startText.substring(currentSQLPosition + 1, identEnd);
452           // select -- from -- where --
453           // update -- set -- where --
454           // insert into -- ( -- ) values ( -- )
455           if (ident.length() >= 3 && ident.length() <= 6) {
456             ident = ident.toLowerCase();
457             switch (ident.length()) {
458             case 3:
459               if (ident.equals("set")) {
460                 //                  System.out.println("set");
461                 token = ITerminalSymbols.TokenNameSQLset;
462                 return token;
463               }
464               break;
465             case 4:
466               if (ident.equals("from")) {
467                 //                  System.out.println("from");
468                 token = ITerminalSymbols.TokenNameSQLfrom;
469                 //getSQLTableName();
470                 return token;
471               } else if (ident.equals("into")) {
472                 //                System.out.println("into");
473                 token = ITerminalSymbols.TokenNameSQLinto;
474                 return token;
475               }
476               break;
477             case 5:
478               if (ident.equals("where")) {
479                 //                  System.out.println("where");
480                 token = ITerminalSymbols.TokenNameSQLwhere;
481                 return token;
482               }
483               break;
484             case 6:
485               if (ident.equals("select")) {
486                 //                  System.out.println("select");
487                 token = ITerminalSymbols.TokenNameSQLselect;
488                 return token;
489               } else if (ident.equals("insert")) {
490                 //                  System.out.println("insert");
491                 token = ITerminalSymbols.TokenNameSQLinsert;
492                 return token;
493               } else if (ident.equals("update")) {
494                 //                  System.out.println("update");
495                 token = ITerminalSymbols.TokenNameSQLupdate;
496                 return token;
497               } else if (ident.equals("values")) {
498                 //                System.out.println("values");
499                 token = ITerminalSymbols.TokenNameSQLvalues;
500                 return token;
501               }
502               break;
503             }
504           }
505           whiteSpace = false;
506           identEnd = -1;
507         } else if (Character.isWhitespace(ch)) {
508         } else {
509           whiteSpace = false;
510         }
511       }
512     } catch (IndexOutOfBoundsException e) {
513     }
514     return ITerminalSymbols.TokenNameEOF;
515   }
516
517   private ICompletionProposal[] internalComputeCompletionProposals(
518       ITextViewer viewer, int offset, int contextOffset) {
519
520     IDocument document = viewer.getDocument();
521     Object[] identifiers = null;
522     IFile file = null;
523     IProject project = null;
524     if (offset > 0) {
525       PHPEditor editor = null;
526       if (fEditor != null && (fEditor instanceof PHPEditor)) {
527         editor = (PHPEditor) fEditor;
528         file = ((IFileEditorInput) editor.getEditorInput()).getFile();
529         project = file.getProject();
530         //        outlinePage = editor.getfOutlinePage();
531         // TODO: get the identifiers from the new model
532         //        if (outlinePage instanceof PHPContentOutlinePage) {
533         //          identifiers = ((PHPContentOutlinePage) outlinePage).getVariables();
534         //        }
535       }
536     }
537
538     final ICompilationUnit unit = fManager.getWorkingCopy(fEditor
539         .getEditorInput());
540
541     //  get buffer contents
542     final IBuffer buffer;
543     CompilationUnitDeclaration unitDecl=null;
544     try {
545       buffer = unit.getBuffer();
546
547       if (project != null && buffer != null) {
548
549         //      final char[] contents = buffer == null ? null :
550         // buffer.getCharacters();
551         //
552         //      // generate structure and compute syntax problems if needed
553         //      CompilationUnitStructureRequestor requestor = new
554         // CompilationUnitStructureRequestor(this, unitInfo, newElements);
555         //      JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo =
556         // getPerWorkingCopyInfo();
557         //      IJavaProject project = getJavaProject();
558         //      boolean computeProblems =
559         // JavaProject.hasJavaNature(project.getProject()) && perWorkingCopyInfo
560         // != null && perWorkingCopyInfo.isActive();
561         IProblemFactory problemFactory = new DefaultProblemFactory();
562         //      Map options = project.getOptions(true);
563         SourceElementParser parser = new SourceElementParser(null,
564             problemFactory, new CompilerOptions(null));
565         //, true/*report local declarations*/);
566         unitDecl = parser.parseCompletionUnit(
567             new net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit() {
568               public char[] getContents() {
569                 return buffer.getCharacters();
570               }
571
572               public char[] getMainTypeName() {
573                 return null;
574               }
575
576               public char[][] getPackageName() {
577                 return null;
578               }
579
580               public char[] getFileName() {
581                 return null;
582               }
583             }, true /* full parse to find local elements */);
584
585       }
586 //      System.out.println(unit.toString());
587     } catch (Exception e1) {
588       // TODO Auto-generated catch block
589       e1.printStackTrace();
590     }
591
592     ContextType phpContextType = ContextTypeRegistry.getInstance()
593         .getContextType("php"); //$NON-NLS-1$
594     ((CompilationUnitContextType) phpContextType).setContextParameters(
595         document, offset, 0);
596     PHPUnitContext context = (PHPUnitContext) phpContextType.createContext();
597     String prefix = context.getKey();
598     TableName sqlTable = new TableName();
599     int lastSignificantToken = getLastToken(viewer, offset, context, sqlTable);
600     boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER)
601         || (lastSignificantToken == ITerminalSymbols.TokenNameVariable)
602         || (lastSignificantToken == ITerminalSymbols.TokenNamenew);
603     boolean emptyPrefix = prefix == null || prefix.equals("");
604     if (fTemplateEngine != null) {
605       IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0];
606       ICompletionProposal[] results;
607       if (!emptyPrefix) {
608         fTemplateEngine.reset();
609         fTemplateEngine.complete(viewer, offset); //, unit);
610         templateResults = fTemplateEngine.getResults();
611       }
612       IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
613       if ((!useClassMembers) && identifiers != null) {
614         IdentifierEngine identifierEngine;
615         ContextType contextType = ContextTypeRegistry.getInstance()
616             .getContextType("php"); //$NON-NLS-1$
617         if (contextType != null) {
618           identifierEngine = new IdentifierEngine(contextType);
619           identifierEngine.complete(viewer, offset, identifiers);
620           identifierResults = identifierEngine.getResults();
621         }
622       }
623       // declarations stored in file project.index on project level
624       IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0];
625       if (project != null) {
626         DeclarationEngine declarationEngine;
627         ContextType contextType = ContextTypeRegistry.getInstance()
628             .getContextType("php"); //$NON-NLS-1$
629         if (contextType != null) {
630           IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault()
631               .getIndexManager(project);
632           SortedMap sortedMap = indexManager.getIdentifierMap();
633           declarationEngine = new DeclarationEngine(contextType,
634               lastSignificantToken, file);
635           declarationEngine.complete(viewer, offset, sortedMap);
636           declarationResults = declarationEngine.getResults();
637         }
638       }
639       // built in function names from phpsyntax.xml
640       ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData();
641       IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
642       if ((!useClassMembers) && syntaxbuffer != null) {
643         BuiltInEngine builtinEngine;
644         String proposal;
645         ContextType contextType = ContextTypeRegistry.getInstance()
646             .getContextType("php"); //$NON-NLS-1$
647         if (contextType != null) {
648           builtinEngine = new BuiltInEngine(contextType);
649           builtinEngine.complete(viewer, offset, syntaxbuffer);
650           builtinResults = builtinEngine.getResults();
651         }
652       }
653       IPHPCompletionProposal[] sqlResults = new IPHPCompletionProposal[0];
654       if (project != null) {
655         // Get The Database bookmark from the Quantum SQL plugin:
656         BookmarkCollection sqlBookMarks = BookmarkCollection.getInstance();
657         if (sqlBookMarks != null) {
658           String bookmarkString = Util.getMiscProjectsPreferenceValue(project,
659               IPreferenceConstants.PHP_BOOKMARK_DEFAULT);
660           if (bookmarkString != null && !bookmarkString.equals("")) {
661             Bookmark bookmark = sqlBookMarks.find(bookmarkString);
662             ArrayList sqlList = new ArrayList();
663             if (bookmark != null && !bookmark.isConnected()) {
664               new ConnectionUtil().connect(bookmark, null);
665             }
666             if (bookmark != null && bookmark.isConnected()) {
667               try {
668                 Connection connection = bookmark.getConnection();
669                 DatabaseMetaData metaData = connection.getMetaData();
670
671                 if (metaData != null) {
672                   int start = context.getStart();
673                   int end = context.getEnd();
674                   String foundSQLTableName = sqlTable.getTableName();
675                   String tableName;
676                   String columnName;
677                   String prefixWithoutDollar = prefix;
678                   boolean isDollarPrefix = false;
679                   if (prefix.length() > 0 && prefix.charAt(0) == '$') {
680                     prefixWithoutDollar = prefix.substring(1);
681                     isDollarPrefix = true;
682                   }
683                   IRegion region = new Region(start, end - start);
684                   ResultSet set;
685                   if (!isDollarPrefix) {
686                     set = metaData.getTables(null, null, prefixWithoutDollar
687                         + "%", null);
688                     while (set.next()) {
689                       //                  String tempSchema = set.getString("TABLE_SCHEM");
690                       //                  tempSchema = (tempSchema == null) ? "" :
691                       // tempSchema.trim();
692                       tableName = set.getString("TABLE_NAME");
693                       tableName = (tableName == null) ? "" : tableName.trim();
694                       if (tableName != null && tableName.length() > 0) {
695                         sqlList.add(new SQLProposal(tableName, context, region,
696                             viewer, PHPUiImages.get(PHPUiImages.IMG_TABLE)));
697                       }
698                     }
699                     set.close();
700                   }
701                   set = metaData.getColumns(null, null, "%",
702                       prefixWithoutDollar + "%");
703                   SQLProposal sqlProposal;
704                   while (set.next()) {
705                     columnName = set.getString("COLUMN_NAME");
706                     columnName = (columnName == null) ? "" : columnName.trim();
707                     tableName = set.getString("TABLE_NAME");
708                     tableName = (tableName == null) ? "" : tableName.trim();
709                     if (tableName != null && tableName.length() > 0
710                         && columnName != null && columnName.length() > 0) {
711                       if (isDollarPrefix) {
712                         sqlProposal = new SQLProposal(tableName, "$"
713                             + columnName, context, region, viewer, PHPUiImages
714                             .get(PHPUiImages.IMG_COLUMN));
715                       } else {
716                         sqlProposal = new SQLProposal(tableName, columnName,
717                             context, region, viewer, PHPUiImages
718                                 .get(PHPUiImages.IMG_COLUMN));
719                       }
720                       if (tableName.equals(foundSQLTableName)) {
721                         sqlProposal.setRelevance(90);
722                       } else if (tableName.indexOf(foundSQLTableName) >= 0) {
723                         sqlProposal.setRelevance(75);
724                       }
725                       sqlList.add(sqlProposal);
726                     }
727                   }
728                   set.close();
729                   sqlResults = new IPHPCompletionProposal[sqlList.size()];
730                   for (int i = 0; i < sqlList.size(); i++) {
731                     sqlResults[i] = (SQLProposal) sqlList.get(i);
732                   }
733                 }
734               } catch (NotConnectedException e) {
735                 // ignore this - not mission critical
736               } catch (SQLException e) {
737                 e.printStackTrace();
738               }
739             }
740           }
741         }
742       }
743       // concatenate the result arrays
744       IPHPCompletionProposal[] total;
745       total = new IPHPCompletionProposal[templateResults.length
746           + identifierResults.length + builtinResults.length
747           + declarationResults.length + sqlResults.length];
748       System.arraycopy(templateResults, 0, total, 0, templateResults.length);
749       System.arraycopy(identifierResults, 0, total, templateResults.length,
750           identifierResults.length);
751       System.arraycopy(builtinResults, 0, total, templateResults.length
752           + identifierResults.length, builtinResults.length);
753       System.arraycopy(declarationResults, 0, total, templateResults.length
754           + identifierResults.length + builtinResults.length,
755           declarationResults.length);
756       System.arraycopy(sqlResults, 0, total, templateResults.length
757           + identifierResults.length + builtinResults.length
758           + declarationResults.length, sqlResults.length);
759       results = total;
760       fNumberOfComputedResults = (results == null ? 0 : results.length);
761       /*
762        * Order here and not in result collector to make sure that the order
763        * applies to all proposals and not just those of the compilation unit.
764        */
765       return order(results);
766     }
767     return new IPHPCompletionProposal[0];
768   }
769
770   private int guessContextInformationPosition(ITextViewer viewer, int offset) {
771     int contextPosition = offset;
772     IDocument document = viewer.getDocument();
773     //    try {
774     //
775     //      PHPCodeReader reader= new PHPCodeReader();
776     //      reader.configureBackwardReader(document, offset, true, true);
777     //  
778     //      int nestingLevel= 0;
779     //
780     //      int curr= reader.read();
781     //      while (curr != PHPCodeReader.EOF) {
782     //
783     //        if (')' == (char) curr)
784     //          ++ nestingLevel;
785     //
786     //        else if ('(' == (char) curr) {
787     //          -- nestingLevel;
788     //        
789     //          if (nestingLevel < 0) {
790     //            int start= reader.getOffset();
791     //            if (looksLikeMethod(reader))
792     //              return start + 1;
793     //          }
794     //        }
795     //
796     //        curr= reader.read();
797     //      }
798     //    } catch (IOException e) {
799     //    }
800     return contextPosition;
801   }
802
803   /*
804    * (non-Javadoc) Method declared on IContentAssistProcessor
805    */
806   //  public IContextInformation[] computeContextInformation(ITextViewer viewer,
807   // int documentOffset) {
808   //    IContextInformation[] result = new IContextInformation[5];
809   //    for (int i = 0; i < result.length; i++)
810   //      result[i] = new
811   // ContextInformation(MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.display.pattern"),
812   // new Object[] { new Integer(i), new Integer(documentOffset)}),
813   // //$NON-NLS-1$
814   //      MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.value.pattern"),
815   // new Object[] { new Integer(i), new Integer(documentOffset - 5), new
816   // Integer(documentOffset + 5)})); //$NON-NLS-1$
817   //    return result;
818   //  }
819   /**
820    * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
821    */
822   public IContextInformation[] computeContextInformation(ITextViewer viewer,
823       int offset) {
824     int contextInformationPosition = guessContextInformationPosition(viewer,
825         offset);
826     List result = addContextInformations(viewer, contextInformationPosition);
827     return (IContextInformation[]) result
828         .toArray(new IContextInformation[result.size()]);
829   }
830
831   private List addContextInformations(ITextViewer viewer, int offset) {
832     ICompletionProposal[] proposals = internalComputeCompletionProposals(
833         viewer, offset, -1);
834     List result = new ArrayList();
835     for (int i = 0; i < proposals.length; i++) {
836       IContextInformation contextInformation = proposals[i]
837           .getContextInformation();
838       if (contextInformation != null) {
839         ContextInformationWrapper wrapper = new ContextInformationWrapper(
840             contextInformation);
841         wrapper.setContextInformationPosition(offset);
842         result.add(wrapper);
843       }
844     }
845     return result;
846   }
847
848   /**
849    * Order the given proposals.
850    */
851   private ICompletionProposal[] order(ICompletionProposal[] proposals) {
852     Arrays.sort(proposals, fComparator);
853     return proposals;
854   }
855
856   /*
857    * (non-Javadoc) Method declared on IContentAssistProcessor
858    */
859   public char[] getCompletionProposalAutoActivationCharacters() {
860     return fProposalAutoActivationSet;
861     //    return null; // new char[] { '$' };
862   }
863
864   /*
865    * (non-Javadoc) Method declared on IContentAssistProcessor
866    */
867   public char[] getContextInformationAutoActivationCharacters() {
868     return new char[] {};
869   }
870
871   /*
872    * (non-Javadoc) Method declared on IContentAssistProcessor
873    */
874   public IContextInformationValidator getContextInformationValidator() {
875     return fValidator;
876   }
877
878   /*
879    * (non-Javadoc) Method declared on IContentAssistProcessor
880    */
881   public String getErrorMessage() {
882     return null;
883   }
884 }