/*********************************************************************************************************************************** * Copyright (c) 2000, 2004 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: IBM Corporation - initial API and implementation **********************************************************************************************************************************/ package net.sourceforge.phpeclipse.wiki.editor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaSection; import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaText; import net.sourceforge.phpeclipse.wiki.sql.WikipediaDB; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.contentassist.IContextInformationValidator; import org.eclipse.jface.text.templates.DocumentTemplateContext; import org.eclipse.jface.text.templates.Template; import org.eclipse.jface.text.templates.TemplateContext; import org.eclipse.jface.text.templates.TemplateContextType; import org.eclipse.jface.text.templates.TemplateException; import org.eclipse.jface.text.templates.TemplateProposal; import org.eclipse.swt.graphics.Image; public class WikiCompletionProcessor implements IContentAssistProcessor { static class StringComparator implements Comparator { public int compare(Object o1, Object o2) { String s1 = (String) o1; String s2 = (String) o2; return s1.compareTo(s2); // return s1.toUpperCase().compareTo(s2.toUpperCase()); } public boolean equals(Object o) { // String s = (String) o; return compare(this, o) == 0; } } private static final String TEMPLATE_ICON = "icons/template.gif"; // private static TreeSet TITLES_SET = null; private static final String WIKIPEDIA_TEMPLATE_CTX = "net.sourceforge.phpeclipse.wiki.editor.templates"; private static final class ProposalComparator implements Comparator { public int compare(Object o1, Object o2) { return ((TemplateProposal) o2).getRelevance() - ((TemplateProposal) o1).getRelevance(); } } private static final Comparator fgProposalComparator = new ProposalComparator(); private final WikiEditor fEditor; public WikiCompletionProcessor(WikiEditor editor) { fEditor = editor; } // private static void readFile(String filename) { // TITLES_SET = new TreeSet(new StringComparator()); // FileReader fileReader; // try { // fileReader = new FileReader(filename); // BufferedReader bufferedReader = new BufferedReader(fileReader); // LineTokenizer lineTokenizer = new LineTokenizer(); // StringBuffer line = new StringBuffer(1024); // while (lineTokenizer.getToken(line, bufferedReader)) { // if (line.length() == 0) { // // this should not happen // } else { // TITLES_SET.add(line.toString()); // line.delete(0, line.length()); // } // } // bufferedReader.close(); // } catch (FileNotFoundException e) { // // ignore this // // TODO DialogBox which asks the user if she/he likes to build new index? // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { WikipediaSection section = fEditor.getSection(); if (section == null) return null; ITextSelection selection = (ITextSelection) viewer.getSelectionProvider().getSelection(); // adjust offset to start of normalized selection: if (selection.getOffset() != offset) offset = selection.getOffset(); String prefix = getPrefix(viewer, offset); Region region = new Region(offset - prefix.length(), prefix.length() + selection.getLength()); List result = new ArrayList(); if (prefix.length() > 2) { if (WikiEditorPlugin.fWikiDB == null) { try { WikiEditorPlugin.fWikiDB = new WikipediaDB(); } catch (Exception ex1) { // ex1.printStackTrace(); // could not start db WikiEditorPlugin.fWikiDB = null; } } if (WikiEditorPlugin.fWikiDB != null) { try { ArrayList list = WikiEditorPlugin.fWikiDB.queryPrefixTitle(prefix); ICompletionProposal[] titleProposals = computeTitleProposals(list, region, viewer); result.addAll(Arrays.asList(titleProposals)); } catch (Exception ex1) { // ex1.printStackTrace(); // could not start db WikiEditorPlugin.fWikiDB = null; } } } // if (TITLES_SET==null) { // TODO make this a preference // readFile("c:\\temp\\titles.txt"); // } // if (TITLES_SET.size()>0 && prefix.length()>3) { // SortedSet subSet = TITLES_SET.subSet(prefix, prefix + '\255'); // Iterator iter = subSet.iterator(); // ArrayList list; // String title; // int maxProposals = 200; // while (iter.hasNext()) { // title = (String) iter.next(); // if (title.toLowerCase().startsWith(prefix.toLowerCase())) { // result.add(title); // } // if (maxProposals-- < 0) { // break; // } // } // } ICompletionProposal[] templateProposals = computeTemplateProposals(viewer, region, section, prefix); // ICompletionProposal[] ingredientProposals = computeIngredientsProposals(viewer, region, recipe, prefix); // ICompletionProposal[] titleProposals = computeTitleProposals(viewer, region, recipe, prefix); // result.addAll(Arrays.asList(ingredientProposals)); result.addAll(Arrays.asList(templateProposals)); // result.addAll(Arrays.asList(titleProposals)); return (ICompletionProposal[]) result.toArray(new ICompletionProposal[result.size()]); } private ICompletionProposal[] computeTitleProposals(ArrayList list, IRegion region, ITextViewer viewer) { ICompletionProposal[] arr = new ICompletionProposal[list.size()]; // String lineDelimiter = TextUtilities.getDefaultLineDelimiter(viewer.getDocument()); String temp; for (int i = 0; i < arr.length; i++) { temp = (String) list.get(i); arr[i] = new CompletionProposal(temp, region.getOffset(), region.getLength(), temp.length(), null, temp, null, null); } return arr; } private TemplateContextType getContextType(WikipediaSection section, int offset) { return WikiEditorPlugin.getDefault().getContextTypeRegistry().getContextType(WIKIPEDIA_TEMPLATE_CTX); } /** * Creates a concrete template context for the given region in the document. This involves finding out which context fType is * valid at the given location, and then creating a context of this fType. The default implementation returns a * DocumentTemplateContext for the context fType at the given location. * * @param viewer * the viewer for which the context is created * @param region * the region into document for which the context is created * @return a template context that can handle template insertion at the given location, or null */ private TemplateContext createContext(ITextViewer viewer, IRegion region, WikipediaSection recipe) { TemplateContextType contextType = getContextType(recipe, region.getOffset()); if (contextType != null) { IDocument document = viewer.getDocument(); return new DocumentTemplateContext(contextType, document, region.getOffset(), region.getLength()); } return null; } private ICompletionProposal[] computeTemplateProposals(ITextViewer viewer, IRegion region, WikipediaSection recipe, String prefix) { TemplateContext context = createContext(viewer, region, recipe); if (context == null) return new ICompletionProposal[0]; ITextSelection selection = (ITextSelection) viewer.getSelectionProvider().getSelection(); context.setVariable("selection", selection.getText()); // name of the selection variables {line, word}_selection String id = context.getContextType().getId(); Template[] templates = WikiEditorPlugin.getDefault().getTemplateStore().getTemplates(id); List matches = new ArrayList(); for (int i = 0; i < templates.length; i++) { Template template = templates[i]; try { context.getContextType().validate(template.getPattern()); } catch (TemplateException e) { continue; } // int relevance = getRelevance(template, prefix); // if (relevance > 0) { matches.add(new TemplateProposal(template, context, region, getImage(template), 1)); // } } Collections.sort(matches, fgProposalComparator); return (ICompletionProposal[]) matches.toArray(new ICompletionProposal[matches.size()]); } /** * Returns the relevance of a template given a prefix. The default implementation returns a number greater than zero if the * template name starts with the prefix, and zero otherwise. * * @param template * the template to compute the relevance for * @param prefix * the prefix after which content assist was requested * @return the relevance of template * @see #getPrefix(ITextViewer, int) */ private int getRelevance(Template template, String prefix) { if (template.getName().startsWith(prefix)) return 90; return 0; } private String getPrefix(ITextViewer viewer, int offset) { int i = offset; IDocument document = viewer.getDocument(); if (i > document.getLength()) return ""; try { while (i > 0) { char ch = document.getChar(i - 1); if (!Character.isLetterOrDigit(ch) && (ch != ':') && (ch != '_')) break; i--; } return document.get(i, offset - i); } catch (BadLocationException e) { return ""; } } /** * Always return the default image. */ private Image getImage(Template template) { ImageRegistry registry = WikiEditorPlugin.getDefault().getImageRegistry(); Image image = registry.get(TEMPLATE_ICON); if (image == null) { ImageDescriptor desc = WikiEditorPlugin.imageDescriptorFromPlugin("net.sourceforge.phpeclipse.wiki.editor", TEMPLATE_ICON); registry.put(TEMPLATE_ICON, desc); image = registry.get(TEMPLATE_ICON); } return image; } public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) { return null; } public char[] getCompletionProposalAutoActivationCharacters() { return null; } public char[] getContextInformationAutoActivationCharacters() { return null; } public String getErrorMessage() { return null; } public IContextInformationValidator getContextInformationValidator() { return null; } }