org.eclipse.xtext.util.concurrent.IUnitOfWork Java Examples

The following examples show how to use org.eclipse.xtext.util.concurrent.IUnitOfWork. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RailroadSynchronizer.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private void updateView(IWorkbenchPart part) {
	if (part instanceof XtextEditor) {
		XtextEditor xtextEditor = (XtextEditor) part;
		IXtextDocument xtextDocument = xtextEditor.getDocument();
		if (xtextDocument != lastActiveDocument) {
			selectionLinker.setXtextEditor(xtextEditor);
			final IFigure contents = xtextDocument.tryReadOnly(new IUnitOfWork<IFigure, XtextResource>() {
				@Override
				public IFigure exec(XtextResource resource) throws Exception {
					return createFigure(resource);
				}
			});
			if (contents != null) {
				view.setContents(contents);
				if (lastActiveDocument != null) {
					lastActiveDocument.removeModelListener(this);
				}
				lastActiveDocument = xtextDocument;
				lastActiveDocument.addModelListener(this);
			}
		}
	}
}
 
Example #2
Source File: N4JSEditorResourceAccess.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/***
 * This method modifies the super method to handle NullPointerException when state is null.
 */
@Override
public <R> R readOnly(final URI targetURI, final IUnitOfWork<R, ResourceSet> work) {
	IXtextDocument document = openDocumentTracker.getOpenDocument(targetURI.trimFragment());
	if (document != null) {
		return document.readOnly(new IUnitOfWork<R, XtextResource>() {
			@Override
			public R exec(XtextResource state) throws Exception {
				// For some reason, sometimes state can be null at this point,
				// The resource set must be retrieved by other means in delegate.readOnly
				if (state == null) {
					return delegate.readOnly(targetURI, work);
				}
				ResourceSet localContext = state.getResourceSet();
				if (localContext != null)
					return work.exec(localContext);
				return null;
			}
		});
	} else

	{
		return delegate.readOnly(targetURI, work);
	}
}
 
Example #3
Source File: DocumentRewriterTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected String rewrite(final CharSequence model, final Procedure2<? super DocumentRewriter, ? super XtextResource> test) {
  try {
    String _xblockexpression = null;
    {
      final XtextDocument document = this.createDocument(model.toString());
      final IUnitOfWork<TextEdit, XtextResource> _function = (XtextResource it) -> {
        TextEdit _xblockexpression_1 = null;
        {
          final DocumentRewriter rewriter = this.factory.create(document, it);
          test.apply(rewriter, it);
          _xblockexpression_1 = this._replaceConverter.convertToTextEdit(rewriter.getChanges());
        }
        return _xblockexpression_1;
      };
      document.<TextEdit>readOnly(_function).apply(document);
      _xblockexpression = document.get();
    }
    return _xblockexpression;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #4
Source File: EditorResourceAccess.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public <R> R readOnly(final URI targetURI, final IUnitOfWork<R, ResourceSet> work) {
	IXtextDocument document = openDocumentTracker.getOpenDocument(targetURI.trimFragment());
	if (document != null) {
		return document.tryReadOnly(new IUnitOfWork<R, XtextResource>() {
			@Override
			public R exec(XtextResource state) throws Exception {
				ResourceSet localContext = state.getResourceSet();
				if (localContext != null)
					return work.exec(localContext);
				return null;
			}
		}, () -> { return null; });
	} else {
		return delegate.readOnly(targetURI, work);
	}
}
 
Example #5
Source File: AllContentsPerformanceTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private void doTestUoWImpl(EObject object, IUnitOfWork<Boolean, EObject> uow) throws Exception {
	if (object == null)
		return;
	if (!uow.exec(object).booleanValue()) {
		EClass clazz = object.eClass();
		for(EReference reference: clazz.getEAllContainments()) {
			// object.eIsSet(..) decreased performance - TODO: investigate the reason
			// TODO: handle feature maps 
			// TODO: What's FeatureListIterator#useIsSet about?
			if (reference.isMany()) {
				@SuppressWarnings("unchecked")
				List<EObject> values = (List<EObject>) object.eGet(reference);
				for(int i = 0; i<values.size(); i++) {
					doTestUoWImpl(values.get(i), uow);
				}
			} else {
				doTestUoWImpl((EObject) object.eGet(reference), uow);
			}
		}
	}
}
 
Example #6
Source File: DotAutoEditStrategy.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private String computeEndTag(IDocument document, DocumentCommand command) {

		IUnitOfWork<String, XtextResource> endTagComputationWork = new IUnitOfWork<String, XtextResource>() {

			@Override
			public String exec(XtextResource state) throws Exception {
				HtmlTag openTag = findOpenTag(state, command);
				if (openTag != null) {
					return "</" + openTag.getName() + ">"; //$NON-NLS-1$ //$NON-NLS-2$
				} else {
					return ""; //$NON-NLS-1$
				}
			}

		};

		return ((XtextDocument) document).readOnly(endTagComputationWork);
	}
 
Example #7
Source File: ResourceAccess.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public <R> R readOnly(URI targetURI, IUnitOfWork<R, ResourceSet> work) {
	URI resourceURI = targetURI.trimFragment();
	Iterable<Pair<IStorage, IProject>> storages = storage2UriMapper.getStorages(resourceURI);
	Iterator<Pair<IStorage, IProject>> iterator = storages.iterator();
	ResourceSet resourceSet = fallBackResourceSet; 
	while(iterator.hasNext()) {
		Pair<IStorage, IProject> pair = iterator.next();
		IProject project = pair.getSecond();
		if (project != null) {
			resourceSet = getResourceSet(project);
			break;
		}
	}
	if(resourceSet != null) {
		resourceSet.getResource(resourceURI, true);
		try {
			return work.exec(resourceSet);
		} catch (Exception e) {
			throw new WrappedException(e);
		}
	}
	return null;
}
 
Example #8
Source File: ReplacingAppendableTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected XtextDocument insertListField(final String model, final String fieldName)
		throws Exception {
	final int cursorPosition = model.indexOf('|');
	String actualModel = model.replace("|", " ");
	final XtendFile file = testHelper.xtendFile("Foo", actualModel);
	final XtextDocument document = documentProvider.get();
	document.set(actualModel);
	XtextResource xtextResource = (XtextResource) file.eResource();
	document.setInput(xtextResource);
	final EObject context = eObjectAtOffsetHelper.resolveElementAt(xtextResource, cursorPosition);
	document.modify(new IUnitOfWork.Void<XtextResource>() {
		@Override
		public void process(XtextResource state) throws Exception {
			ReplacingAppendable a = appendableFactory.create(document, state, cursorPosition, 1);
			ITypeReferenceOwner owner = new StandardTypeReferenceOwner(services, context);
			LightweightTypeReference typeRef = owner.toLightweightTypeReference(services.getTypeReferences().getTypeForName(List.class, context, typesFactory.createJvmWildcardTypeReference()));
			a.append(typeRef);
			a.append(" ").append(fieldName);
			a.commitChanges();
		}
	});
	return document;
}
 
Example #9
Source File: ProblemHoverTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
	super.setUp();
	modelAsText = "stuff mystuff\nstuff yourstuff refs _mystuff stuff hisstuff refs _yourstuff// Comment";
	IFile file = IResourcesSetupUtil.createFile("test/test.testlanguage", modelAsText);
	editor = openEditor(file);
	document = editor.getDocument();
	hover = TestsActivator.getInstance().getInjector(getEditorId()).getInstance(ProblemAnnotationHover.class);
	hover.setSourceViewer(editor.getInternalSourceViewer());
	List<Issue> issues = document.readOnly(new IUnitOfWork<List<Issue>, XtextResource>() {
		@Override
		public List<Issue> exec(XtextResource state) throws Exception {
			return state.getResourceServiceProvider().getResourceValidator().validate(state, CheckMode.ALL, null);
		}	
	});
	MarkerCreator markerCreator =  TestsActivator.getInstance().getInjector(getEditorId()).getInstance(MarkerCreator.class);
	for (Issue issue : issues) {
		markerCreator.createMarker(issue, file, MarkerTypes.forCheckType(issue.getType()));
	}
}
 
Example #10
Source File: LinkingErrorTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testSemanticIssueResolution() throws Exception {
	IFile dslFile = dslFile(MODEL_WITH_LINKING_ERROR);
	XtextEditor xtextEditor = openEditor(dslFile);
	URI uriToProblem = xtextEditor.getDocument().readOnly(new IUnitOfWork<URI, XtextResource>() {
		@Override
		public URI exec(XtextResource state) throws Exception {
			Main main = (Main) state.getContents().get(0);
			Element element = main.getElements().get(1);
			return EcoreUtil.getURI(element);
		}
	});
	Issue.IssueImpl issue = new Issue.IssueImpl();
	issue.setUriToProblem(uriToProblem);
	issue.setCode(QuickfixCrossrefTestLanguageQuickfixProvider.SEMANTIC_FIX_ID);

	List<IssueResolution> resolutions = issueResolutionProvider.getResolutions(issue);
	assertEquals(1, resolutions.size());
	IssueResolution issueResolution = resolutions.get(0);
	issueResolution.apply();
	xtextEditor.doSave(null);
	List<Issue> issues = getAllValidationIssues(xtextEditor.getDocument());
	assertTrue(issues.isEmpty());
}
 
Example #11
Source File: GamlResource.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
/**
 * In the case of synthetic resources, pass the URI they depend on
 *
 * @throws IOException
 */
public void loadSynthetic(final InputStream is, final IExecutionContext additionalLinkingContext)
		throws IOException {
	final OnChangeEvictingCache r = getCache();
	r.getOrCreate(this).set("linking", additionalLinkingContext);
	getCache().execWithoutCacheClear(this, new IUnitOfWork.Void<GamlResource>() {

		@Override
		public void process(final GamlResource state) throws Exception {
			state.load(is, null);
			EcoreUtil.resolveAll(GamlResource.this);
		}
	});
	r.getOrCreate(this).set("linking", null);

}
 
Example #12
Source File: CodetemplatesProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void complete_Literal(EObject model, RuleCall ruleCall, final ContentAssistContext context,
		final ICompletionProposalAcceptor acceptor) {
	if ((mode & NESTED) != 0) {
		final TemplateData data = new TemplateData(model);
		if (data.doCreateProposals()) {
			final EvaluatedTemplate evaluatedTemplate = new EvaluatedTemplate(data.template);
			temporaryResourceProvider.useTemporaryResource(data.template.eResource().getResourceSet(), 
					data.language, data.rule, evaluatedTemplate.getMappedString(), new IUnitOfWork.Void<XtextResource>() {
				@Override
				public void process(XtextResource resource) throws Exception {
					IPartialEditingContentAssistContextFactory delegateFactory = languageRegistry.getPartialContentAssistContextFactory(data.language);
					delegateFactory.initializeFor(data.rule);
					String mappedInput = evaluatedTemplate.getMappedString();
					int mappedOffset = Math.min(mappedInput.length(), evaluatedTemplate.getMappedOffset(context.getOffset()));
					DummyDocument document = new DummyDocument(mappedInput);
					DummyTextViewer dummyViewer = new DummyTextViewer(TextSelection.emptySelection(), document);
					ContentAssistContext[] contexts = delegateFactory.create(dummyViewer, mappedOffset, resource);
					ICompletionProposalAcceptor mappingAcceptor = new ProjectionAwareProposalAcceptor(acceptor, evaluatedTemplate);
					createNestedProposals(contexts, context.getViewer(), mappingAcceptor, data);
				}
			});
		}
	}
}
 
Example #13
Source File: OrganizeImportsHandler.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public void doOrganizeImports(final IXtextDocument document) {
	List<ReplaceRegion> result = document.priorityReadOnly(new IUnitOfWork<List<ReplaceRegion>, XtextResource>() {
		@Override
		public List<ReplaceRegion> exec(XtextResource state) throws Exception {
			return importOrganizer.getOrganizedImportChanges(state);
		}
	});
	if (result == null || result.isEmpty())
		return;
	try {
		DocumentRewriteSession session = null;
		if(document instanceof IDocumentExtension4) {
			session = ((IDocumentExtension4)document).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
		}
		replaceConverter.convertToTextEdit(result).apply(document);
		if(session != null) {
			((IDocumentExtension4)document).stopRewriteSession(session);
		}
	} catch (BadLocationException e) {
		LOG.error(Messages.OrganizeImportsHandler_organizeImportsErrorMessage, e);
	}
}
 
Example #14
Source File: ReferenceFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void findReferences(final TargetURIs targetURIs, IResourceDescription resourceDescription,
		IResourceAccess resourceAccess, final Acceptor acceptor, final IProgressMonitor monitor) {
	final URI resourceURI = resourceDescription.getURI();
	if (resourceAccess != null && targetURIs.containsResource(resourceURI)) {
		IUnitOfWork.Void<ResourceSet> finder = new IUnitOfWork.Void<ResourceSet>() {
			@Override
			public void process(final ResourceSet state) throws Exception {
				Resource resource = state.getResource(resourceURI, true);
				findReferences(targetURIs, resource, acceptor, monitor);
			}
		};
		resourceAccess.readOnly(resourceURI, finder);
	} else {
		findReferencesInDescription(targetURIs, resourceDescription, resourceAccess, acceptor, monitor);
	}
}
 
Example #15
Source File: CachingBatchTypeResolver.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
/* @NonNull */
protected IResolvedTypes doResolveTypes(final /* @Nullable */ EObject object, final /* @Nullable */ CancelIndicator monitor) {
	// TODO: remove when we switch to an Xtend scope provider without artificial feature calls  
	EObject nonArtificialObject = object;
	if(object.eResource() == null && object instanceof XAbstractFeatureCall) {
		nonArtificialObject = ((XAbstractFeatureCall) object).getFeature();
	}
	// TODO
	final Resource resource = nonArtificialObject.eResource();
	final LazyResolvedTypes result = cache.get(CachingBatchTypeResolver.class, resource, new Provider<LazyResolvedTypes>() {
		@Override
		public LazyResolvedTypes get() {
			final IReentrantTypeResolver resolver = delegate.getTypeResolver(object);
			return new LazyResolvedTypes(resolver, resource);
		}
	});
	cache.execWithoutCacheClear(resource, new IUnitOfWork.Void<Resource>() {
		@Override
		public void process(Resource state) throws Exception {
			// trigger the actual resolution after the thing was cached
			result.resolveTypes(monitor == null ? CancelIndicator.NullImpl : monitor); 
		}
	});
	return result;
}
 
Example #16
Source File: AbstractOutlineNode.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public <T> T readOnly(final IUnitOfWork<T, EObject> work) {
	if (getEObjectURI() == null) return null;

	try {
		return getDocument().tryReadOnly(new IUnitOfWork<T, XtextResource>() {
			@Override
			public T exec(XtextResource state) throws Exception {
				EObject eObject;
				if (state.getResourceSet() != null)
					eObject = state.getResourceSet().getEObject(getEObjectURI(), true);
				else
					eObject = state.getEObject(getEObjectURI().fragment());
				if (eObject == null) return null;

				return work.exec(eObject);
			}
		});
	} catch (RuntimeException e) {
		LOG.warn(e.getMessage(), e);
		return null;
	}
}
 
Example #17
Source File: TemporaryResourceProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public <Result> Result useTemporaryResource(
		ResourceSet resourceSet, Grammar language, 
		AbstractRule rootRule, String content, IUnitOfWork<Result, XtextResource> runnable) {
	XtextResource resource = languageRegistry.createTemporaryResourceIn(language, resourceSet);
	if (rootRule != null)
		PartialParser.assignRootRule(resource, (ParserRule) rootRule);
	try {
		resource.load(new StringInputStream(content, resource.getEncoding()), null);
		return runnable.exec(resource);
	} catch(Exception e) {
		throw new RuntimeException(e);
	} finally {
		if (resource != null) {
			if (resource.isLoaded())
				resource.unload();
			resourceSet.getResources().remove(resource);
		}
	}
}
 
Example #18
Source File: SelectionUtil.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public static IFile getSelectedFile(ISelection selection) {
	if (selection instanceof IStructuredSelection) {
		IStructuredSelection ssel = (IStructuredSelection) selection;
		Object firstElement = ssel.getFirstElement();
		IFile file = Adapters.adapt(firstElement, IFile.class);
		if (file != null) {
			return file;
		}
		else if (firstElement instanceof IOutlineNode) {
			IOutlineNode outlineNode = (IOutlineNode) firstElement;
			return outlineNode.tryReadOnly(new IUnitOfWork<IFile, EObject>() {
				@Override
				public IFile exec(EObject state) throws Exception {
					Resource resource = state.eResource();
					URI uri = resource.getURI();
					IPath path = new Path(uri.toPlatformString(true));
					return ResourcesPlugin.getWorkspace().getRoot().getFile(path);
				}});
		}
	}
	return null;
}
 
Example #19
Source File: XtextGrammarQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Fix(EMPTY_KEYWORD)
public void replaceEmptyKeywordWithRuleName(final Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.accept(issue, "Replace empty keyword with rule name", "Replace empty keyword with rule name", NULL_QUICKFIX_IMAGE,
			new IModification() {
				@Override
				public void apply(IModificationContext context) throws Exception {
					final IXtextDocument document = context.getXtextDocument();
					final String containingRuleName = document.tryPriorityReadOnly(new IUnitOfWork<String, XtextResource>() {
						@Override
						public String exec(XtextResource state) throws Exception {
							return Optional.ofNullable(issue.getUriToProblem().fragment()).map(state::getEObject)
									.map(GrammarUtil::containingRule).map(AbstractRule::getName).map(Strings::toFirstLower)
									.orElse(null);
						}
					});
					if (containingRuleName != null) {
						final String quote = String.valueOf(document.getChar(issue.getOffset()));
						document.replace(issue.getOffset(), issue.getLength(), quote + containingRuleName + quote);
					}
				}
			});
}
 
Example #20
Source File: EditorCopyQualifiedNameHandler.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected String getQualifiedName(ExecutionEvent event) {
	XtextEditor activeXtextEditor = EditorUtils.getActiveXtextEditor(event);
	if (activeXtextEditor == null) {
		return null;
	}
	final ITextSelection selection = getTextSelection(activeXtextEditor);
	return activeXtextEditor.getDocument().priorityReadOnly(new IUnitOfWork<String, XtextResource>() {

		@Override
		public String exec(XtextResource xTextResource) throws Exception {
			EObject context = getContext(selection, xTextResource);
			EObject selectedElement = getSelectedName(selection, xTextResource);
			return getQualifiedName(selectedElement, context);
		}

	});
}
 
Example #21
Source File: RefactoringTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected IRenameSupport createRenameSupportForElement() {
	if(!languageServices.hasRefactoring())
		return null;
	IRenameElementContext renameElementContext = editor.getDocument().tryReadOnly(
			new IUnitOfWork<IRenameElementContext, XtextResource>() {
				@Override
				public IRenameElementContext exec(XtextResource state) throws Exception {
					Model model = (Model) state.getContents().get(0);
					ReferenceHolder referenceHolder = model.getReferenceHolder().get(0);
					return languageServices.renameContextFactory.createRenameElementContext(referenceHolder,
							editor, null, state);
				}
			});
	if (renameElementContext == null) return null;

	IRenameSupport renameSupport = languageServices.renameSupportFactory.create(renameElementContext,
			"newTestName");
	return renameSupport;
}
 
Example #22
Source File: OutlineSynchronisationTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test
@Ignore("Fails on CI Server with - TimeoutException: Timeout in Syncer")
public void testRenameFile() throws Exception {
	IPath newPath = file.getFullPath().removeLastSegments(1).append("_new")
			.addFileExtension(file.getFileExtension());
	outlinePage.resetSyncer();
	file.move(newPath, true, null);
	outlinePage.waitForUpdate(ERROR_TIMEOUT);  // <= fails here
	assertFirstNodeName("one");

	outlinePage.resetSyncer();
	editor.getDocument().modify(new IUnitOfWork.Void<XtextResource>() {
		@Override
		public void process(XtextResource state) throws Exception {
			((Model) state.getContents().get(0)).getElements().get(0).setName("new_one");
		}
	});
	outlinePage.waitForUpdate(ERROR_TIMEOUT);
	assertFirstNodeName("new_one");
}
 
Example #23
Source File: EObjectContentProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Retrieve the object's values for the given EAttributes.
 * 
 * @param attributes
 *          the EAttributes
 * @return List<Pair<EAttribute, Object>> the attribute+values - possibly containing null entries
 */
private List<AttributeValuePair> valuesForAttributes(final EList<EAttribute> attributes) {
  final URI elementUri = xtextElementSelectionListener.getSelectedElementUri();
  XtextEditor editor = xtextElementSelectionListener.getEditor();
  if (editor != null && elementUri != null) {
    return editor.getDocument().readOnly(new IUnitOfWork<List<AttributeValuePair>, XtextResource>() {
      @SuppressWarnings("PMD.SignatureDeclareThrowsException")
      public List<AttributeValuePair> exec(final XtextResource state) throws Exception {
        final EObject eObject = state.getEObject(elementUri.fragment());
        List<AttributeValuePair> pairs = Lists.transform(attributes, new Function<EAttribute, AttributeValuePair>() {
          public AttributeValuePair apply(final EAttribute from) {
            return new AttributeValuePair(from, eObject.eGet(from));
          }
        });
        return pairs;
      }
    });
  }
  return newArrayList();
}
 
Example #24
Source File: RefactoringTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected IRenameSupport createRenameSupportForJvmReference() {
	if(!languageServices.hasRefactoring())
		return null;
	IRenameElementContext renameElementContext = editor.getDocument().tryReadOnly(
			new IUnitOfWork<IRenameElementContext, XtextResource>() {
				@Override
				public IRenameElementContext exec(XtextResource state) throws Exception {
					Model model = (Model) state.getContents().get(0);
					JvmType defaultReference = model.getReferenceHolder().get(0).getDefaultReference();
					return languageServices.renameContextFactory.createRenameElementContext(defaultReference,
							editor, null, state);
				}
			});
	if (renameElementContext == null) return null;

	IRenameSupport renameSupport = languageServices.renameSupportFactory.create(renameElementContext,
			"NewJavaClass");
	return renameSupport;
}
 
Example #25
Source File: XtextGrammarQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(SPACES_IN_KEYWORD)
public void fixKeywordNoSpaces(final Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.accept(issue, "Fix keyword with spaces", "Fix keyword with spaces", NULL_QUICKFIX_IMAGE, new IModification() {
		@Override
		public void apply(IModificationContext context) throws Exception {
			final int offset = issue.getOffset();
			final int length = issue.getLength();
			final IXtextDocument document = context.getXtextDocument();
			final String quote = String.valueOf(document.getChar(offset));
			final String identifiers = document.get(offset, length).replaceAll("'|\"", "").trim();
			if (!Strings.isEmpty(identifiers)) {
				document.replace(offset, length, quote + Joiner.on(quote + " " + quote).join(identifiers.split("\\s+")) + quote);
			} else {
				final String containingRuleName = document.tryPriorityReadOnly(new IUnitOfWork<String, XtextResource>() {
					@Override
					public String exec(XtextResource state) throws Exception {
						return Optional.ofNullable(issue.getUriToProblem().fragment()).map(state::getEObject)
								.map(GrammarUtil::containingRule).map(AbstractRule::getName).map(Strings::toFirstLower)
								.orElse(null);
					}
				});
				if (containingRuleName != null) {
					document.replace(offset, length, quote + containingRuleName + quote);
				}
			}
		}
	});
}
 
Example #26
Source File: DirtyStateEditorSupportTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <T> T readOnly(IUnitOfWork<T, XtextResource> work) {
	try {
		return work.exec(resource);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #27
Source File: DefaultOutlineTreeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.2
 */
protected boolean isLocalElement(IOutlineNode node, final EObject element) {
	if (node instanceof AbstractOutlineNode) {
		return ((AbstractOutlineNode) node).getDocument().tryReadOnly(new IUnitOfWork<Boolean, XtextResource>() {
			@Override
			public Boolean exec(XtextResource state) throws Exception {
				return element.eResource() == state;
			}
		}, () -> false);
	}
	return true;
}
 
Example #28
Source File: LinkedEditingRefactoringIntegrationTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testRefactorEcoreCrossLanguage() throws Exception {
	EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage();
	ePackage.setName("test");
	ePackage.setNsPrefix("test");
	ePackage.setNsURI("http://test");
	EClass eClass = EcoreFactory.eINSTANCE.createEClass();
	eClass.setName(TEST_CLASS);
	ePackage.getEClassifiers().add(eClass);
	Resource ecoreResource = new ResourceSetImpl().createResource(URI.createPlatformResourceURI(TEST_PROJECT + "/Test.ecore", true));
	ecoreResource.getContents().add(ePackage);
	ecoreResource.save(null);
	ecoreResource.unload();
	project.refreshLocal(IResource.DEPTH_INFINITE, null);
	
	String model = "ref test." + TEST_CLASS;
	IFile file = createFile(TEST_PROJECT + "/ref.referringtestlanguage", model);
	waitForBuild();
	final XtextEditor editor = openEditor(file);
	final TextSelection selection = new TextSelection(model.indexOf(TEST_CLASS), TEST_CLASS.length());
	editor.getSelectionProvider().setSelection(selection);
	waitForDisplay();
	IRenameElementContext context = editor.getDocument().readOnly(new IUnitOfWork<IRenameElementContext, XtextResource>() {
		@Override
		public IRenameElementContext exec(XtextResource state) throws Exception {
			Reference ref = (Reference) state.getContents().get(0).eContents().get(0);
			EObject referenced = ref.getReferenced();
			assertNotNull(referenced);
			return new IRenameElementContext.Impl(EcoreUtil.getURI(referenced), referenced.eClass(), editor, selection, state.getURI());
		}
	});
	renameRefactoringController.startRefactoring(context);
	waitForDisplay();
	pressKeys(editor, "NewTestClass\n");
	waitForReconciler(editor);
	waitForDisplay();
	waitForBuild();
	ecoreResource.load(null);
	assertEquals("NewTestClass", ((EPackage)ecoreResource.getContents().get(0)).getEClassifiers().get(0).getName());
}
 
Example #29
Source File: LinkedModelCalculatorIntegrationTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testCorrectTextEditsDeclarationNotInFile() throws Exception {
	String initialModel1 = "A { B ref A } C { D ref A }";
	createFile(pathToFile1, initialModel1);
	String initialModel2 = "E { ref A } F { ref E ref A}";
	IFile file2 = createFile(pathToFile2, initialModel2);
	waitForBuild();
	XtextEditor editor = openEditor(file2);
	EObject a = editor.getDocument().readOnly(new IUnitOfWork<EObject, XtextResource>() {

		@Override
		public EObject exec(XtextResource state) throws Exception {
			return ((Element) state.getContents().get(0).eContents().get(0)).getReferenced().get(0);
		}

	});

	URI uri = EcoreUtil.getURI(a);
	selectElementInEditor(a, uri, editor, (XtextResource) a.eResource());
	IRenameElementContext renameElementContext = new IRenameElementContext.Impl(uri, a.eClass(), editor, editor
			.getSelectionProvider().getSelection(), uriToFile2);
	LinkedPositionGroup linkedPositionGroup = linkedModelCalculator.getLinkedPositionGroup(renameElementContext,
			new NullProgressMonitor()).get();
	LinkedPosition[] positions = linkedPositionGroup.getPositions();
	assertEquals(2, positions.length);

	int[] offsets = { 8, 26 };
	for (int i = 0; i < positions.length; i++) {
		assertEquals(offsets[i], positions[i].getOffset());
	}
}
 
Example #30
Source File: EncodingTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void openEditorAndCheckEncoding(IFile file, final String charset) throws CoreException, Exception {
	XtextEditor openedEditor = openEditor(file);
	assertNotNull(openedEditor);
	IXtextDocument document = openedEditor.getDocument();
	document.readOnly(new IUnitOfWork.Void<XtextResource>() {
		@Override
		public void process(XtextResource resource) throws Exception {
			assertEquals(charset, resource.getEncoding());
		}
	});
	openedEditor.close(false);
	openedEditor.dispose();
}