org.eclipse.core.runtime.Adapters Java Examples

The following examples show how to use org.eclipse.core.runtime.Adapters. 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: ToggleSLCommentAction.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Implementation of the <code>IUpdate</code> prototype method discovers
 * the operation through the current editor's
 * <code>ITextOperationTarget</code> adapter, and sets the enabled state
 * accordingly.
 */
@Override
public void update() {
	super.update();

	if (!canModifyEditor()) {
		setEnabled(false);
		return;
	}

	ITextEditor editor= getTextEditor();
	if (fOperationTarget == null && editor != null)
		fOperationTarget= Adapters.adapt(editor, ITextOperationTarget.class);

	boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(ITextOperationTarget.PREFIX) && fOperationTarget.canDoOperation(ITextOperationTarget.STRIP_PREFIX));
	setEnabled(isEnabled);
}
 
Example #2
Source File: AbstractDebugAdapterLaunchShortcut.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public IResource getLaunchableResource(ISelection selection) {
	if (selection instanceof IStructuredSelection) {
		IStructuredSelection structuredSelection = (IStructuredSelection) selection;
		if (structuredSelection.size() != 1) {
			return null;
		}
		Object firstObject = structuredSelection.getFirstElement();
		IResource resource = Adapters.adapt(firstObject, IResource.class);
		int resourceType = resource.getType();
		if (resourceType == IResource.FILE) {
			if (canLaunch(resource.getLocation().toFile())) {
				return resource;
			}
		} else if (resourceType == IResource.PROJECT || resourceType == IResource.FOLDER) {
			return getLaunchableResource(Adapters.adapt(resource, IContainer.class));
		}
	}
	return null;
}
 
Example #3
Source File: LaunchShortcutUtil.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public static IStructuredSelection replaceWithJavaElementDelegates(IStructuredSelection selection, Class<? extends JavaElementDelegate> delegateType) {
	Object[] originalSelection = selection.toArray();
	Object[] fakeSelection = new Object[originalSelection.length];
	for(int i = 0; i < originalSelection.length; i++) {
		Object original = originalSelection[i];
		if (original == null || original instanceof IJavaElement || original instanceof JavaElementDelegate || !(original instanceof IAdaptable)) {
			fakeSelection[i] = original;
		} else {
			
			JavaElementDelegate javaElementDelegate = Adapters.adapt(original, delegateType);
			if (javaElementDelegate != null) {
				fakeSelection[i] = javaElementDelegate;
			} else {
				fakeSelection[i] = original;
			}
		}
	}
	StructuredSelection newSelection = new StructuredSelection(fakeSelection);
	return newSelection;
}
 
Example #4
Source File: XbaseBreakpointUtil.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public IResource getBreakpointResource(IEditorInput input) throws CoreException {
	IResource resource = Adapters.adapt(input, IResource.class);
	if (resource != null)
		return resource;
	if (input instanceof IStorageEditorInput) {
		IStorage storage = ((IStorageEditorInput) input).getStorage();
		if (storage instanceof IResource)
			return (IResource) storage;
		if (storage instanceof IJarEntryResource) {
			IResource underlyingResource = ((IJarEntryResource) storage).getPackageFragmentRoot().getUnderlyingResource();
			if (underlyingResource != null)
				return underlyingResource;
		}
	} else {
		IClassFile classFile = Adapters.adapt(input, IClassFile.class);
		if (classFile != null) {
			return getBreakpointResource(classFile.findPrimaryType());
		}
	}
	return ResourcesPlugin.getWorkspace().getRoot();
}
 
Example #5
Source File: SelectionUtils.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
private static IFile getSelectedIFile() {
	try {
		ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
		if (selection instanceof IStructuredSelection) {
			return Adapters.adapt(((IStructuredSelection)selection).getFirstElement(), IFile.class);
		}
	} catch (Exception e) {
		Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
	}
	IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
	if (editor != null) {
		IEditorInput input = editor.getEditorInput();
		if (input instanceof IFileEditorInput) {
			return ((IFileEditorInput)input).getFile();
		}
	}
	return null;
}
 
Example #6
Source File: SelectionUtils.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
public static File getFile(ISelection selection, Predicate<File> condition) {
	if (selection instanceof IStructuredSelection) {
		IStructuredSelection structuredSelection = (StructuredSelection)selection;
		Object firstElement = structuredSelection.getFirstElement();
		IResource resource = Adapters.adapt(firstElement, IResource.class);
		if (resource != null) {
			File file = resource.getLocation().toFile();
			if (condition == null || condition.test(file)) {
				return file;
			}
		}
	}
	if (selection instanceof TextSelection) {
		// check whether it comes from active editor
		IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
		if (part instanceof ITextEditor) { // most likely the source of the selection
			return getFile(((IEditorPart)part).getEditorInput(), condition);
		}
	}
	return null;
}
 
Example #7
Source File: EditorUtils.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public static XtextEditor getActiveXtextEditor() {
	IWorkbench workbench = PlatformUI.getWorkbench();
	IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
	if (workbenchWindow == null) 
		return null;
	
	IWorkbenchPage activePage = workbenchWindow.getActivePage();
	if (activePage == null) 
		return null;
	
	IEditorPart activeEditor = activePage.getActiveEditor();
	if (activeEditor == null)
		return null;
	
	return Adapters.adapt(activeEditor, XtextEditor.class);
}
 
Example #8
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 #9
Source File: IsNodeProjectPropertyTester.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
@Override public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
	if (IS_NODE_RESOURCE_PROPERTY.equals(property)) {
		IResource resource = Adapters.adapt(receiver, IResource.class);
		if (resource == null) {
			return false;
		}
		if (resource instanceof IFile) {
			IContentTypeManager contentTypeManager = Platform.getContentTypeManager();
			IContentType jsContentType = contentTypeManager.getContentType("org.eclipse.wildwebdeveloper.js");
			IContentType tsContentType = contentTypeManager.getContentType("org.eclipse.wildwebdeveloper.ts");
			try (
				InputStream content = ((IFile) resource).getContents();
			) {
				List<IContentType> contentTypes = Arrays.asList(contentTypeManager.findContentTypesFor(content, resource.getName()));
				return contentTypes.contains(jsContentType) || contentTypes.contains(tsContentType);
			} catch (Exception e) {
				return false;
			}
		}
	}
	return false;
}
 
Example #10
Source File: ImportsAwareClipboardAction.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private void doPasteJavaCode(String textFromClipboard, JavaImportData javaImportsContent, boolean withImports) {
	IRewriteTarget target = Adapters.adapt(getTextEditor(), IRewriteTarget.class);
	if (target != null) {
		target.beginCompoundChange();
	}
	try {
		textOperationTarget.doOperation(operationCode);
		if (withImports) {
			importsUtil.addImports(javaImportsContent.getImports(), javaImportsContent.getStaticImports(),
					new String[] {}, getXtextDocument());
		}
	} catch (Exception e) {
		XbaseActivator.getInstance().getLog().log(new Status(IStatus.ERROR,
				XbaseActivator.getInstance().getBundle().getSymbolicName(), "Unexpected internal error: ", e));
	} finally {
		if (target != null) {
			target.endCompoundChange();
		}
	}
}
 
Example #11
Source File: DotnetDebugLaunchShortcut.java    From aCute with Eclipse Public License 2.0 6 votes vote down vote up
@Override public IResource getLaunchableResource(ISelection selection) {
	Set<IResource> resources = new HashSet<>();
	if (selection instanceof IStructuredSelection) {
		for (Object o : ((IStructuredSelection) selection).toArray()) {
			IResource resource = Adapters.adapt(o, IResource.class);
			if (resource != null) {
				resources.add(resource);
			}
		}
	}
	if (resources.isEmpty()) {
		return null;
	} else if (resources.size() == 1) {
		return resources.iterator().next();
	} else {
		// TODO ambiguous
		return null;
	}
}
 
Example #12
Source File: ClassFileBasedOpenerContributor.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean collectSourceFileOpeners(IEditorPart editor, IAcceptor<FileOpener> acceptor) {
	if (!(editor instanceof XtextEditor) && editor.getEditorInput() != null) {
		try {
			IClassFile classFile = Adapters.adapt(editor, IClassFile.class);
			if (classFile == null) {
				return false;
			}
			ITrace trace = traceForTypeRootProvider.getTraceToSource(classFile);
			if (trace == null) {
				return false;
			}
			for (ILocationInResource location : trace.getAllAssociatedLocations()) {
				String name = location.getAbsoluteResourceURI().getURI().lastSegment();
				IEditorDescriptor editorDescriptor = IDE.getEditorDescriptor(name);
				acceptor.accept(createEditorOpener(editor.getEditorInput(), editorDescriptor.getId()));
				return true;
			}
		} catch (PartInitException e) {
			LOG.error(e.getMessage(), e);
		}
	}
	return false;
}
 
Example #13
Source File: ImportsAwareClipboardAction.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private void doPasteXbaseCode(XbaseClipboardData xbaseClipboardData, boolean withImports) {
	IRewriteTarget target = Adapters.adapt(getTextEditor(), IRewriteTarget.class);
	if (target != null) {
		target.beginCompoundChange();
	}
	try {
		textOperationTarget.doOperation(operationCode);
		if (withImports) {
			importsUtil.addImports(xbaseClipboardData.getImports(), xbaseClipboardData.getStaticImports(),
					xbaseClipboardData.getExtensionImports(), getXtextDocument());
		}
	} catch (Exception e) {
		XbaseActivator.getInstance().getLog().log(new Status(IStatus.ERROR,
				XbaseActivator.getInstance().getBundle().getSymbolicName(), "Unexpected internal error: ", e));
	} finally {
		if (target != null) {
			target.endCompoundChange();
		}
	}
}
 
Example #14
Source File: ImportsAwareClipboardAction.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void update() {
	super.update();
	if (isModifyOperation() && !canModifyEditor()) {
		setEnabled(false);
		return;
	}
	if (textOperationTarget == null) {
		textOperationTarget = Adapters.adapt(getTextEditor(), ITextOperationTarget.class);
	}
	boolean isEnabled = (textOperationTarget != null && textOperationTarget.canDoOperation(getOperationCode()));
	setEnabled(isEnabled);
}
 
Example #15
Source File: ClassFileBasedOpenerContributor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean collectGeneratedFileOpeners(IEditorPart editor, IAcceptor<FileOpener> acceptor) {
	if (editor instanceof XtextEditor && editor.getEditorInput() != null) {
		if (Adapters.adapt(editor.getEditorInput(), IClassFile.class) != null) {
			acceptor.accept(createEditorOpener(editor.getEditorInput(), JavaUI.ID_CF_EDITOR));
			return true;
		}
	}
	return false;
}
 
Example #16
Source File: JavaApplicationLaunchShortcut.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void launch(IEditorPart editor, String mode) {
	JavaElementDelegate javaElementDelegate = Adapters.adapt(editor, JavaElementDelegateMainLaunch.class);
	if (javaElementDelegate != null) {
		launch(new StructuredSelection(javaElementDelegate), mode);
	} else {
		super.launch(editor, mode);
	}
}
 
Example #17
Source File: JUnitPDELaunchShortcut.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void launch(IEditorPart editor, String mode) {
	JavaElementDelegate javaElementDelegate = Adapters.adapt(editor, JavaElementDelegateJunitLaunch.class);
	if (javaElementDelegate != null) {
		launch(new StructuredSelection(javaElementDelegate), mode);
	} else {
		super.launch(editor, mode);
	}
}
 
Example #18
Source File: JUnitLaunchShortcut.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void launch(IEditorPart editor, String mode) {
	JavaElementDelegate javaElementDelegate = Adapters.adapt(editor, JavaElementDelegateJunitLaunch.class);
	if (javaElementDelegate != null) {
		launch(new StructuredSelection(javaElementDelegate), mode);
	} else {
		super.launch(editor, mode);
	}
}
 
Example #19
Source File: MarkerResolutionGenerator.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public XtextEditor findEditor(IResource resource) {
	if(resource instanceof IFile) {
		IWorkbenchPage activePage = workbench.getActiveWorkbenchWindow().getActivePage();
		IEditorPart editor = activePage.findEditor(new FileEditorInput((IFile) resource));
		if(editor instanceof XtextEditor) {
			return (XtextEditor)editor;
		} else if (editor != null) {
			return Adapters.adapt(editor, XtextEditor.class);
		}
	}
	return null;

}
 
Example #20
Source File: ToggleXtextNatureCommand.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	ISelection selection = HandlerUtil.getCurrentSelection(event);
	if (selection instanceof IStructuredSelection) {
		for (Iterator<?> it = ((IStructuredSelection) selection).iterator(); it.hasNext();) {
			IProject project = Adapters.adapt(it.next(), IProject.class);
			if (project != null) {
				toggleNature(project);
			}
		}
	}
	return null;
}
 
Example #21
Source File: XbaseBreakpointUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public SourceRelativeURI getBreakpointURI(IEditorInput input) {
	IResource resource = Adapters.adapt(input, IResource.class);
	if (resource != null)
		return null;
	if (input instanceof IStorageEditorInput) {
		IStorage storage;
		try {
			storage = ((IStorageEditorInput) input).getStorage();
			if (storage instanceof IResource)
				return null;
			if (storage instanceof IJarEntryResource) {
				IJarEntryResource jarEntryResource = (IJarEntryResource) storage;
				if (!jarEntryResource.getPackageFragmentRoot().isArchive())
					return null;
				Object parent = jarEntryResource.getParent();
				if (parent instanceof IPackageFragment) {
					String path = ((IPackageFragment) parent).getElementName().replace('.', '/');
					return new SourceRelativeURI(path + "/" + storage.getName());
				} else if (parent instanceof IPackageFragmentRoot) {
					return new SourceRelativeURI(storage.getName());
				}
			}
		} catch (CoreException e) {
			logger.error("Error finding breakpoint URI", e);
			return null;
		}
	} else {
		IClassFile classFile = Adapters.adapt(input, IClassFile.class);
		if (classFile != null) {
			ITrace traceToSource = traceForTypeRootProvider.getTraceToSource(classFile);
			if (traceToSource == null)
				return null;
			for (ILocationInResource loc : traceToSource.getAllAssociatedLocations())
				return loc.getSrcRelativeResourceURI();
			return null;
		}
	}
	return null;
}
 
Example #22
Source File: XtextEditorPropertyTester.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
	if (Constants.LANGUAGE_NAME.equals(property)) {
		XtextEditor xtextEditor = Adapters.adapt(receiver, XtextEditor.class);
		if (xtextEditor != null) {
			return xtextEditor.getLanguageName().equals(expectedValue);
		}
	}
	return false;
}
 
Example #23
Source File: FieldInitializerUtil.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public IJavaElement getSelectedResource(IStructuredSelection selection) {
	IJavaElement elem = null;
	if(selection != null && !selection.isEmpty()){
		Object o = selection.getFirstElement();
		elem = Adapters.adapt(o, IJavaElement.class);
		if(elem == null){
			elem = getPackage(o);
		}
	}
	if (elem == null) {
		IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		IWorkbenchPart part = activePage.getActivePart();
		if (part instanceof ContentOutline) {
			part= activePage.getActiveEditor();
		}
		if (part instanceof XtextEditor) {
			IXtextDocument doc = ((XtextEditor)part).getDocument();
			IFile file = Adapters.adapt(doc, IFile.class);
			elem = getPackage(file);
		}
	}
	if (elem == null || elem.getElementType() == IJavaElement.JAVA_MODEL) {
		try {
			IJavaProject[] projects= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
			if (projects.length == 1) {
				elem= projects[0];
			}
		} catch (JavaModelException e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	return elem;
}
 
Example #24
Source File: FieldInitializerUtil.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
private IJavaElement getPackage(Object o) {
	IJavaElement elem = null;
	IResource resource = Adapters.adapt(o, IResource.class);
	if (resource != null && resource.getType() != IResource.ROOT) {
		while(elem == null && resource.getType() != IResource.PROJECT){
			resource = resource.getParent();
			elem = Adapters.adapt(resource, IJavaElement.class);
		}
	}
	if (elem == null) {
		elem = JavaCore.create(resource);
	}
	return elem;
}
 
Example #25
Source File: PythonSnippetUtils.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get a IScriptConsoleCodeGenerator adapted object for object
 * @param object to adapt
 * @return adapted object, or <code>null</code> if not adaptable
 * @see IScriptConsoleCodeGenerator
 */
public static IScriptConsoleCodeGenerator getScriptConsoleCodeGeneratorAdapter(Object object) {
    if (object == null) {
        return null;
    }
    if (object instanceof IScriptConsoleCodeGenerator) {
        return (IScriptConsoleCodeGenerator) object;
    }
    Object adaptedNode = Adapters.adapt(object, IScriptConsoleCodeGenerator.class, true);
    if (adaptedNode instanceof IScriptConsoleCodeGenerator) {
        return (IScriptConsoleCodeGenerator) adaptedNode;
    }
    return null;
}
 
Example #26
Source File: ProjectExplorerViewerComparator.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
    Repository currentRepository = RepositoryManager.getInstance().getCurrentRepository();
    IProject project = currentRepository.getProject();
    IResource resource = Adapters.adapt(e1, IResource.class);
    if (resource != null && !Objects.equals(resource.getProject(), project)) {
        return defaultSorter.compare(viewer, e1, e2);
    }
    if (comparingWebPages(e1, e2)) {
        return compareWebPages(currentRepository, viewer, resource, Adapters.adapt(e2, IFolder.class));
    }
    return super.compare(viewer, e1, e2);
}
 
Example #27
Source File: ProjectExplorerViewerComparator.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private boolean comparingWebPages(Object e1, Object e2) {
    IFolder project1 = Adapters.adapt(e1, IFolder.class);
    IFolder project2 = Adapters.adapt(e2, IFolder.class);
    if (project1 != null && project2 != null) {
        return UIDArtifactFilters.isUIDArtifactFrom(project1, "web_page")
                && UIDArtifactFilters.isUIDArtifactFrom(project2, "web_page");
    }
    return false;
}
 
Example #28
Source File: BonitaContentOutlineTreeView.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected PageRec doCreatePage(IWorkbenchPart part) {
    Object obj = Adapters.adapt(part, IContentOutlinePage.class, false);
    if (obj instanceof IContentOutlinePage && part instanceof DiagramEditor) {
        TreeViewer viewer = new TreeViewer();
        viewer.setRootEditPart(new DiagramRootTreeEditPart());
        IContentOutlinePage page = new BonitaTreeOutlinePage(viewer, (DiagramEditor) part);
        if (page instanceof IPageBookViewPage) {
            initPage((IPageBookViewPage) page);
        }
        page.createControl(getPageBook());
        return new PageRec(part, page);
    }
    return null;
}
 
Example #29
Source File: BonitaContentOutlineView.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected PageRec doCreatePage(IWorkbenchPart part) {
    Object obj = Adapters.adapt(part, IContentOutlinePage.class, false);
    if (obj instanceof IContentOutlinePage && part instanceof DiagramEditor) {
        return super.doCreatePage(part);
    }
    return null;
}
 
Example #30
Source File: NewCargoProjectWizard.java    From corrosion with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
	wizardPage = new NewCargoProjectWizardPage();
	setWindowTitle(Messages.NewCargoProjectWizard_title);

	Iterator<?> selectionIterator = selection.iterator();
	Set<IWorkingSet> workingSets = new HashSet<>();
	IResource selectedResource = null;

	while (selectionIterator.hasNext()) {
		Object element = selectionIterator.next();
		IResource asResource = toResource(element);

		if (asResource != null && selectedResource == null) {
			selectedResource = asResource;
		} else {
			IWorkingSet asWorkingSet = Adapters.adapt(element, IWorkingSet.class);
			if (asWorkingSet != null) {
				workingSets.add(asWorkingSet);
			}
		}
	}

	if (workingSets.isEmpty() && selectedResource != null) {
		workingSets.addAll(getWorkingSets(selectedResource));
	}
	wizardPage.setWorkingSets(workingSets);

	if (selectedResource != null) {
		wizardPage.setDirectory(toFile(selectedResource));
	} else {
		wizardPage.setDirectory(newFolderLocation());
	}
}