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