Java Code Examples for org.eclipse.ui.handlers.HandlerUtil#getCurrentSelection()

The following examples show how to use org.eclipse.ui.handlers.HandlerUtil#getCurrentSelection() . 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: CallEditor.java    From codeexamples-eclipse with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	// get the page
	IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
	IWorkbenchPage page = window.getActivePage();
	// get the selection
	ISelection selection = HandlerUtil.getCurrentSelection(event);
	if (selection != null && selection instanceof IStructuredSelection) {
		Object obj = ((IStructuredSelection) selection).getFirstElement();
		// if we had a selection lets open the editor
		if (obj != null) {
			Task todo = (Task) obj;
			TaskEditorInput input = new TaskEditorInput(todo.getId());
			try {
				page.openEditor(input, TaskEditor.ID);
			} catch (PartInitException e) {
				throw new RuntimeException(e);
			}
		}
	}
	return null;
}
 
Example 2
Source File: NewFolderHandler.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {

    // Check if we are closing down
    IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    if (window == null) {
        return null;
    }

    ISelection selection = HandlerUtil.getCurrentSelection(event);
    if (!(selection instanceof IStructuredSelection)) {
        return null;
    }
    final Object element = ((IStructuredSelection) selection).getFirstElement();
    if (!(element instanceof TmfTraceFolder)) {
        return null;
    }
    TmfTraceFolder parent = (TmfTraceFolder) element;

    // Fire the New Folder dialog
    Shell shell = window.getShell();
    NewFolderDialog dialog = new NewFolderDialog(shell, parent);
    dialog.open();

    return null;
}
 
Example 3
Source File: BillingProposalViewCreateBillsHandler.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
private List<Konsultation> getToBill(ExecutionEvent event){
	String selectionParameter =
		event.getParameter("ch.elexis.core.ui.BillingProposalViewCreateBills.selection");
	if ("selection".equals(selectionParameter)) {
		ISelection selection = HandlerUtil.getCurrentSelection(event);
		if (selection != null && !selection.isEmpty()) {
			@SuppressWarnings("unchecked")
			List<Object> selectionList = ((IStructuredSelection) selection).toList();
			// map to List<Konsultation> depending on type
			if (selectionList.get(0) instanceof Konsultation) {
				return selectionList.stream().map(o -> ((Konsultation) o))
					.collect(Collectors.toList());
			} else if (selectionList.get(0) instanceof BillingProposalView.BillingInformation) {
				return selectionList.stream()
					.map(o -> ((BillingProposalView.BillingInformation) o).getKonsultation())
					.collect(Collectors.toList());
			}
		}
	} else {
		BillingProposalView view = getOpenView(event);
		if (view != null) {
			return view.getToBill();
		}
	}
	return Collections.emptyList();
}
 
Example 4
Source File: DocumentExportHandler.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException{
	Shell shell = PlatformUI.getWorkbench().getDisplay().getActiveShell();
	ISelection selection = HandlerUtil.getCurrentSelection(event);
	if (selection instanceof StructuredSelection
		&& !((StructuredSelection) selection).isEmpty()) {
		List<?> iDocuments = ((StructuredSelection) selection).toList();
		
		for (Object documentToExport : iDocuments) {
			if (documentToExport instanceof IDocument) {
				openExportDialog(shell, (IDocument) documentToExport);
			}
		}
	}
	return null;
}
 
Example 5
Source File: IgnoreCaughtExceptionCommandHandler.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    ISelection selection = HandlerUtil.getCurrentSelection(event);
    if (selection instanceof StructuredSelection) {
        StructuredSelection structuredSelection = (StructuredSelection) selection;
        Object elem = structuredSelection.getFirstElement();
        if (elem instanceof IAdaptable) {
            IAdaptable iAdaptable = (IAdaptable) elem;
            elem = iAdaptable.getAdapter(IStackFrame.class);

        }
        if (elem instanceof PyStackFrame) {
            try {
                PyStackFrame pyStackFrame = (PyStackFrame) elem;
                IPath path = pyStackFrame.getPath();
                int lineNumber = pyStackFrame.getLineNumber();
                PyExceptionBreakPointManager.getInstance().ignoreCaughtExceptionsWhenThrownFrom
                        .addIgnoreThrownExceptionIn(path.toFile(), lineNumber);
            } catch (DebugException e) {
                Log.log(e);
            }
        }
    }

    return null;
}
 
Example 6
Source File: InitializeConfigurationsHandler.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    final Shell shell = HandlerUtil.getActiveShell(event);

    final ISelection selection = HandlerUtil.getCurrentSelection(event);
    final IWorkbenchWindow workbenchWindow = HandlerUtil.getActiveWorkbenchWindow(event);
    final IWorkbench workbench;
    if (workbenchWindow != null) {
        workbench = workbenchWindow.getWorkbench();
    } else {
        workbench = null;
    }
    GenconfEditorLauncher.openNewGenerationWizard(workbench, shell, (IStructuredSelection) selection);

    return null;
}
 
Example 7
Source File: SelectionUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static IFile getSelectedFile(ExecutionEvent event) {
	ISelection selection = HandlerUtil.getCurrentSelection(event);
	if (selection instanceof TextSelection) {
		IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
		return getSelectedFile(activeEditor);
	} else if (selection instanceof IStructuredSelection) {
		return getSelectedFile(selection);
	}
	return null;
}
 
Example 8
Source File: OutlineCopyQualifiedNameHandler.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private IOutlineNode getOutlineNode(ExecutionEvent event) {
	ISelection currentSelection = HandlerUtil.getCurrentSelection(event);
	if (!(currentSelection instanceof IStructuredSelection)) {
		return null;
	}
	IStructuredSelection structuredSelection = (IStructuredSelection) currentSelection;
	return (IOutlineNode) structuredSelection.getFirstElement();
}
 
Example 9
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 10
Source File: AddBuilder.java    From uml2solidity with Eclipse Public License 1.0 5 votes vote down vote up
public static IProject getProject(final ExecutionEvent event) {
	final ISelection selection = HandlerUtil.getCurrentSelection(event);
	if (selection instanceof IStructuredSelection) {
		final Object element = ((IStructuredSelection) selection).getFirstElement();

		return (IProject) Platform.getAdapterManager().getAdapter(element, IProject.class);
	}
	return null;
}
 
Example 11
Source File: AbstractBuildFileCommandHandler.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    ISelection selection = HandlerUtil.getCurrentSelection(event);
    List<IResource> resources = SelectionUtils.getObjectsFromStructuredSelection(selection, IResource.class);
    int i = 0;
    if (resources.isEmpty()) {
        IResource resource = CoreEditorUtils.getActiveEditorInputAsResource();
        if (resource != null) {
            resources = new ArrayList<IResource>(1);
            resources.add(resource);
        }
    }
    
    if (!CoreEditorUtils.saveEditors(false)) {
        return null;
    }

    final ArrayList<BuilderUtils.MultipleBuildItem> itemsToBuild = new ArrayList<BuilderUtils.MultipleBuildItem>(); 

    for (IResource res : resources) {
        Map<String, String> args = new HashMap<String, String>();
        args.putAll(getCommonProperties());
        String absolutePath = ResourceUtils.getAbsolutePath(res);
        args.put(XdsSourceBuilderConstants.SOURCE_FILE_PATH_KEY_PREFIX
                + (++i), absolutePath);

        IProject p = res.getProject();

        itemsToBuild.add(new BuilderUtils.MultipleBuildItem(buildKind, p, args));
    }
    
    BuilderUtils.invokeMultipleBuild(itemsToBuild, new BuilderUtils.IMiltipleBuildFinishListener() {
        @Override
        public void allItemsAreFinished() {
            AbstractBuildProjectCommandHandler.printSummary(itemsToBuild);
        }
    });

    return null;
}
 
Example 12
Source File: StandardResourceActionHandler.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
@Override
   public Object execute(ExecutionEvent event) throws ExecutionException {
       ISelection selection = HandlerUtil.getCurrentSelection(event);
       if (selection instanceof IStructuredSelection) {
       	action.selectionChanged((IStructuredSelection)selection);
       }
       action.run();
       return null;
   }
 
Example 13
Source File: ExportHandler.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 得到选中项
 * @param event
 * @return ;
 */
protected IStructuredSelection getSelectionToUse(ExecutionEvent event) {
	String partId = HandlerUtil.getActivePartId(event);
	if (Constant.NAVIGATOR_VIEW_ID.equals(partId)) {
		ISelection selection = HandlerUtil.getCurrentSelection(event);
		if (selection instanceof IStructuredSelection) {
			return (IStructuredSelection) selection;
		}
	}
	return StructuredSelection.EMPTY;
}
 
Example 14
Source File: AbstractCordovaHandler.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
protected IProject getProject(ExecutionEvent event) {
	final ISelection currentSelection = HandlerUtil.getCurrentSelection(event);
	if (!currentSelection.isEmpty() && currentSelection instanceof IStructuredSelection) {
		final Object object = ((IStructuredSelection) currentSelection).getFirstElement();
		return (IProject) Platform.getAdapterManager().getAdapter(object, IProject.class);
	}
	return null;
}
 
Example 15
Source File: PrettyPrintCommandHandler.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    ISelection selection = HandlerUtil.getCurrentSelection(event);
    Tuple<AbstractDebugTarget, IVariableLocator> context = RunCustomOperationCommand
            .extractContextFromSelection(selection);
    if (context != null) {
        RunCustomOperationCommand cmd = new RunCustomOperationCommand(context.o1, context.o2, PPRINT_CODE,
                PPRINT_FUNCTION);
        context.o1.postCommand(cmd);
    }

    return null;
}
 
Example 16
Source File: EditTemplatePropertiesHandler.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    final Shell shell = HandlerUtil.getActiveShell(event);
    final ISelection selection = HandlerUtil.getCurrentSelection(event);
    if (!selection.isEmpty() && selection instanceof IStructuredSelection) {
        final IFile templateFile = (IFile) ((IStructuredSelection) selection).getFirstElement();
        final URI templateURI = URI.createPlatformResourceURI(templateFile.getFullPath().toString(), true);

        WizardDialog dialog = new WizardDialog(shell, new TemplateCustomPropertiesWizard(templateURI)) {

            @Override
            public void create() {
                super.create();
                getShell().setText("Template properties");
            }

            @Override
            public void showPage(IWizardPage page) {
                super.showPage(page);
                getShell().setText("Template properties");
            }
        };
        dialog.open();
    }

    return null;
}
 
Example 17
Source File: JavaScriptVisualizeSelectedDiagramsHandler.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	JavaScriptVisualizeWizard wizard = new JavaScriptVisualizeWizard();
	WizardDialog wizardDialog = new WizardDialog(null, wizard);
	wizardDialog.create();

	VisualizeTxtUMLPage page = ((VisualizeTxtUMLPage) wizardDialog.getSelectedPage());

	// get selected files
	ISelection selection = HandlerUtil.getCurrentSelection(event);
	IStructuredSelection strSelection = (IStructuredSelection) selection;

	List<ICompilationUnit> selectedCompilationUnits = new ArrayList<>();
	Stream.of(strSelection.toArray()).forEach(s -> selectedCompilationUnits
			.add((ICompilationUnit) ((IAdaptable) s).getAdapter(ICompilationUnit.class)));
	try {
		List<IType> types = new ArrayList<>();
		for (ICompilationUnit cu : selectedCompilationUnits) {
			types.addAll(Arrays.asList(cu.getTypes()));
		}
		page.selectElementsInDiagramTree(types.toArray(), false);
		page.setExpandedLayouts(types);
	} catch (JavaModelException ex) {
	}

	wizardDialog.open();
	return null;
}
 
Example 18
Source File: CreateNewN4JSElementInModuleHandler.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the active tree resource selection if there is one.
 *
 * Examines the active workspace selection and if it is a resource inside of a tree returns it.
 *
 * @param event
 *            The execution event
 * @returns The resource or {@code null} on failure.
 *
 */
private static IResource getActiveTreeResourceSelection(ExecutionEvent event) {

	ISelection activeSelection = HandlerUtil.getCurrentSelection(event);

	if (activeSelection instanceof TreeSelection) {
		Object firstElement = ((TreeSelection) activeSelection).getFirstElement();

		if (firstElement instanceof IResource) {
			return (IResource) firstElement;
		}
	}
	return null;
}
 
Example 19
Source File: AbstractCompareWithRouteActionHandler.java    From eip-designer with Apache License 2.0 4 votes vote down vote up
/**
 * The command has been executed, so extract the needed information
 * from the application context.
 */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
   ISelection currentSelection = HandlerUtil.getCurrentSelection(event);
   
   if (currentSelection != null && currentSelection instanceof IStructuredSelection) {
      // Retrieve file corresponding to current selection.
      IStructuredSelection selection = (IStructuredSelection)currentSelection;
      IFile selectionFile = (IFile)selection.getFirstElement();
      
      // Open compare target selection dialog.
      CompareTargetSelectionDialog dialog = new CompareTargetSelectionDialog(
            HandlerUtil.getActiveShellChecked(event), 
            selectionFile.getName());
      
      if (dialog.open() != Window.OK) {
         return null;
      }
      
      // Ask concrete subclass to parse source file and extract Route for comparison.
      Route left = extractRouteFromFile(selectionFile);
      
      // Retrieve EMF Object corresponding to selected reference Route.
      Route right = dialog.getSelectedRoute();
      
      // Cause Spring parser cannot retrieve route name, force it using those of the model.
      // TODO Find a fix later for that in the generator/parser couple
      left.setName(right.getName());
      
      // Launch EMFCompare UI with input.
      EMFCompareConfiguration configuration = new EMFCompareConfiguration(new CompareConfiguration());
      ICompareEditingDomain editingDomain = EMFCompareEditingDomain.create(left, right, null);
      AdapterFactory adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
      EMFCompare comparator = EMFCompare.builder().setPostProcessorRegistry(EMFCompareRCPPlugin.getDefault().getPostProcessorRegistry()).build();
      IComparisonScope scope = new DefaultComparisonScope(left, right, null);
      
      CompareEditorInput input = new ComparisonScopeEditorInput(configuration, editingDomain, adapterFactory, comparator, scope);
      CompareUI.openCompareDialog(input);
   }
   
   return null;
}
 
Example 20
Source File: DocumentSendAsMailHandler.java    From elexis-3-core with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException{
	ISelection selection = HandlerUtil.getCurrentSelection(event);
	if (selection instanceof StructuredSelection
		&& !((StructuredSelection) selection).isEmpty()) {
		List<?> iDocuments = ((StructuredSelection) selection).toList();
		
		List<File> attachments = new ArrayList<File>();
		for (Object iDocument : iDocuments) {
			if (iDocument instanceof IDocument) {
				Optional<File> tmpFile = getTempFile((IDocument) iDocument);
				if (tmpFile.isPresent()) {
					attachments.add(tmpFile.get());
				}
			}
		}
		if (!attachments.isEmpty()) {
			ICommandService commandService = (ICommandService) HandlerUtil
				.getActiveWorkbenchWindow(event).getService(ICommandService.class);
			try {
				String attachmentsString = getAttachmentsString(attachments);
				Command sendMailCommand =
					commandService.getCommand("ch.elexis.core.mail.ui.sendMail");
				
				HashMap<String, String> params = new HashMap<String, String>();
				params.put("ch.elexis.core.mail.ui.sendMail.attachments", attachmentsString);
				Patient patient = ElexisEventDispatcher.getSelectedPatient();
				if (patient != null) {
					params.put("ch.elexis.core.mail.ui.sendMail.subject",
						"Patient: " + patient.getLabel());
				}
				
				ParameterizedCommand parametrizedCommmand =
					ParameterizedCommand.generateCommand(sendMailCommand, params);
				PlatformUI.getWorkbench().getService(IHandlerService.class)
					.executeCommand(parametrizedCommmand, null);
			} catch (Exception ex) {
				throw new RuntimeException("ch.elexis.core.mail.ui.sendMail not found", ex);
			}
		}
		removeTempAttachments(attachments);
	}
	return null;
}