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