下面列出了怎么用org.eclipse.ui.IEditorReference的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void activateEditor(IWorkbenchPage page, IStructuredSelection selection) {
if (!(selection.getFirstElement() instanceof ModelElement))
return;
ModelElement element = (ModelElement) selection.getFirstElement();
for (IEditorReference ref : Editors.getReferences()) {
try {
if (!(ref.getEditorInput() instanceof ModelEditorInput))
continue;
ModelEditorInput input = (ModelEditorInput) ref.getEditorInput();
if (element.getContent().equals(input.getDescriptor())) {
App.openEditor(element.getContent());
}
} catch (PartInitException e) {
var log = LoggerFactory.getLogger(getClass());
log.error("Error activating editor", e);
}
}
}
/**
* Obtains all editors that are currently opened.
* @return the collection of the opened editors
*/
public static List<IEditorPart> getEditors() {
List<IEditorPart> editors = new ArrayList<IEditorPart>();
IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
for (IWorkbenchWindow window : windows) {
IWorkbenchPage[] pages = window.getPages();
for (IWorkbenchPage page : pages) {
IEditorReference[] refs = page.getEditorReferences();
for (IEditorReference ref : refs) {
IEditorPart part = ref.getEditor(false);
if (part != null) {
editors.add(part);
}
}
}
}
return editors;
}
/**
* hide open dashboards
*/
private void hideDashboards() {
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
try {
IWorkbenchPage page = window.getActivePage();
List<IEditorReference> openEditors = new ArrayList<IEditorReference>();
IEditorReference[] editorReferences = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.getEditorReferences();
for (IEditorReference iEditorReference : editorReferences) {
if (DASHBOARD_VIEW_ID.equals(iEditorReference.getId())) {
openEditors.add(iEditorReference);
}
}
if (openEditors.size() > 0) {
page.closeEditors(openEditors.toArray(new IEditorReference[] {}), false);
}
} catch (Exception e) {
MessageDialog.openError(window.getShell(), "Could not hide dashboards for perspective", e.getMessage());
}
}
private static LSPDocumentInfo infoFromOpenEditors() {
for (IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows()) {
for (IWorkbenchPage page : window.getPages()) {
for (IEditorReference editor : page.getEditorReferences()) {
IEditorInput input;
try {
input = editor.getEditorInput();
} catch (PartInitException e) {
continue;
}
if (input.getName().endsWith(".rs") && editor.getEditor(false) instanceof ITextEditor) { //$NON-NLS-1$
IDocument document = (((ITextEditor) editor.getEditor(false)).getDocumentProvider())
.getDocument(input);
Collection<LSPDocumentInfo> infos = LanguageServiceAccessor.getLSPDocumentInfosFor(document,
capabilities -> Boolean.TRUE.equals(capabilities.getReferencesProvider()));
if (!infos.isEmpty()) {
return infos.iterator().next();
}
}
}
}
}
return null;
}
protected ExportBosArchiveOperation createExportBOSOperation() {
final ExportBosArchiveOperation operation = new ExportBosArchiveOperation();
operation.setDestinationPath(getDetinationPath());
operation.setFileStores(getSelectedFileStores());
operation.addResources(getSelectedResoureContainer());
try {
final Set<IResource> toOpen = new HashSet<>();
for (final IEditorReference ref : PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.getEditorReferences()) {
final IFile file = (IFile) EditorUtil.retrieveResourceFromEditorInput(ref.getEditorInput());
if (operation.getResources().contains(file)) {
toOpen.add(file);
}
}
operation.setResourcesToOpen(toOpen);
} catch (final Exception e) {
BonitaStudioLog.error(e);
}
return operation;
}
/**
* When services connection is renamed, refresh the connection label in the component view of job.
*
* @param item
*/
@Override
public void refreshComponentView(Item item) {
try {
IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
IEditorReference[] editors = activePage.getEditorReferences();
for (IEditorReference er : editors) {
IEditorPart part = er.getEditor(false);
if (part instanceof AbstractMultiPageTalendEditor) {
AbstractMultiPageTalendEditor editor = (AbstractMultiPageTalendEditor) part;
CommandStack stack = (CommandStack) editor.getTalendEditor().getAdapter(CommandStack.class);
if (stack != null) {
IProcess process = editor.getProcess();
for (final INode processNode : process.getGraphicalNodes()) {
if (processNode instanceof Node) {
checkRepository((Node) processNode, item, stack);
}
}
}
}
}
} catch (Exception e) {
ExceptionHandler.process(e);
}
}
public static ManifestMultiPageEditor getManifestEditor(IDominoDesignerProject project) {
for (IEditorReference ref : PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getEditorReferences()) {
try {
if (ref.getEditorInput() instanceof BluemixManifestEditorInput) {
if (((BluemixManifestEditorInput)ref.getEditorInput()).getDesignerProject() == project) {
return (ManifestMultiPageEditor) ref.getEditor(false);
}
}
} catch (PartInitException e) {
if (BluemixLogger.BLUEMIX_LOGGER.isErrorEnabled()) {
BluemixLogger.BLUEMIX_LOGGER.errorp(BluemixUtil.class, "getManifestEditor", e, "Failed to get manifest editor"); // $NON-NLS-1$ $NLE-BluemixUtil.Failedtogetmanifesteditor-2$
}
}
}
return null;
}
/**
* @return
*/
private ProcessDiagramEditor getTheOnlyOneEditor() {
IEditorPart editor;
ProcessDiagramEditor processEditor;
final IEditorReference[] editorReferences = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.getEditorReferences();
final StringBuilder sb = new StringBuilder();
for (final IEditorReference iEditorReference : editorReferences) {
sb.append(iEditorReference);
}
assertEquals("There should be only be 1 editor after save. But there are:\n" + sb.toString(),
1,
editorReferences.length);
editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
assertTrue(editor instanceof ProcessDiagramEditor);
processEditor = (ProcessDiagramEditor) editor;
return processEditor;
}
/**
* Finds an editor and sets focus to the editor
*
* @param bot
* the workbench bot
* @param editorName
* the editor name
* @return the corresponding SWTBotEditor
*/
public static SWTBotEditor activateEditor(SWTWorkbenchBot bot, String editorName) {
Matcher<IEditorReference> matcher = WidgetMatcherFactory.withPartName(editorName);
final SWTBotEditor editorBot = bot.editor(matcher);
IEditorPart iep = editorBot.getReference().getEditor(true);
final TmfEventsEditor tmfEd = (TmfEventsEditor) iep;
editorBot.show();
UIThreadRunnable.syncExec(new VoidResult() {
@Override
public void run() {
tmfEd.setFocus();
}
});
WaitUtils.waitForJobs();
activeEventsEditor(bot);
assertNotNull(tmfEd);
return editorBot;
}
/**
*
* @param fileName
* the fileName
* @return the editor with the given fileName, or null if not found.
*/
public static IEditorPart findOpenedEditor( String fileName )
{
IWorkbenchPage page = PlatformUI.getWorkbench( )
.getActiveWorkbenchWindow( )
.getActivePage( );
IEditorReference[] editors = page.getEditorReferences( );
for ( int i = 0; i < editors.length; i++ )
{
IEditorPart part = editors[i].getEditor( true );
IPath location = ( (IPathEditorInput) part.getEditorInput( ) ).getPath( );
if ( fileName.equalsIgnoreCase( location.toOSString( ) ) )
{
return part;
}
}
return null;
}
private static void getOpenedFileInProject( IProject project,
List<IEditorPart> openedEditorRefs,
List<IEditorPart> openedDirtyEditorRefs )
{
IEditorReference[] editors = getOpenedFileRefs( );
for ( int i = 0; i < editors.length; i++ )
{
IFile file = getEditorFile( editors[i] );
if ( ( file != null )
&& ( file.getProject( ) != null )
&& file.getProject( ).equals( project ) )
{
checkAndAddToEditorLists( openedEditorRefs,
openedDirtyEditorRefs,
editors[i] );
}
}
}
private static void checkOpenResources( List<IResource> itemsToCheck,
List<IEditorPart> openedEditorRefs,
List<IEditorPart> openedDirtyEditorRefs ) throws CoreException
{
for ( IResource resourceToCheck : itemsToCheck )
{
switch ( resourceToCheck.getType( ) )
{
case IResource.FILE :
IEditorReference fileRef = getEditorRefInOpenFileList( (IFile) resourceToCheck );
checkAndAddToEditorLists( openedEditorRefs,
openedDirtyEditorRefs,
fileRef );
break;
case IResource.PROJECT :
getOpenedFileInProject( (IProject) resourceToCheck,
openedEditorRefs,
openedDirtyEditorRefs );
break;
default :
checkOpenResources( Arrays.asList( ( (IContainer) resourceToCheck ).members( ) ),
openedEditorRefs,
openedDirtyEditorRefs );
}
}
}
private static IFile getEditorFile( IEditorReference fileRef )
{
if ( fileRef != null )
{
IEditorPart part = (IEditorPart) fileRef.getPart( false );
if ( part != null )
{
IEditorInput input = part.getEditorInput( );
if ( input != null && input instanceof IFileEditorInput )
{
return ( (IFileEditorInput) input ).getFile( );
}
}
}
return null;
}
public static void reopenWithGWTJavaEditor(IEditorReference[] openEditors) {
IWorkbenchPage page = JavaPlugin.getActivePage();
for (IEditorReference editorRef : openEditors) {
try {
IEditorPart editor = editorRef.getEditor(false);
IEditorInput input = editorRef.getEditorInput();
// Close the editor, prompting the user to save if document is dirty
if (page.closeEditor(editor, true)) {
// Re-open the .java file in the GWT Java Editor
IEditorPart gwtEditor = page.openEditor(input, GWTJavaEditor.EDITOR_ID);
// Save the file from the new editor if the Java editor's
// auto-format-on-save action screwed up the JSNI formatting
gwtEditor.doSave(null);
}
} catch (PartInitException e) {
GWTPluginLog.logError(e, "Could not open GWT Java editor on {0}", editorRef.getTitleToolTip());
}
}
}
private static void checkAndAddToEditorLists(
List<IEditorPart> openedEditorRefs,
List<IEditorPart> openedDirtyEditorRefs, IEditorReference fileRef )
{
if ( fileRef != null )
{
IEditorPart part = (IEditorPart) fileRef.getPart( false );
if ( part != null )
{
if ( part.isDirty( ) )
{
openedDirtyEditorRefs.add( part );
}
openedEditorRefs.add( part );
}
}
}
/**
* Tries to find opened editors matching given resource roots. The editors will be closed without confirmation and
* only if the editor resource does not exists anymore.
*
* @param resourceRoots
* non null array with deleted resource tree roots
* @param deletedOnly
* true to close only editors on resources which do not exist
*/
static void closeMatchingEditors(final List<? extends IResource> resourceRoots, final boolean deletedOnly) {
if (resourceRoots.isEmpty()) { return; }
final Runnable runnable = () -> SafeRunner.run(new SafeRunnable(IDEWorkbenchMessages.ErrorOnCloseEditors) {
@Override
public void run() {
final IWorkbenchWindow w = getActiveWindow();
if (w != null) {
final List<IEditorReference> toClose = getMatchingEditors(resourceRoots, w, deletedOnly);
if (toClose.isEmpty()) { return; }
closeEditors(toClose, w);
}
}
});
BusyIndicator.showWhile(PlatformUI.getWorkbench().getDisplay(), runnable);
}
static List<IEditorReference> getMatchingEditors(final List<? extends IResource> resourceRoots,
final IWorkbenchWindow w, final boolean deletedOnly) {
final List<IEditorReference> toClose = new ArrayList<>();
final IEditorReference[] editors = getEditors(w);
for (final IEditorReference ref : editors) {
final IResource resource = getAdapter(ref);
// only collect editors for non existing resources
if (resource != null && belongsTo(resourceRoots, resource)) {
if (deletedOnly && resource.exists()) {
continue;
}
toClose.add(ref);
}
}
return toClose;
}
public void partActivated(IWorkbenchPartReference partRef)
{
if (partRef instanceof IViewReference)
{
IViewReference viewRef = (IViewReference) partRef;
String id = viewRef.getId();
if ("org.eclipse.ui.console.ConsoleView".equals(id) || "org.eclipse.jdt.ui.TypeHierarchy".equals(id) //$NON-NLS-1$ //$NON-NLS-2$
|| "org.eclipse.jdt.callhierarchy.view".equals(id)) //$NON-NLS-1$
{
final IViewPart part = viewRef.getView(false);
Display.getCurrent().asyncExec(new Runnable()
{
public void run()
{
hijackView(part, false);
}
});
return;
}
}
if (partRef instanceof IEditorReference)
{
hijackOutline();
}
}
/**
* Most SVN workspace actions modify the workspace and thus should
* save dirty editors.
* @see org.tigris.subversion.subclipse.ui.actions.SVNAction#needsToSaveDirtyEditors()
*/
protected boolean needsToSaveDirtyEditors() {
IResource[] selectedResources = getSelectedResources();
if (selectedResources != null && selectedResources.length > 0) {
IEditorReference[] editorReferences = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getEditorReferences();
for (IEditorReference editorReference : editorReferences) {
if (editorReference.isDirty()) {
try {
IEditorInput editorInput = editorReference.getEditorInput();
if (editorInput instanceof IFileEditorInput) {
IFile file = ((IFileEditorInput)editorInput).getFile();
if (needsToSave(file, selectedResources)) {
return true;
}
}
} catch (PartInitException e) {}
}
}
}
return false;
}
protected void cleanupWorkbench(IFile targetFile, IWorkbenchPage page) throws CoreException {
if (targetFile.exists()) {
IEditorReference[] refs = page.getEditorReferences();
for (IEditorReference ref : refs) {
IEditorPart part = ref.getEditor(false);
if (part != null) {
IEditorInput inp = part.getEditorInput();
if (inp instanceof FileEditorInput) {
if (((FileEditorInput) inp).getFile().equals(targetFile)) {
page.closeEditor(ref.getEditor(false), true);
}
}
}
}
}
}
private Control createBufferTip(Composite parent, IEditorReference ref) {
Composite result = new Composite(parent, SWT.NO_FOCUS);
Color bg = parent.getBackground();
result.setBackground(bg);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 1;
result.setLayout(gridLayout);
StyledText name = new StyledText(result, SWT.READ_ONLY | SWT.HIDE_SELECTION);
// italics results in slightly clipped text unless extended
String text = ref.getTitleToolTip() + ' ';
name.setText(text);
name.setBackground(bg);
name.setCaret(null);
StyleRange styleIt = new StyleRange(0, text.length(), null, bg);
styleIt.fontStyle = SWT.ITALIC;
name.setStyleRange(styleIt);
return result;
}
/**
* Returns the file behind the referenced workbench part.
*
* @param partRef
* the workbench part in question
* @return the editors file or <code>null</code> if the workbench part is no file based editor
*/
private IFile getEditorFile(IWorkbenchPartReference partRef) {
if (!(partRef instanceof IEditorReference)) {
return null;
}
IFile file = null;
IWorkbenchPart part = partRef.getPart(false); // fix for 3522695
// do *NOT* restore the part here to prevent startup issues with large
// number of opened files
// instead use a different path the rip the input file reference
IEditorInput input = null;
if (part != null && part instanceof IEditorPart) {
IEditorPart editor = (IEditorPart) part;
input = editor.getEditorInput();
} else {
// fix for 3522695 - rip input file from editor ref without initializing
// the actual part
IEditorReference editRef = (IEditorReference) partRef;
input = getRestoredInput(editRef);
}
if (input instanceof FileEditorInput) {
file = ((FileEditorInput) input).getFile();
}
return file;
}
private IEditorInput getRestoredInput(IEditorReference e) {
IMemento editorMem = null;
if (CheckstyleUIPlugin.isE3()) {
editorMem = getMementoE3(e);
} else {
editorMem = getMementoE4(e);
}
if (editorMem == null) {
return null;
}
IMemento inputMem = editorMem.getChild(IWorkbenchConstants.TAG_INPUT);
String factoryID = null;
if (inputMem != null) {
factoryID = inputMem.getString(IWorkbenchConstants.TAG_FACTORY_ID);
}
if (factoryID == null) {
return null;
}
IAdaptable input = null;
IElementFactory factory = PlatformUI.getWorkbench().getElementFactory(factoryID);
if (factory == null) {
return null;
}
input = factory.createElement(inputMem);
if (input == null) {
return null;
}
if (!(input instanceof IEditorInput)) {
return null;
}
return (IEditorInput) input;
}
public static void swtichToOpenedEditor(final IEditorReference openEditor) {
if (isIntroOpen()) {
closeIntro();
}
PlatformUI.getWorkbench().getActiveWorkbenchWindow().setActivePage(openEditor.getPage());
try {
openEditor.getPage().openEditor(openEditor.getEditorInput(), openEditor.getId());
} catch (final PartInitException e) {
e.printStackTrace();
}
}
/**
* Tries to open an Eclipse editor given the specified input and the ID of
* the editor.
*
* @param input
* The editor's input.
* @param id
* The Eclipse editor's ID as defined in the plug-in extensions.
* @return The opened editor, or {@code null} if it could not be opened.
*/
protected IEditorReference openEditor(final IEditorInput input,
final String id) {
final AtomicReference<IEditorReference> editorRef = new AtomicReference<IEditorReference>();
// This must be done on the UI thread. Use syncExec so that this method
// will block until the editor can be opened.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
// Get the workbench window so we can open an editor.
IWorkbenchWindow window = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();
// Try to open the editor in the workbench.
try {
// IEditorPart editor = page.openEditor(input, id);
IEditorReference[] refs = page.openEditors(
new IEditorInput[] { input }, new String[] { id },
IWorkbenchPage.MATCH_NONE);
if (refs.length > 0) {
editorRef.set(refs[0]);
}
} catch (MultiPartInitException e) {
// Nothing to do.
}
return;
}
});
return editorRef.get();
}
/**
* Updates the image of the passed editor.
*/
private void updateImage(PyEdit pyEdit, IEditorReference iEditorReference, IPath path) {
String lastSegment = path.lastSegment();
if (lastSegment != null) {
if (lastSegment.startsWith("__init__.")) {
Image initIcon = ImageCache.asImage(PyTitlePreferencesPage.getInitIcon());
if (initIcon != null) {
if (pyEdit != null) {
pyEdit.setEditorImage(initIcon);
} else {
setEditorReferenceImage(iEditorReference, initIcon);
}
}
} else if (PyTitlePreferencesPage.isDjangoModuleToDecorate(lastSegment)) {
try {
IEditorInput editorInput;
if (pyEdit != null) {
editorInput = pyEdit.getEditorInput();
} else {
editorInput = iEditorReference.getEditorInput();
}
if (isDjangoHandledModule(PyTitlePreferencesPage.getDjangoModulesHandling(), editorInput,
lastSegment)) {
Image image = ImageCache.asImage(PyTitlePreferencesPage.getDjangoModuleIcon(lastSegment));
if (pyEdit != null) {
pyEdit.setEditorImage(image);
} else {
setEditorReferenceImage(iEditorReference, image);
}
}
} catch (PartInitException e) {
//ignore
}
}
}
}
/** {@inheritDoc} */
public boolean matches(final Object item) {
if (item instanceof IEditorReference) {
IEditorReference ref = (IEditorReference) item;
regExMatcher.reset(ref.getName());
if (regExMatcher.matches()) {
return true;
}
}
return false;
}
/**
* Close all duplicates when joining after one or more split commands
*
* @param page
* @throws PartInitException
*/
public static boolean closeAllDuplicates(IWorkbenchPage page) throws PartInitException {
boolean closed = false;
if (page != null) {
IEditorReference[] refs = page.getEditorReferences();
closed = closeDuplicates(page, refs);
}
return closed;
}
/**
* Retrieves the list of resources opened in editor
*
* @return an array of paths of opened resources
*/
public static String[] getOpenedResources() {
IEditorReference[] references = getActivePage().getEditorReferences();
String[] openedResources = new String[references.length];
for (int i = 0; i < references.length; i++) {
openedResources[i] = references[i].getContentDescription();
}
return openedResources;
}
/**
* Verify that the editor in the location is still in use
*
* @param location
* @return true if editor is valid
*/
private boolean checkEditor(IBufferLocation location) {
boolean result = false;
if (location != null) {
ITextEditor editor = location.getEditor();
if (editor != null) {
IEditorInput input = editor.getEditorInput();
// check all the editor references that match the input for a match
IEditorReference[] refs = EmacsPlusUtils.getWorkbenchPage().findEditors(input,null, IWorkbenchPage.MATCH_INPUT);
for (int i=0; i< refs.length; i++) {
IEditorPart ed = refs[i].getEditor(false);
// multi page annoyance
if (ed instanceof MultiPageEditorPart) {
IEditorPart[] eds = ((MultiPageEditorPart)ed).findEditors(input);
for (int j=0; j < eds.length; j++) {
if (eds[i] == editor) {
result = true;
break;
}
}
if (result) {
break;
}
} else {
if (ed == editor) {
result = true;
break;
}
}
}
}
}
return result;
}