Search in sources :

Example 11 with IModification

use of org.eclipse.xtext.ui.editor.model.edit.IModification in project xtext-eclipse by eclipse.

the class XbaseQuickfixProvider method fixObsoletCast.

@Fix(IssueCodes.OBSOLETE_CAST)
public void fixObsoletCast(final Issue issue, IssueResolutionAcceptor acceptor) {
    String fixup = "Remove unnecessary cast";
    acceptor.accept(issue, fixup, fixup, null, new IModification() {

        @Override
        public void apply(IModificationContext context) throws Exception {
            final IXtextDocument document = context.getXtextDocument();
            ReplaceRegion replacement = document.readOnly(new IUnitOfWork<ReplaceRegion, XtextResource>() {

                @Override
                public ReplaceRegion exec(XtextResource state) throws Exception {
                    EObject type = state.getEObject(issue.getUriToProblem().fragment());
                    XCastedExpression cast = EcoreUtil2.getContainerOfType(type, XCastedExpression.class);
                    INode castNode = NodeModelUtils.findActualNodeFor(cast);
                    INode targetNode = NodeModelUtils.findActualNodeFor(cast.getTarget());
                    return new ReplaceRegion(castNode.getTotalTextRegion(), targetNode.getText());
                }
            });
            document.replace(replacement.getOffset(), replacement.getLength(), replacement.getText());
        }
    });
}
Also used : XCastedExpression(org.eclipse.xtext.xbase.XCastedExpression) IUnitOfWork(org.eclipse.xtext.util.concurrent.IUnitOfWork) INode(org.eclipse.xtext.nodemodel.INode) ReplaceRegion(org.eclipse.xtext.util.ReplaceRegion) EObject(org.eclipse.emf.ecore.EObject) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) XtextResource(org.eclipse.xtext.resource.XtextResource) WrappedException(org.eclipse.emf.common.util.WrappedException) BadLocationException(org.eclipse.jface.text.BadLocationException) IModification(org.eclipse.xtext.ui.editor.model.edit.IModification) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Fix(org.eclipse.xtext.ui.editor.quickfix.Fix)

Example 12 with IModification

use of org.eclipse.xtext.ui.editor.model.edit.IModification in project xtext-eclipse by eclipse.

the class CreateJavaTypeQuickfixes method newJavaInterfaceQuickfix.

protected void newJavaInterfaceQuickfix(final String typeName, final String explicitPackage, final XtextResource resource, Issue issue, IssueResolutionAcceptor issueResolutionAcceptor) {
    String packageDescription = getPackageDescription(explicitPackage);
    issueResolutionAcceptor.accept(issue, "Create Java interface '" + typeName + "'" + packageDescription, "Opens the new Java interface wizard to create the type '" + typeName + "'" + packageDescription, "java_interface.gif", new IModification() {

        @Override
        public void apply(/* @Nullable */
        IModificationContext context) throws Exception {
            runAsyncInDisplayThread(new Runnable() {

                @Override
                public void run() {
                    NewInterfaceWizardPage classWizardPage = new NewInterfaceWizardPage();
                    NewInterfaceCreationWizard wizard = new NewInterfaceCreationWizard(classWizardPage, true);
                    WizardDialog dialog = createWizardDialog(wizard);
                    configureWizardPage(classWizardPage, resource.getURI(), typeName, explicitPackage);
                    dialog.open();
                }
            });
        }
    });
}
Also used : NewInterfaceWizardPage(org.eclipse.jdt.ui.wizards.NewInterfaceWizardPage) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) NewInterfaceCreationWizard(org.eclipse.jdt.internal.ui.wizards.NewInterfaceCreationWizard) WizardDialog(org.eclipse.jface.wizard.WizardDialog) JavaModelException(org.eclipse.jdt.core.JavaModelException) IModification(org.eclipse.xtext.ui.editor.model.edit.IModification)

Example 13 with IModification

use of org.eclipse.xtext.ui.editor.model.edit.IModification in project xtext-eclipse by eclipse.

the class StatemachineQuickfixProvider method capitalizeName.

@Fix(StatemachineValidator.INVALID_NAME)
public void capitalizeName(final Issue issue, final IssueResolutionAcceptor acceptor) {
    String _firstLower = StringExtensions.toFirstLower(IterableExtensions.<String>head(((Iterable<String>) Conversions.doWrapArray(issue.getData()))));
    String _plus = ("Change to \'" + _firstLower);
    String _plus_1 = (_plus + "\'.");
    String _firstLower_1 = StringExtensions.toFirstLower(IterableExtensions.<String>head(((Iterable<String>) Conversions.doWrapArray(issue.getData()))));
    String _plus_2 = ("Change to \'" + _firstLower_1);
    String _plus_3 = (_plus_2 + "\'.");
    final IModification _function = (IModificationContext it) -> {
        final String firstLetter = it.getXtextDocument().get((issue.getOffset()).intValue(), 1);
        it.getXtextDocument().replace((issue.getOffset()).intValue(), 1, firstLetter.toLowerCase());
    };
    acceptor.accept(issue, _plus_1, _plus_3, "upcase.png", _function);
}
Also used : IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) IModification(org.eclipse.xtext.ui.editor.model.edit.IModification) Fix(org.eclipse.xtext.ui.editor.quickfix.Fix)

Example 14 with IModification

use of org.eclipse.xtext.ui.editor.model.edit.IModification in project xtext-eclipse by eclipse.

the class XtextGrammarQuickfixProvider method fixTerminalRuleName.

@Fix(INVALID_TERMINALRULE_NAME)
public void fixTerminalRuleName(final Issue issue, IssueResolutionAcceptor acceptor) {
    if (issue.getData().length == 1) {
        final String upperCase = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, issue.getData()[0]).toString();
        acceptor.accept(issue, "Change name to " + upperCase, "Change name to " + upperCase, "upcase.png", new IModification() {

            @Override
            public void apply(IModificationContext context) throws Exception {
                final IXtextDocument xtextDocument = context.getXtextDocument();
                xtextDocument.replace(issue.getOffset(), issue.getLength(), upperCase);
                xtextDocument.modify(new IUnitOfWork.Void<XtextResource>() {

                    @Override
                    public void process(XtextResource state) throws Exception {
                        final EObject terminalRule = state.getEObject(issue.getUriToProblem().fragment());
                        Iterable<RuleCall> candidates = Iterables.filter(Iterables.filter(Lists.newArrayList(state.getAllContents()), RuleCall.class), new Predicate<RuleCall>() {

                            @Override
                            public boolean apply(RuleCall ruleCall) {
                                return ruleCall.getRule() == terminalRule;
                            }
                        });
                        for (RuleCall ruleCall : candidates) {
                            List<INode> nodes = NodeModelUtils.findNodesForFeature(ruleCall, XtextPackage.eINSTANCE.getRuleCall_Rule());
                            for (INode node : nodes) {
                                ITextRegion textRegion = node.getTextRegion();
                                xtextDocument.replace(textRegion.getOffset(), textRegion.getLength(), upperCase);
                            }
                        }
                    }
                });
            }
        });
    }
}
Also used : INode(org.eclipse.xtext.nodemodel.INode) XtextResource(org.eclipse.xtext.resource.XtextResource) CoreException(org.eclipse.core.runtime.CoreException) InvocationTargetException(java.lang.reflect.InvocationTargetException) BadLocationException(org.eclipse.jface.text.BadLocationException) IOException(java.io.IOException) RuleCall(org.eclipse.xtext.RuleCall) ITextRegion(org.eclipse.xtext.util.ITextRegion) EObject(org.eclipse.emf.ecore.EObject) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) IModification(org.eclipse.xtext.ui.editor.model.edit.IModification) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Fix(org.eclipse.xtext.ui.editor.quickfix.Fix)

Example 15 with IModification

use of org.eclipse.xtext.ui.editor.model.edit.IModification in project xtext-eclipse by eclipse.

the class XtextGrammarQuickfixProvider method fixExternalImportedPackage.

@Fix(INVALID_PACKAGE_REFERENCE_EXTERNAL)
public void fixExternalImportedPackage(final Issue issue, IssueResolutionAcceptor acceptor) {
    if (issue.getData().length == 1)
        acceptor.accept(issue, "Update the imported package '" + issue.getData()[0] + "'", "Fix the bogus package import\n" + "import '" + issue.getData()[0] + "'", NULL_QUICKFIX_IMAGE, new IModification() {

            @Override
            public void apply(IModificationContext context) throws BadLocationException {
                String replaceString = valueConverterService.toString(issue.getData()[0], "STRING");
                IXtextDocument document = context.getXtextDocument();
                final List<String> importedPackages = document.priorityReadOnly(new IUnitOfWork<List<String>, XtextResource>() {

                    @Override
                    public List<String> exec(XtextResource state) throws Exception {
                        IResourceDescriptions descriptions = resourceDescriptionsProvider.getResourceDescriptions(state);
                        ResourceSet resourceSet = state.getResourceSet();
                        final Map<URI, URI> uriMap = Maps.newHashMap();
                        EPackage ePackage = loadPackageFromIndex(descriptions, resourceSet, uriMap, issue.getData()[0]);
                        if (ePackage != null) {
                            final Map<String, EPackage> packagePerNsURI = Maps.newHashMap();
                            packagePerNsURI.put(ePackage.getNsURI(), ePackage);
                            final Set<URI> updatedReferences = fixReferencesInPackages(ePackage, packagePerNsURI, uriMap, descriptions, resourceSet);
                            if (updatedReferences.isEmpty())
                                return null;
                            Iterator<EPackage> iterator = packagePerNsURI.values().iterator();
                            while (iterator.hasNext()) {
                                EPackage pack = iterator.next();
                                Resource resource = pack.eResource();
                                if (!resource.getURI().isPlatformResource()) {
                                    iterator.remove();
                                }
                            }
                            final List<String> result = Lists.newArrayList();
                            new WorkspaceModifyOperation() {

                                /* workspace lock */
                                @Override
                                protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException {
                                    try {
                                        for (EPackage pack : packagePerNsURI.values()) {
                                            Resource resource = pack.eResource();
                                            resource.save(Collections.singletonMap(XMLResource.OPTION_URI_HANDLER, new URIHandlerImpl.PlatformSchemeAware() {

                                                @Override
                                                public URI deresolve(URI uri) {
                                                    // replace archive uris with platform:/plugin
                                                    if (!uri.isArchive() || !updatedReferences.contains(uri)) {
                                                        return super.deresolve(uri);
                                                    }
                                                    URI withoutFragment = uri.trimFragment();
                                                    if (uriMap.containsKey(withoutFragment)) {
                                                        withoutFragment = uriMap.get(withoutFragment);
                                                    }
                                                    return super.deresolve(withoutFragment.appendFragment(uri.fragment()));
                                                }
                                            }));
                                            result.add(resource.getURI().toString());
                                        }
                                    } catch (IOException ioe) {
                                        throw new InvocationTargetException(ioe);
                                    }
                                }
                            }.run(new NullProgressMonitor());
                            for (int i = resourceSet.getResources().size() - 1; i >= 0; i--) {
                                Resource resource = resourceSet.getResources().get(i);
                                if (!resource.getContents().isEmpty() && resource.getContents().get(0) instanceof GenModel) {
                                    resourceSet.getResources().remove(i);
                                }
                            }
                            return result;
                        }
                        return null;
                    }

                    private Set<URI> fixReferencesInPackages(EPackage ePackage, Map<String, EPackage> packagePerNsURI, Map<URI, URI> uriMap, IResourceDescriptions descriptions, ResourceSet resourceSet) {
                        Set<URI> result = Sets.newHashSet();
                        Map<EObject, Collection<Setting>> allReferences = EcoreUtil.CrossReferencer.find(Collections.singletonList(ePackage));
                        for (final Setting setting : Iterables.concat(allReferences.values())) {
                            if (setting.getEStructuralFeature().isChangeable()) {
                                final Object referenced = setting.get(true);
                                List<Object> references = null;
                                if (referenced instanceof EObject) {
                                    references = new AbstractList<Object>() {

                                        @Override
                                        public Object set(int index, Object element) {
                                            setting.set(element);
                                            return referenced;
                                        }

                                        @Override
                                        public Object get(int index) {
                                            return referenced;
                                        }

                                        @Override
                                        public int size() {
                                            return 1;
                                        }
                                    };
                                } else {
                                    @SuppressWarnings("unchecked") List<Object> casted = (List<Object>) referenced;
                                    references = casted;
                                }
                                for (int i = 0; i < references.size(); i++) {
                                    if (references.get(i) instanceof EObject) {
                                        EObject referencedEObject = (EObject) references.get(i);
                                        EPackage transitive = EcoreUtil2.getContainerOfType(referencedEObject, EPackage.class);
                                        if (isRegisteredPackage(transitive)) {
                                            if (referencedEObject instanceof EDataType)
                                                continue;
                                            if (referencedEObject == EcorePackage.Literals.EOBJECT)
                                                continue;
                                            EPackage fromWorkspace = packagePerNsURI.get(transitive.getNsURI());
                                            if (fromWorkspace == null && !packagePerNsURI.containsKey(transitive.getNsURI())) {
                                                fromWorkspace = loadPackageFromIndex(descriptions, resourceSet, uriMap, transitive.getNsURI());
                                                packagePerNsURI.put(transitive.getNsURI(), fromWorkspace);
                                            }
                                            if (fromWorkspace != null) {
                                                String fragment = transitive.eResource().getURIFragment(referencedEObject);
                                                EObject replacement = fromWorkspace.eResource().getEObject(fragment);
                                                if (replacement != null) {
                                                    result.add(EcoreUtil.getURI(replacement));
                                                    references.set(i, replacement);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        return result;
                    }

                    private boolean isRegisteredPackage(EPackage ePackage) {
                        return ePackage != null && (ePackage.eResource() == null || ePackage.getNsURI().equals(ePackage.eResource().getURI().toString()));
                    }

                    private EPackage loadPackageFromIndex(IResourceDescriptions descriptions, ResourceSet resourceSet, Map<URI, URI> uriMap, String nsURI) {
                        Iterable<IEObjectDescription> fixUs = descriptions.getExportedObjects(EcorePackage.Literals.EPACKAGE, QualifiedName.create(nsURI), false);
                        for (IEObjectDescription description : fixUs) {
                            if (description.getEObjectURI().isPlatformResource()) {
                                EObject result = resourceSet.getEObject(description.getEObjectURI(), true);
                                if (result instanceof EPackage) {
                                    return (EPackage) result;
                                }
                            }
                        }
                        URI genModelURI = EcorePlugin.getEPackageNsURIToGenModelLocationMap(false).get(nsURI);
                        if (genModelURI != null) {
                            Resource genmodelResource = resourceSet.getResource(genModelURI, true);
                            GenModel genModel = (GenModel) genmodelResource.getContents().get(0);
                            for (GenPackage genPackage : genModel.getGenPackages()) {
                                Object object = genPackage.eGet(GenModelPackage.Literals.GEN_PACKAGE__ECORE_PACKAGE, false);
                                if (object instanceof EObject) {
                                    EObject proxy = (EObject) object;
                                    URI proxyURI = EcoreUtil.getURI(proxy);
                                    URI resolvedProxyURI = proxyURI.resolve(genModelURI);
                                    if (nsURI.equals(genPackage.getEcorePackage().getNsURI())) {
                                        EPackage result = genPackage.getEcorePackage();
                                        uriMap.put(result.eResource().getURI(), resolvedProxyURI.trimFragment());
                                        return result;
                                    }
                                }
                            }
                        }
                        return null;
                    }
                });
                String delimiter = document.get(issue.getOffset(), 1);
                if (!replaceString.startsWith(delimiter)) {
                    replaceString = delimiter + replaceString.substring(1, replaceString.length() - 1) + delimiter;
                }
                document.replace(issue.getOffset(), issue.getLength(), replaceString);
                if (importedPackages != null && !importedPackages.isEmpty()) {
                    final Shell shell = workbench.getActiveWorkbenchWindow().getShell();
                    shell.getDisplay().asyncExec(new Runnable() {

                        @Override
                        public void run() {
                            String title = "Please update the Ecore2XtextDslProjectContributor that generates the language.";
                            String message = "Please make sure that the Ecore2XtextDslProjectContributor that generates the language is up-to date.\n" + "Especially important is the registration of the referenced packages.\n" + "Please refer to the reference documentation for details.";
                            MessageDialog dialog = new MessageDialog(shell, title, null, message, MessageDialog.INFORMATION, new String[] { "Open Documentation", "Close" }, 1);
                            if (dialog.open() == 0) {
                                try {
                                    workbench.getBrowserSupport().getExternalBrowser().openURL(new URL(GRAMMAR_LANG_DOC));
                                } catch (Exception e) {
                                // ignore
                                }
                            }
                        }
                    });
                }
            }
        });
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) Set(java.util.Set) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) WorkspaceModifyOperation(org.eclipse.ui.actions.WorkspaceModifyOperation) EDataType(org.eclipse.emf.ecore.EDataType) XtextResource(org.eclipse.xtext.resource.XtextResource) GenPackage(org.eclipse.emf.codegen.ecore.genmodel.GenPackage) URI(org.eclipse.emf.common.util.URI) URL(java.net.URL) EPackage(org.eclipse.emf.ecore.EPackage) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription) Shell(org.eclipse.swt.widgets.Shell) EObject(org.eclipse.emf.ecore.EObject) Iterator(java.util.Iterator) AbstractList(java.util.AbstractList) List(java.util.List) MessageDialog(org.eclipse.jface.dialogs.MessageDialog) IModification(org.eclipse.xtext.ui.editor.model.edit.IModification) AbstractList(java.util.AbstractList) Setting(org.eclipse.emf.ecore.EStructuralFeature.Setting) Resource(org.eclipse.emf.ecore.resource.Resource) XMLResource(org.eclipse.emf.ecore.xmi.XMLResource) XtextResource(org.eclipse.xtext.resource.XtextResource) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) IOException(java.io.IOException) CoreException(org.eclipse.core.runtime.CoreException) InvocationTargetException(java.lang.reflect.InvocationTargetException) BadLocationException(org.eclipse.jface.text.BadLocationException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IResourceDescriptions(org.eclipse.xtext.resource.IResourceDescriptions) GenModel(org.eclipse.emf.codegen.ecore.genmodel.GenModel) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) EObject(org.eclipse.emf.ecore.EObject) Map(java.util.Map) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Fix(org.eclipse.xtext.ui.editor.quickfix.Fix)

Aggregations

IModification (org.eclipse.xtext.ui.editor.model.edit.IModification)25 IModificationContext (org.eclipse.xtext.ui.editor.model.edit.IModificationContext)23 Fix (org.eclipse.xtext.ui.editor.quickfix.Fix)16 BadLocationException (org.eclipse.jface.text.BadLocationException)12 IXtextDocument (org.eclipse.xtext.ui.editor.model.IXtextDocument)11 XtextResource (org.eclipse.xtext.resource.XtextResource)7 CoreException (org.eclipse.core.runtime.CoreException)5 EObject (org.eclipse.emf.ecore.EObject)5 WizardDialog (org.eclipse.jface.wizard.WizardDialog)5 IUnitOfWork (org.eclipse.xtext.util.concurrent.IUnitOfWork)5 IOException (java.io.IOException)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 List (java.util.List)3 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)3 WrappedException (org.eclipse.emf.common.util.WrappedException)3 INode (org.eclipse.xtext.nodemodel.INode)3 Rule (com.avaloq.tools.ddk.xtext.format.format.Rule)2 Map (java.util.Map)2 Set (java.util.Set)2 IFile (org.eclipse.core.resources.IFile)2