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
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 import net.sourceforge.phpdt.core.ToolFactory;
22 import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
23 import net.sourceforge.phpdt.core.compiler.InvalidInputException;
24 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
25 import net.sourceforge.phpdt.internal.corext.template.ContextType;
26 import net.sourceforge.phpdt.internal.corext.template.ContextTypeRegistry;
27 import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContextType;
28 import net.sourceforge.phpdt.internal.corext.template.php.PHPUnitContext;
29 import net.sourceforge.phpdt.internal.ui.PHPUiImages;
30 import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal;
31 import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator;
32 import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine;
33 import net.sourceforge.phpdt.internal.ui.text.template.DeclarationEngine;
34 import net.sourceforge.phpdt.internal.ui.text.template.IdentifierEngine;
35 import net.sourceforge.phpdt.internal.ui.text.template.IdentifierProposal;
36 import net.sourceforge.phpdt.internal.ui.text.template.TemplateEngine;
37 import net.sourceforge.phpeclipse.IPreferenceConstants;
38 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
39 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
40 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
41 import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr;
42 import org.eclipse.core.resources.IFile;
43 import org.eclipse.core.resources.IProject;
44 import org.eclipse.jface.text.BadLocationException;
45 import org.eclipse.jface.text.IDocument;
46 import org.eclipse.jface.text.IRegion;
47 import org.eclipse.jface.text.ITextViewer;
48 import org.eclipse.jface.text.Region;
49 import org.eclipse.jface.text.TextPresentation;
50 import org.eclipse.jface.text.contentassist.ICompletionProposal;
51 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
52 import org.eclipse.jface.text.contentassist.IContextInformation;
53 import org.eclipse.jface.text.contentassist.IContextInformationExtension;
54 import org.eclipse.jface.text.contentassist.IContextInformationPresenter;
55 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
56 import org.eclipse.swt.graphics.Image;
57 import org.eclipse.ui.IEditorPart;
58 import org.eclipse.ui.IFileEditorInput;
59 import net.sourceforge.phpeclipse.overlaypages.Util;
60 import com.quantum.model.Bookmark;
61 import com.quantum.model.BookmarkCollection;
62 import com.quantum.model.NotConnectedException;
63 import com.quantum.util.connection.ConnectionUtil;
65 * Example PHP completion processor.
67 public class PHPCompletionProcessor implements IContentAssistProcessor {
69 * Simple content assist tip closer. The tip is valid in a range of 5
70 * characters around its popup location.
72 protected static class Validator
74 IContextInformationValidator,
75 IContextInformationPresenter {
76 protected int fInstallOffset;
78 * @see IContextInformationValidator#isContextInformationValid(int)
80 public boolean isContextInformationValid(int offset) {
81 return Math.abs(fInstallOffset - offset) < 5;
84 * @see IContextInformationValidator#install(IContextInformation,
87 public void install(IContextInformation info, ITextViewer viewer, int offset) {
88 fInstallOffset = offset;
91 * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int,
94 public boolean updatePresentation(int documentPosition,
95 TextPresentation presentation) {
99 private static class ContextInformationWrapper
102 IContextInformationExtension {
103 private final IContextInformation fContextInformation;
104 private int fPosition;
105 public ContextInformationWrapper(IContextInformation contextInformation) {
106 fContextInformation = contextInformation;
109 * @see IContextInformation#getContextDisplayString()
111 public String getContextDisplayString() {
112 return fContextInformation.getContextDisplayString();
115 * @see IContextInformation#getImage()
117 public Image getImage() {
118 return fContextInformation.getImage();
121 * @see IContextInformation#getInformationDisplayString()
123 public String getInformationDisplayString() {
124 return fContextInformation.getInformationDisplayString();
127 * @see IContextInformationExtension#getContextInformationPosition()
129 public int getContextInformationPosition() {
132 public void setContextInformationPosition(int position) {
133 fPosition = position;
136 private char[] fProposalAutoActivationSet;
137 protected IContextInformationValidator fValidator = new Validator();
138 private TemplateEngine fTemplateEngine;
139 private PHPCompletionProposalComparator fComparator;
140 private int fNumberOfComputedResults = 0;
141 public PHPCompletionProcessor() {
142 ContextType contextType = ContextTypeRegistry.getInstance().getContextType(
143 "php"); //$NON-NLS-1$
144 if (contextType != null)
145 fTemplateEngine = new TemplateEngine(contextType);
146 fComparator = new PHPCompletionProposalComparator();
149 * Tells this processor to order the proposals alphabetically.
152 * <code>true</code> if proposals should be ordered.
154 public void orderProposalsAlphabetically(boolean order) {
155 fComparator.setOrderAlphabetically(order);
158 * Sets this processor's set of characters triggering the activation of the
159 * completion proposal computation.
161 * @param activationSet
164 public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
165 fProposalAutoActivationSet = activationSet;
168 * (non-Javadoc) Method declared on IContentAssistProcessor
170 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
171 int documentOffset) {
172 int contextInformationPosition = guessContextInformationPosition(viewer,
174 return internalComputeCompletionProposals(viewer, documentOffset,
175 contextInformationPosition);
177 private int getLastToken(ITextViewer viewer, int completionPosition,
178 PHPUnitContext context) {
179 IDocument document = viewer.getDocument();
180 int start = context.getStart();
181 int end = context.getEnd();
183 int lastSignificantToken = ITerminalSymbols.TokenNameEOF;
185 // begin search 2 lines behind of this
190 ch = document.getChar(j);
196 ch = document.getChar(j);
203 // scan the line for the dereferencing operator '->'
204 startText = document.get(j, start - j);
206 System.out.println(startText);
208 int token = ITerminalSymbols.TokenNameEOF;
210 token = getLastSQLToken(startText);
212 Scanner scanner = ToolFactory.createScanner(false, false, false);
213 scanner.setSource(startText.toCharArray());
214 scanner.setPHPMode(true);
216 int beforeLastToken = ITerminalSymbols.TokenNameEOF;
217 int lastToken = ITerminalSymbols.TokenNameEOF;
219 token = scanner.getNextToken();
221 while (token != ITerminalSymbols.TokenNameERROR
222 && token != ITerminalSymbols.TokenNameEOF) {
223 beforeLastToken = lastToken;
225 // System.out.println(scanner.toStringAction(lastToken));
226 token = scanner.getNextToken();
228 } catch (InvalidInputException e1) {
231 case ITerminalSymbols.TokenNameMINUS_GREATER :
232 // dereferencing operator '->' found
233 lastSignificantToken = ITerminalSymbols.TokenNameMINUS_GREATER;
234 if (beforeLastToken == ITerminalSymbols.TokenNameVariable) {
235 lastSignificantToken = ITerminalSymbols.TokenNameVariable;
238 case ITerminalSymbols.TokenNamenew :
239 lastSignificantToken = ITerminalSymbols.TokenNamenew;
243 } catch (BadLocationException e) {
245 return lastSignificantToken;
249 * Detect the last significant SQL token in the text before the completion
253 private int getLastSQLToken(String startText) {
255 // scan for sql identifiers
257 int currentSQLPosition = startText.length();
260 boolean whiteSpace = true;
263 ch = startText.charAt(--currentSQLPosition);
264 if (ch >= 'A' && ch <= 'Z') {
266 identEnd = currentSQLPosition + 1;
268 } else if (ch >= 'a' && ch <= 'z') {
270 identEnd = currentSQLPosition + 1;
272 } else if (identEnd >= 0) {
273 ident = startText.substring(currentSQLPosition + 1, identEnd);
274 // select -- from -- where --
275 // update -- set -- where --
276 // insert into -- ( -- ) values ( -- )
277 if (ident.length() >= 3 && ident.length() <= 6) {
278 ident = ident.toLowerCase();
279 switch (ident.length()) {
281 if (ident.equals("set")) {
282 // System.out.println("set");
283 token = ITerminalSymbols.TokenNameSQLset;
288 if (ident.equals("from")) {
289 // System.out.println("from");
290 token = ITerminalSymbols.TokenNameSQLfrom;
292 } else if (ident.equals("into")) {
293 // System.out.println("into");
294 token = ITerminalSymbols.TokenNameSQLinto;
299 if (ident.equals("where")) {
300 // System.out.println("where");
301 token = ITerminalSymbols.TokenNameSQLwhere;
306 if (ident.equals("select")) {
307 // System.out.println("select");
308 token = ITerminalSymbols.TokenNameSQLselect;
310 } else if (ident.equals("insert")) {
311 // System.out.println("insert");
312 token = ITerminalSymbols.TokenNameSQLinsert;
314 } else if (ident.equals("update")) {
315 // System.out.println("update");
316 token = ITerminalSymbols.TokenNameSQLupdate;
318 } else if (ident.equals("values")) {
319 // System.out.println("values");
320 token = ITerminalSymbols.TokenNameSQLvalues;
328 } else if (Character.isWhitespace(ch)) {
333 } catch (IndexOutOfBoundsException e) {
335 return ITerminalSymbols.TokenNameEOF;
338 private ICompletionProposal[] internalComputeCompletionProposals(
339 ITextViewer viewer, int offset, int contextOffset) {
340 IDocument document = viewer.getDocument();
341 Object[] identifiers = null;
343 IProject project = null;
345 PHPEditor editor = null;
346 // JavaOutlinePage outlinePage = null;
347 IEditorPart targetEditor = PHPeclipsePlugin.getActiveWorkbenchWindow()
348 .getActivePage().getActiveEditor();
349 if (targetEditor != null && (targetEditor instanceof PHPEditor)) {
350 editor = (PHPEditor) targetEditor;
351 file = ((IFileEditorInput) editor.getEditorInput()).getFile();
352 project = file.getProject();
353 // outlinePage = editor.getfOutlinePage();
354 // TODO: get the identifiers from the new model
355 // if (outlinePage instanceof PHPContentOutlinePage) {
356 // identifiers = ((PHPContentOutlinePage) outlinePage).getVariables();
360 ContextType phpContextType = ContextTypeRegistry.getInstance()
361 .getContextType("php"); //$NON-NLS-1$
362 ((CompilationUnitContextType) phpContextType).setContextParameters(
363 document, offset, 0);
364 PHPUnitContext context = (PHPUnitContext) phpContextType.createContext();
365 String prefix = context.getKey();
366 int lastSignificantToken = getLastToken(viewer, offset, context);
367 boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER)
368 || (lastSignificantToken == ITerminalSymbols.TokenNameVariable)
369 || (lastSignificantToken == ITerminalSymbols.TokenNamenew);
370 boolean emptyPrefix = prefix == null || prefix.equals("");
371 if (fTemplateEngine != null) {
372 IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0];
373 ICompletionProposal[] results;
375 fTemplateEngine.reset();
376 fTemplateEngine.complete(viewer, offset); //, unit);
377 templateResults = fTemplateEngine.getResults();
379 IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
380 if ((!useClassMembers) && identifiers != null) {
381 IdentifierEngine identifierEngine;
382 ContextType contextType = ContextTypeRegistry.getInstance()
383 .getContextType("php"); //$NON-NLS-1$
384 if (contextType != null) {
385 identifierEngine = new IdentifierEngine(contextType);
386 identifierEngine.complete(viewer, offset, identifiers);
387 identifierResults = identifierEngine.getResults();
390 // declarations stored in file project.index on project level
391 IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0];
392 if (project != null) {
393 DeclarationEngine declarationEngine;
394 ContextType contextType = ContextTypeRegistry.getInstance()
395 .getContextType("php"); //$NON-NLS-1$
396 if (contextType != null) {
397 IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault()
398 .getIndexManager(project);
399 SortedMap sortedMap = indexManager.getIdentifierMap();
400 declarationEngine = new DeclarationEngine(contextType,
401 lastSignificantToken, file);
402 declarationEngine.complete(viewer, offset, sortedMap);
403 declarationResults = declarationEngine.getResults();
406 // built in function names from phpsyntax.xml
407 ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData();
408 IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
409 if ((!useClassMembers) && syntaxbuffer != null) {
410 BuiltInEngine builtinEngine;
412 ContextType contextType = ContextTypeRegistry.getInstance()
413 .getContextType("php"); //$NON-NLS-1$
414 if (contextType != null) {
415 builtinEngine = new BuiltInEngine(contextType);
416 builtinEngine.complete(viewer, offset, syntaxbuffer);
417 builtinResults = builtinEngine.getResults();
420 IPHPCompletionProposal[] sqlResults = new IPHPCompletionProposal[0];
421 if (project != null) {
422 // Get The Database bookmark from the Quantum SQL plugin:
423 BookmarkCollection sqlBookMarks = BookmarkCollection.getInstance();
424 if (sqlBookMarks != null) {
425 String bookmarkString = Util.getMiscProjectsPreferenceValue(project,
426 IPreferenceConstants.PHP_BOOKMARK_DEFAULT);
427 if (bookmarkString != null && !bookmarkString.equals("")) {
428 Bookmark bookmark = sqlBookMarks.find(bookmarkString);
429 ArrayList list = new ArrayList();
430 if (bookmark != null && !bookmark.isConnected()) {
431 new ConnectionUtil().connect(bookmark, null);
433 if (bookmark != null && bookmark.isConnected()) {
435 Connection connection = bookmark.getConnection();
436 DatabaseMetaData metaData = connection.getMetaData();
437 if (metaData != null) {
438 int start = context.getStart();
439 int end = context.getEnd();
440 IRegion region = new Region(start, end - start);
441 ResultSet set = metaData.getTables(null, null, prefix + "%",
444 // String tempSchema = set.getString("TABLE_SCHEM");
445 // tempSchema = (tempSchema == null) ? "" :
446 // tempSchema.trim();
447 String tableName = set.getString("TABLE_NAME");
448 tableName = (tableName == null) ? "" : tableName.trim();
449 if (tableName != null && tableName.length() > 0) {
454 set = metaData.getColumns(null, null, "%", prefix + "%");
456 String tableName = set.getString("COLUMN_NAME");
457 tableName = (tableName == null) ? "" : tableName.trim();
458 if (tableName != null && tableName.length() > 0) {
461 tableName = set.getString("TABLE_NAME");
462 tableName = (tableName == null) ? "" : tableName.trim();
463 if (tableName != null && tableName.length() > 0) {
468 sqlResults = new IPHPCompletionProposal[list.size()];
469 for (int i = 0; i < list.size(); i++) {
470 sqlResults[i] = new IdentifierProposal(
471 (String) list.get(i), context, region, viewer,
472 PHPUiImages.get(PHPUiImages.IMG_FUN), PHPUiImages
473 .get(PHPUiImages.IMG_VAR));
476 } catch (NotConnectedException e) {
477 // ignore this - not mission critical
478 } catch (SQLException e) {
485 // concatenate the result arrays
486 IPHPCompletionProposal[] total;
487 total = new IPHPCompletionProposal[templateResults.length
488 + identifierResults.length + builtinResults.length
489 + declarationResults.length + sqlResults.length];
490 System.arraycopy(templateResults, 0, total, 0, templateResults.length);
491 System.arraycopy(identifierResults, 0, total, templateResults.length,
492 identifierResults.length);
493 System.arraycopy(builtinResults, 0, total, templateResults.length
494 + identifierResults.length, builtinResults.length);
495 System.arraycopy(declarationResults, 0, total, templateResults.length
496 + identifierResults.length + builtinResults.length,
497 declarationResults.length);
498 System.arraycopy(sqlResults, 0, total, templateResults.length
499 + identifierResults.length + builtinResults.length
500 + declarationResults.length, sqlResults.length);
502 fNumberOfComputedResults = (results == null ? 0 : results.length);
504 * Order here and not in result collector to make sure that the order
505 * applies to all proposals and not just those of the compilation unit.
507 return order(results);
509 return new IPHPCompletionProposal[0];
511 private int guessContextInformationPosition(ITextViewer viewer, int offset) {
512 int contextPosition = offset;
513 IDocument document = viewer.getDocument();
516 // PHPCodeReader reader= new PHPCodeReader();
517 // reader.configureBackwardReader(document, offset, true, true);
519 // int nestingLevel= 0;
521 // int curr= reader.read();
522 // while (curr != PHPCodeReader.EOF) {
524 // if (')' == (char) curr)
527 // else if ('(' == (char) curr) {
530 // if (nestingLevel < 0) {
531 // int start= reader.getOffset();
532 // if (looksLikeMethod(reader))
537 // curr= reader.read();
539 // } catch (IOException e) {
541 return contextPosition;
544 * (non-Javadoc) Method declared on IContentAssistProcessor
546 // public IContextInformation[] computeContextInformation(ITextViewer viewer,
547 // int documentOffset) {
548 // IContextInformation[] result = new IContextInformation[5];
549 // for (int i = 0; i < result.length; i++)
551 // ContextInformation(MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.display.pattern"),
552 // new Object[] { new Integer(i), new Integer(documentOffset)}),
554 // MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.value.pattern"),
555 // new Object[] { new Integer(i), new Integer(documentOffset - 5), new
556 // Integer(documentOffset + 5)})); //$NON-NLS-1$
560 * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
562 public IContextInformation[] computeContextInformation(ITextViewer viewer,
564 int contextInformationPosition = guessContextInformationPosition(viewer,
566 List result = addContextInformations(viewer, contextInformationPosition);
567 return (IContextInformation[]) result
568 .toArray(new IContextInformation[result.size()]);
570 private List addContextInformations(ITextViewer viewer, int offset) {
571 ICompletionProposal[] proposals = internalComputeCompletionProposals(
573 List result = new ArrayList();
574 for (int i = 0; i < proposals.length; i++) {
575 IContextInformation contextInformation = proposals[i]
576 .getContextInformation();
577 if (contextInformation != null) {
578 ContextInformationWrapper wrapper = new ContextInformationWrapper(
580 wrapper.setContextInformationPosition(offset);
587 * Order the given proposals.
589 private ICompletionProposal[] order(ICompletionProposal[] proposals) {
590 Arrays.sort(proposals, fComparator);
594 * (non-Javadoc) Method declared on IContentAssistProcessor
596 public char[] getCompletionProposalAutoActivationCharacters() {
597 return fProposalAutoActivationSet;
598 // return null; // new char[] { '$' };
601 * (non-Javadoc) Method declared on IContentAssistProcessor
603 public char[] getContextInformationAutoActivationCharacters() {
607 * (non-Javadoc) Method declared on IContentAssistProcessor
609 public IContextInformationValidator getContextInformationValidator() {
613 * (non-Javadoc) Method declared on IContentAssistProcessor
615 public String getErrorMessage() {