下面列出了怎么用org.eclipse.jface.text.templates.TemplateProposal的API类实例代码及写法,或者点击链接到github查看源代码。
/** {@inheritDoc} */
@SuppressWarnings({"rawtypes", "unchecked"})
public int compare(final ICompletionProposal o1, final ICompletionProposal o2) {
// Template sorting by relevance and then alphabetically by name
if (o1 instanceof TemplateProposal && o2 instanceof TemplateProposal) {
TemplateProposal t1 = (TemplateProposal) o1;
TemplateProposal t2 = (TemplateProposal) o2;
if (t1.getRelevance() == t2.getRelevance()) {
return o1.getDisplayString().compareTo(o2.getDisplayString());
}
return ((Integer) t1.getRelevance()).compareTo(t1.getRelevance());
}
// Templates always first
if (o1 instanceof TemplateProposal) {
return -1;
} else if (o2 instanceof TemplateProposal) {
return 1;
}
// Fallback
if ((o1 instanceof Comparable) && (o2 instanceof Comparable)) {
return ((Comparable) o1).compareTo(o2);
}
return o1.getDisplayString().compareTo(o2.getDisplayString());
}
/**
* @see msi.gama.lang.gaml.ui.editor.IGamlEditor#applyTemplate(org.eclipse.jface.text.templates.Template)
*/
public void applyTemplateAtTheEnd(final Template t) {
try {
final IDocument doc = getDocument();
int offset = doc.getLineOffset(doc.getNumberOfLines() - 1);
doc.replace(offset, 0, "\n\n");
offset += 2;
final int length = 0;
final Position pos = new Position(offset, length);
final XtextTemplateContextType ct = new XtextTemplateContextType();
final DocumentTemplateContext dtc = new DocumentTemplateContext(ct, doc, pos);
final IRegion r = new Region(offset, length);
final TemplateProposal tp = new TemplateProposal(t, dtc, r, null);
tp.apply(getInternalSourceViewer(), (char) 0, 0, offset);
} catch (final BadLocationException e) {
e.printStackTrace();
}
}
private String applyProposal(ICompletionProposal proposal, IXtextDocument document) {
return document.modify(
state -> {
state.setValidationDisabled(false);
if (!(proposal instanceof TemplateProposal)) {
proposal.apply(document);
}
return document.get();
});
}
private String applyProposal(ICompletionProposal proposal, IXtextDocument document) {
return document.modify(
new IUnitOfWork<String, XtextResource>() {
@Override
public String exec(XtextResource state) throws Exception {
state.setValidationDisabled(false);
if (!(proposal instanceof TemplateProposal)) {
proposal.apply(document);
}
return document.get();
}
});
}
/**
* Returns relevance of given proposal.
*
* @param proposal either a {@link ConfigurableCompletionProposal} or a {@link TemplateProposal}
* @return relevance (higher value indicates higher relevance) or <code>null</code>
* @since 2.3
*/
protected Integer getRelevance(ICompletionProposal proposal) {
if (proposal instanceof ConfigurableCompletionProposal) {
return ((ConfigurableCompletionProposal) proposal).getPriority();
} else if (proposal instanceof TemplateProposal) {
return ((TemplateProposal) proposal).getRelevance();
} else if (proposal instanceof QuickAssistCompletionProposal) {
return ((QuickAssistCompletionProposal) proposal).getRelevance();
}
return null;
}
protected TemplateProposal doCreateProposal(Template template,
TemplateContext templateContext, ContentAssistContext context,
Image image, int relevance) {
EObject currentModel = context.getCurrentModel();
if (isEdgeTemplate(template)) {
template = replaceOpVariable(currentModel, template);
}
if (isHtmlLabelTemplate(template)) {
if (currentModel instanceof Attribute) {
ID attributeNameID = ((Attribute) currentModel).getName();
if (attributeNameID != null) {
String attributeName = attributeNameID.toValue();
switch (attributeName) {
case DotAttributes.HEADLABEL__E:
case DotAttributes.LABEL__GCNE:
case DotAttributes.TAILLABEL__E:
case DotAttributes.XLABEL__NE:
return super.doCreateProposal(template, templateContext,
context, image, relevance);
default:
return null;
}
}
} else {
return null;
}
}
return super.doCreateProposal(template, templateContext, context, image,
relevance);
}
/**
* Apply template proposal.
*
* @param templateProposal
* the template proposal, must not be {@code null}
* @param offset
* offset in test file
* @return the document text after application of the template proposal, never {@code null}
*/
private String applyTemplateProposal(final TemplateProposal templateProposal, final int offset) {
// Apply proposal
UiThreadDispatcher.dispatchAndWait(new Runnable() {
@Override
public void run() {
Assert.assertNotNull(EDITOR_HAS_NO_VIEWER, getViewer());
templateProposal.apply(getViewer(), ' ', 0, offset);
}
});
waitForValidation();
return getDocument().get();
}
/**
* Adds the populated check configuration.
*
* @param templateContext
* the template context
* @param context
* the context
* @param acceptor
* the acceptor
*/
@SuppressWarnings("all")
private void addCatalogConfigurations(final TemplateContext templateContext, final ContentAssistContext context, final ITemplateAcceptor acceptor) {
final String templateName = "Add all registered catalogs"; //$NON-NLS-1$
final String templateDescription = "configures all missing catalogs"; //$NON-NLS-1$
final String contextTypeId = templateContext.getContextType().getId();
if (context.getRootModel() instanceof CheckConfiguration) {
final CheckConfiguration conf = (CheckConfiguration) context.getRootModel();
List<IEObjectDescription> allElements = Lists.newArrayList(scopeProvider.getScope(conf, CheckcfgPackage.Literals.CONFIGURED_CATALOG__CATALOG).getAllElements());
StringBuilder builder = new StringBuilder();
for (IEObjectDescription description : allElements) {
if (description.getEObjectOrProxy() instanceof CheckCatalog) {
CheckCatalog catalog = (CheckCatalog) description.getEObjectOrProxy();
if (catalog.eIsProxy()) {
catalog = (CheckCatalog) EcoreUtil.resolve(catalog, conf);
}
if (isCatalogConfigured(conf, catalog)) {
continue;
} else if (allElements.indexOf(description) > 0) {
builder.append(Strings.newLine());
}
final String catalogName = qualifiedNameValueConverter.toString(description.getQualifiedName().toString());
builder.append("catalog ").append(catalogName).append(" {}").append(Strings.newLine()); //$NON-NLS-1$ //$NON-NLS-2$
}
}
if (builder.length() > 0) {
builder.append("${cursor}"); //$NON-NLS-1$
Template t = new Template(templateName, templateDescription, contextTypeId, builder.toString(), true);
TemplateProposal tp = createProposal(t, templateContext, context, images.forConfiguredCatalog(), getRelevance(t));
acceptor.accept(tp);
}
}
}
/**
* Adds template proposals for all checks which may be referenced in current catalog configuration. Only proposals for checks
* which have not yet been configured are provided.
*
* @param templateContext
* the template context
* @param context
* the context
* @param acceptor
* the acceptor
*/
private void addConfiguredCheckTemplates(final TemplateContext templateContext, final ContentAssistContext context, final ITemplateAcceptor acceptor) { // NOPMD
ConfiguredCatalog configuredCatalog = EcoreUtil2.getContainerOfType(context.getCurrentModel(), ConfiguredCatalog.class);
Iterable<String> alreadyConfiguredCheckNames = Iterables.filter(Iterables.transform(configuredCatalog.getCheckConfigurations(), new Function<ConfiguredCheck, String>() {
@Override
public String apply(final ConfiguredCheck from) {
if (from.getCheck() != null) {
return from.getCheck().getName();
}
return null;
}
}), Predicates.notNull());
final CheckCatalog catalog = configuredCatalog.getCatalog();
for (final Check check : catalog.getAllChecks()) {
// create a template on the fly
final String checkName = check.getName();
if (!Iterables.contains(alreadyConfiguredCheckNames, checkName)) {
// check if referenced check has configurable parameters
final StringJoiner paramsJoiner = new StringJoiner(", ", " (", ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
paramsJoiner.setEmptyValue(""); //$NON-NLS-1$
for (final FormalParameter param : check.getFormalParameters()) {
final String paramName = param.getName();
final Object defaultValue = interpreter.evaluate(param.getRight()).getResult();
final String valuePlaceholder = helper.createLiteralValuePattern(paramName, defaultValue);
paramsJoiner.add(paramName + " = " + valuePlaceholder); //$NON-NLS-1$
}
final String severity = (catalog.isFinal() || check.isFinal()) ? "default " : "${default:Enum('SeverityKind')} "; //$NON-NLS-1$ //$NON-NLS-2$
final String description = "Configures the check \"" + check.getLabel() + "\""; //$NON-NLS-1$ //$NON-NLS-2$
final String contextTypeId = "com.avaloq.tools.ddk.checkcfg.CheckCfg.ConfiguredCheck." + checkName; //$NON-NLS-1$
final String pattern = severity + qualifiedNameValueConverter.toString(checkName) + paramsJoiner + "${cursor}"; //$NON-NLS-1$
Template t = new Template(checkName, description, contextTypeId, pattern, true);
TemplateProposal tp = createProposal(t, templateContext, context, images.forConfiguredCheck(check.getDefaultSeverity()), getRelevance(t));
acceptor.accept(tp);
}
}
}
private void createFeatureConfigurationTemplates(TemplateContext templateContext, ContentAssistContext context,
ITemplateAcceptor acceptor) {
GeneratorModel model = (GeneratorModel) EcoreUtil2.getRootContainer(context.getCurrentModel());
Optional<IGeneratorDescriptor> generatorDescriptor = GeneratorExtensions
.getGeneratorDescriptor(model.getGeneratorId());
if (!generatorDescriptor.isPresent()) {
return;
}
Iterable<ILibraryDescriptor> libraryDescriptor = LibraryExtensions
.getLibraryDescriptors(generatorDescriptor.get().getLibraryIDs());
for (ILibraryDescriptor desc : libraryDescriptor) {
ResourceSet set = new ResourceSetImpl();
Resource resource = set.getResource(desc.getURI(), true);
FeatureTypeLibrary lib = (FeatureTypeLibrary) resource.getContents().get(0);
EList<FeatureType> types = lib.getTypes();
for (FeatureType featureType : types) {
Template template = new Template(featureType.getName() + " feature",
"Creates feature " + featureType.getName(), featureType.getName(),
creator.createProposal(featureType,
desc.createFeatureValueProvider(GenmodelActivator.getInstance()
.getInjector(GenmodelActivator.ORG_YAKINDU_SCT_GENERATOR_GENMODEL_SGEN)),
context.getCurrentModel()),
false);
TemplateProposal proposal = createProposal(template, templateContext, context, getImage(template),
getRelevance(template));
acceptor.accept(proposal);
}
}
}
public void applyTemplate(final Template t) {
// TODO Create a specific context type (with GAML specific variables ??)
final XtextTemplateContextType ct = new XtextTemplateContextType();
final IDocument doc = getDocument();
final ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
final int offset = selection.getOffset();
final int length = selection.getLength();
final Position pos = new Position(offset, length);
final DocumentTemplateContext dtc = new DocumentTemplateContext(ct, doc, pos);
final IRegion r = new Region(offset, length);
final TemplateProposal tp = new TemplateProposal(t, dtc, r, null);
tp.apply(getInternalSourceViewer(), (char) 0, 0, offset);
}
private int getRelevance(ICompletionProposal obj) {
if (obj instanceof IJavaCompletionProposal) {
IJavaCompletionProposal jcp= (IJavaCompletionProposal) obj;
return jcp.getRelevance();
} else if (obj instanceof TemplateProposal) {
TemplateProposal tp= (TemplateProposal) obj;
return tp.getRelevance();
}
// catch all
return 0;
}
@Override
public Point getSelection(IDocument document) {
TemplateProposal executed2 = getExecuted();
if (executed2 != null) {
return executed2.getSelection(document);
}
return null;
}
@Override
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
if (edit != null) {
//We have to reparse to make sure that we'll have an accurate AST.
edit.getParser().reparseDocument();
}
TemplateProposal executed2 = getExecuted();
if (executed2 != null) {
executed2.apply(viewer, trigger, stateMask, 0);
forceReparseInBaseEditorAnd();
}
}
/**
* Applies the template if one was specified.
*/
@Override
protected void afterEditorCreated(final IEditorPart openEditor) {
if (!(openEditor instanceof PyEdit)) {
return; //only works for PyEdit...
}
RunInUiThread.async(new Runnable() {
@Override
public void run() {
PyEdit pyEdit = (PyEdit) openEditor;
if (pyEdit.isDisposed()) {
return;
}
TemplateSelectDialog dialog = new TemplateSelectDialog(Display.getCurrent().getActiveShell());
dialog.open();
TemplatePersistenceData selectedTemplate = dialog.getSelectedTemplate();
if (selectedTemplate == null) {
return; //no template selected, nothing to apply!
}
Template template = selectedTemplate.getTemplate();
Region region = new Region(0, 0);
PyDocumentTemplateContext context = PyDocumentTemplateContext.createContext(new PyContextType(),
pyEdit.getPySourceViewer(), region);
TemplateProposal templateProposal = new TemplateProposal(template, context, region, null);
templateProposal.apply(pyEdit.getPySourceViewer(), '\n', 0, 0);
}
});
}
public List<ICompletionProposal> completeAndReturnResults(SourceOpContext sourceOpContext, IDocument document)
throws CommonException {
complete(sourceOpContext, document);
TemplateProposal[] templateProposals = getResults();
return CollectionUtil.<ICompletionProposal>createArrayList(templateProposals);
}
@Override
public void accept(TemplateProposal template) {
delegate.accept(template);
}
@Override
public void accept(TemplateProposal template) {
if (template == null)
throw new NullPointerException("template may not be null");
proposals.add(template);
}
@Override
public void accept(TemplateProposal template) {
if (template != null)
super.accept(template);
}
protected TemplateProposal createProposal(Template template, TemplateContext templateContext,
ContentAssistContext context, Image image, int relevance) {
if (!validate(template, context))
return null;
return doCreateProposal(template, templateContext, context, image, relevance);
}
protected TemplateProposal doCreateProposal(Template template, TemplateContext templateContext,
ContentAssistContext context, Image image, int relevance) {
return new XtextTemplateProposal(template, templateContext, context.getReplaceRegion(), image, relevance);
}
/**
* Returns the array of matching templates.
*
* @return the template proposals
*/
public TemplateProposal[] getResults() {
return fProposals.toArray(new TemplateProposal[fProposals.size()]);
}
void accept(TemplateProposal template);