org.eclipse.ui.IWorkbenchPartSite#getService ( )源码实例Demo

下面列出了org.eclipse.ui.IWorkbenchPartSite#getService ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: google-cloud-eclipse   文件: ServiceUtils.java
/**
 * 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);
}
 
源代码2 项目: tlaplus   文件: AbstractPDFViewerRunnable.java
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);
	}
}
 
源代码3 项目: e4macs   文件: BaseYankHandler.java
/**
 * 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) {
			}
		}
}
 
源代码4 项目: neoscada   文件: VisualInterfaceFactory.java
@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;
}
 
源代码5 项目: neoscada   文件: ChartViewFactory.java
@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;
}
 
源代码6 项目: tracecompass   文件: SWTBotUtils.java
/**
 * 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());
    }
}
 
源代码7 项目: APICloud-Studio   文件: FindBarActions.java
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();
	}
}
 
源代码8 项目: e4macs   文件: ConsoleCopyCutHandler.java
/**
 * @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;
}
 
源代码9 项目: tracecompass   文件: AbstractTimeGraphView.java
/**
 * 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);
    }
}
 
源代码10 项目: APICloud-Studio   文件: FindBarActions.java
/**
 * @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;
}
 
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;
}
 
源代码12 项目: tmxeditor8   文件: ConcordanceSearchHandler.java
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;
}
 
源代码13 项目: Pydev   文件: FirstCharAction.java
/**
 * 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;
}