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