initial contribution
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / editor / WikiCompletionProcessor.java
1 /***********************************************************************************************************************************
2  * Copyright (c) 2000, 2004 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made
3  * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at
4  * http://www.eclipse.org/legal/cpl-v10.html
5  * 
6  * Contributors: IBM Corporation - initial API and implementation
7  **********************************************************************************************************************************/
8 package net.sourceforge.phpeclipse.wiki.editor;
9
10 import java.util.ArrayList;
11 import java.util.Arrays;
12 import java.util.Collections;
13 import java.util.Comparator;
14 import java.util.List;
15
16 import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaSection;
17 import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaText;
18
19 import org.eclipse.jface.resource.ImageDescriptor;
20 import org.eclipse.jface.resource.ImageRegistry;
21 import org.eclipse.jface.text.BadLocationException;
22 import org.eclipse.jface.text.IDocument;
23 import org.eclipse.jface.text.IRegion;
24 import org.eclipse.jface.text.ITextSelection;
25 import org.eclipse.jface.text.ITextViewer;
26 import org.eclipse.jface.text.Region;
27 import org.eclipse.jface.text.TextUtilities;
28 import org.eclipse.jface.text.contentassist.CompletionProposal;
29 import org.eclipse.jface.text.contentassist.ICompletionProposal;
30 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
31 import org.eclipse.jface.text.contentassist.IContextInformation;
32 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
33 import org.eclipse.jface.text.templates.DocumentTemplateContext;
34 import org.eclipse.jface.text.templates.Template;
35 import org.eclipse.jface.text.templates.TemplateContext;
36 import org.eclipse.jface.text.templates.TemplateContextType;
37 import org.eclipse.jface.text.templates.TemplateException;
38 import org.eclipse.jface.text.templates.TemplateProposal;
39 import org.eclipse.swt.graphics.Image;
40
41 public class WikiCompletionProcessor implements IContentAssistProcessor {
42
43   private static final String TEMPLATE_ICON = "icons/template.gif";
44
45 //  private static final String PREPARATION_TEMPLATE_CTX = "net.sourceforge.phpeclipse.wiki.editor.preparation";
46
47   private static final String INGREDIENTS_TEMPLATE_CTX = "net.sourceforge.phpeclipse.wiki.editor.templates";
48
49   private static final class ProposalComparator implements Comparator {
50     public int compare(Object o1, Object o2) {
51       return ((TemplateProposal) o2).getRelevance() - ((TemplateProposal) o1).getRelevance();
52     }
53   }
54
55   private static final Comparator fgProposalComparator = new ProposalComparator();
56
57   private final WikiEditor fEditor;
58
59   public WikiCompletionProcessor(WikiEditor editor) {
60     fEditor = editor;
61   }
62
63   public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
64     WikipediaSection section = fEditor.getSection();
65     if (section == null)
66       return null;
67
68     ITextSelection selection = (ITextSelection) viewer.getSelectionProvider().getSelection();
69     // adjust offset to start of normalized selection:
70     if (selection.getOffset() != offset)
71       offset = selection.getOffset();
72
73     String prefix = getPrefix(viewer, offset);
74     Region region = new Region(offset - prefix.length(), prefix.length() + selection.getLength());
75
76     ICompletionProposal[] templateProposals = computeTemplateProposals(viewer, region, section, prefix);
77 //    ICompletionProposal[] ingredientProposals = computeIngredientsProposals(viewer, region, recipe, prefix);
78 //    ICompletionProposal[] titleProposals = computeTitleProposals(viewer, region, recipe, prefix);
79     List result = new ArrayList();
80 //    result.addAll(Arrays.asList(ingredientProposals));
81     result.addAll(Arrays.asList(templateProposals));
82 //    result.addAll(Arrays.asList(titleProposals));
83
84     return (ICompletionProposal[]) result.toArray(new ICompletionProposal[result.size()]);
85   }
86
87   private ICompletionProposal[] computeTitleProposals(ITextViewer viewer, IRegion region, WikipediaText recipe, String prefix) {
88     List props = new ArrayList(2);
89     //          if (recipe.getIngredientsSection() == null)
90     //                  props.add(createTitleProposal("Zutaten:", region, viewer));
91     //          if (recipe.getPreparationSection() == null)
92     //                  props.add(createTitleProposal("Zubereitung:", region, viewer));
93     return (ICompletionProposal[]) props.toArray(new ICompletionProposal[props.size()]);
94   }
95
96   private CompletionProposal createTitleProposal(String name, IRegion region, ITextViewer viewer) {
97     String lineDelimiter = TextUtilities.getDefaultLineDelimiter(viewer.getDocument());
98     return new CompletionProposal(name + lineDelimiter, region.getOffset(), region.getLength(), region.getOffset() + name.length()
99         + lineDelimiter.length(), null, name, null, null);
100   }
101
102   private ICompletionProposal[] computeIngredientsProposals(ITextViewer viewer, IRegion region, WikipediaText recipe, String prefix) {
103     return new ICompletionProposal[0];
104     //          Step[] steps= recipe.getSteps();
105     //          if (steps == null || steps.length == 0)
106     //                  return new ICompletionProposal[0];
107     //          
108     //          int offset= region.getOffset();
109     //          Step first= steps[0];
110     //          if (offset < first.getOffset())
111     //                  return new ICompletionProposal[0];
112     //          
113     //          Ingredient[] ingredients= recipe.getIngredients();
114     //          if (ingredients == null)
115     //                  return new ICompletionProposal[0];
116     //          
117     //          prefix= prefix.toLowerCase();
118     //          
119     //          ArrayList proposals= new ArrayList();
120     //          for (int i= 0; i < ingredients.length; i++) {
121     //                  String ingredient= ingredients[i].getName();
122     //                  if (ingredient.toLowerCase().startsWith(prefix))
123     //                          proposals.add(new CompletionProposal(ingredient, offset, region.getLength(), ingredient.length()));
124     //          }
125     //          return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]);
126   }
127
128   private TemplateContextType getContextType(WikipediaSection section, int offset) {
129 //    if (recipe.getPreparationSection() != null && recipe.getPreparationSection().getOffset() < offset)
130 //      return WikiEditorPlugin.getDefault().getContextTypeRegistry().getContextType(PREPARATION_TEMPLATE_CTX);
131 //    else
132       return WikiEditorPlugin.getDefault().getContextTypeRegistry().getContextType(INGREDIENTS_TEMPLATE_CTX);
133   }
134
135   /**
136    * Creates a concrete template context for the given region in the document. This involves finding out which context fType is valid
137    * at the given location, and then creating a context of this fType. The default implementation returns a
138    * <code>DocumentTemplateContext</code> for the context fType at the given location.
139    * 
140    * @param viewer
141    *          the viewer for which the context is created
142    * @param region
143    *          the region into <code>document</code> for which the context is created
144    * @return a template context that can handle template insertion at the given location, or <code>null</code>
145    */
146   private TemplateContext createContext(ITextViewer viewer, IRegion region, WikipediaSection recipe) {
147     TemplateContextType contextType = getContextType(recipe, region.getOffset());
148     if (contextType != null) {
149       IDocument document = viewer.getDocument();
150       return new DocumentTemplateContext(contextType, document, region.getOffset(), region.getLength());
151     }
152     return null;
153   }
154
155   private ICompletionProposal[] computeTemplateProposals(ITextViewer viewer, IRegion region, WikipediaSection recipe, String prefix) {
156     TemplateContext context = createContext(viewer, region, recipe);
157     if (context == null)
158       return new ICompletionProposal[0];
159
160     ITextSelection selection = (ITextSelection) viewer.getSelectionProvider().getSelection();
161     context.setVariable("selection", selection.getText()); // name of the selection variables {line, word}_selection
162
163     String id = context.getContextType().getId();
164     Template[] templates = WikiEditorPlugin.getDefault().getTemplateStore().getTemplates(id);
165
166     List matches = new ArrayList();
167     for (int i = 0; i < templates.length; i++) {
168       Template template = templates[i];
169       try {
170         context.getContextType().validate(template.getPattern());
171       } catch (TemplateException e) {
172         continue;
173       }
174       int relevance = getRelevance(template, prefix);
175       if (relevance > 0) {
176         matches.add(new TemplateProposal(template, context, region, getImage(template), relevance));
177       }
178     }
179
180     Collections.sort(matches, fgProposalComparator);
181
182     return (ICompletionProposal[]) matches.toArray(new ICompletionProposal[matches.size()]);
183   }
184
185   /**
186    * Returns the relevance of a template given a prefix. The default implementation returns a number greater than zero if the
187    * template name starts with the prefix, and zero otherwise.
188    * 
189    * @param template
190    *          the template to compute the relevance for
191    * @param prefix
192    *          the prefix after which content assist was requested
193    * @return the relevance of <code>template</code>
194    * @see #getPrefix(ITextViewer, int)
195    */
196   private int getRelevance(Template template, String prefix) {
197     if (template.getName().startsWith(prefix))
198       return 90;
199     return 0;
200   }
201
202   private String getPrefix(ITextViewer viewer, int offset) {
203     int i = offset;
204     IDocument document = viewer.getDocument();
205     if (i > document.getLength())
206       return "";
207
208     try {
209       while (i > 0) {
210         char ch = document.getChar(i - 1);
211         if (!Character.isLetterOrDigit(ch))
212           break;
213         i--;
214       }
215
216       return document.get(i, offset - i);
217     } catch (BadLocationException e) {
218       return "";
219     }
220   }
221
222   /**
223    * Always return the default image.
224    */
225   private Image getImage(Template template) {
226     ImageRegistry registry = WikiEditorPlugin.getDefault().getImageRegistry();
227     Image image = registry.get(TEMPLATE_ICON);
228     if (image == null) {
229       ImageDescriptor desc = WikiEditorPlugin.imageDescriptorFromPlugin("net.sourceforge.phpeclipse.wiki.editor", TEMPLATE_ICON);
230       registry.put(TEMPLATE_ICON, desc);
231       image = registry.get(TEMPLATE_ICON);
232     }
233     return image;
234   }
235
236   public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
237     return null;
238   }
239
240   public char[] getCompletionProposalAutoActivationCharacters() {
241     return null;
242   }
243
244   public char[] getContextInformationAutoActivationCharacters() {
245     return null;
246   }
247
248   public String getErrorMessage() {
249     return null;
250   }
251
252   public IContextInformationValidator getContextInformationValidator() {
253     return null;
254   }
255 }