Java Code Examples for org.eclipse.ui.commands.ICommandService#getCommand()

The following examples show how to use org.eclipse.ui.commands.ICommandService#getCommand() . 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: EditLocalDocumentUtil.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * If {@link Preferences#P_TEXT_EDIT_LOCAL} is set, the
 * <code> ch.elexis.core.ui.command.startEditLocalDocument </code> command is called with the
 * provided {@link IDocumentLetter}, and the provided {@link IViewPart} is hidden.
 * 
 * @param view
 * @param document
 * @return returns true if edit local is started and view is hidden
 */
public static boolean startEditLocalDocument(IViewPart view, IDocumentLetter document){
	if (CoreHub.localCfg.get(Preferences.P_TEXT_EDIT_LOCAL, false) && document != null) {
		// open for editing
		ICommandService commandService =
			(ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
		Command command =
			commandService.getCommand("ch.elexis.core.ui.command.startEditLocalDocument"); //$NON-NLS-1$
		
		PlatformUI.getWorkbench().getService(IEclipseContext.class)
			.set(command.getId().concat(".selection"), new StructuredSelection(document));
		try {
			command.executeWithChecks(
				new ExecutionEvent(command, Collections.EMPTY_MAP, view, null));
		} catch (ExecutionException | NotDefinedException | NotEnabledException
				| NotHandledException e) {
			MessageDialog.openError(view.getSite().getShell(), Messages.TextView_errortitle,
				Messages.TextView_errorlocaleditmessage);
		}
		view.getSite().getPage().hideView(view);
		return true;
	}
	return false;
}
 
Example 2
Source File: CommandsPropertyTester.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
public boolean test(final Object receiver, final String property,
		final Object[] args, final Object expectedValue) {
	if (receiver instanceof IServiceLocator && args.length == 1
			&& args[0] instanceof String) {
		final IServiceLocator locator = (IServiceLocator) receiver;
		if (TOGGLE_PROPERTY_NAME.equals(property)) {
			final String commandId = args[0].toString();
			final ICommandService commandService = (ICommandService) locator
					.getService(ICommandService.class);
			final Command command = commandService.getCommand(commandId);
			final State state = command
					.getState(RegistryToggleState.STATE_ID);
			if (state != null) {
				return state.getValue().equals(expectedValue);
			}
		}
	}
	return false;
}
 
Example 3
Source File: Handler.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
private static Object execute(IViewSite origin, String commandID, Map<String, Object> params){
	if (origin == null) {
		log.error("origin is null");
		return null;
	}
	IHandlerService handlerService = (IHandlerService) origin.getService(IHandlerService.class);
	ICommandService cmdService = (ICommandService) origin.getService(ICommandService.class);
	try {
		Command command = cmdService.getCommand(commandID);
		String name = StringTool.unique("CommandHandler"); //$NON-NLS-1$
		paramMap.put(name, params);
		Parameterization px = new Parameterization(new DefaultParameter(), name);
		ParameterizedCommand parmCommand =
			new ParameterizedCommand(command, new Parameterization[] {
				px
		});
		
		return handlerService.executeCommand(parmCommand, null);
		
	} catch (Exception ex) {
		throw new RuntimeException("add.command not found"); //$NON-NLS-1$
	}
}
 
Example 4
Source File: KbdMacroDefineHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Define the Command to be used when executing the named kbd macro
 * 
 * @param editor
 * @param id - the full command id
 * @param name - the short name
 * @param category - the category to use in the definition
 * @return the Command
 */
Command defineKbdMacro(ITextEditor editor, String id, String name, String category) {
	Command command = null;
	if (id != null) {
		// Now create the executable command 
		ICommandService ics = (editor != null ) ? (ICommandService) editor.getSite().getService(ICommandService.class) : 
			(ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);		
		command = ics.getCommand(id);
		IParameter[] parameters = null;
		try {
			// kludge: Eclipse has no way to dynamically define a parameter, so grab it from a known command
			IParameter p = ics.getCommand(PARAMETER_CMD).getParameter(PARAMETER);
			parameters = new IParameter[] { p };
		} catch (Exception e) { 
		}
		command.define(name, String.format(KBD_DESCRIPTION,name), ics.getCategory(category), parameters);
		command.setHandler(new KbdMacroNameExecuteHandler(name));
	}
	return command;
}
 
Example 5
Source File: PCalTranslateAutomaticallyHandler.java    From tlaplus with MIT License 6 votes vote down vote up
@Inject
public void initializeAtStartup(final IWorkbench workbench, final ICommandService commandService) {
	/*
	 * Check the UI state of the IHandler/Command which indicates if the user
	 * enabled automatic PlusCal conversion.
	 */
	final Command command = commandService.getCommand("toolbox.command.module.translate.automatially");
	final State state = command.getState(RegistryToggleState.STATE_ID);
	if (!((Boolean) state.getValue()).booleanValue()) {
		return;
	}
	// This IHander is stateful even across Toolbox restarts. In other words, if the
	// user enables automatic PlusCal translation, it will remain enabled even after
	// a Toolbox restart. This means we have to register this EventHandler at the
	// IEventBroker during Toolbox startup.
	// It is vital that we use the Workbench's IEventBroker instance. If e.g. we
	// would use an IEventBroker from higher up the IEclipseContext hierarchy, the
	// broker would be disposed when a new spec gets opened while the IHandler's state
	// remains enabled.
	workbench.getService(IEventBroker.class).unsubscribe(this);
	Assert.isTrue(workbench.getService(IEventBroker.class).subscribe(TLAEditor.PRE_SAVE_EVENT, this));
}
 
Example 6
Source File: EditLabItemUi.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
public static void executeWithParams(PersistentObject parameter){
	try {
		// get the command
		IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
		ICommandService cmdService = (ICommandService) window.getService(ICommandService.class);
		Command cmd = cmdService.getCommand(COMMANDID);
		// create the parameter
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put(PARAMETERID, parameter);
		// build the parameterized command
		ParameterizedCommand pc = ParameterizedCommand.generateCommand(cmd, param);
		// execute the command
		IHandlerService handlerService =
			(IHandlerService) PlatformUI.getWorkbench().getActiveWorkbenchWindow()
				.getService(IHandlerService.class);
		handlerService.executeCommand(pc, null);
	} catch (Exception ex) {
		throw new RuntimeException(COMMANDID, ex);
	}
}
 
Example 7
Source File: CommandsPropertyTester.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
public boolean test(final Object receiver, final String property,
		final Object[] args, final Object expectedValue) {
	if (receiver instanceof IServiceLocator && args.length == 1
			&& args[0] instanceof String) {
		final IServiceLocator locator = (IServiceLocator) receiver;
		if (TOGGLE_PROPERTY_NAME.equals(property)) {
			final String commandId = args[0].toString();
			final ICommandService commandService = (ICommandService) locator
					.getService(ICommandService.class);
			final Command command = commandService.getCommand(commandId);
			final State state = command
					.getState(RegistryToggleState.STATE_ID);
			if (state != null) {
				return state.getValue().equals(expectedValue);
			}
		}
	}
	return false;
}
 
Example 8
Source File: AbstractShieldCommandStartup.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
public void earlyStartup() {
	Set<String> unusedCommand = getUnusedCommandSet();
	IWorkbench workbench = PlatformUI.getWorkbench();
	ICommandService commandService = (ICommandService) workbench.getService(ICommandService.class);
	Command command;
	for (String commandId : unusedCommand) {
		command = commandService.getCommand(commandId);
		command.undefine();
	}
}
 
Example 9
Source File: ToggleWordWrapHandler.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setEnabled(Object evaluationContext)
{
	Object activeSite = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_SITE_NAME);
	Object activeEditor = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_EDITOR_NAME);
	if (activeSite instanceof IWorkbenchSite && activeEditor instanceof AbstractThemeableEditor)
	{
		ICommandService commandService = (ICommandService) ((IWorkbenchSite) activeSite)
				.getService(ICommandService.class);
		Command command = commandService.getCommand(COMMAND_ID);
		State state = command.getState(RegistryToggleState.STATE_ID);
		state.setValue(((AbstractThemeableEditor) activeEditor).getWordWrapEnabled());
	}
}
 
Example 10
Source File: CommonEditorPlugin.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
private void setCommandState(boolean state)
{
	ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
	Command command = service.getCommand(COMMAND_ID);
	State commandState = command.getState(COMMAND_STATE);
	if (((Boolean) commandState.getValue()) != state)
	{
		commandState.setValue(state);
		service.refreshElements(COMMAND_ID, null);
	}
}
 
Example 11
Source File: SendBriefAsMailHandler.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException{
	Brief brief = (Brief) ElexisEventDispatcher.getSelected(Brief.class);
	if (brief != null) {
		List<File> attachments = new ArrayList<File>();
		Optional<File> tmpFile = getTempFile(brief);
		if (tmpFile.isPresent()) {
			attachments.add(tmpFile.get());
			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;
}
 
Example 12
Source File: KbdMacroBindHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Add the binding to the Emacs+ scheme
 * 
 * @param editor
 * @param bindingResult
 */
private void addBinding(ITextEditor editor, IBindingResult bindingResult, String name) {
	IBindingService service = (IBindingService) editor.getSite().getService(IBindingService.class);
	if (service instanceof  BindingService) {
		try {
			BindingService bindingMgr = (BindingService) service;
			if (bindingResult.getKeyBinding() != null) {
				// we're overwriting a binding, out with the old
				bindingMgr.removeBinding(bindingResult.getKeyBinding());
			}
			Command command = null;
			if (name != null) {
				ICommandService ics = (ICommandService) editor.getSite().getService(ICommandService.class);
				String id = EmacsPlusUtils.kbdMacroId(name);
				// check first, as getCommand will create it if it doesn't already exist
				if (ics.getDefinedCommandIds().contains(id)) {
					command = ics.getCommand(id);
				}
			} else {
				// use the unexposed category
				command = nameKbdMacro(KBD_LNAME + nameid++, editor, KBD_GAZONK);
			}
			if (command != null) {
				Binding binding = new KeyBinding(bindingResult.getTrigger(), new ParameterizedCommand(command, null),
						KBD_SCHEMEID, KBD_CONTEXTID, null, null, null, Binding.USER);
				bindingMgr.addBinding(binding);
				asyncShowMessage(editor, String.format(BOUND, bindingResult.getKeyString()), false);
			} else {
				asyncShowMessage(editor, String.format(NO_NAME_UNO, name), true);									
			}
		} catch (Exception e) { 
			asyncShowMessage(editor, String.format(ABORT, bindingResult.getKeyString()), true);				
		}
	}
}
 
Example 13
Source File: MultipageEditorTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testOpenBlankFile() throws Exception {
	IFile file = createFile("foo/y.testlanguage", "/* multi line */\n" + "stuff foo\n" + "stuff bar\n" + "// end");
	XtextEditor openedEditor = openEditor(file);
	assertNotNull(openedEditor);
	
	ICommandService service = PlatformUI.getWorkbench().getService(ICommandService.class);
	Command command = service.getCommand("org.eclipse.xtext.ui.editor.hyperlinking.OpenDeclaration");
	assertTrue(command.isEnabled());
	
	openedEditor.close(false);
}
 
Example 14
Source File: SymbolContext.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Execute an Eclipse command
 *
 * @param commandId
 *            the command to execute
 * @param eventData
 *            the parameter event data (depends on the command)
 */
public void executeCommand ( final String commandId, final Map<String, String> eventData )
{
    try
    {
        final ICommandService commandService = (ICommandService)PlatformUI.getWorkbench ().getService ( ICommandService.class );
        final IHandlerService handlerService = (IHandlerService)PlatformUI.getWorkbench ().getService ( IHandlerService.class );

        final Command command = commandService.getCommand ( commandId );

        final Parameterization[] parameterizations = new Parameterization[eventData.size ()];

        int i = 0;
        for ( final Map.Entry<String, String> entry : eventData.entrySet () )
        {
            parameterizations[i] = new Parameterization ( command.getParameter ( entry.getKey () ), entry.getValue () );
            i++;
        }
        final ParameterizedCommand parameterCommand = new ParameterizedCommand ( command, parameterizations );

        handlerService.executeCommand ( parameterCommand, null );
    }
    catch ( final Exception e )
    {
        logger.warn ( "Failed to execute command", e );
        StatusManager.getManager ().handle ( StatusHelper.convertStatus ( Activator.PLUGIN_ID, e ), StatusManager.BLOCK );
    }
}
 
Example 15
Source File: TestSave.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testSaveButtonAndMenuNotEnableAtInitiationAndEnableAfterChange() {
    // When opening Bonita soft
    final Matcher<MenuItem> matcher = withMnemonic(SAVE_BUTTON_TEXT);
    bot.waitUntil(Conditions.waitForMenu(bot.activeShell(), matcher));
    bot.waitUntil(Conditions.waitForWidget(withId(SWTBotConstants.SWTBOT_ID_SAVE_EDITOR)));

    // test button
    bot.waitUntil(new AssertionCondition() {

        @Override
        protected void makeAssert() throws Exception {
            Assert.assertFalse("Error: Save button must be disabled when opening Bonita Studio.",
                    bot.toolbarButtonWithId(SWTBotConstants.SWTBOT_ID_SAVE_EDITOR).isEnabled());
        }
    });

    // test menu
    bot.waitUntil(widgetIsDisabled(bot.menu("File").click().menu("Save")));

    // When Creating a new Diagram
    SWTBotTestUtil.createNewDiagram(bot);
    final SWTBotEditor botEditor = bot.activeEditor();
    final SWTBotGefEditor gmfEditor = bot.gefEditor(botEditor.getTitle());
    final List<SWTBotGefEditPart> runnableEPs = gmfEditor.editParts(new BaseMatcher<EditPart>() {

        @Override
        public boolean matches(final Object item) {
            return item instanceof PoolEditPart;
        }

        @Override
        public void describeTo(final Description description) {

        }
    });
    Assert.assertFalse(runnableEPs.isEmpty());
    gmfEditor.select(runnableEPs.get(0));

    // test button
    bot.waitUntil(new AssertionCondition() {

        @Override
        protected void makeAssert() throws Exception {
            Assert.assertTrue("Error: Save button must be enabled when creating a new diagram.",
                    bot.toolbarButtonWithId(SWTBotConstants.SWTBOT_ID_SAVE_EDITOR).isEnabled());

        }
    });

    // test menu
    bot.waitUntil(Conditions.widgetIsEnabled(bot.menu("File").menu("Save")));

    bot.toolbarButtonWithId(SWTBotConstants.SWTBOT_ID_SAVE_EDITOR).click();

    // test button
    bot.waitUntil(new AssertionCondition() {

        @Override
        protected void makeAssert() throws Exception {
            Assert.assertFalse("Error: Save button must be disabled after saving a diagram.",
                    bot.toolbarButtonWithId(SWTBotConstants.SWTBOT_ID_SAVE_EDITOR).isEnabled());

        }
    });

    final ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
    final Command cmd = service.getCommand(SAVE_COMMAND_ID);
    assertFalse(cmd.isEnabled());
}
 
Example 16
Source File: OpenLaunchDialogHanderPDETest.java    From eclipse-extras with Eclipse Public License 1.0 4 votes vote down vote up
private Command getOpenLaunchDialogCommand() {
  ICommandService commandService = ServiceHelper.getService( workbenchWindow, ICommandService.class );
  return commandService.getCommand( OpenLaunchDialogHander.COMMAND_ID );
}
 
Example 17
Source File: ConcordanceSearchHandler.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
public Object execute(ExecutionEvent event) throws ExecutionException {
	if (!isEnabled()) {
		return null;
	}
	IEditorPart editor = HandlerUtil.getActiveEditor(event);
	if (editor instanceof IXliffEditor) {
		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(ConcordanceSearchHandler.class).error("Exception:key hs008 is lost.(Can't find the key)");
			System.exit(0);
		}
		IXliffEditor xliffEditor = (IXliffEditor) editor;
		String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor";

		IEditorPart editorRefer = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
				.getActiveEditor();
		if (editorRefer.getSite().getId().equals(XLIFF_EDITOR_ID)) {
			// IProject project = ((FileEditorInput) editorRefer.getEditorInput()).getFile().getProject();
			IFile file = ((FileEditorInput) editorRefer.getEditorInput()).getFile();
			ProjectConfiger projectConfig = ProjectConfigerFactory.getProjectConfiger(file.getProject());
			List<DatabaseModelBean> lstDatabase = projectConfig.getAllTmDbs();
			if (lstDatabase.size() == 0) {
				MessageDialog.openInformation(HandlerUtil.getActiveShell(event),
						Messages.getString("handler.ConcordanceSearchHandler.msgTitle"),
						Messages.getString("handler.ConcordanceSearchHandler.msg"));
				return null;
			}

			String selectText = xliffEditor.getSelectPureText();
			if ((selectText == null || selectText.equals("")) && xliffEditor.getSelectedRowIds().size() == 1) {
				selectText = xliffEditor.getXLFHandler().getSrcPureText(xliffEditor.getSelectedRowIds().get(0));
			} else if (selectText == null) {
				selectText = "";
			}
			ConcordanceSearchDialog dialog = new ConcordanceSearchDialog(editorRefer.getSite().getShell(), file,
					xliffEditor.getSrcColumnName(), xliffEditor.getTgtColumnName(), selectText.trim());
			dialog.open();
			if (selectText != null && !selectText.trim().equals("")) {
				dialog.initGroupIdAndSearch();
				IWorkbenchPartSite site = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getSite();
				ICommandService commandService = (ICommandService) site.getService(
						ICommandService.class);
				Command command = commandService
						.getCommand(ActionFactory.COPY.getCommandId());
				IEvaluationService evalService = (IEvaluationService) site.getService(
						IEvaluationService.class);
				IEvaluationContext currentState = evalService.getCurrentState();
				ExecutionEvent executionEvent = new ExecutionEvent(command, Collections.EMPTY_MAP, this, currentState);
				try {
					command.executeWithChecks(executionEvent);
				} catch (Exception e1) {}
			}
		}
	}
	return null;
}
 
Example 18
Source File: PreferenceCoolbarItem.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
private Command getCommand() {
    final ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
    return service.getCommand("org.eclipse.ui.window.preferences");
}
 
Example 19
Source File: HelpCoolbarItem.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
private Command getCommand() {
    final ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
    return service.getCommand("org.bonitasoft.studio.application.showHelp");
}
 
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;
}