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