org.eclipse.ui.ide.IDE Java Examples

The following examples show how to use org.eclipse.ui.ide.IDE. 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: EditorOpener.java    From typescript.java with MIT License 8 votes vote down vote up
public IEditorPart openAndSelect(IWorkbenchPage wbPage, IFile file, int offset, int length, boolean activate) throws PartInitException {
	String editorId= null;
	IEditorDescriptor desc= IDE.getEditorDescriptor(file);
	if (desc == null || !desc.isInternal()) {
		editorId= "org.eclipse.ui.DefaultTextEditor"; //$NON-NLS-1$
	} else {
		editorId= desc.getId();
	}

	IEditorPart editor;
	if (NewSearchUI.reuseEditor()) {
		editor= showWithReuse(file, wbPage, editorId, activate);
	} else {
		editor= showWithoutReuse(file, wbPage, editorId, activate);
	}

	if (editor instanceof ITextEditor) {
		ITextEditor textEditor= (ITextEditor) editor;
		textEditor.selectAndReveal(offset, length);
	} else if (editor != null) {
		showWithMarker(editor, file, offset, length);
	}
	return editor;
}
 
Example #2
Source File: XMLAnalysesManagerPreferencePage.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Edit analysis file(s) with built-in editor.
 */
private void editAnalysis() {
    Map<@NonNull String, @NonNull File> listFiles = XmlUtils.listFiles();
    for (TableItem item : fAnalysesTable.getSelection()) {
        String selection = XmlUtils.createXmlFileString(item.getText());
        @Nullable File file = listFiles.get(selection);
        if (file == null) {
            Activator.logError(NLS.bind(Messages.ManageXMLAnalysisDialog_FailedToEdit, selection));
            TraceUtils.displayErrorMsg(NLS.bind(Messages.ManageXMLAnalysisDialog_FailedToEdit, selection), NLS.bind(Messages.ManageXMLAnalysisDialog_FailedToEdit, selection));
            return;
        }
        try {
            IEditorPart editorPart = IDE.openEditorOnFileStore(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), EFS.getStore(file.toURI()));
            // Remove listener first in case the editor was already opened
            editorPart.removePropertyListener(SAVE_EDITOR_LISTENER);
            editorPart.addPropertyListener(SAVE_EDITOR_LISTENER);
        } catch (CoreException e) {
            Activator.logError(NLS.bind(Messages.ManageXMLAnalysisDialog_FailedToEdit, selection));
            TraceUtils.displayErrorMsg(NLS.bind(Messages.ManageXMLAnalysisDialog_FailedToEdit, selection), e.getMessage());
        }
    }
}
 
Example #3
Source File: TestXML.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDTDFile() throws Exception {
	final IFile file = project.getFile("blah.dtd");
	file.create(new ByteArrayInputStream("FAIL".getBytes()), true, null);
	ITextEditor editor = (ITextEditor) IDE
			.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file);
	editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("<!--<!-- -->");
	assertTrue("Diagnostic not published", new DisplayHelper() {
		@Override
		protected boolean condition() {
			try {
				return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0;
			} catch (CoreException e) {
				return false;
			}
		}
	}.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000));
}
 
Example #4
Source File: FileOpener.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static IEditorPart openFileInFileSystem(final URI uri) throws PartInitException {
	if (uri == null) { return null; }
	IFileStore fileStore;
	try {
		fileStore = EFS.getLocalFileSystem().getStore(Path.fromOSString(uri.toFileString()));
	} catch (final Exception e1) {
		MessageDialog.openWarning(WorkbenchHelper.getShell(), "No file found",
				"The file'" + uri.toString() + "' cannot be found.");
		return null;
	}
	IFileInfo info;
	try {
		info = fileStore.fetchInfo();
	} catch (final Exception e) {
		MessageDialog.openWarning(WorkbenchHelper.getShell(), "No file found",
				"The file'" + uri.toString() + "' cannot be found.");
		return null;
	}
	if (!info.exists()) {
		MessageDialog.openWarning(WorkbenchHelper.getShell(), "No file found",
				"The file'" + uri.toString() + "' cannot be found.");
	}
	return IDE.openInternalEditorOnFileStore(PAGE, fileStore);
}
 
Example #5
Source File: XdsConsoleLink.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
public void gotoLink(boolean activateEditor) {
    try {
        IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        if (marker != null) {
            if (marker.exists()) {
                IDE.openEditor(page, marker, activateEditor);
            }
        } else {
        	// LSA80 : ������ �������? ����� � ������ �� ��������� ������ �� core-��� ������� �������, 
        	// ����� � ������� ����� ����������, �� ����� ��� ����������.
            page.showView("org.eclipse.ui.views.ProblemView", null, IWorkbenchPage.VIEW_ACTIVATE); 
        }
    }
    catch (Exception e) { // hz (NPE, PartInitException...)
        e.printStackTrace();
    }
}
 
Example #6
Source File: CloseResourceAction.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Validates the operation against the model providers.
 *
 * @return whether the operation should proceed
 */
private boolean validateClose() {
	final IResourceChangeDescriptionFactory factory = ResourceChangeValidator.getValidator().createDeltaFactory();
	final List<? extends IResource> resources = getActionResources();
	for (final IResource resource : resources) {
		if (resource instanceof IProject) {
			final IProject project = (IProject) resource;
			factory.close(project);
		}
	}
	String message;
	if (resources.size() == 1) {
		message = NLS.bind(IDEWorkbenchMessages.CloseResourceAction_warningForOne, resources.get(0).getName());
	} else {
		message = IDEWorkbenchMessages.CloseResourceAction_warningForMultiple;
	}
	return IDE.promptToConfirm(WorkbenchHelper.getShell(), IDEWorkbenchMessages.CloseResourceAction_confirm,
			message, factory.getDelta(), getModelProviderIds(), false /* no need to syncExec */);
}
 
Example #7
Source File: OpenDeclarations.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void openSingleFileAtLineNumber(final String relativeFilename, final int lineNumber) {
	final IPath path = new Path(relativeFilename).removeFirstSegments(1); // strip off project
	Display.getDefault().asyncExec(() -> {
		try {
			IFile file = project.getFile(path);
			IMarker marker = file.createMarker(IMarker.TEXT);
			marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
			IDE.openEditor(EclipseMessageUtils.getWorkbenchPage(), marker);
			EclipseMessageUtils.getWorkbenchPage().getWorkbenchWindow().getShell().forceActive();
		}
		catch (CoreException e) {
			EclipseMessageUtils.error("Error opening the file containing at line " + lineNumber,
				e);
		}
	});
}
 
Example #8
Source File: ApplicationWorkbenchAdvisor.java    From tlaplus with MIT License 6 votes vote down vote up
public void initialize(IWorkbenchConfigurer configurer)
{
    // save the positions of windows etc...
    configurer.setSaveAndRestore(true);

    super.initialize(configurer);
    
    Bundle ideBundle = Platform.getBundle(IDE_PLUGIN);
    declareWorkbenchImage(configurer, ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT, PRJ_OBJ,
            true);
    declareWorkbenchImage(configurer, ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED, PRJ_OBJ_C, true);
    
    declareWorkbenchImage(configurer, ideBundle, IMG_DLGBAN_SAVEAS_DLG, SAVEAS_DLG, true);
    
    // register adapter
    IDE.registerAdapters();
}
 
Example #9
Source File: OriginalEditorSelector.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
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);
}
 
Example #10
Source File: EclipseMessageUtils.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Displays the given file in an editor using the Java perspective.  
 * If something goes wrong, this method has no effect. 
 * 
 * @param file The file to display.
 * @param workbench The workbench.
 */
public static void displayInEditor(IFile file, IWorkbench workbench) {
	new UIJob("Display in editor") {
		@Override
		public IStatus runInUIThread(IProgressMonitor m) {
			try {
				IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
				IDE.openEditor(window.getActivePage(), file);
				workbench.showPerspective("org.eclipse.jdt.ui.JavaPerspective", window);
				return Status.OK_STATUS;
			}
			catch (NullPointerException | WorkbenchException e) {
				return Status.CANCEL_STATUS;
			}
		}
	}.schedule();
}
 
Example #11
Source File: TestXML.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testComplexXML() throws Exception {
	final IFile file = project.getFile("blah.xml");
	String content = "<layout:BlockLayoutCell\n" +
			"	xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"	\n" +
			"    xsi:schemaLocation=\"sap.ui.layout https://openui5.hana.ondemand.com/downloads/schemas/sap.ui.layout.xsd\"\n" +
			"	xmlns:layout=\"sap.ui.layout\">\n" +
			"    |\n" +
			"</layout:BlockLayoutCell>";
	int offset = content.indexOf('|');
	content = content.replace("|", "");
	file.create(new ByteArrayInputStream(content.getBytes()), true, null);
	AbstractTextEditor editor = (AbstractTextEditor) IDE
			.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file, "org.eclipse.ui.genericeditor.GenericEditor");
	editor.getSelectionProvider().setSelection(new TextSelection(offset, 0));
	LSContentAssistProcessor processor = new LSContentAssistProcessor();
	proposals = processor.computeCompletionProposals(Utils.getViewer(editor), offset);
	DisplayHelper.sleep(editor.getSite().getShell().getDisplay(), 2000);
	assertTrue(proposals.length > 1);
}
 
Example #12
Source File: EditorSearchHyperlink.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
public void open()
{
	try
	{
		final IFileStore store = EFS.getStore(document);
		// Now open an editor to this file (and highlight the occurrence if possible)
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		IEditorPart part = IDE.openEditorOnFileStore(page, store);
		// Now select the occurrence if we can
		IFindReplaceTarget target = (IFindReplaceTarget) part.getAdapter(IFindReplaceTarget.class);
		if (target != null && target.canPerformFind())
		{
			target.findAndSelect(0, searchString, true, caseSensitive, wholeWord);
		}
	}
	catch (Exception e)
	{
		IdeLog.logError(CommonEditorPlugin.getDefault(), e);
	}
}
 
Example #13
Source File: TestLanguageServers.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testYAMLFile() throws Exception {
	final IFile file = project.getFile("blah.yaml");
	file.create(new ByteArrayInputStream("FAIL".getBytes()), true, null);
	ITextEditor editor = (ITextEditor) IDE
			.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file);
	editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("hello: '");
	assertTrue("Diagnostic not published", new DisplayHelper() {
		@Override
		protected boolean condition() {
			try {
				return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0;
			} catch (CoreException e) {
				return false;
			}
		}
	}.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000));
}
 
Example #14
Source File: TMinGenericEditorTest.java    From tm4e with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testTMHighlightInGenericEditorEdit() throws IOException, PartInitException {
	f = File.createTempFile("test" + System.currentTimeMillis(), ".ts");
	FileOutputStream fileOutputStream = new FileOutputStream(f);
	fileOutputStream.write("let a = '';".getBytes());
	fileOutputStream.close();
	f.deleteOnExit();
	editor = IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(),
			f.toURI(), editorDescriptor.getId(), true);
	StyledText text = (StyledText)editor.getAdapter(Control.class);
	Assert.assertTrue(new DisplayHelper() {
		@Override
		protected boolean condition() {
			return text.getStyleRanges().length > 1;
		}
	}.waitForCondition(text.getDisplay(), 3000));
	int initialNumberOfRanges = text.getStyleRanges().length;
	text.setText("let a = '';\nlet b = 10;\nlet c = true;");
	Assert.assertTrue("More styles should have been added", new DisplayHelper() {
		@Override protected boolean condition() {
			return text.getStyleRanges().length > initialNumberOfRanges + 3;
		}
	}.waitForCondition(text.getDisplay(), 300000));
}
 
Example #15
Source File: TMinGenericEditorTest.java    From tm4e with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testTMHighlightInGenericEditor() throws IOException, PartInitException {
	f = File.createTempFile("test" + System.currentTimeMillis(), ".ts");
	FileOutputStream fileOutputStream = new FileOutputStream(f);
	fileOutputStream.write("let a = '';\nlet b = 10;\nlet c = true;".getBytes());
	fileOutputStream.close();
	f.deleteOnExit();
	editor = IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(),
			f.toURI(), editorDescriptor.getId(), true);
	StyledText text = (StyledText)editor.getAdapter(Control.class);
	Assert.assertTrue(new DisplayHelper() {
		@Override
		protected boolean condition() {
			return text.getStyleRanges().length > 1;
		}
	}.waitForCondition(text.getDisplay(), 3000));
}
 
Example #16
Source File: TestLanguageServers.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testTSFile() throws Exception {
	final IFile file = project.getFile("blah.ts");
	file.create(new ByteArrayInputStream("ERROR".getBytes()), true, null);
	ITextEditor editor = (ITextEditor) IDE
			.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file);
	editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("FAIL");
	assertTrue("Diagnostic not published", new DisplayHelper() {
		@Override
		protected boolean condition() {
			try {
				return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0;
			} catch (CoreException e) {
				return false;
			}
		}
	}.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000));
}
 
Example #17
Source File: BibtexEditor.java    From slr-toolkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * open the file document which is refered to in the bibtex entry. The path
 * has to start from the root of the project where the bibtex entry is
 * included.
 */
private void openPdf() {
	IFile res = Utils.getIFilefromDocument(document);
	if (res == null || res.getProject() == null) {
		MessageDialog.openInformation(this.getSite().getShell(), "Bibtex" + document.getKey(), "Root or Resource not found");
		return;
	}
	IFile file = res.getProject().getFile(document.getFile());
	if (file.exists()) {
		IFileStore fileStore = EFS.getLocalFileSystem().getStore(file.getLocation());
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

		try {
			IDE.openEditorOnFileStore(page, fileStore);
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	} else {
		MessageDialog.openInformation(this.getSite().getShell(), "Bibtex" + document.getKey(), "Document not found");
	}
}
 
Example #18
Source File: ApplicationWorkbenchAdvisor.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void initialize(final IWorkbenchConfigurer configurer) {

	ResourcesPlugin.getPlugin().getStateLocation();
	try {
		super.initialize(configurer);
		IDE.registerAdapters();
		configurer.setSaveAndRestore(true);

		final IDecoratorManager dm = configurer.getWorkbench().getDecoratorManager();
		dm.setEnabled("org.eclipse.pde.ui.binaryProjectDecorator", false);
		dm.setEnabled("org.eclipse.team.svn.ui.decorator.SVNLightweightDecorator", false);
		dm.setEnabled("msi.gama.application.decorator", true);
		dm.setEnabled("org.eclipse.ui.LinkedResourceDecorator", false);
		dm.setEnabled("org.eclipse.ui.VirtualResourceDecorator", false);
		dm.setEnabled("org.eclipse.xtext.builder.nature.overlay", false);
		if ( Display.getCurrent() != null ) {
			Display.getCurrent().getThread().setUncaughtExceptionHandler(GamaExecutorService.EXCEPTION_HANDLER);
		}
	} catch (final CoreException e) {
		// e.printStackTrace();
	}
	PluginActionBuilder.setAllowIdeLogging(false);
}
 
Example #19
Source File: TMEditorColorTest.java    From tm4e with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void systemDefaultEditorColorTest() throws IOException, PartInitException {
	f = File.createTempFile("test" + System.currentTimeMillis(), ".ts");

	editor = IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), f.toURI(),
			editorDescriptor.getId(), true);

	StyledText styledText = (StyledText) editor.getAdapter(Control.class);

	String themeId = manager.getDefaultTheme().getId();
	ITheme theme = manager.getThemeById(themeId);
	assertEquals("Default light theme isn't set", themeId, SolarizedLight);
	assertEquals("Background colors isn't equals", theme.getEditorBackground(), styledText.getBackground());
	assertEquals("Foreground colors isn't equals", theme.getEditorForeground(), styledText.getForeground());
	assertNull("System default selection background should be null", theme.getEditorSelectionBackground());
	assertNull("System default selection foreground should be null", theme.getEditorSelectionForeground());

	Color lineHighlight = ColorManager.getInstance()
			.getPreferenceEditorColor(EDITOR_CURRENTLINE_HIGHLIGHT);
	assertNotNull("Highlight shouldn't be a null", theme.getEditorCurrentLineHighlight());
	assertNotEquals("Default Line highlight should be from TM theme", lineHighlight,
			theme.getEditorCurrentLineHighlight());

}
 
Example #20
Source File: WorkingSetRootModeActionGroup.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
private IAction[] createActions() {

		ISharedImages sharedImages = PlatformUI.getWorkbench()
				.getSharedImages();

		projectsAction = new TopLevelContentAction(false);
		projectsAction
				.setText(WorkbenchNavigatorMessages.actions_WorkingSetRootModeActionGroup_Project_);
		projectsAction.setImageDescriptor(sharedImages
				.getImageDescriptor(IDE.SharedImages.IMG_OBJ_PROJECT));

		workingSetsAction = new TopLevelContentAction(true);
		workingSetsAction
				.setText(WorkbenchNavigatorMessages.actions_WorkingSetRootModeActionGroup_Working_Set_);
		workingSetsAction.setImageDescriptor(WorkbenchNavigatorPlugin
				.getDefault().getImageRegistry().getDescriptor(
						"full/obj16/workingsets.gif")); //$NON-NLS-1$

		return new IAction[] { projectsAction, workingSetsAction };
	}
 
Example #21
Source File: EclipseUIUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** Opens given file in a editor with given ID within given workbench page. Returns opened editor on null. */
public static IEditorPart openFileEditor(final IFile file, final IWorkbenchPage page, String editorId) {
	checkNotNull(file, "Provided file was null.");
	checkNotNull(page, "Provided page was null.");
	checkNotNull(editorId, "Provided editor ID was null.");

	AtomicReference<IEditorPart> refFileEditor = new AtomicReference<>();

	UIUtils.getDisplay().syncExec(new Runnable() {

		@Override
		public void run() {
			try {
				refFileEditor.set(IDE.openEditor(page, file, editorId, true));
			} catch (PartInitException e) {
				e.printStackTrace();
			}
		}
	});
	return refFileEditor.get();
}
 
Example #22
Source File: TestLSPIntegration.java    From aCute with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testLSFindsDiagnosticsCSProj() throws Exception  {
	IProject project = getProject("csprojWithError");
	IFile csharpSourceFile = project.getFile("Program.cs");
	IEditorPart editor = IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), csharpSourceFile);
	SourceViewer viewer = (SourceViewer)getTextViewer(editor);
	workaroundOmniSharpIssue1088(viewer.getDocument());
	new DisplayHelper() {
		@Override
		protected boolean condition() {
			try {
				return csharpSourceFile.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO).length > 0;
			} catch (Exception e) {
				return false;
			}
		}
	}.waitForCondition(Display.getDefault(), 5000);
	DisplayHelper.sleep(500); // time to fill marker details
	IMarker marker = csharpSourceFile.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)[0];
	assertTrue(marker.getType().contains("lsp4e"));
	assertEquals(12, marker.getAttribute(IMarker.LINE_NUMBER, -1));
}
 
Example #23
Source File: JavadocLinkDialogLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Image getImage(Object element) {
	if (element instanceof JavadocLinkRef) {
		JavadocLinkRef ref= (JavadocLinkRef) element;
		ImageDescriptor desc;
		if (ref.isProjectRef()) {
			desc= PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(IDE.SharedImages.IMG_OBJ_PROJECT);
		} else {
			desc= JavaUI.getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJS_JAR);
		}
		if (ref.getURL() == null) {
			return JavaPlugin.getImageDescriptorRegistry().get(new JavaElementImageDescriptor(desc, JavaElementImageDescriptor.WARNING, JavaElementImageProvider.SMALL_SIZE));
		}
		return JavaPlugin.getImageDescriptorRegistry().get(desc);
	}
	return null;
}
 
Example #24
Source File: NewDiagramWizard.java    From ermaster-b with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean performFinish() {
	try {
		String database = this.page2.getDatabase();

		this.page1.createERDiagram(database);

		IFile file = this.page1.createNewFile();

		if (file == null) {
			return false;
		}

		IWorkbenchPage page = this.workbench.getActiveWorkbenchWindow()
				.getActivePage();

		IDE.openEditor(page, file, true);

	} catch (Exception e) {
		Activator.showExceptionDialog(e);
	}

	return true;
}
 
Example #25
Source File: CopyFilesAndFoldersOperation.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Validates the copy or move operation.
 *
 * @param resources
 *            the resources being copied or moved
 * @param destinationPath
 *            the destination of the copy or move
 * @return whether the operation should proceed
 * @since 3.2
 */
private boolean validateOperation(IResource[] resources, IPath destinationPath) {
    IResourceChangeDescriptionFactory factory = ResourceChangeValidator.getValidator().createDeltaFactory();
    for (int i = 0; i < resources.length; i++) {
        IResource resource = resources[i];
        if (isMove()) {
            factory.move(resource, destinationPath.append(resource.getName()));
        } else {
            factory.copy(resource, destinationPath.append(resource.getName()));
        }
    }
    String title;
    String message;
    if (isMove()) {
        title = IDEWorkbenchMessages.CopyFilesAndFoldersOperation_confirmMove;
        message = IDEWorkbenchMessages.CopyFilesAndFoldersOperation_warningMove;
    } else {
        title = IDEWorkbenchMessages.CopyFilesAndFoldersOperation_confirmCopy;
        message = IDEWorkbenchMessages.CopyFilesAndFoldersOperation_warningCopy;
    }
    return IDE
            .promptToConfirm(messageShell, title, message, factory.getDelta(), modelProviderIds,
                    true /* syncExec */);
}
 
Example #26
Source File: LanguageSpecificURIEditorOpener.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public IEditorPart open(final URI uri, final EReference crossReference, final int indexInList, final boolean select) {
	Iterator<Pair<IStorage, IProject>> storages = mapper.getStorages(uri.trimFragment()).iterator();
	if (storages != null && storages.hasNext()) {
		try {
			IStorage storage = storages.next().getFirst();
			IEditorInput editorInput = EditorUtils.createEditorInput(storage);
			IWorkbenchPage activePage = workbench.getActiveWorkbenchWindow().getActivePage();
			final IEditorPart editor = IDE.openEditor(activePage, editorInput, getEditorId());
			selectAndReveal(editor, uri, crossReference, indexInList, select);
			return EditorUtils.getXtextEditor(editor);
		} catch (WrappedException e) {
			logger.error("Error while opening editor part for EMF URI '" + uri + "'", e.getCause());
		} catch (PartInitException partInitException) {
			logger.error("Error while opening editor part for EMF URI '" + uri + "'", partInitException);
		}
	}
	return null;
}
 
Example #27
Source File: TestLSPIntegration.java    From corrosion with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testLSWorks() throws IOException, CoreException {
	IProject project = getProject(BASIC_ERRORS_PROJECT_NAME);
	IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
	IEditorPart editor = null;
	// This is a workaround, since the test is failing occasionally.
	// The RLS may not be fully initialized without this timeout.
	try {
		Thread.sleep(200);
	} catch (InterruptedException e1) {
		e1.printStackTrace();
	}
	IFile file = project.getFolder("src").getFile("main.rs");
	editor = IDE.openEditor(activePage, file);
	Display display = editor.getEditorSite().getShell().getDisplay();
	DisplayHelper.waitForCondition(display, 30000, () -> {
		try {
			return file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)[0]
					.getAttribute(IMarker.LINE_NUMBER, -1) == 3;
		} catch (Exception e) {
			return false;
		}
	});
	IMarker[] markers = file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO);
	boolean markerFound = false;
	for (IMarker marker : markers) {
		assertTrue(marker.getType().contains("lsp4e"));
		int lineNumber = marker.getAttribute(IMarker.LINE_NUMBER, -1);
		if (lineNumber == 3) {
			markerFound = true;
		}
	}
	assertTrue("No error marker found at line 3.", markerFound);
}
 
Example #28
Source File: PyDebugModelPresentation.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This was copied from {@link org.eclipse.jdt.internal.debug.ui.JDIModelPresentation.getEditorId(IEditorInput, Object)}.
 * <p>
 * Use {@link IDE#getEditorDescriptor(String)} rather than sending a static String; this'll open the editior
 * attached to the file instead of always Python editor (which expect Python code).
 *
 * @see <a href="http://git.eclipse.org/c/jdt/eclipse.jdt.debug.git/tree/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JDIModelPresentation.java#n1216">JDIModelPresentation</a>
 */
@Override
public String getEditorId(final IEditorInput input, final Object element) {
    try {
        return IDE.getEditorDescriptor(input.getName(), true, false).getId();
    } catch (@SuppressWarnings("unused") PartInitException | OperationCanceledException ignored) {
        return null;
    }
}
 
Example #29
Source File: OpenDeclarations.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void openSingleFile(IASTFileLocation location, String functionName) {
	String pathToFix = location.getFileName();
	String projectName = project.getName();
	int index = pathToFix.indexOf(projectName);
	if (index == -1) {
		EclipseMessageUtils.error("Error opening the file containing " + pathToFix);
		return;
	}
	String relativePath = pathToFix.substring(index);
	final IPath path = new Path(relativePath).removeFirstSegments(1); // strip off project name
	final int offset = location.getNodeOffset();
	final int length = location.getNodeLength();
	final String fName = functionName;
	Display.getDefault().asyncExec(() -> {
		try {
			IFile file = project.getFile(path);
			IMarker marker = file.createMarker(IMarker.TEXT);
			marker.setAttribute(IMarker.CHAR_START, offset);
			marker.setAttribute(IMarker.CHAR_END, offset + length);
			IDE.openEditor(EclipseMessageUtils.getWorkbenchPage(), marker);
			symbolMap.put(fName, marker);
			EclipseMessageUtils.getWorkbenchPage().getWorkbenchWindow().getShell().forceActive();
		}
		catch (CoreException e) {
			EclipseMessageUtils.error("Error opening the file containing " + fName, e);
		}
	});
}
 
Example #30
Source File: ExampleModelOpener.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public void openModelFiles(IProject project) {
	List<IFile> filesToOpen = Lists.newArrayList();
	addStatecharts(project, filesToOpen);

	if (filesToOpen == null || getPage() == null) {
		return;
	}
	Display.getDefault().asyncExec(() -> {
		try {
			for (IFile file : filesToOpen) {
				IDE.openEditor(getPage(), file, false);
			}

			if (online()) {
				String browserid = "org.eclipse.ui.browser.editor";
				String baseURL = "https://itemis.com/en/yakindu/state-machine/documentation/examples/example/";
				URL url = new URL((baseURL + project.getName().replace(".", "-")));
				final IWebBrowser browser = PlatformUI.getWorkbench().getBrowserSupport().createBrowser(browserid);
				browser.openURL(url);
			} else {
				openExampleReadme(project);
			}
		} catch (PartInitException | MalformedURLException e) {
			e.printStackTrace();
			return;
		}
	});
}