Java Code Examples for org.eclipse.ui.IWorkbenchPartSite#getService()

The following examples show how to use org.eclipse.ui.IWorkbenchPartSite#getService() . 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: ServiceUtils.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an OSGi service from {@link ExecutionEvent}. It looks up a service in the following
 * locations (if exist) in the given order:
 *
 * {@code HandlerUtil.getActiveSite(event)}
 * {@code HandlerUtil.getActiveEditor(event).getEditorSite()}
 * {@code HandlerUtil.getActiveEditor(event).getSite()}
 * {@code HandlerUtil.getActiveWorkbenchWindow(event)}
 * {@code PlatformUI.getWorkbench()}
 */
public static <T> T getService(ExecutionEvent event, Class<T> api) {
  IWorkbenchSite activeSite = HandlerUtil.getActiveSite(event);
  if (activeSite != null) {
    return activeSite.getService(api);
  }

  IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
  if (activeEditor != null) {
    IEditorSite editorSite = activeEditor.getEditorSite();
    if (editorSite != null) {
      return editorSite.getService(api);
    }
    IWorkbenchPartSite site = activeEditor.getSite();
    if (site != null) {
      return site.getService(api);
    }
  }

  IWorkbenchWindow workbenchWindow = HandlerUtil.getActiveWorkbenchWindow(event);
  if (workbenchWindow != null) {
    return workbenchWindow.getService(api);
  }

  return PlatformUI.getWorkbench().getService(api);
}
 
Example 2
Source File: AbstractPDFViewerRunnable.java    From tlaplus with MIT License 6 votes vote down vote up
public AbstractPDFViewerRunnable(ProducePDFHandler handler, IWorkbenchPartSite site, IResource aSpecFile) {
	Assert.isNotNull(handler);
	Assert.isNotNull(site);
	Assert.isNotNull(aSpecFile);
	this.handler = handler;
	this.specFile = aSpecFile;
	
	final boolean autoRegenerate = TLA2TeXActivator.getDefault().getPreferenceStore()
			.getBoolean(ITLA2TeXPreferenceConstants.AUTO_REGENERATE);
	if (autoRegenerate) {
		// Subscribe to the event bus with which the TLA Editor save events are
		// distributed. In other words, every time the user saves a spec, we
		// receive an event and provided the spec corresponds to this PDF, we
		// regenerate it.
		// Don't subscribe in EmbeddedPDFViewerRunnable#though, because it is run
		// repeatedly and thus would cause us to subscribe multiple times.
		final IEventBroker eventService = site.getService(IEventBroker.class);
		Assert.isTrue(eventService.subscribe(TLAEditor.SAVE_EVENT, this));
		
		// Register for part close events to deregister the event handler
		// subscribed to the event bus. There is no point in regenerating
		// the PDF if no PDFEditor is open anymore.
		final IPartService partService = site.getService(IPartService.class);
		partService.addPartListener(this);
	}
}
 
Example 3
Source File: BaseYankHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * In the console context, use paste as
 * in some consoles (e.g. org.eclipse.debug.internal.ui.views.console.ProcessConsole), updateText
 * will not simulate keyboard input
 *  
 * @param event the ExecutionEvent
 * @param widget The consoles StyledText widget
 */
protected void paste(ExecutionEvent event, StyledText widget) {
		IWorkbenchPart apart = HandlerUtil.getActivePart(event);
		if (apart != null) {
			try {
				IWorkbenchPartSite site = apart.getSite();
				if (site != null) {
					IHandlerService service = (IHandlerService) site.getService(IHandlerService.class);
					if (service != null) {
						service.executeCommand(IEmacsPlusCommandDefinitionIds.EMP_PASTE, null);
						KillRing.getInstance().setYanked(true);
					}
				}
			} catch (CommandException e) {
			}
		}
}
 
Example 4
Source File: VisualInterfaceFactory.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ViewInstance createViewInstance ( final ViewManager viewManager, final ViewManagerContext viewManagerContext, final ViewInstanceDescriptor descriptor, final Composite viewHolder, final ResourceManager manager, final IWorkbenchPartSite site )
{
    final VisualInterfaceViewInstance instance = new VisualInterfaceViewInstance ( viewManager, viewManagerContext, viewHolder, descriptor, site.getService ( IEvaluationService.class ) );
    instance.init ();
    return instance;
}
 
Example 5
Source File: ChartViewFactory.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ViewInstance createViewInstance ( final ViewManager viewManager, final ViewManagerContext viewManagerContext, final ViewInstanceDescriptor descriptor, final Composite viewHolder, final ResourceManager manager, final IWorkbenchPartSite site )
{
    final ChartView view = new ChartView ( viewManagerContext, manager, descriptor, viewHolder, (IEvaluationService)site.getService ( IEvaluationService.class ), true );
    view.init ();
    return view;
}
 
Example 6
Source File: SWTBotUtils.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Maximize a part. Calling this a second time will "un-maximize" a part.
 *
 * @param part
 *            the workbench part
 */
public static void maximize(@NonNull IWorkbenchPart part) {
    assertNotNull(part);
    IWorkbenchPartSite site = part.getSite();
    assertNotNull(site);
    // The annotation is to make the compiler not complain.
    @Nullable Object handlerServiceObject = site.getService(IHandlerService.class);
    assertTrue(handlerServiceObject instanceof IHandlerService);
    IHandlerService handlerService = (IHandlerService) handlerServiceObject;
    try {
        handlerService.executeCommand(IWorkbenchCommandConstants.WINDOW_MAXIMIZE_ACTIVE_VIEW_OR_EDITOR, null);
    } catch (ExecutionException | NotDefinedException | NotEnabledException | NotHandledException e) {
        fail(e.getMessage());
    }
}
 
Example 7
Source File: FindBarActions.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
private void setFindBarContextActive(boolean activate)
{
	fActivated = activate;
	IWorkbenchPartSite site = textEditor.getSite();
	IHandlerService handlerService = (IHandlerService) site.getService(IHandlerService.class);
	IBindingService service = (IBindingService) site.getService(IBindingService.class);

	if (activate)
	{

		// These will be the only active commands (note that they may have multiple keybindings
		// defined in plugin.xml)
		for (Map.Entry<String, AbstractHandler> entry : fCommandToHandler.entrySet())
		{
			AbstractHandler handler = entry.getValue();
			if (handler != null)
			{
				fHandlerActivations.add(handlerService.activateHandler(entry.getKey(), handler));
			}
		}

		// Yes, no longer execute anything from the binding service (we'll do our own handling so that the commands
		// we need still get executed).
		service.setKeyFilterEnabled(false);

		service.addBindingManagerListener(fClearCommandToBindingOnChangesListener);
	}
	else
	{
		fCommandToBinding = null;
		service.setKeyFilterEnabled(true);

		service.removeBindingManagerListener(fClearCommandToBindingOnChangesListener);
		handlerService.deactivateHandlers(fHandlerActivations);
		fHandlerActivations.clear();
	}
}
 
Example 8
Source File: ConsoleCopyCutHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.ConsoleCmdHandler#consoleDispatch(TextConsoleViewer, IConsoleView, ExecutionEvent)
 */
@Override
public Object consoleDispatch(TextConsoleViewer viewer, IConsoleView activePart, ExecutionEvent event) {
	Object result = null;
	IDocument doc = viewer.getDocument();
	try {
		IWorkbenchPartSite site = activePart.getSite();
		if (site != null) {
			IHandlerService service = (IHandlerService) site.getService(IHandlerService.class);
			if (doc != null && service != null) {
				doc.addDocumentListener(KillRing.getInstance());
				String cmdId = getId(event, viewer);
				if (cmdId != null) {
					result = service.executeCommand(cmdId, null);
				}
			}
		}
	} catch (CommandException e) {
		// Shouldn't happen as the Command id will be null or valid
		e.printStackTrace();
	} finally {
		if (doc != null) {
			doc.removeDocumentListener(KillRing.getInstance());
		}
		// clear kill command flag
		KillRing.getInstance().setKill(null, false);
	}
	
	MarkUtils.clearConsoleMark(viewer);
	return result;
}
 
Example 9
Source File: AbstractTimeGraphView.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Forces a rebuild of the entries list, even if entries already exist for this
 * trace
 */
protected void rebuild() {
    try (FlowScopeLog parentLogger = new FlowScopeLogBuilder(LOGGER, Level.FINE, "TimeGraphView:Rebuilding").setCategory(getViewId()).build()) { //$NON-NLS-1$
        setTimeBoundsAndRefresh();
        ITmfTrace viewTrace = fTrace;
        if (viewTrace == null) {
            return;
        }
        resetView(viewTrace);

        List<IMarkerEventSource> markerEventSources = new ArrayList<>();
        synchronized (fBuildJobMap) {
            // Run the build jobs through the site progress service if available
            IWorkbenchSiteProgressService service = null;
            IWorkbenchPartSite site = getSite();
            if (site != null) {
                service = site.getService(IWorkbenchSiteProgressService.class);
            }
            for (ITmfTrace trace : getTracesToBuild(viewTrace)) {
                if (trace == null) {
                    break;
                }
                List<@NonNull IMarkerEventSource> adapters = TmfTraceAdapterManager.getAdapters(trace, IMarkerEventSource.class);
                markerEventSources.addAll(adapters);

                Job buildJob = new Job(getTitle() + Messages.AbstractTimeGraphView_BuildJob) {
                    @Override
                    protected IStatus run(IProgressMonitor monitor) {
                        new BuildRunnable(trace, viewTrace, parentLogger).run(monitor);
                        monitor.done();
                        return Status.OK_STATUS;
                    }
                };
                fBuildJobMap.put(trace, buildJob);
                if (service != null) {
                    service.schedule(buildJob);
                } else {
                    buildJob.schedule();
                }
            }
        }
        fMarkerEventSourcesMap.put(viewTrace, markerEventSources);
    }
}
 
Example 10
Source File: FindBarActions.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @return a map with the commands -> bindings available.
 */
public HashMap<String, List<TriggerSequence>> getCommandToBindings()
{
	HashMap<String, List<TriggerSequence>> commandToBinding = new HashMap<String, List<TriggerSequence>>();

	IWorkbenchPartSite site = textEditor.getSite();
	IBindingService service = (IBindingService) site.getService(IBindingService.class);
	Binding[] bindings = service.getBindings();

	for (int i = 0; i < bindings.length; i++)
	{
		Binding binding = bindings[i];
		ParameterizedCommand command = binding.getParameterizedCommand();
		if (command != null)
		{
			String id = command.getId();
			// Filter only the actions we decided would be active.
			//
			// Note: we don't just make all actions active because they conflict with the find bar
			// expected accelerators, so, things as Alt+W don't work -- even a second Ctrl+F isn't properly
			// treated as specified in the options.
			// A different option could be filtering those out and let everything else enabled,
			// but this would need to be throughly tested to know if corner-cases work.
			if (fCommandToHandler.containsKey(id))
			{
				List<TriggerSequence> list = commandToBinding.get(id);
				if (list == null)
				{
					list = new ArrayList<TriggerSequence>();
					commandToBinding.put(id, list);
				}
				list.add(binding.getTriggerSequence());
			}

			// Uncomment to know which actions will be disabled
			// else
			// {
			// try
			// {
			// System.out.println("Command disabled: " + id + ": " + command.getName());
			// }
			// catch (NotDefinedException e)
			// {
			//
			// }
			// }
		}
	}
	return commandToBinding;
}
 
Example 11
Source File: ConcordanceSearchHandler.java    From translationstudio8 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) {
		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 = "";
			}
			String srcLang = xliffEditor.getSrcColumnName();
			String tgtLang = xliffEditor.getTgtColumnName();
			ConcordanceSearchDialog dialog = new ConcordanceSearchDialog(editorRefer.getSite().getShell(), file,
					srcLang,tgtLang, selectText.trim());
			Language srcLangL = LocaleService.getLanguageConfiger().getLanguageByCode(srcLang);
			Language tgtLangL = LocaleService.getLanguageConfiger().getLanguageByCode(tgtLang);
			dialog.open();
			if (srcLangL.isBidi() || tgtLangL.isBidi()) {
				dialog.getShell().setOrientation(SWT.RIGHT_TO_LEFT);
			}
			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 12
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 13
Source File: FirstCharAction.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a handler that will properly treat home considering python code (if it's still not defined
 * by the platform -- otherwise, just go with what the platform provides).
 */
public static VerifyKeyListener createVerifyKeyListener(final SourceViewer viewer, final IWorkbenchPartSite site,
        boolean forceCreation) {
    // This only needs to be done for eclipse 3.2 (where line start is not
    // defined).
    // Eclipse 3.3 onwards already defines the home key in the text editor.

    final boolean isDefined;
    if (site != null) {
        ICommandService commandService = (ICommandService) site.getService(ICommandService.class);
        Collection definedCommandIds = commandService.getDefinedCommandIds();
        isDefined = definedCommandIds.contains("org.eclipse.ui.edit.text.goto.lineStart");

    } else {
        isDefined = false;
    }

    if (forceCreation || !isDefined) {
        return new VerifyKeyListener() {

            @Override
            public void verifyKey(VerifyEvent event) {
                if (event.doit) {
                    boolean isHome;
                    if (isDefined) {
                        isHome = KeyBindingHelper.matchesKeybinding(event.keyCode, event.stateMask,
                                "org.eclipse.ui.edit.text.goto.lineStart");
                    } else {
                        isHome = event.keyCode == SWT.HOME && event.stateMask == 0;
                    }
                    if (isHome) {
                        ISelection selection = viewer.getSelection();
                        if (selection instanceof ITextSelection) {
                            FirstCharAction firstCharAction = new FirstCharAction();
                            firstCharAction.viewer = viewer;
                            firstCharAction.perform(viewer.getDocument(), (ITextSelection) selection);
                            event.doit = false;
                        }
                    }
                }
            }
        };
    }
    return null;
}