Java 类org.eclipse.xtext.util.concurrent.IUnitOfWork 实例源码

项目:dsl-devkit    文件:FormatQuickfixProvider.java   
/**
 * Semantic quickfix setting the override flag for a rule.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(FormatJavaValidator.OVERRIDE_MISSING_CODE)
public void setOverride(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, "Set override", "Set override flag.", null, new IModification() {
    @Override
    public void apply(final IModificationContext context) throws BadLocationException {
      context.getXtextDocument().modify(new IUnitOfWork<Void, XtextResource>() {
        @Override
        public java.lang.Void exec(final XtextResource state) {
          Rule rule = (Rule) state.getEObject(issue.getUriToProblem().fragment());
          rule.setOverride(true);
          return null;
        }
      });
    }
  });
}
项目:n4js    文件:N4JSEditorResourceAccess.java   
/***
 * 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);
    }
}
项目:n4js    文件:N4ModificationWrapper.java   
@Override
public final void apply(IModificationContext context) throws Exception {
    context.getXtextDocument().modify(new IUnitOfWork.Void<XtextResource>() {
        @Override
        public void process(XtextResource resource) throws Exception {
            final IMarker marker = issue instanceof N4JSIssue ? ((N4JSIssue) issue).getMarker() : null;
            final EObject element = resource.getEObject(issue.getUriToProblem().fragment());
            final Collection<? extends IChange> changes = modification.computeChanges(
                    context,
                    marker,
                    issue.getOffset(),
                    issue.getLength(),
                    element);

            modification.computeFinalChanges();
            changeManager.applyAll(changes);
        }
    });
}
项目:n4js    文件:N4JSLinker.java   
/**
 * Clears the list of encoded URIs in {@link N4JSResource}, installs proxies for all cross references inside the
 * parsed model. If validation is enabled finally the {@link ASTStructureValidator} is triggered, that checks the
 * now linked AST structure.
 */
@Override
protected void doLinkModel(final EObject model, final IDiagnosticConsumer consumer) {
    final LinkingDiagnosticProducer producer = new LinkingDiagnosticProducer(consumer);
    getCache().execWithoutCacheClear((N4JSResource) model.eResource(), new IUnitOfWork.Void<N4JSResource>() {

        @Override
        public void process(N4JSResource resource) throws Exception {
            // actual linking
            resource.clearLazyProxyInformation();
            clearReferences(model);
            installProxies(resource, model, producer);
            TreeIterator<EObject> iterator = model.eAllContents();
            while (iterator.hasNext()) {
                EObject eObject = iterator.next();
                clearReferences(eObject);
                installProxies(resource, eObject, producer);
            }
            // pre-processing of AST
            preProcessor.process(resource.getScript(), resource);
            // AST structure validation
            if (!resource.isValidationDisabled())
                getStructureValidator().validate(model, consumer);
        }
    });
}
项目:lcdsl    文件:AbstractLaunchConfigGeneratorHandler.java   
protected LaunchConfig getLaunchConfigFromEditor(ExecutionEvent event) {
    XtextEditor activeXtextEditor = EditorUtils.getActiveXtextEditor(event);
    if (activeXtextEditor == null) {
        return null;
    }
    final ITextSelection selection = (ITextSelection) activeXtextEditor.getSelectionProvider().getSelection();
    return activeXtextEditor.getDocument().priorityReadOnly(new IUnitOfWork<LaunchConfig, XtextResource>() {

        @Override
        public LaunchConfig exec(XtextResource xTextResource) throws Exception {
            EObject lc = eObjectAtOffsetHelper.resolveContainedElementAt(xTextResource, selection.getOffset());
            return findParentLaunchConfig(lc);
        }

    });
}
项目:xtext-extras    文件:CachingBatchTypeResolver.java   
@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;
}
项目:xtext-core    文件:ReferenceFinder.java   
protected void doFindReferencesWith(final IReferenceFinder referenceFinder, final TargetURIs targetURIs, final URI candidate,
        IResourceAccess resourceAccess, IResourceDescriptions descriptions, final Acceptor acceptor,
        final IProgressMonitor monitor) {
    IResourceDescription resourceDescription = null;
    if (!targetURIs.getTargetResourceURIs().contains(candidate) && (resourceDescription = descriptions.getResourceDescription(candidate)) != null) {
        referenceFinder.findReferences(targetURIs, resourceDescription, resourceAccess, acceptor, monitor);
    } else if (resourceAccess != null) {
        resourceAccess.readOnly(candidate, new IUnitOfWork.Void<ResourceSet>() {
            @Override
            public void process(final ResourceSet state) throws Exception {
                Resource resource = state.getResource(candidate, false);
                if (resource != null) {
                    referenceFinder.findReferences(targetURIs, resource, acceptor, monitor);
                }
            }
        });
    }
}
项目:xtext-core    文件:ReferenceFinder.java   
@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);
    }
}
项目:xtext-core    文件:LazyLinker.java   
@Override
protected void doLinkModel(final EObject model, IDiagnosticConsumer consumer) {
    final Multimap<EStructuralFeature.Setting, INode> settingsToLink = ArrayListMultimap.create();
    final LinkingDiagnosticProducer producer = new LinkingDiagnosticProducer(consumer);
    cache.execWithoutCacheClear(model.eResource(), new IUnitOfWork.Void<Resource>() {
        @Override
        public void process(Resource state) throws Exception {
            TreeIterator<EObject> iterator = getAllLinkableContents(model);
            boolean clearAllReferencesRequired = isClearAllReferencesRequired(state);
            while (iterator.hasNext()) {
                EObject eObject = iterator.next();
                if (clearAllReferencesRequired) {
                    clearReferences(eObject);
                }
                installProxies(eObject, producer, settingsToLink);
            }
        }
    });
    installQueuedLinks(settingsToLink);
}
项目:xtext-core    文件:AllContentsPerformanceTest.java   
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);
            }
        }
    }
}
项目:xtext-core    文件:ReadWriteAccessTest.java   
private Runnable reader(final AbstractReadWriteAcces<Foo> access) {
    return new Runnable() {
        @Override
        public void run() {
            access.readOnly(new IUnitOfWork<Object, Foo>() {

                // iterate 20 times { checking the state remains, wait 50 ms}
                @Override
                public Object exec(Foo state) throws Exception {
                    String val = state.val;
                    for (int i = 0; i < 10; i++) {
                        assertEquals(val, state.val);
                        Thread.sleep(50);
                    }
                    return null;
                }
            });
        }
    };
}
项目:xtext-core    文件:DefaultCallHierarchyBuilder.java   
protected void findTargetDeclarations(final URI sourceDeclarationURI, final IProgressMonitor monitor, final Procedure2<? super IEObjectDescription, ? super IReferenceDescription> acceptor) {
  final IUnitOfWork<Object, EObject> _function = (EObject sourceDeclaration) -> {
    Object _xblockexpression = null;
    {
      IResourceServiceProvider.Registry _resourceServiceProviderRegistry = this.getResourceServiceProviderRegistry();
      final IAcceptor<IReferenceDescription> _function_1 = (IReferenceDescription reference) -> {
        boolean _filterReference = this.filterReference(reference);
        if (_filterReference) {
          IEObjectDescription _findTargetDeclaration = null;
          if (reference!=null) {
            _findTargetDeclaration=this.findTargetDeclaration(reference);
          }
          final IEObjectDescription targetDeclaration = _findTargetDeclaration;
          acceptor.apply(targetDeclaration, reference);
        }
      };
      ReferenceAcceptor _referenceAcceptor = new ReferenceAcceptor(_resourceServiceProviderRegistry, _function_1);
      this.getReferenceFinder().findAllReferences(sourceDeclaration, _referenceAcceptor, monitor);
      _xblockexpression = null;
    }
    return _xblockexpression;
  };
  this.<Object>readOnly(sourceDeclarationURI, _function);
}
项目:dsl-devkit    文件:FormatQuickfixProvider.java   
/**
 * Semantic quickfix removing the override flag for a rule.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(FormatJavaValidator.OVERRIDE_ILLEGAL_CODE)
public void removeOverride(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, "Remove override", "Remove override.", null, new IModification() {
    @Override
    public void apply(final IModificationContext context) throws BadLocationException {
      context.getXtextDocument().modify(new IUnitOfWork<Void, XtextResource>() {
        @Override
        public java.lang.Void exec(final XtextResource state) {
          Rule rule = (Rule) state.getEObject(issue.getUriToProblem().fragment());
          rule.setOverride(false);
          return null;
        }
      });
    }
  });
}
项目:dsl-devkit    文件:EObjectContentProvider.java   
/**
 * 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();
}
项目:dsl-devkit    文件:EObjectContentProviderTest.java   
/**
 * Mocks XtextEditor and XtextElementSelectionListener to return an element selection that has:
 * - given EAttribute with a specific value (AttributeValuePair)
 * - given EStructuralFeature
 * - given EOperation.
 *
 * @param attributeValuePair
 *          EAttribute with a specific value
 * @param feature
 *          the EStructuralFeature
 * @param operation
 *          the EOperation
 * @return the EClass of the "selected" element
 */
@SuppressWarnings("unchecked")
private EClass mockSelectedElement(final AttributeValuePair attributeValuePair, final EStructuralFeature feature, final EOperation operation) {
  EClass mockSelectionEClass = mock(EClass.class);
  when(mockSelectionListener.getSelectedElementType()).thenReturn(mockSelectionEClass);
  // Mockups for returning AttributeValuePair
  URI elementUri = URI.createURI("");
  when(mockSelectionListener.getSelectedElementUri()).thenReturn(elementUri);
  XtextEditor mockEditor = mock(XtextEditor.class);
  when(mockSelectionListener.getEditor()).thenReturn(mockEditor);
  IXtextDocument mockDocument = mock(IXtextDocument.class);
  when(mockEditor.getDocument()).thenReturn(mockDocument);
  when(mockDocument.<ArrayList<AttributeValuePair>> readOnly(any(IUnitOfWork.class))).thenReturn(newArrayList(attributeValuePair));
  // Mockups for returning EOperation
  BasicEList<EOperation> mockEOperationsList = new BasicEList<EOperation>();
  mockEOperationsList.add(operation);
  when(mockSelectionEClass.getEAllOperations()).thenReturn(mockEOperationsList);
  // Mockups for returning EStructuralFeature
  BasicEList<EStructuralFeature> mockEStructuralFeatureList = new BasicEList<EStructuralFeature>();
  mockEStructuralFeatureList.add(feature);
  mockEStructuralFeatureList.add(attributeValuePair.getAttribute());
  when(mockSelectionEClass.getEAllStructuralFeatures()).thenReturn(mockEStructuralFeatureList);
  return mockSelectionEClass;
}
项目:dsl-devkit    文件:AbstractOutlineTest.java   
/**
 * Inspects the outline nodes and checks that given condition applies to at least one of the represented model objects.
 *
 * @param <T>
 *          the generic type
 * @param clazz
 *          the clazz
 * @param predicate
 *          the predicate
 */
protected <T extends EObject> void assertEObjectInOutlineNodesExists(final Class<T> clazz, final Predicate<T> predicate) {
  final List<T> result = Lists.newArrayList();
  for (final IOutlineNode n : getOutlineMap().get(clazz)) {
    result.add(n.readOnly(new IUnitOfWork<T, EObject>() {
      @Override
      @SuppressWarnings("unchecked")
      public T exec(final EObject state) throws Exception { // NOPMD
        return (T) state;
      }
    }));
  }
  try {
    Assert.assertNotNull(NLS.bind("At least one outline node represents an object of type \"{0}\"", clazz.getName()), Iterables.find(result, predicate));
  } catch (NoSuchElementException e) {
    Assert.fail(NLS.bind("Could not find an object of type \"{0}\" in outline", clazz.getName()));
  }
}
项目:dsl-devkit    文件:AbstractXtextEditorTest.java   
/**
 * Insert the given value at offset in {@link #getDocument()}.
 *
 * @param offset
 *          the offset
 * @param value
 *          the value
 */
protected void insertAtOffset(final int offset, final String value) {
  PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
    @Override
    public void run() {
      // the modify() is invoked to ensure a (fast-only) re-validation of the document is triggered
      getDocument().modify(new IUnitOfWork<Void, XtextResource>() {
        @Override
        public java.lang.Void exec(final XtextResource state) {
          try {
            getDocument().replace(offset, 0, value);
          } catch (BadLocationException e) {
            throw new WrappedException("Could not insert \"" + value + "\" at affset " + offset, e);
          }
          return null;
        }
      });
    }
  });
}
项目:dsl-devkit    文件:FixedHighlightingReconciler.java   
/**
 * Refreshes the highlighting.
 */
@Override
public void refresh() {
  if (calculator != null) {
    IDocument document;
    if (editor != null) {
      document = editor.getDocument();
    } else {
      document = sourceViewer.getDocument();
    }
    if (document instanceof IXtextDocument) {
      ((IXtextDocument) document).readOnly(new IUnitOfWork.Void<XtextResource>() {
        @Override
        public void process(final XtextResource state) throws Exception {
          modelChanged(state);
        }
      });
    }
  } else {
    Display display = getDisplay();
    display.asyncExec(presenter.createSimpleUpdateRunnable());
  }
}
项目:dsl-devkit    文件:CheckQuickfixProvider.java   
/** {@inheritDoc} */
@Override
public void apply(final IModificationContext context) throws BadLocationException {
  final IXtextDocument xtextDocument = context.getXtextDocument();
  xtextDocument.readOnly(new IUnitOfWork.Void<XtextResource>() {
    @Override
    public void process(final XtextResource state) throws Exception { // NOPMD
      final EObject target = EcoreUtil2.getContainerOfType(state.getEObject(issue.getUriToProblem().fragment()), type);
      if (type.isInstance(target)) {
        int offset = NodeModelUtils.findActualNodeFor(target).getOffset();
        int lineOfOffset = xtextDocument.getLineOfOffset(offset);
        int lineOffset = xtextDocument.getLineOffset(lineOfOffset);
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < (offset - lineOffset); i++) {
          buffer.append(' ');
        }
        xtextDocument.replace(offset, 0, NLS.bind(autodocumentation, buffer.toString()));
      }
    }
  });
}
项目:z80editor    文件:Z80InstructionHelpView.java   
private void loadCycleInfo(final int offset, final int length, XtextEditor editor, final IDocument doc) {
    final ILocationInFileProvider locationInFileProvider = Z80Activator.getInstance().getInjector(Z80Activator.ORG_EFRY_Z80EDITOR_Z80).getInstance(ILocationInFileProvider.class);

    editor.getDocument().readOnly(new IUnitOfWork<Boolean, XtextResource>() {

        @Override
        public Boolean exec(XtextResource state) throws Exception {
            Z80OperationTypeWalker operationInstructions = new Z80OperationTypeWalker(state, locationInFileProvider, offset, offset + length);

            Z80CycleCalculator calc = new Z80CycleCalculator();

            for (Operation o : operationInstructions) {
                ITextRegion region = locationInFileProvider.getFullTextRegion(o);
                calc.addOperation(o, doc.get(region.getOffset(), region.getLength()));
            }
            label.setText(calc.getHtmlFormattedText());
            return Boolean.TRUE;
        }
    });
}
项目:bts    文件:ShowQuickOutlineActionHandler.java   
public Object execute(final ExecutionEvent event) throws ExecutionException {
    final XtextEditor xtextEditor = EditorUtils.getActiveXtextEditor(event);
    if (xtextEditor != null) {
        final IXtextDocument document = xtextEditor.getDocument();
        document.readOnly(new IUnitOfWork.Void<XtextResource>()  {
            @Override
            public void process(XtextResource state) throws Exception {
                final QuickOutlinePopup quickOutlinePopup = createPopup(xtextEditor.getEditorSite().getShell());
                quickOutlinePopup.setEditor(xtextEditor);
                quickOutlinePopup.setInput(document);
                quickOutlinePopup.setEvent((Event) event.getTrigger());
                quickOutlinePopup.open();
            }
        });
    }
    return null;
}
项目:bts    文件:AbstractOutlineNode.java   
public List<IOutlineNode> getChildren() {
    if (isLeaf)
        return Collections.emptyList();
    if (children == null) {
        readOnly(new IUnitOfWork.Void<EObject>() {
            @Override
            public void process(EObject eObject) throws Exception {
                getTreeProvider().createChildren(AbstractOutlineNode.this, eObject);
            }
        });
        if (children == null) {
            // tree provider did not create any child
            isLeaf = true;
            return Collections.emptyList();
        }
    }
    return Collections.unmodifiableList(children);
}
项目:bts    文件:AbstractOutlineNode.java   
public <T> T readOnly(final IUnitOfWork<T, EObject> work) {
    if (getEObjectURI() != null) {
        return getDocument().readOnly(new IUnitOfWork<T, XtextResource>() {
            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());
                return work.exec(eObject);
            }

        });
    } else {
        return null;
    }
}
项目:bts    文件:OutlineNodeElementOpener.java   
public void open(IOutlineNode node, ISourceViewer textViewer) {
    if (node != null) {
        ITextRegion textRegion = node.getSignificantTextRegion();
        if (textRegion != null && textRegion != ITextRegion.EMPTY_REGION) {
            int offset = textRegion.getOffset();
            int length = textRegion.getLength();
            textViewer.setRangeIndication(offset, length, true);
            textViewer.revealRange(offset, length);
            textViewer.setSelectedRange(offset, length);
        } else {
            node.readOnly(new IUnitOfWork.Void<EObject>() {
                @Override
                public void process(EObject state) throws Exception {
                    openEObject(state);
                }
            });
        }

    }
}
项目:bts    文件:DocumentBasedDirtyResource.java   
public void connect(IXtextDocument document) {
    if (document == null)
        throw new IllegalArgumentException("document may not be null");
    if (this.document == document)
        return;
    if (this.document != null)
        throw new IllegalStateException("Dirty resource was already connected to another document");
    this.document = document;
    document.readOnly(new IUnitOfWork.Void<XtextResource>() {
        @Override
        public void process(XtextResource resource) {
            if (resource != null) {
                DocumentBasedDirtyResource.this.normalizedUri = EcoreUtil2.getNormalizedURI(resource);
                initiallyProcessResource(resource);
            }
        }
    });
}
项目:bts    文件:DocumentBasedDirtyResource.java   
/**
 * Callback method for the copied resource description. Is triggered as soon as somebody is 
 * interested in the reference descriptions which shall be up to date all the time.
 * This allows for lazy resolution of proxies instead of eager copying.
 * @return the current resource description of the associated document. May be <code>null</code>.
 */
public IResourceDescription get() {
    IResourceDescription result = document.readOnly(new IUnitOfWork<IResourceDescription, XtextResource>() {
        public IResourceDescription exec(XtextResource resource) {
            if (resource != null) {
                IResourceServiceProvider serviceProvider = resource.getResourceServiceProvider();
                if (serviceProvider != null) {
                    IResourceDescription.Manager manager = serviceProvider.getResourceDescriptionManager();
                    if (manager != null) {
                        return manager.getResourceDescription(resource);
                    }
                }
            }
            return null;
        }
    });
    return result;
}
项目:bts    文件:GlobalURIEditorOpener.java   
protected void selectAndReveal(IEditorPart openEditor, final URI uri, final EReference crossReference,
        final int indexInList, final boolean select) {
    final XtextEditor xtextEditor = EditorUtils.getXtextEditor(openEditor);
    if (xtextEditor != null) {
        if (uri.fragment() != null) {
            xtextEditor.getDocument().readOnly(new IUnitOfWork.Void<XtextResource>() {
                @Override
                public void process(XtextResource resource) throws Exception {
                    if (resource != null) {
                        EObject object = resource.getEObject(uri.fragment());
                        ITextRegion location = (crossReference != null) ? locationProvider.getSignificantTextRegion(object,
                                crossReference, indexInList) : locationProvider.getSignificantTextRegion(object);
                        if (select) {
                            xtextEditor.selectAndReveal(location.getOffset(), location.getLength());
                        } else {
                            xtextEditor.reveal(location.getOffset(), location.getLength());                             
                        }
                    }
                }
            });
        }
    }
}
项目:bts    文件:LoadingResourceAccess.java   
public <R> R readOnly(URI targetURI, IUnitOfWork<R, ResourceSet> work) {
    Iterable<Pair<IStorage, IProject>> storages = storage2UriMapper.getStorages(targetURI.trimFragment());
    Iterator<Pair<IStorage, IProject>> iterator = storages.iterator();
    while(iterator.hasNext()) {
        Pair<IStorage, IProject> pair = iterator.next();
        IProject project = pair.getSecond();
        if (project != null) {
            ResourceSet resourceSet = resourceSetProvider.get(project);
            if(resourceSet != null)
                resourceSet.getResource(targetURI, true);
                try {
                    return work.exec(resourceSet);
                } catch (Exception e) {
                    throw new WrappedException(e);
                }
        }
    }
    return null;
}
项目:bts    文件:ResourceAccess.java   
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;
}
项目:bts    文件:DefaultReferenceFinder.java   
protected void findLocalReferences(Iterable<URI> localTargets, ILocalResourceAccess localResourceAccess,
        final IAcceptor<IReferenceDescription> acceptor, IProgressMonitor monitor) {
    if ((monitor != null && monitor.isCanceled()))
        return;
    final Multimap<URI, URI> resource2target = LinkedHashMultimap.create();
    for (URI targetURI : localTargets) {
        resource2target.put(targetURI.trimFragment(), targetURI);
    }
    final SubMonitor subMonitor = SubMonitor.convert(monitor, resource2target.keySet().size());
    for (final URI resourceURI : resource2target.keySet()) {
        if (subMonitor.isCanceled())
            return;
        localResourceAccess.readOnly(resourceURI, new IUnitOfWork.Void<ResourceSet>() {
            @Override
            public void process(ResourceSet resourceSet) throws Exception {
                Resource resource = resourceSet.getResource(resourceURI, true);
                findLocalReferencesInResource(resource2target.get(resourceURI), resource, acceptor);
            }
        });
        subMonitor.worked(1);
    }
}
项目:bts    文件:FindReferencesHandler.java   
public Object execute(ExecutionEvent event) throws ExecutionException {
    try {
        XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
        if (editor != null) {
            final ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
            editor.getDocument().readOnly(new IUnitOfWork.Void<XtextResource>() {
                @Override
                public void process(XtextResource state) throws Exception {
                    EObject target = eObjectAtOffsetHelper.resolveElementAt(state, selection.getOffset());
                    findReferences(target);
                }
            });
        }
    } catch (Exception e) {
        LOG.error(Messages.FindReferencesHandler_3, e);
    }
    return null;
}
项目:bts    文件:AbstractEObjectHover.java   
@Override
public IRegion getHoverRegion(final ITextViewer textViewer, final int offset) {
    IXtextDocument xtextDocument = XtextDocumentUtil.get(textViewer);
    if(xtextDocument == null) 
        return null;
    //TODO this is being called on change in the UI-thread. Not a good idea to do such expensive stuff.
    // returning the region on a per token basis would be better.
    return xtextDocument.readOnly(new IUnitOfWork<IRegion, XtextResource>() {
        public IRegion exec(XtextResource state) throws Exception {
            // resource can be null e.g. read only zip/jar entry
            if (state == null) {
                return null;
            }
            Pair<EObject, IRegion> element = getXtextElementAt(state, offset);
            if (element != null) {
                return element.getSecond();
            } else {
                return null;
            }
        }
    });
}
项目:bts    文件:AbstractEObjectHover.java   
public Object getHoverInfo2(final ITextViewer textViewer, final IRegion hoverRegion) {
    if (hoverRegion == null)
        return null;
    IXtextDocument xtextDocument = XtextDocumentUtil.get(textViewer);
    if(xtextDocument == null) 
        return null;
    return xtextDocument.readOnly(new IUnitOfWork<Object, XtextResource>() {
        public Object exec(XtextResource state) throws Exception {
            // resource can be null e.g. read only zip/jar entry
            if (state == null) {
                return null;
            }
            Pair<EObject, IRegion> element = getXtextElementAt(state, hoverRegion.getOffset());
            if (element != null && element.getFirst() != null) {
                return getHoverInfo(element.getFirst(), textViewer, hoverRegion);
            }
            return null;
        }
    });
}
项目:bts    文件:LanguageSpecificURIEditorOpener.java   
protected void selectAndReveal(IEditorPart openEditor, final URI uri, final EReference crossReference,
        final int indexInList, final boolean select) {
    final XtextEditor xtextEditor = EditorUtils.getXtextEditor(openEditor);
    if (xtextEditor != null) {
        xtextEditor.getDocument().readOnly(new IUnitOfWork.Void<XtextResource>() {
            @Override
            public void process(XtextResource resource) throws Exception {
                if (resource != null) {
                    EObject object = findEObjectByURI(uri, resource);
                    if (object != null) {
                        ITextRegion location = (crossReference != null) ? locationProvider
                                .getSignificantTextRegion(object, crossReference, indexInList)
                                : locationProvider.getSignificantTextRegion(object);
                        if (select)
                            xtextEditor.selectAndReveal(location.getOffset(), location.getLength());
                    }
                }
            }
        });
    }
}
项目:bts    文件:HighlightingReconciler.java   
/**
 * Refreshes the highlighting.
 */
public void refresh() {
    if (calculator != null) {
        new Job("calculating highlighting") {
            @Override
            protected IStatus run(IProgressMonitor monitor) {
                ((XtextDocument) sourceViewer.getDocument()).readOnly(new IUnitOfWork.Void<XtextResource>() {
                    @Override
                    public void process(XtextResource state) throws Exception {
                        modelChanged(state);
                    }
                });
                return Status.OK_STATUS;
            }
        }.schedule();

    } else {
        Display display = getDisplay();
        display.asyncExec(presenter.createSimpleUpdateRunnable());
    }
}
项目:bts    文件:EditorCopyQualifiedNameHandler.java   
@Override
protected String getQualifiedName(ExecutionEvent event) {
    XtextEditor activeXtextEditor = EditorUtils.getActiveXtextEditor(event);
    if (activeXtextEditor == null) {
        return null;
    }
    final ITextSelection selection = getTextSelection(activeXtextEditor);
    return activeXtextEditor.getDocument().readOnly(new IUnitOfWork<String, XtextResource>() {

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

    });
}
项目:bts    文件:XtextReconciler.java   
public void performNecessaryUpdates(Processor processor) {
    try {
        if (!pendingChanges.isEmpty()) {
            processor.process(new IUnitOfWork.Void<XtextResource>() {
                @Override
                public void process(XtextResource state) throws Exception {
                    doRun(state, null);
                }
            });
        }
    } catch (Exception exc) {
        log.error("Error while forcing reconciliation", exc);
    }
    if (sessionStarted && !paused) {
        pause();
    }
}
项目:bts    文件:XtextReconciler.java   
@Override
protected IStatus run(final IProgressMonitor monitor) {
    if (monitor.isCanceled() || paused)
        return Status.CANCEL_STATUS;

    long start = System.currentTimeMillis();
    final IXtextDocument document = XtextDocumentUtil.get(textViewer);
    if (document instanceof XtextDocument) {
        ((XtextDocument) document).internalModify(new IUnitOfWork.Void<XtextResource>() {
            @Override
            public void process(XtextResource state) throws Exception {
                doRun(state, monitor);
            }
        });
    }
    if (log.isDebugEnabled())
        log.debug("Reconciliation finished. Time required: " + (System.currentTimeMillis() - start)); //$NON-NLS-1$
    return Status.OK_STATUS;
}
项目:bts    文件:RenameRefactoringController.java   
protected String getOriginalName(final XtextEditor xtextEditor) {
    return xtextEditor.getDocument().readOnly(new IUnitOfWork<String, XtextResource>() {
        public String exec(XtextResource state) throws Exception {
            try {
                EObject targetElement = state.getResourceSet().getEObject(renameElementContext.getTargetElementURI(),
                    false);
                IRenameStrategy.Provider strategyProvider = globalServiceProvider.findService(targetElement,
                        IRenameStrategy.Provider.class);
                if (strategyProvider != null) {
                    IRenameStrategy strategy = strategyProvider.get(targetElement, renameElementContext);
                    if (strategy != null)
                        return strategy.getOriginalName();
                }
            } catch(NoSuchStrategyException e) {
                // null
            }
            return null;
        }
    });
}
项目:bts    文件:EgyTextEditorPart.java   
private boolean checkTransliterationHasNoErrors(BTSText text2) {
    // XXX irgendwo fehler: wenn vorher irgendwann man errors drin waren,
    // bleibt das auch wenn man den text wechselt...
    IXtextDocument document = embeddedEditor.getDocument();

    EList<EObject> objects = document
            .readOnly(new IUnitOfWork<EList<EObject>, XtextResource>() {
                @Override
                public EList<EObject> exec(XtextResource state)
                        throws Exception {
                    return state.getContents();
                }
            });
    EObject eo = objects.get(0);
    Resource resource = eo.eResource();
    boolean valid = checkResourceErrors(resource);
    return valid;
}