下面列出了怎么用org.eclipse.ui.ide.ResourceUtil的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns {@link IDocument} in the open editor, or null if the editor
* is not open.
*/
static IDocument getCurrentDocument(IFile file) {
try {
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
IEditorPart editorPart = ResourceUtil.findEditor(activePage, file);
if (editorPart != null) {
IDocument document = editorPart.getAdapter(IDocument.class);
return document;
}
return null;
} catch (IllegalStateException ex) {
//If workbench does not exist
return null;
}
}
public IEditorDescriptor findXbaseEditor(IEditorInput editorInput, boolean ignorePreference) {
IFile file = ResourceUtil.getFile(editorInput);
if (file == null)
return null;
if (!ignorePreference) {
if (file.exists()) {
try {
String favoriteEditor = file.getPersistentProperty(IDE.EDITOR_KEY);
if (favoriteEditor != null)
return null;
} catch (CoreException e) {
logger.debug(e.getMessage(), e);
}
}
}
// TODO stay in same editor if local navigation
Decision decision = decisions.decideAccordingToCaller();
if (decision == Decision.FORCE_JAVA) {
return null;
}
IEclipseTrace traceToSource = traceInformation.getTraceToSource(file);
return getXtextEditor(traceToSource);
}
@Deprecated
public IXtextDocument getXtextDocument(IResource resource) {
IXtextDocument result = xtextDocumentUtil.getXtextDocument(resource);
if(result == null) {
IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage();
try {
IFile file = ResourceUtil.getFile(resource);
IEditorInput input = new FileEditorInput(file);
IEditorPart newEditor = page.openEditor(input, getEditorId());
return xtextDocumentUtil.getXtextDocument(newEditor);
} catch (PartInitException e) {
return null;
}
}
return result;
}
@Override
public Object execute( ExecutionEvent event ) {
IEditorInput editorInput = HandlerUtil.getActiveEditorInput( event );
IFile resource = ResourceUtil.getFile( editorInput );
if( resource != null ) {
if( resource.isAccessible() ) {
deleteResource( HandlerUtil.getActiveWorkbenchWindow( event ), resource );
}
} else {
File file = getFile( editorInput );
IWorkbenchWindow workbenchWindow = HandlerUtil.getActiveWorkbenchWindow( event );
if( file != null && prompter.confirmDelete( workbenchWindow, file )) {
deleteFile( workbenchWindow, file );
}
}
return null;
}
/**
* Attempts to guess the most relevant resource for the current workbench state
*/
public static IResource getContextResource() {
IWorkbenchPage page = getActivePage();
if (page == null) {
return null;
}
final ISelection selection = page.getSelection();
if (selection instanceof IStructuredSelection) {
final IStructuredSelection ss = (IStructuredSelection) selection;
if (!ss.isEmpty()) {
final Object obj = ss.getFirstElement();
if (obj instanceof IResource) {
return (IResource) obj;
}
}
}
IEditorPart editor = page.getActiveEditor();
if (editor == null) {
return null;
}
IEditorInput editorInput = editor.getEditorInput();
return ResourceUtil.getResource(editorInput);
}
@Override
public IStructuredSelection findSelection(IEditorInput input) {
IFile file = ResourceUtil.getFile(input);
if (file != null) {
return new StructuredSelection(file);
}
IFileStore fileStore = (IFileStore) input.getAdapter(IFileStore.class);
if (fileStore == null && input instanceof FileStoreEditorInput) {
URI uri = ((FileStoreEditorInput)input).getURI();
try {
fileStore = EFS.getStore(uri);
} catch (CoreException e) {
}
}
if (fileStore != null) {
return new StructuredSelection(fileStore);
}
return StructuredSelection.EMPTY;
}
static ITextViewer getViewer(IFile file) {
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
IEditorPart editorPart = ResourceUtil.findEditor(activePage, file);
ITextOperationTarget target = editorPart.getAdapter(ITextOperationTarget.class);
if (target instanceof ITextViewer) {
return (ITextViewer) target;
}
return null;
}
public IEditorInput findOriginalSource(IEditorInput input) {
IFile resource = ResourceUtil.getFile(input);
if (resource == null) {
return input;
}
IEditorInput original = findOriginalSourceForOuputFolderCopy(input);
if (original != input) {
return original;
}
IEclipseTrace trace = traceInformation.getTraceToSource(resource);
if (trace == null) {
return input;
}
for (ILocationInEclipseResource candidate : trace.getAllAssociatedLocations()) {
if (languageInfo.equals(candidate.getLanguage())) {
IStorage storage = candidate.getPlatformResource();
if (storage != null) {
return EditorUtils.createEditorInput(storage);
}
}
}
return input;
}
private static IFile extractFileFromSelection( IStructuredSelection selection ) {
IFile result = null;
if( selection.size() == 1 ) {
result = ResourceUtil.getFile( selection.getFirstElement() );
}
return result;
}
private static boolean isEnabled( IEvaluationContext evaluationContext ) {
Object variable = evaluationContext.getVariable( ISources.ACTIVE_EDITOR_INPUT_NAME );
boolean result = false;
if( variable instanceof IEditorInput ) {
IEditorInput editorInput = ( IEditorInput )variable;
result = ResourceUtil.getFile( editorInput ) != null || getFile( editorInput ) != null;
}
return result;
}
private IPath querySaveAsFilePath() {
SaveAsDialog dialog = new SaveAsDialog( getSite().getShell() );
IEditorInput editorInput = getEditorInput();
IFile originalFile = ResourceUtil.getFile( editorInput );
if( originalFile != null ) {
dialog.setOriginalFile( originalFile );
} else {
dialog.setOriginalName( editorInput.getName() );
}
int dialogResult = dialog.open();
return dialogResult == Window.OK ? dialog.getResult() : null;
}
public IStructuredSelection findSelection(IEditorInput input) {
IJavaElement element= JavaUI.getEditorInputJavaElement(input);
if (element == null) {
IFile file = ResourceUtil.getFile(input);
if (file != null) {
element= JavaCore.create(file);
}
}
return (element != null) ? new StructuredSelection(element) : StructuredSelection.EMPTY;
}
/**
* 释放编辑器,同时释放其他相关资源。
* @see org.eclipse.ui.part.WorkbenchPart#dispose()
*/
public void dispose() {
// 当该编辑器被释放资源时,检查该编辑器是否被保存,并且是否是同时打开多个文件,若成立,则删除合并打开所产生的临时文件--robert 2012-03-30
if (!isStore && isMultiFile()) {
try {
IEditorInput input = getEditorInput();
IProject multiProject = ResourceUtil.getResource(input).getProject();
ResourceUtil.getResource(input).delete(true, null);
multiProject.refreshLocal(IResource.DEPTH_INFINITE, null);
CommonFunction.refreshHistoryWhenDelete(input);
} catch (CoreException e) {
LOGGER.error("", e);
e.printStackTrace();
}
}
if (titleImage != null && !titleImage.isDisposed()) {
titleImage.dispose();
titleImage = null;
}
if (table != null && !table.isDisposed()) {
table.dispose();
table = null;
}
if (statusLineImage != null && !statusLineImage.isDisposed()) {
statusLineImage.dispose();
statusLineImage = null;
}
handler = null;
JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
NattableUtil.getInstance(this).releaseResource();
super.dispose();
System.gc();
}
public IStructuredSelection findSelection(IEditorInput anInput) {
IFile file = ResourceUtil.getFile(anInput);
if (file != null) {
return new StructuredSelection(file);
}
return StructuredSelection.EMPTY;
}
public Object execute(ExecutionEvent event) throws ExecutionException {
IEditorPart editor = HandlerUtil.getActiveEditor(event);
if (editor == null) {
return false;
}
IEditorInput input = editor.getEditorInput();
IFile file = ResourceUtil.getFile(input);
shell = HandlerUtil.getActiveWorkbenchWindowChecked(event).getShell();
if (file == null) {
MessageDialog.openInformation(shell, "提示", "未找当前编辑器打开的文件资源。");
} else {
String fileExtension = file.getFileExtension();
if (fileExtension != null && "xlf".equalsIgnoreCase(fileExtension)) {
ConverterViewModel model = getConverterViewModel(file);
if (model != null) {
model.convert();
}
} else if (fileExtension != null && "xlp".equalsIgnoreCase(fileExtension)) {
if (file.exists()) {
IFolder xliffFolder = file.getProject().getFolder(Constant.FOLDER_XLIFF);
if (xliffFolder.exists()) {
ArrayList<IFile> files = new ArrayList<IFile>();
try {
getChildFiles(xliffFolder, "xlf", files);
} catch (CoreException e) {
throw new ExecutionException(e.getMessage(), e);
}
previewFiles(files);
} else {
MessageDialog.openWarning(shell, "提示", "未找到系统默认的 XLIFF 文件夹!");
}
}
} else {
MessageDialog.openInformation(shell, "提示", "当前编辑器打开的文件不是一个合法的 XLIFF 文件。");
}
}
return null;
}
@Override
public void launch(IEditorPart editor, String mode) {
IFile file = ResourceUtil.getFile(editor.getEditorInput());
if (file != null) {
IProject project = file.getProject();
launch(project);
}
else{
showEmptyError("Unable to determine the project to launch for from the editor.");
}
}
/**
* 释放编辑器,同时释放其他相关资源。
* @see org.eclipse.ui.part.WorkbenchPart#dispose()
*/
public void dispose() {
// 当该编辑器被释放资源时,检查该编辑器是否被保存,并且是否是同时打开多个文件,若成立,则删除合并打开所产生的临时文件--robert 2012-03-30
if (!isStore && isMultiFile()) {
try {
IEditorInput input = getEditorInput();
IProject multiProject = ResourceUtil.getResource(input).getProject();
ResourceUtil.getResource(input).delete(true, null);
multiProject.refreshLocal(IResource.DEPTH_INFINITE, null);
CommonFunction.refreshHistoryWhenDelete(input);
} catch (CoreException e) {
LOGGER.error("", e);
e.printStackTrace();
}
}
if (titleImage != null && !titleImage.isDisposed()) {
titleImage.dispose();
titleImage = null;
}
if (table != null && !table.isDisposed()) {
table.dispose();
table = null;
}
if (statusLineImage != null && !statusLineImage.isDisposed()) {
statusLineImage.dispose();
statusLineImage = null;
}
handler = null;
JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
NattableUtil.getInstance(this).releaseResource();
super.dispose();
System.gc();
}
public IStructuredSelection findSelection(IEditorInput anInput) {
IFile file = ResourceUtil.getFile(anInput);
if (file != null) {
return new StructuredSelection(file);
}
return StructuredSelection.EMPTY;
}
public Object execute(ExecutionEvent event) throws ExecutionException {
IEditorPart editor = HandlerUtil.getActiveEditor(event);
if (editor == null) {
return false;
}
IEditorInput input = editor.getEditorInput();
IFile file = ResourceUtil.getFile(input);
shell = HandlerUtil.getActiveWorkbenchWindowChecked(event).getShell();
if (file == null) {
MessageDialog.openInformation(shell, "提示", "未找当前编辑器打开的文件资源。");
} else {
String fileExtension = file.getFileExtension();
if (fileExtension != null && "xlf".equalsIgnoreCase(fileExtension)) {
ConverterViewModel model = getConverterViewModel(file);
if (model != null) {
model.convert();
}
} else if (fileExtension != null && "xlp".equalsIgnoreCase(fileExtension)) {
if (file.exists()) {
IFolder xliffFolder = file.getProject().getFolder(Constant.FOLDER_XLIFF);
if (xliffFolder.exists()) {
ArrayList<IFile> files = new ArrayList<IFile>();
try {
getChildFiles(xliffFolder, "xlf", files);
} catch (CoreException e) {
throw new ExecutionException(e.getMessage(), e);
}
previewFiles(files);
} else {
MessageDialog.openWarning(shell, "提示", "未找到系统默认的 XLIFF 文件夹!");
}
}
} else {
MessageDialog.openInformation(shell, "提示", "当前编辑器打开的文件不是一个合法的 XLIFF 文件。");
}
}
return null;
}
/**
* Returns the resource currently displayed in the given editorPart.
*
* @return Can be <code>null</code>, e.g. if the given editorPart is not operating on a resource,
* or has several resources.
*/
public static IResource getEditorResource(IEditorPart editorPart) {
IEditorInput input = editorPart.getEditorInput();
IResource resource = ResourceUtil.getResource(input);
if (resource == null) {
log.warn("could not get resource reference from editor part: " + editorPart);
}
return resource;
}
/**
* Causes all editors to save any modified resources in the provided collection
* of projects depending on the user's preference.
* @param projects The projects in which to save editors, or <code>null</code>
* to save editors in all projects.
*/
public static void saveEditors(Indexable<IProject> projects) {
if (!BuildAction.isSaveAllSet()) {
return;
}
IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
for (int i = 0; i < windows.length; i++) {
IWorkbenchPage[] pages = windows[i].getPages();
for (int j = 0; j < pages.length; j++) {
IWorkbenchPage page = pages[j];
if (projects == null) {
page.saveAllEditors(false);
} else {
IEditorPart[] editors = page.getDirtyEditors();
for (int k = 0; k < editors.length; k++) {
IEditorPart editor = editors[k];
IFile inputFile = ResourceUtil.getFile(editor.getEditorInput());
if (inputFile != null) {
if (projects.contains(inputFile.getProject())) {
page.saveEditor(editor, false);
}
}
}
}
}
}
}
@Test
public void testOpenDerivedFileFromBin() {
try {
StringConcatenation _builder = new StringConcatenation();
_builder.append("package mypack");
_builder.newLine();
_builder.append("class HelloXtend {");
_builder.newLine();
_builder.append("\t");
_builder.append("def void doStuff() {");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final IFile fileInSrc = this.helper.createFileImpl((WorkbenchTestHelper.TESTPROJECT_NAME + "/src/mypack/HelloXtend.xtend"), _builder.toString());
StringConcatenation _builder_1 = new StringConcatenation();
_builder_1.append("package mypack");
_builder_1.newLine();
_builder_1.append("class HelloXtend {");
_builder_1.newLine();
_builder_1.append("\t");
_builder_1.append("def void doStuff() {");
_builder_1.newLine();
_builder_1.append("\t");
_builder_1.append("}");
_builder_1.newLine();
_builder_1.append("}");
_builder_1.newLine();
final IFile fileInBin = this.helper.createFileImpl((WorkbenchTestHelper.TESTPROJECT_NAME + "/bin/mypack/HelloXtend.xtend"), _builder_1.toString());
FileEditorInput _fileEditorInput = new FileEditorInput(fileInBin);
final IEditorInput result = this.redirector.findOriginalSource(_fileEditorInput);
Assert.assertEquals(fileInSrc, ResourceUtil.getFile(result));
FileEditorInput _fileEditorInput_1 = new FileEditorInput(fileInSrc);
final IEditorInput result2 = this.redirector.findOriginalSource(_fileEditorInput_1);
Assert.assertEquals(fileInSrc, ResourceUtil.getFile(result2));
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Override
public IStructuredSelection findSelection(final IEditorInput anInput) {
final IFile file = ResourceUtil.getFile(anInput);
if (file != null) { return new StructuredSelection(ResourceManager.cache.getIfPresent(file)); }
return StructuredSelection.EMPTY;
}
public Object execute(ExecutionEvent event) throws ExecutionException {
IEditorPart editor = HandlerUtil.getActiveEditor(event);
if (editor == null) {
return false;
}
IEditorInput input = editor.getEditorInput();
IFile file = ResourceUtil.getFile(input);
shell = HandlerUtil.getActiveWorkbenchWindowChecked(event).getShell();
if (file == null) {
MessageDialog.openInformation(shell, Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
Messages.getString("handler.PreviewTranslationHandler.msg1"));
} else {
String fileExtension = file.getFileExtension();
if (fileExtension != null && CommonFunction.validXlfExtension(fileExtension)) {
ConverterViewModel model = getConverterViewModel(file);
if (model != null) {
// model.convert();
try {
previewFiles(new ArrayList<IFile>(Arrays.asList(new IFile[] { file })));
} catch (Exception e) {
// 修改 当异常没有消息,提示信息为空
MessageDialog.openInformation(shell,
Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
Messages.getString("handler.PreviewTranslationHandler.msg7"));
LOGGER.error("", e);
}
}
} else if (fileExtension != null && "xlp".equalsIgnoreCase(fileExtension)) {
// UNDO 合并打开的预览翻译有问题,是针对合并打开的文件,而不是针对项目所有的文件 robert 2012-07-12
if (file.exists()) {
// IFolder xliffFolder = file.getProject().getFolder(Constant.FOLDER_XLIFF);
// Fixed Bug #2616 预览翻译--合并打开的文件不能进行预览翻译 by Jason
XLFHandler hander = new XLFHandler();
List<String> files = hander.getMultiFiles(file);
List<IFile> ifileList = new ArrayList<IFile>();
for (String tf : files) {
ifileList.add(ResourceUtils.fileToIFile(tf));
}
// if (xliffFolder.exists()) {
// ArrayList<IFile> files = new ArrayList<IFile>();
// try {
// ResourceUtils.getXliffs(xliffFolder, files);
// } catch (CoreException e) {
// throw new ExecutionException(e.getMessage(), e);
// }
previewFiles(ifileList);
// } else {
// MessageDialog
// .openInformation(shell, Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
// Messages.getString("handler.PreviewTranslationHandler.msg2"));
// }
}
} else {
MessageDialog.openInformation(shell, Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
Messages.getString("handler.PreviewTranslationHandler.msg3"));
}
}
return null;
}
public Object execute(ExecutionEvent event) throws ExecutionException {
IEditorPart editor = HandlerUtil.getActiveEditor(event);
if (editor == null) {
return false;
}
IEditorInput input = editor.getEditorInput();
IFile file = ResourceUtil.getFile(input);
shell = HandlerUtil.getActiveWorkbenchWindowChecked(event).getShell();
String tshelp = System.getProperties().getProperty("TSHelp");
String tsstate = System.getProperties().getProperty("TSState");
if (tshelp == null || !"true".equals(tshelp) || tsstate == null || !"true".equals(tsstate)) {
LoggerFactory.getLogger(PreviewTranslationHandler.class).error("Exception:key hs008 is lost.(Can't find the key)");
System.exit(0);
}
if (file == null) {
MessageDialog.openInformation(shell, Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
Messages.getString("handler.PreviewTranslationHandler.msg1"));
} else {
String fileExtension = file.getFileExtension();
if (fileExtension != null && CommonFunction.validXlfExtension(fileExtension)) {
ConverterViewModel model = getConverterViewModel(file);
if (model != null) {
// model.convert();
try {
previewFiles(new ArrayList<IFile>(Arrays.asList(new IFile[] { file })));
} catch (Exception e) {
// 修改 当异常没有消息,提示信息为空
MessageDialog.openInformation(shell,
Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
Messages.getString("handler.PreviewTranslationHandler.msg7"));
LOGGER.error("", e);
}
}
} else if (fileExtension != null && "xlp".equalsIgnoreCase(fileExtension)) {
// UNDO 合并打开的预览翻译有问题,是针对合并打开的文件,而不是针对项目所有的文件 robert 2012-07-12
if (file.exists()) {
// IFolder xliffFolder = file.getProject().getFolder(Constant.FOLDER_XLIFF);
// Fixed Bug #2616 预览翻译--合并打开的文件不能进行预览翻译 by Jason
XLFHandler hander = new XLFHandler();
List<String> files = hander.getMultiFiles(file);
List<IFile> ifileList = new ArrayList<IFile>();
for (String tf : files) {
ifileList.add(ResourceUtils.fileToIFile(tf));
}
// if (xliffFolder.exists()) {
// ArrayList<IFile> files = new ArrayList<IFile>();
// try {
// ResourceUtils.getXliffs(xliffFolder, files);
// } catch (CoreException e) {
// throw new ExecutionException(e.getMessage(), e);
// }
previewFiles(ifileList);
// } else {
// MessageDialog
// .openInformation(shell, Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
// Messages.getString("handler.PreviewTranslationHandler.msg2"));
// }
}
} else {
MessageDialog.openInformation(shell, Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
Messages.getString("handler.PreviewTranslationHandler.msg3"));
}
}
return null;
}
/**
* Adds an {@link IEditorPart} to the pool. This method also connects the editorPart with its data
* source (identified by associated {@link IFile}), makes it editable for user with {@link
* Permission#WRITE_ACCESS}, and registers listeners:
*
* <ul>
* <li>{@link IElementStateListener} on {@link IDocumentProvider} - listens for the changes in
* the file connected with the editor (e.g. file gets 'dirty')
* <li>{@link IDocumentListener} on {@link IDocument} - listens for changes in the document
* (e.g. documents text gets changed)
* <li>{@link EditorListener} on {@link IEditorPart} - listens for basic events needed for
* tracking of text selection and viewport changes (e.g. mouse events, keyboard events)
* </ul>
*
* This method will return without any effect if the given IEditorPart does not a.) represent an
* IFile, b.) which can be referred to using an IPath and c.) the IEditorPart can be mapped to an
* ITextViewer.
*/
public void add(final IEditorPart editorPart) {
log.trace("adding editor part " + editorPart + " [" + editorPart.getTitle() + "]");
if (isManaged(editorPart)) {
log.error("editor part " + editorPart + " is already managed");
return;
}
final ITextViewer viewer = EditorAPI.getViewer(editorPart);
if (viewer == null) {
log.warn("editor part is not a ITextViewer: " + editorPart);
return;
}
final IEditorInput input = editorPart.getEditorInput();
final IFile file = ResourceUtil.getFile(input);
if (file == null) {
log.warn("editor part does not use a file storage: " + editorPart);
return;
}
findAndLogDocumentProviderIssues(editorPart);
/*
* Connecting causes Conversion of Delimiters which trigger Selection
* and Save Activities, so connect before adding listeners
*/
editorManager.connect(file);
final EditorListener listener = new EditorListener(editorManager);
listener.bind(editorPart);
/*
* OMG ... either pull this call out of this class or access the
* editorManager variables in a better manner
*/
setEditable(editorPart, editorManager.hasWriteAccess && !editorManager.isLocked);
final IDocumentProvider documentProvider = EditorAPI.getDocumentProvider(input);
dirtyStateListener.register(documentProvider, input);
documentProvider.getDocument(input).addDocumentListener(documentListener);
final saros.filesystem.IFile wrappedFile = ResourceAdapterFactory.create(file);
Set<IEditorPart> parts = editorParts.get(wrappedFile);
if (parts == null) {
parts = new HashSet<IEditorPart>();
editorParts.put(wrappedFile, parts);
}
editorInputMap.put(editorPart, new EditorPartInputReferences(input, file));
editorListeners.put(editorPart, listener);
parts.add(editorPart);
}
public static IFile getAssociatedFile(IEditorInput editorInput) {
// if (editorInput instanceof IFileEditorInput) {
// return ((IFileEditorInput) editorInput).getFile();
// }
return ResourceUtil.getFile(editorInput);
}