下面列出了怎么用org.eclipse.ui.IWorkbenchPart的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (part == null || selection == null) {
return;
}
if (!(part instanceof TmxEditorViewer)) {
return;
}
if (selection.isEmpty() || !(selection instanceof IStructuredSelection)) {
return;
}
// tgtLangcodeInTmxEditor = TmxEditorViewer.getInstance().getTmxEditor().getTgtLang();
StructuredSelection struct = (StructuredSelection) selection;
Object obj = struct.getFirstElement();
if (obj instanceof TmxEditorSelection) {
currentSelected = (TmxEditorSelection) obj;
tableViewerManager.get(TU_ATTRS).setInput(new TableViewerInput(TU_ATTRS, currentSelected));
tableViewerManager.get(TUV_ATTRS).setInput(new TableViewerInput(TUV_ATTRS, currentSelected));
tableViewerManager.get(TU_NODE_NOTE).setInput(null);
tableViewerManager.get(TU_NODE_NOTE).setInput(new TableViewerInput(TU_NODE_NOTE, currentSelected));
tableViewerManager.get(TU_NODE_PROPS).setInput(new TableViewerInput(TU_NODE_PROPS, currentSelected));
compostie.layout();
scrolledComposite.setMinSize(compostie.computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
}
@Override
public boolean isEnabled() {
// Check if we are closing down
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window == null) {
return false;
}
// Get the selection
IWorkbenchPage page = window.getActivePage();
IWorkbenchPart part = page.getActivePart();
if (part instanceof FilterView) {
FilterView tcv = (FilterView) part;
ISelection selection = tcv.getSite().getSelectionProvider().getSelection();
// only enable if tree is in focus
if (!selection.isEmpty() && tcv.isTreeInFocus()) {
return true;
}
}
return false;
}
private void updateActions() {
IWorkbenchPart activePart= JavaPlugin.getActivePage().getActivePart();
if (!(activePart instanceof JavaEditor))
return;
ISelection javaSelection= getEditorSelection((JavaEditor) activePart);
if (javaSelection == null)
return;
for (int i= 0; i < fRetargetActions.length; i++) {
RetargetAction action= fRetargetActions[i];
IAction actionHandler= action.getActionHandler();
if (actionHandler instanceof SelectionDispatchAction) {
((SelectionDispatchAction) actionHandler).update(javaSelection);
}
}
}
public PartListenerGroup(ITextEditor editorPart) {
fPart= editorPart;
fCurrentJob= null;
fAstListeners= new ListenerList(ListenerList.IDENTITY);
fSelectionListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection= event.getSelection();
if (selection instanceof ITextSelection) {
fireSelectionChanged((ITextSelection) selection);
}
}
};
fPostSelectionListener= new ISelectionListener() {
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (part == fPart && selection instanceof ITextSelection)
firePostSelectionChanged((ITextSelection) selection);
}
};
}
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (part instanceof XtextEditor && !selection.isEmpty()) {
final XtextEditor editor = (XtextEditor) part;
final IXtextDocument document = editor.getDocument();
document.readOnly(new IUnitOfWork.Void<XtextResource>() {
@Override
public void process(XtextResource resource) throws Exception {
IParseResult parseResult = resource.getParseResult();
if (parseResult != null) {
ICompositeNode root = parseResult.getRootNode();
EObject taxonomy = NodeModelUtils.findActualSemanticObjectFor(root);
if (taxonomy instanceof Model) {
ModelRegistryPlugin.getModelRegistry().setActiveTaxonomy((Model) taxonomy);
}
}
}
});
}
}
/**
* @param part
*/
public ResetImageSizeAction( IWorkbenchPart part )
{
super( part );
setId( ID );
setText( LABEL );
}
public ChangeBackgroundColorAction(IWorkbenchPart part, ERDiagram diagram) {
super(part, Action.AS_DROP_DOWN_MENU);
this.setId(ID);
this.setText(ResourceString
.getResourceString("action.title.change.background.color"));
this.setToolTipText(ResourceString
.getResourceString("action.title.change.background.color"));
int[] defaultColor = diagram.getDefaultColor();
this.rgb = new RGB(defaultColor[0], defaultColor[1], defaultColor[2]);
this.setColorToImage();
}
public void close() {
if (close) {
return;
}
for (Listener listener : closingListeners) {
Event event = new Event();
event.data = this;
listener.handleEvent(event);
}
close = true; // 状态改为已经关闭
xliffEditor.getTable().removeDisposeListener(this);
StyledText text = viewer.getTextWidget();
if (text != null && !text.isDisposed()) {
actionHandler.removeTextViewer();
text.setMenu(null); // dispose前应去掉右键menu,因为右键menu是和nattable共享的
viewer.reset();
text.dispose();
text = null;
}
// 如果 XLIFF 编辑器仍处于激活状态,则把焦点交给编辑器
try {
IWorkbenchPart activepart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.getActivePart();
if (xliffEditor.equals(activepart)) {
xliffEditor.setFocus();
}
} catch (NullPointerException e) {
}
// NatTable table = xliffEditor.getTable();
// int[] rowPositions = new int[] { hsCellEditor.getRowPosition() };
// table.doCommand(new AutoResizeCurrentRowsCommand(table, rowPositions, table.getConfigRegistry()));
}
@Override
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
if (targetPart instanceof CommonNavigator) {
navigator = (CommonNavigator) targetPart;
useSpecificPattern = action.getId().startsWith("de.tobject.findbugs.filterSpecificPattern");
}
}
@Override
public boolean isEnabled() {
// Check if we are closing down
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window == null) {
return false;
}
// Get the selection
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IWorkbenchPart part = page.getActivePart();
if (part == null) {
return false;
}
ISelectionProvider selectionProvider = part.getSite().getSelectionProvider();
if (selectionProvider == null) {
return false;
}
ISelection selection = selectionProvider.getSelection();
// Make sure there is only one selection and that it is an experiment
fExperiment = null;
if (selection instanceof TreeSelection) {
TreeSelection sel = (TreeSelection) selection;
// There should be only one item selected as per the plugin.xml
Object element = sel.getFirstElement();
if (element instanceof TmfExperimentElement) {
fExperiment = (TmfExperimentElement) element;
}
}
return (fExperiment != null);
}
/** Replies the Java element that corresponds to the given selection.
*
* @param selection the current selection.
* @return the Java element.
*/
@SuppressWarnings("static-method")
public IJavaElement getSelectedResource(IStructuredSelection selection) {
IJavaElement elem = null;
if (selection != null && !selection.isEmpty()) {
final Object object = selection.getFirstElement();
if (object instanceof IAdaptable) {
final IAdaptable adaptable = (IAdaptable) object;
elem = adaptable.getAdapter(IJavaElement.class);
if (elem == null) {
elem = getPackage(adaptable);
}
}
}
if (elem == null) {
final IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IWorkbenchPart part = activePage.getActivePart();
if (part instanceof ContentOutline) {
part = activePage.getActiveEditor();
}
if (part instanceof XtextEditor) {
final IXtextDocument doc = ((XtextEditor) part).getDocument();
final IFile file = doc.getAdapter(IFile.class);
elem = getPackage(file);
}
}
if (elem == null || elem.getElementType() == IJavaElement.JAVA_MODEL) {
try {
final IJavaProject[] projects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
if (projects.length == 1) {
elem = projects[0];
}
} catch (JavaModelException e) {
throw new RuntimeException(e.getMessage());
}
}
return elem;
}
/**
* Maximize a workbench part and wait for one of its controls to be resized.
* Calling this a second time will "un-maximize" the part.
*
* @param partReference
* the {@link IWorkbenchPartReference} which contains the control
* @param controlBot
* a control that should be resized
*/
public static void maximize(IWorkbenchPartReference partReference, AbstractSWTBotControl<?> controlBot) {
final AtomicBoolean controlResized = new AtomicBoolean();
Control control = controlBot.widget;
assertNotNull(control);
UIThreadRunnable.syncExec(new VoidResult() {
@Override
public void run() {
control.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
control.removeControlListener(this);
controlResized.set(true);
}
});
}
});
IWorkbenchPart part = partReference.getPart(false);
assertNotNull(part);
maximize(part);
new SWTBot().waitUntil(new DefaultCondition() {
@Override
public boolean test() throws Exception {
return controlResized.get();
}
@Override
public String getFailureMessage() {
return "Control was not resized";
}
});
}
/**
* Hides all the working sets in the list from the Package Explorer.
*
* @param selection the selection of working sets
* @since 3.8
*/
private void hideWorkingSets(List<IWorkingSet> selection) {
IWorkbenchPage page= JavaPlugin.getActivePage();
if (page != null) {
IWorkbenchPart activePart= page.getActivePart();
if (activePart instanceof PackageExplorerPart) {
PackageExplorerPart packagePart= (PackageExplorerPart) activePart;
WorkingSetModel model= packagePart.getWorkingSetModel();
List<IWorkingSet> activeWorkingSets= new ArrayList<IWorkingSet>(Arrays.asList(model.getActiveWorkingSets()));
activeWorkingSets.removeAll(selection);
model.setActiveWorkingSets(activeWorkingSets.toArray(new IWorkingSet[activeWorkingSets.size()]));
}
}
}
@Override
protected IWorkbenchPart doOpen() {
FilterImplementationWizard wizard = new FilterImplementationWizard(getContent());
WizardDialog wd = new WizardDialog(Display.getCurrent().getActiveShell(), wizard);
wd.open();
return null;
}
private static void switchEditor(IWorkbenchPage activePage, boolean next)
{
IEditorPart activeEditor = activePage.getActiveEditor();
if (activeEditor != null)
{
IEditorReference[] editorReferences = activePage.getEditorReferences();
if (editorReferences != null && editorReferences.length >= 2)
{
List<IEditorPart> editorsList = new LinkedList<IEditorPart>();
for (IEditorReference editorReference : editorReferences)
{
IWorkbenchPart editorPart = editorReference.getPart(true);
if (editorPart instanceof IEditorPart)
{
editorsList.add((IEditorPart) editorPart);
}
}
int activeEditorIndex = editorsList.indexOf(activeEditor);
int toEditorIndex = ((activeEditorIndex == -1) ? 0 : (activeEditorIndex + (next ? 1 : -1)));
if (toEditorIndex < 0)
{
toEditorIndex = editorsList.size() - 1;
}
else if (toEditorIndex >= editorsList.size())
{
toEditorIndex = 0;
}
activePage.activate(editorsList.get(toEditorIndex));
}
}
}
/**
* Add a listener to the global selection service and set the currently selected query
*/
protected void addListener ()
{
if ( this.selectionListener == null )
{
getViewSite ().getWorkbenchWindow ().getSelectionService ().addSelectionListener ( this.selectionListener = new ISelectionListener () {
@Override
public void selectionChanged ( final IWorkbenchPart part, final ISelection selection )
{
QueryViewPart.this.setSelection ( selection );
}
} );
}
}
public RepositoryBranchTagOperation(IWorkbenchPart part, ISVNClientAdapter svnClient, SVNUrl[] sourceUrls, SVNUrl destinationUrl, SVNRevision revision, String message, boolean makeParents) {
super(part);
this.svnClient = svnClient;
this.sourceUrls = sourceUrls;
this.destinationUrl = destinationUrl;
this.revision = revision;
this.message = message;
this.makeParents = makeParents;
}
/**
* Constructs a insert row action.
*
* @param part
* work bench part.
*/
public InsertRowAction( IWorkbenchPart part )
{
super( part );
setId( ID );
setText( ACTION_MSG_INSERT );
}
public void partVisible(IWorkbenchPartReference ref) {
if (ref.getId().equals(getSite().getId())) {
IWorkbenchPart activePart= ref.getPage().getActivePart();
if (activePart != null)
selectionChanged(activePart, ref.getPage().getSelection());
startListeningForSelectionChanges();
}
}
@Override
public void setInput(final IWorkbenchPart part, final ISelection selection) {
super.setInput(part, selection);
for (final IExtensibleGridPropertySectionContribution contrib : contributions) {
if (contrib.isRelevantFor(getEObject())) {
contrib.setSelection(selection);
}
}
if (part instanceof DiagramEditor) {
this.part = part;
((DiagramEditor) part).getDiagramGraphicalViewer().removeSelectionChangedListener(selectionListener);
((DiagramEditor) part).getDiagramGraphicalViewer().addSelectionChangedListener(selectionListener);
}
}
protected Pair<URI, IXtextDocument> getEntry(IWorkbenchPartReference partRef) {
IWorkbenchPart part = partRef.getPart(false);
if (part instanceof XtextEditor) {
XtextEditor xtextEditor = (XtextEditor) part;
URI resourceURI = getResourceURI(xtextEditor);
IXtextDocument document = xtextEditor.getDocument();
if (resourceURI != null && document != null)
return Tuples.create(resourceURI, document);
}
return null;
}
public void selectionChanged( IWorkbenchPart part, ISelection selection )
{
deactivateCellEditor( );
if ( SessionHandleAdapter.getInstance( ).getModule( ) == moduleHandle )
{
if ( part != null
&& !ReportPlugin.getDefault( )
.containIgnoreViewID( part.getSite( ).getId( ) ) )
{
IMediator mediator = SessionHandleAdapter.getInstance( )
.getMediator( moduleHandle, false );
if ( mediator != null
&& mediator.getState( ) != null
&& mediator.getState( ).getData( ) instanceof List )
{
// When close and reopen the attribute view, display the
// old selection.
ReportRequest request = new ReportRequest( this );
request.setSelectionObject( (List) mediator.getState( )
.getData( ) );
request.setType( ReportRequest.SELECTION );
SessionHandleAdapter.getInstance( )
.getMediator( moduleHandle )
.notifyRequest( request );
}
}
}
}
/**
* Empty method to override a change in the selection
*/
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
// TODO Auto-generated method stub
// Make sure the selection is not empty before and is the right type
if (!selection.isEmpty() && selection instanceof IStructuredSelection) {
selectedItem = selection;
}
}
/**
* Sets the current selection for the given range.
*
* @param editor the editor to be operated on
* @param offset the offset of the range, must not be negative
* @param length the length of the range, must not be negative
*/
public static void setSelection(IEditorPart editor, int offset, int length)
{
ISelectionProvider provider = editor.getEditorSite().getSelectionProvider();
if (provider != null) {
IWorkbenchPart activePart = WorkbenchUtils.getActivePart();
if (activePart instanceof IEditorPart) {
IWorkbenchPage page = WorkbenchUtils.getActivePage();
page.getNavigationHistory().markLocation((IEditorPart) activePart);
}
provider.setSelection(new TextSelection(offset, length));
}
}
@Override
public void setInput(final IWorkbenchPart part, final ISelection selection) {
super.setInput(part, selection);
selectionProvider.setSelection(selection);
}
private StartedFromViewJob(String name, IResource resource, List<WorkItem> resources, IWorkbenchPart targetPart) {
super(name, resource);
this.resources = resources;
this.resource = resource;
this.targetPart = targetPart;
}
public void setActivePart(IAction action, IWorkbenchPart targetPart)
{
}
protected boolean isMatchingPart(IWorkbenchPartReference partRef) {
IWorkbenchPart visiblePart = partRef.getPart(false);
return part == visiblePart;
}
private IBoxEnabledEditor getEditor(final IWorkbenchPartReference ref) {
final IWorkbenchPart part = ref.getPart(false);
if (part == null) { return null; }
return part instanceof IBoxEnabledEditor ? (IBoxEnabledEditor) part : null;
}
/**
* Test the behavior with two traces.
*/
@Ignore
@Test
public void testPinTwoTraces() {
ITmfTrace ust = TmfTraceManager.getInstance().getActiveTrace();
assertNotNull(ust);
ITmfTrace kernelTestTrace = CtfTmfTestTraceUtils.getTrace(CtfTestTrace.CONTEXT_SWITCHES_KERNEL);
SWTBotUtils.openTrace(TRACE_PROJECT_NAME, kernelTestTrace.getPath(), TRACETYPE_ID);
/* Finish waiting for the trace to index */
WaitUtils.waitForJobs();
SWTBotEditor kernelEditor = SWTBotUtils.activateEditor(fBot, kernelTestTrace.getName());
// wait for the editor to be ready.
fBot.editorByTitle(kernelTestTrace.getName());
// assert that the pin to drop down menuItems are present for both traces.
fBot.waitUntil(new DefaultCondition() {
WidgetNotFoundException fException;
@Override
public boolean test() throws Exception {
try {
SWTBotToolbarDropDownButton toolbarDropDownButton = fOriginalViewBot.toolbarDropDownButton(PIN_VIEW_BUTTON_NAME);
toolbarDropDownButton.menuItem(PIN_TO_PREFIX + kernelTestTrace.getName());
toolbarDropDownButton.menuItem(PIN_TO_PREFIX + fUstTestTrace.getName()).click();
return true;
} catch (WidgetNotFoundException e) {
fException = e;
return false;
}
}
@Override
public String getFailureMessage() {
return "Traces not available in toolbar drop down menu: " + fException;
}
});
/*
* assert that the pinned view is the UST trace despite the active trace being
* the kernel trace.
*/
assertOriginalViewTitle(PINNED_TO_UST_TIME_GRAPH_VIEW_TITLE);
ITmfTrace activeTrace = TmfTraceManager.getInstance().getActiveTrace();
assertNotNull("There should be an active trace", activeTrace);
assertEquals("context-switches-kernel should be the active trace", kernelTestTrace.getName(), activeTrace.getName());
// Get the window range of the kernel trace
TmfTraceManager traceManager = TmfTraceManager.getInstance();
ITmfTrace kernelTrace = traceManager.getActiveTrace();
assertNotNull(kernelTrace);
// switch back and forth
SWTBotUtils.activateEditor(fBot, fUstTestTrace.getName());
assertOriginalViewTitle(PINNED_TO_UST_TIME_GRAPH_VIEW_TITLE);
SWTBotUtils.activateEditor(fBot, kernelTestTrace.getName());
assertOriginalViewTitle(PINNED_TO_UST_TIME_GRAPH_VIEW_TITLE);
IWorkbenchPart part = fOriginalViewBot.getViewReference().getPart(false);
assertTrue(part instanceof AbstractTimeGraphView);
AbstractTimeGraphView abstractTimeGraphView = (AbstractTimeGraphView) part;
TmfSignalManager.dispatchSignal(new TmfWindowRangeUpdatedSignal(this, RANGE, kernelTrace));
// assert that the ust trace's window range did not change
SWTBotUtils.activateEditor(fBot, fUstTestTrace.getName());
fBot.waitUntil(ConditionHelpers.timeGraphRangeCondition(abstractTimeGraphView, ust, INITIAL_UST_RANGE));
// unpin from another active trace
SWTBotUtils.activateEditor(fBot, kernelTrace.getName());
fOriginalViewBot.toolbarButton(UNPIN_VIEW_BUTTON_NAME).click();
assertOriginalViewTitle(TIME_GRAPH_VIEW_TITLE);
fOriginalViewBot.toolbarButton(PIN_VIEW_BUTTON_NAME).click();
assertOriginalViewTitle(PINNED_TO_KERNEL_TIME_GRAPH_VIEW_TITLE);
SWTBotTable kernelEventTable = kernelEditor.bot().table();
SWTBotTableItem kernelEvent = kernelEventTable.getTableItem(5);
kernelEvent.contextMenu(FOLLOW_TIME_UPDATES_FROM_OTHER_TRACES).click();
TmfTimeRange expectedUstWindowRange = new TmfTimeRange(TmfTimestamp.fromNanos(UST_START + SECOND), TmfTimestamp.fromNanos(UST_END - SECOND));
TmfSignalManager.dispatchSignal(new TmfWindowRangeUpdatedSignal(this, expectedUstWindowRange, ust));
fBot.waitUntil(ConditionHelpers.timeGraphRangeCondition(abstractTimeGraphView, kernelTrace, expectedUstWindowRange));
// close the pinned trace
SWTBotEditor kernelTable = fBot.editorByTitle(kernelTestTrace.getName());
kernelTable.close();
assertOriginalViewTitle(TIME_GRAPH_VIEW_TITLE);
kernelTestTrace.dispose();
}