diff options
author | Jonah Graham | 2018-11-20 16:20:42 +0000 |
---|---|---|
committer | Jonah Graham | 2018-11-22 21:47:02 +0000 |
commit | 170e654b4796bad1453ae85a427b97317d67a69a (patch) | |
tree | 6ca9b8a8fedd5fd25f97eb79c408312e256ff981 /dsf/org.eclipse.cdt.dsf.ui/src | |
parent | 35996a5c5ca5c254959ba48241eaada6dbf8628d (diff) | |
download | org.eclipse.cdt-170e654b4796bad1453ae85a427b97317d67a69a.tar.gz org.eclipse.cdt-170e654b4796bad1453ae85a427b97317d67a69a.tar.xz org.eclipse.cdt-170e654b4796bad1453ae85a427b97317d67a69a.zip |
Bug 540373: Cleanup: Format & Remove trailing whitespace
This was done by selecting all projects in Eclipse then
Source -> Clean Up... -> choosing:
- Format source code
- Remove trailing white spaces on all lines
and completing the wizard
Change-Id: I63685372c6bcc67719bcf145123bcb72e5b00394
Diffstat (limited to 'dsf/org.eclipse.cdt.dsf.ui/src')
315 files changed, 28622 insertions, 28326 deletions
diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/CSourceNotFoundDescriptionFactory.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/CSourceNotFoundDescriptionFactory.java index 57fc7705fdc..75a4cc3cd42 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/CSourceNotFoundDescriptionFactory.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/CSourceNotFoundDescriptionFactory.java @@ -85,7 +85,7 @@ public class CSourceNotFoundDescriptionFactory implements IAdapterFactory { /** * Creates a brief description of stack frame data. Based on code in * StackFrameVMNode. - * + * * @param frame * @return the frame description */ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/DebugTextHoverAdapterFactory.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/DebugTextHoverAdapterFactory.java index 2c183fb1c3b..70f0d5a674a 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/DebugTextHoverAdapterFactory.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/DebugTextHoverAdapterFactory.java @@ -23,36 +23,36 @@ import org.eclipse.core.runtime.IAdapterFactory; /** * Adapter factory adapting an {@link IDMVMContext} to an {@link ICEditorTextHover}. - * + * * @since 2.1 */ public class DebugTextHoverAdapterFactory implements IAdapterFactory { - private static final Class<?>[] TYPES = { ICEditorTextHover.class }; - private static final Object fDebugTextHover= new DsfDebugTextHover(); - - @SuppressWarnings("unchecked") + private static final Class<?>[] TYPES = { ICEditorTextHover.class }; + private static final Object fDebugTextHover = new DsfDebugTextHover(); + + @SuppressWarnings("unchecked") @Override - public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { - if (adaptableObject instanceof IDMVMContext) { - IDMContext dmc = ((IDMVMContext) adaptableObject).getDMContext(); - // try session specific hover - T sessionHover = dmc.getAdapter(adapterType); - if (sessionHover != null) { - return sessionHover; - } - // use default - IFrameDMContext frameDmc = DMContexts.getAncestorOfType(dmc, IFrameDMContext.class); - if (frameDmc != null) { - return (T)fDebugTextHover; - } - } - return null; - } + public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { + if (adaptableObject instanceof IDMVMContext) { + IDMContext dmc = ((IDMVMContext) adaptableObject).getDMContext(); + // try session specific hover + T sessionHover = dmc.getAdapter(adapterType); + if (sessionHover != null) { + return sessionHover; + } + // use default + IFrameDMContext frameDmc = DMContexts.getAncestorOfType(dmc, IFrameDMContext.class); + if (frameDmc != null) { + return (T) fDebugTextHover; + } + } + return null; + } - @Override - public Class<?>[] getAdapterList() { - return TYPES; - } + @Override + public Class<?>[] getAdapterList() { + return TYPES; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/DisassemblyToggleBreakpointsTarget.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/DisassemblyToggleBreakpointsTarget.java index e785db96408..0d54e8c153c 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/DisassemblyToggleBreakpointsTarget.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/DisassemblyToggleBreakpointsTarget.java @@ -34,39 +34,37 @@ public class DisassemblyToggleBreakpointsTarget extends AbstractDisassemblyBreak * @see org.eclipse.cdt.dsf.debug.internal.ui.disassembly.provisional.AbstractDisassemblyBreakpointsTarget#createLineBreakpoint(java.lang.String, org.eclipse.core.resources.IResource, int) */ @Override - protected void createLineBreakpoint( String sourceHandle, IResource resource, int lineNumber ) throws CoreException { - CDIDebugModel.createLineBreakpoint( sourceHandle, resource, getBreakpointType(), lineNumber, true, 0, "", true ); //$NON-NLS-1$ + protected void createLineBreakpoint(String sourceHandle, IResource resource, int lineNumber) throws CoreException { + CDIDebugModel.createLineBreakpoint(sourceHandle, resource, getBreakpointType(), lineNumber, true, 0, "", true); //$NON-NLS-1$ + } + + @Override + protected void createLineBreakpointInteractive(IWorkbenchPart part, String sourceHandle, IResource resource, + int lineNumber) throws CoreException { + ICLineBreakpoint lineBp = CDIDebugModel.createBlankLineBreakpoint(); + Map<String, Object> attributes = new HashMap<String, Object>(); + CDIDebugModel.setLineBreakpointAttributes(attributes, sourceHandle, getBreakpointType(), lineNumber, true, 0, + ""); //$NON-NLS-1$ + openBreakpointPropertiesDialog(lineBp, part, resource, attributes); } - @Override - protected void createLineBreakpointInteractive(IWorkbenchPart part, String sourceHandle, IResource resource, - int lineNumber) throws CoreException - { - ICLineBreakpoint lineBp = CDIDebugModel.createBlankLineBreakpoint(); - Map<String, Object> attributes = new HashMap<String, Object>(); - CDIDebugModel.setLineBreakpointAttributes( - attributes, sourceHandle, getBreakpointType(), lineNumber, true, 0, "" ); //$NON-NLS-1$ - openBreakpointPropertiesDialog(lineBp, part, resource, attributes); - } - /* (non-Javadoc) * @see org.eclipse.cdt.dsf.debug.internal.ui.disassembly.provisional.AbstractDisassemblyBreakpointsTarget#createAddressBreakpoint(org.eclipse.core.resources.IResource, org.eclipse.cdt.core.IAddress) */ @Override - protected void createAddressBreakpoint( IResource resource, IAddress address ) throws CoreException { - CDIDebugModel.createAddressBreakpoint( null, null, resource, getBreakpointType(), address, true, 0, "", true ); //$NON-NLS-1$ + protected void createAddressBreakpoint(IResource resource, IAddress address) throws CoreException { + CDIDebugModel.createAddressBreakpoint(null, null, resource, getBreakpointType(), address, true, 0, "", true); //$NON-NLS-1$ } - @Override - protected void createAddressBreakpointInteractive(IWorkbenchPart part, IResource resource, IAddress address) - throws CoreException - { - ICLineBreakpoint lineBp = CDIDebugModel.createBlankAddressBreakpoint(); - Map<String, Object> attributes = new HashMap<String, Object>(); - CDIDebugModel.setAddressBreakpointAttributes( - attributes, null, null, getBreakpointType(), -1, address, true, 0, "" ); //$NON-NLS-1$ - openBreakpointPropertiesDialog(lineBp, part, resource, attributes); - } + @Override + protected void createAddressBreakpointInteractive(IWorkbenchPart part, IResource resource, IAddress address) + throws CoreException { + ICLineBreakpoint lineBp = CDIDebugModel.createBlankAddressBreakpoint(); + Map<String, Object> attributes = new HashMap<String, Object>(); + CDIDebugModel.setAddressBreakpointAttributes(attributes, null, null, getBreakpointType(), -1, address, true, 0, + ""); //$NON-NLS-1$ + openBreakpointPropertiesDialog(lineBp, part, resource, attributes); + } protected int getBreakpointType() { return ICBreakpointType.REGULAR; diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/EvaluationContextManager.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/EvaluationContextManager.java index ed71b276ce9..6b84831d599 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/EvaluationContextManager.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/EvaluationContextManager.java @@ -13,7 +13,7 @@ * Ericsson - DSF-GDB version * Nokia - Made generic to DSF *******************************************************************************/ -package org.eclipse.cdt.dsf.debug.internal.ui; +package org.eclipse.cdt.dsf.debug.internal.ui; import org.eclipse.cdt.dsf.ui.viewmodel.datamodel.IDMVMContext; import org.eclipse.debug.ui.DebugUITools; @@ -27,23 +27,23 @@ import org.eclipse.ui.IWindowListener; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; - + /** * Manages the current evaluation context (stack frame) for evaluation actions. * In each page, the selection is tracked in each debug view (if any). When a debug * target selection exists, the "debuggerActive" System property is set to true. * This property is used to make the "Run to Line", "Resume at Line", * "Move to Line" and "Add Watch Expression" actions - * visible in editors only if there is a running debug session. + * visible in editors only if there is a running debug session. */ public class EvaluationContextManager implements IWindowListener, IDebugContextListener { - // Avoid referencing the cdt.debug.ui plugin for this constnat so that the - // cdt.debug.ui is not automatically activated - // Bug 343867. - private static final String CDT_DEBUG_UI_PLUGIN_ID = "org.eclipse.cdt.debug.ui"; //$NON-NLS-1$ - - // Must use the same ID than the base CDT uses since we want to enable actions that are registered by base CDT. + // Avoid referencing the cdt.debug.ui plugin for this constnat so that the + // cdt.debug.ui is not automatically activated + // Bug 343867. + private static final String CDT_DEBUG_UI_PLUGIN_ID = "org.eclipse.cdt.debug.ui"; //$NON-NLS-1$ + + // Must use the same ID than the base CDT uses since we want to enable actions that are registered by base CDT. private final static String DEBUGGER_ACTIVE = CDT_DEBUG_UI_PLUGIN_ID + ".debuggerActive"; //$NON-NLS-1$ protected static EvaluationContextManager fgManager; @@ -56,91 +56,91 @@ public class EvaluationContextManager implements IWindowListener, IDebugContextL @Override public void run() { - if ( fgManager == null ) { + if (fgManager == null) { // FindBugs reported that it is unsafe to set s_resources // before we finish to initialize the object, because of // multi-threading. This is why we use a temporary variable. EvaluationContextManager manager = new EvaluationContextManager(); IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchWindow[] windows = workbench.getWorkbenchWindows(); - for( int i = 0; i < windows.length; i++ ) { - manager.windowOpened( windows[i] ); + for (int i = 0; i < windows.length; i++) { + manager.windowOpened(windows[i]); } - workbench.addWindowListener( manager ); - + workbench.addWindowListener(manager); + fgManager = manager; } } }; Display display = Display.getCurrent(); - if ( display == null ) + if (display == null) display = Display.getDefault(); - display.asyncExec( r ); + display.asyncExec(r); } /* (non-Javadoc) * @see org.eclipse.ui.IWindowListener#windowActivated(org.eclipse.ui.IWorkbenchWindow) */ @Override - public void windowActivated( IWorkbenchWindow window ) { - IDebugContextService service = DebugUITools.getDebugContextManager().getContextService(window); - service.addDebugContextListener(this); - selectionChanged( service.getActiveContext() ); + public void windowActivated(IWorkbenchWindow window) { + IDebugContextService service = DebugUITools.getDebugContextManager().getContextService(window); + service.addDebugContextListener(this); + selectionChanged(service.getActiveContext()); } /* (non-Javadoc) * @see org.eclipse.ui.IWindowListener#windowDeactivated(org.eclipse.ui.IWorkbenchWindow) */ @Override - public void windowDeactivated( IWorkbenchWindow window ) { - DebugUITools.getDebugContextManager().getContextService(window).removeDebugContextListener(this); + public void windowDeactivated(IWorkbenchWindow window) { + DebugUITools.getDebugContextManager().getContextService(window).removeDebugContextListener(this); } /* (non-Javadoc) * @see org.eclipse.ui.IWindowListener#windowClosed(org.eclipse.ui.IWorkbenchWindow) */ @Override - public void windowClosed( IWorkbenchWindow window ) { + public void windowClosed(IWorkbenchWindow window) { } /* (non-Javadoc) * @see org.eclipse.ui.IWindowListener#windowOpened(org.eclipse.ui.IWorkbenchWindow) */ @Override - public void windowOpened( IWorkbenchWindow window ) { + public void windowOpened(IWorkbenchWindow window) { } @Override public void debugContextChanged(DebugContextEvent event) { - selectionChanged(event.getContext()); + selectionChanged(event.getContext()); } - - private void selectionChanged(ISelection selection ) { - if ( selection instanceof IStructuredSelection ) { - IStructuredSelection ss = (IStructuredSelection)selection; - if ( ss.size() == 1 ) { - Object element = ss.getFirstElement(); - if ( element instanceof IDMVMContext ) { - setContext( (IDMVMContext)element ); - return; - } - } - } - // no context in the given view - removeContext(); + + private void selectionChanged(ISelection selection) { + if (selection instanceof IStructuredSelection) { + IStructuredSelection ss = (IStructuredSelection) selection; + if (ss.size() == 1) { + Object element = ss.getFirstElement(); + if (element instanceof IDMVMContext) { + setContext((IDMVMContext) element); + return; + } + } + } + // no context in the given view + removeContext(); } /** * Sets the evaluation context. */ - private void setContext( IDMVMContext target ) { - System.setProperty( DEBUGGER_ACTIVE, Boolean.TRUE.toString() ); + private void setContext(IDMVMContext target) { + System.setProperty(DEBUGGER_ACTIVE, Boolean.TRUE.toString()); } /** * Removes an evaluation context. */ private void removeContext() { - System.setProperty( DEBUGGER_ACTIVE, Boolean.FALSE.toString() ); + System.setProperty(DEBUGGER_ACTIVE, Boolean.FALSE.toString()); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/ExpressionInformationControlCreator.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/ExpressionInformationControlCreator.java index 1dd13b82c16..76477e9124c 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/ExpressionInformationControlCreator.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/ExpressionInformationControlCreator.java @@ -59,44 +59,45 @@ import org.eclipse.ui.IWorkbenchPartSite; /** * Creates an information control to display an expression in a hover control. * <br/> This class is derivative work from JDT's <code>ExpressionInformationControlCreator</code>. - * + * * @noextend This class is not intended to be subclassed by clients. - * + * * @since 2.1 */ @SuppressWarnings("restriction") public class ExpressionInformationControlCreator implements IInformationControlCreator { - /** - * A presentation context for the expression hover control. - * Implements equals and hashCode based on id comparison. - */ - private static final class ExpressionHoverPresentationContext extends PresentationContext { - - private ExpressionHoverPresentationContext(String id) { - super(id); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof ExpressionHoverPresentationContext) { - if (getId().equals(((PresentationContext) obj).getId())) { - return true; - } - } - return false; - } - - @Override - public int hashCode() { - return getId().hashCode(); - } - } - - class ExpressionInformationControl extends AbstractInformationControl implements IInformationControlExtension2, IViewerInputRequestor { + /** + * A presentation context for the expression hover control. + * Implements equals and hashCode based on id comparison. + */ + private static final class ExpressionHoverPresentationContext extends PresentationContext { + + private ExpressionHoverPresentationContext(String id) { + super(id); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof ExpressionHoverPresentationContext) { + if (getId().equals(((PresentationContext) obj).getId())) { + return true; + } + } + return false; + } + + @Override + public int hashCode() { + return getId().hashCode(); + } + } + + class ExpressionInformationControl extends AbstractInformationControl + implements IInformationControlExtension2, IViewerInputRequestor { /** * Dialog setting key for height @@ -104,7 +105,7 @@ public class ExpressionInformationControlCreator implements IInformationControlC private static final String HEIGHT = "HEIGHT"; //$NON-NLS-1$ /** - * Dialog setting key for width. + * Dialog setting key for width. */ private static final String WIDTH = "WIDTH"; //$NON-NLS-1$ @@ -116,7 +117,7 @@ public class ExpressionInformationControlCreator implements IInformationControlC /** * Dialog setting key for details sash weight */ - private static final String SASH_WEIGHT_DETAILS = "SashWeightDetails"; //$NON-NLS-1$ + private static final String SASH_WEIGHT_DETAILS = "SashWeightDetails"; //$NON-NLS-1$ /** * Variable to display. @@ -132,7 +133,7 @@ public class ExpressionInformationControlCreator implements IInformationControlC private ViewerInputService fInputService; - private IInformationControlCreator fInformationControlCreator; + private IInformationControlCreator fInformationControlCreator; /** * Inner class implementing IDetailPaneContainer methods. Handles changes to detail @@ -153,14 +154,14 @@ public class ExpressionInformationControlCreator implements IInformationControlC */ @Override public IStructuredSelection getCurrentSelection() { - return (IStructuredSelection)fViewer.getSelection(); + return (IStructuredSelection) fViewer.getSelection(); } /* * @see org.eclipse.debug.internal.ui.views.variables.details.IDetailPaneContainer#refreshDetailPaneContents() */ @Override - public void refreshDetailPaneContents() { + public void refreshDetailPaneContents() { fDetailPane.display(getCurrentSelection()); } @@ -185,8 +186,9 @@ public class ExpressionInformationControlCreator implements IInformationControlC */ @Override public void paneChanged(String newPaneID) { - if (DefaultDetailPane.ID.equals(newPaneID)){ - fDetailPane.getCurrentControl().setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND)); + if (DefaultDetailPane.ID.equals(newPaneID)) { + fDetailPane.getCurrentControl() + .setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } } @@ -194,7 +196,7 @@ public class ExpressionInformationControlCreator implements IInformationControlC /** * Constructs a new control in the given shell. - * + * * @param parentShell shell * @param resize whether resize is supported */ @@ -212,7 +214,7 @@ public class ExpressionInformationControlCreator implements IInformationControlC // Bug 417559: The TextViewerHoverManager constrains the size of a newly created // ExpressionInformationControl by 100 chars by 12 chars (602x182). The control // size can be expanded beyond that, however when re-created it will still be constrained. - // By removing the constraint in the presence of a non-null IDialogSettings, + // By removing the constraint in the presence of a non-null IDialogSettings, // the size gets restored properly even when previously expanded. Point dialogSettingsSize = getDialogSettingsSize(); if (dialogSettingsSize != null) { @@ -237,7 +239,7 @@ public class ExpressionInformationControlCreator implements IInformationControlC if (x > 0) { int y = getIntSetting(settings, HEIGHT); if (y > 0) { - return new Point(x,y); + return new Point(x, y); } } } @@ -247,16 +249,16 @@ public class ExpressionInformationControlCreator implements IInformationControlC @Override public void setSize(int width, int height) { - if (!isResizable() && fDetailPaneComposite != null) { - // add height of details pane - height += fDetailPaneComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y; - } - super.setSize(width, height); + if (!isResizable() && fDetailPaneComposite != null) { + // add height of details pane + height += fDetailPaneComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y; + } + super.setSize(width, height); } /** * Returns the dialog settings for this hover or <code>null</code> if none - * + * * @param create whether to create the settings */ private IDialogSettings getDialogSettings(boolean create) { @@ -270,7 +272,7 @@ public class ExpressionInformationControlCreator implements IInformationControlC /** * Returns an integer value in the given dialog settings or -1 if none. - * + * * @param settings dialog settings * @param key key * @return value or -1 if not present @@ -291,7 +293,7 @@ public class ExpressionInformationControlCreator implements IInformationControlC /** * Persists dialog settings. - * + * * @param shell */ private void persistSettings(Shell shell) { @@ -301,14 +303,13 @@ public class ExpressionInformationControlCreator implements IInformationControlC Point size = shell.getSize(); settings.put(WIDTH, size.x); settings.put(HEIGHT, size.y); - int[] weights = fSashForm.getWeights(); - if (weights.length == 1) { - settings.put(SASH_WEIGHT_TREE, weights[0]); - } - else if (weights.length == 2) { - settings.put(SASH_WEIGHT_TREE, weights[0]); - settings.put(SASH_WEIGHT_DETAILS, weights[1]); - } + int[] weights = fSashForm.getWeights(); + if (weights.length == 1) { + settings.put(SASH_WEIGHT_TREE, weights[0]); + } else if (weights.length == 2) { + settings.put(SASH_WEIGHT_TREE, weights[0]); + settings.put(SASH_WEIGHT_DETAILS, weights[1]); + } } } } @@ -337,10 +338,11 @@ public class ExpressionInformationControlCreator implements IInformationControlC // update presentation context AbstractDebugView view = getViewToEmulate(); - IPresentationContext context = new ExpressionHoverPresentationContext(IDsfDebugUIConstants.ID_EXPRESSION_HOVER); + IPresentationContext context = new ExpressionHoverPresentationContext( + IDsfDebugUIConstants.ID_EXPRESSION_HOVER); if (view != null) { // copy over properties - IPresentationContext copy = ((TreeModelViewer)view.getViewer()).getPresentationContext(); + IPresentationContext copy = ((TreeModelViewer) view.getViewer()).getPresentationContext(); try { String[] properties = copy.getProperties(); for (int i = 0; i < properties.length; i++) { @@ -354,7 +356,7 @@ public class ExpressionInformationControlCreator implements IInformationControlC fViewer = new TreeModelViewer(fSashForm, SWT.MULTI | SWT.VIRTUAL | SWT.FULL_SELECTION, context); fViewer.setAutoExpandLevel(fExpansionLevel); - + if (view != null) { // copy over filters StructuredViewer structuredViewer = (StructuredViewer) view.getViewer(); @@ -366,38 +368,40 @@ public class ExpressionInformationControlCreator implements IInformationControlC } } fInputService = new ViewerInputService(fViewer, this); - fTree = fViewer.getTree(); - - if (fShowDetailPane) { - fDetailPaneComposite = SWTFactory.createComposite(fSashForm, 1, 1, GridData.FILL_BOTH); - Layout layout = fDetailPaneComposite.getLayout(); - if (layout instanceof GridLayout) { - GridLayout gl = (GridLayout) layout; - gl.marginHeight = 0; - gl.marginWidth = 0; - } - - fDetailPane = new DetailPaneProxy(new DetailPaneContainer()); - fDetailPane.display(null); // Bring up the default pane so the user doesn't see an empty composite - - fTree.addSelectionListener(new SelectionListener() { - @Override + fTree = fViewer.getTree(); + + if (fShowDetailPane) { + fDetailPaneComposite = SWTFactory.createComposite(fSashForm, 1, 1, GridData.FILL_BOTH); + Layout layout = fDetailPaneComposite.getLayout(); + if (layout instanceof GridLayout) { + GridLayout gl = (GridLayout) layout; + gl.marginHeight = 0; + gl.marginWidth = 0; + } + + fDetailPane = new DetailPaneProxy(new DetailPaneContainer()); + fDetailPane.display(null); // Bring up the default pane so the user doesn't see an empty composite + + fTree.addSelectionListener(new SelectionListener() { + @Override public void widgetSelected(SelectionEvent e) { - fDetailPane.display((IStructuredSelection)fViewer.getSelection()); - } - @Override - public void widgetDefaultSelected(SelectionEvent e) {} - }); - } - + fDetailPane.display((IStructuredSelection) fViewer.getSelection()); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + } + initSashWeights(); // add update listener to auto-select and display details of root expression fViewerUpdateListener = new IViewerUpdateListener() { @Override public void viewerUpdatesComplete() { - fViewer.getDisplay().timerExec(100, new Runnable() { - @Override + fViewer.getDisplay().timerExec(100, new Runnable() { + @Override public void run() { if (!fViewer.getTree().isDisposed()) { TreeSelection selection = (TreeSelection) fViewer.getSelection(); @@ -412,24 +416,26 @@ public class ExpressionInformationControlCreator implements IInformationControlC } }); } + @Override public void viewerUpdatesBegin() { } + @Override public void updateStarted(IViewerUpdate update) { } + @Override public void updateComplete(IViewerUpdate update) { } }; - + fViewer.addViewerUpdateListener(fViewerUpdateListener); - setForegroundColor(getShell().getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND)); + setForegroundColor(getShell().getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND)); setBackgroundColor(getShell().getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } - /** * Attempts to find an appropriate view to emulate, this will either be the * variables view or the expressions view. @@ -449,45 +455,44 @@ public class ExpressionInformationControlCreator implements IInformationControlC return expressionsView; } return variablesView; - } + } /** - * Initializes the sash form weights from the preference store (using default values if + * Initializes the sash form weights from the preference store (using default values if * no sash weights were stored previously). */ - protected void initSashWeights(){ + protected void initSashWeights() { IDialogSettings settings = getDialogSettings(false); if (settings != null) { int tree = getIntSetting(settings, SASH_WEIGHT_TREE); if (tree > 0) { - if (fDetailPane != null) { - int details = getIntSetting(settings, SASH_WEIGHT_DETAILS); - if (details <= 0) { - details = tree / 2; - } - fSashForm.setWeights(new int[]{tree, details}); - } - else { - fSashForm.setWeights(new int[]{tree}); - } + if (fDetailPane != null) { + int details = getIntSetting(settings, SASH_WEIGHT_DETAILS); + if (details <= 0) { + details = tree / 2; + } + fSashForm.setWeights(new int[] { tree, details }); + } else { + fSashForm.setWeights(new int[] { tree }); + } } } } - @Override - public void setForegroundColor(Color foreground) { - super.setForegroundColor(foreground); - if (fDetailPaneComposite != null) { - fDetailPaneComposite.setForeground(foreground); - } - fTree.setForeground(foreground); - } + @Override + public void setForegroundColor(Color foreground) { + super.setForegroundColor(foreground); + if (fDetailPaneComposite != null) { + fDetailPaneComposite.setForeground(foreground); + } + fTree.setForeground(foreground); + } - @Override + @Override public void setBackgroundColor(Color background) { super.setBackgroundColor(background); if (fDetailPaneComposite != null) { - fDetailPaneComposite.setBackground(background); + fDetailPaneComposite.setBackground(background); } fTree.setBackground(background); } @@ -519,14 +524,14 @@ public class ExpressionInformationControlCreator implements IInformationControlC @Override public IInformationControlCreator getInformationPresenterControlCreator() { - if (fInformationControlCreator == null) { - fInformationControlCreator = new ExpressionInformationControlCreator(fShowDetailPane, fExpansionLevel) { - @Override - public IInformationControl createInformationControl(Shell shell) { - return new ExpressionInformationControl(shell, true); - } - }; - } + if (fInformationControlCreator == null) { + fInformationControlCreator = new ExpressionInformationControlCreator(fShowDetailPane, fExpansionLevel) { + @Override + public IInformationControl createInformationControl(Shell shell) { + return new ExpressionInformationControl(shell, true); + } + }; + } return fInformationControlCreator; } @@ -537,31 +542,31 @@ public class ExpressionInformationControlCreator implements IInformationControlC } - protected final boolean fShowDetailPane; - protected final int fExpansionLevel; + protected final boolean fShowDetailPane; + protected final int fExpansionLevel; - /** - * Create default expression information control creator. - * <p> - * Same as {@code ExpressionInformationControlCreator(true, 1)}. - * </p> - */ - public ExpressionInformationControlCreator() { - this(true, 1); - } + /** + * Create default expression information control creator. + * <p> + * Same as {@code ExpressionInformationControlCreator(true, 1)}. + * </p> + */ + public ExpressionInformationControlCreator() { + this(true, 1); + } /** * Create expression information control creator with customization options. - * - * @param showDetailPane if <code>true</code> the detail pane will be shown - * @param expansionLevel tree level to which the expression should be expanded by default - */ - public ExpressionInformationControlCreator(boolean showDetailPane, int expansionLevel) { - fShowDetailPane = showDetailPane; - fExpansionLevel = expansionLevel; - } - - /* + * + * @param showDetailPane if <code>true</code> the detail pane will be shown + * @param expansionLevel tree level to which the expression should be expanded by default + */ + public ExpressionInformationControlCreator(boolean showDetailPane, int expansionLevel) { + fShowDetailPane = showDetailPane; + fExpansionLevel = expansionLevel; + } + + /* * @see org.eclipse.jface.text.IInformationControlCreator#createInformationControl(org.eclipse.swt.widgets.Shell) */ @Override diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/IDsfDebugHelpContextIds.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/IDsfDebugHelpContextIds.java index 27e80c88b2c..3ee26010a6c 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/IDsfDebugHelpContextIds.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/IDsfDebugHelpContextIds.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,16 +20,16 @@ import org.eclipse.debug.ui.IDebugUIConstants; */ public interface IDsfDebugHelpContextIds { - public static final String PREFIX = IDebugUIConstants.PLUGIN_ID + "."; //$NON-NLS-1$ + public static final String PREFIX = IDebugUIConstants.PLUGIN_ID + "."; //$NON-NLS-1$ - public static final String DETAIL_PANE = PREFIX + "detail_pane_context"; //$NON-NLS-1$ - public static final String DETAIL_PANE_ASSIGN_VALUE_ACTION = PREFIX + "detail_pane_assign_value_action_context"; //$NON-NLS-1$ - public static final String DETAIL_PANE_CONTENT_ASSIST_ACTION = PREFIX + "detail_pane_content_assist_action_context"; //$NON-NLS-1$ - public static final String DETAIL_PANE_CUT_ACTION = PREFIX + "detail_pane_cut_action_context"; //$NON-NLS-1$ - public static final String DETAIL_PANE_COPY_ACTION = PREFIX + "detail_pane_copy_action_context"; //$NON-NLS-1$ - public static final String DETAIL_PANE_PASTE_ACTION = PREFIX + "detail_pane_paste_action_context"; //$NON-NLS-1$ - public static final String DETAIL_PANE_SELECT_ALL_ACTION = PREFIX + "detail_pane_select_all_action_context"; //$NON-NLS-1$ - public static final String DETAIL_PANE_FIND_REPLACE_ACTION = PREFIX + "detail_pane_find_replace_action_context"; //$NON-NLS-1$ - public static final String DETAIL_PANE_WORD_WRAP_ACTION = PREFIX + "detail_pane_word_wrap_action_context"; //$NON-NLS-1$ - public static final String DETAIL_PANE_MAX_LENGTH_ACTION = PREFIX + "detail_pane_max_length_action_context"; //$NON-NLS-1$ + public static final String DETAIL_PANE = PREFIX + "detail_pane_context"; //$NON-NLS-1$ + public static final String DETAIL_PANE_ASSIGN_VALUE_ACTION = PREFIX + "detail_pane_assign_value_action_context"; //$NON-NLS-1$ + public static final String DETAIL_PANE_CONTENT_ASSIST_ACTION = PREFIX + "detail_pane_content_assist_action_context"; //$NON-NLS-1$ + public static final String DETAIL_PANE_CUT_ACTION = PREFIX + "detail_pane_cut_action_context"; //$NON-NLS-1$ + public static final String DETAIL_PANE_COPY_ACTION = PREFIX + "detail_pane_copy_action_context"; //$NON-NLS-1$ + public static final String DETAIL_PANE_PASTE_ACTION = PREFIX + "detail_pane_paste_action_context"; //$NON-NLS-1$ + public static final String DETAIL_PANE_SELECT_ALL_ACTION = PREFIX + "detail_pane_select_all_action_context"; //$NON-NLS-1$ + public static final String DETAIL_PANE_FIND_REPLACE_ACTION = PREFIX + "detail_pane_find_replace_action_context"; //$NON-NLS-1$ + public static final String DETAIL_PANE_WORD_WRAP_ACTION = PREFIX + "detail_pane_word_wrap_action_context"; //$NON-NLS-1$ + public static final String DETAIL_PANE_MAX_LENGTH_ACTION = PREFIX + "detail_pane_max_length_action_context"; //$NON-NLS-1$ } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/IInternalDsfDebugUIConstants.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/IInternalDsfDebugUIConstants.java index 2cb2da5ae7b..f399a4fadff 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/IInternalDsfDebugUIConstants.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/IInternalDsfDebugUIConstants.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,10 +19,10 @@ import org.eclipse.cdt.dsf.debug.ui.IDsfDebugUIConstants; * @since 2.0 */ public interface IInternalDsfDebugUIConstants { - /** - * Boolean preference controlling whether the text in the detail panes is - * wrapped. When <code>true</code> the text in the detail panes will be - * wrapped in new variable view. - */ - public static final String PREF_DETAIL_PANE_WORD_WRAP = IDsfDebugUIConstants.PLUGIN_ID + ".detail_pane_word_wrap"; //$NON-NLS-1$ + /** + * Boolean preference controlling whether the text in the detail panes is + * wrapped. When <code>true</code> the text in the detail panes will be + * wrapped in new variable view. + */ + public static final String PREF_DETAIL_PANE_WORD_WRAP = IDsfDebugUIConstants.PLUGIN_ID + ".detail_pane_word_wrap"; //$NON-NLS-1$ } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/Messages.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/Messages.java index 3874a800b09..d2f65542959 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/Messages.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/Messages.java @@ -10,7 +10,7 @@ * * Contributors: * Wind River Systems - initial API and implementation - * Patrick Chuong (Texas Instruments) - Bug 315446: Invalid event breakpoint type (group) name + * Patrick Chuong (Texas Instruments) - Bug 315446: Invalid event breakpoint type (group) name * Alvaro Sanchez-Leon (Ericsson AB) - Support for Step into selection (bug 244865) * Alvaro Sanchez-Leon (Ericsson AB) - Support Register Groups (Bug 235747) *******************************************************************************/ @@ -30,7 +30,7 @@ public class Messages extends NLS { public static String RegisterGroupConfirmRestoreMessage; public static String RegisterGroupRestore; public static String RegisterGroupRestoreCancel; - + static { // initialize resource bundle NLS.initializeMessages(Messages.class.getName(), Messages.class); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/PreferenceInitializer.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/PreferenceInitializer.java index 076406f6b5a..4c5e3c3005f 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/PreferenceInitializer.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/PreferenceInitializer.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ @@ -29,10 +29,10 @@ public class PreferenceInitializer extends AbstractPreferenceInitializer { */ @Override public void initializeDefaultPreferences() { - + IPreferenceStore prefs = DsfUIPlugin.getDefault().getPreferenceStore(); - /* + /* * Debug View */ prefs.setDefault(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT, 10); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/SuspendResumeAdapterFactory.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/SuspendResumeAdapterFactory.java index 516ff73a02f..7441c631f79 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/SuspendResumeAdapterFactory.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/SuspendResumeAdapterFactory.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Ericsson - Updated to support Move-To-Line @@ -29,73 +29,84 @@ import org.eclipse.debug.core.model.ISuspendResume; /** * Adapter factory for Run-To-Line, Move-To-Line * and Resume-At-Line - * + * * @since 2.1 */ public class SuspendResumeAdapterFactory implements IAdapterFactory { - static class SuspendResume implements ISuspendResume, IAdaptable { + static class SuspendResume implements ISuspendResume, IAdaptable { + + private final RunToLine fRunToLine; + private final MoveToLine fMoveToLine; + private final ResumeAtLine fResumeAtLine; + + SuspendResume(IExecutionDMContext execCtx) { + fRunToLine = new RunToLine(execCtx); + fMoveToLine = new MoveToLine(execCtx); + fResumeAtLine = new ResumeAtLine(execCtx); + } + + @SuppressWarnings("unchecked") + @Override + public <T> T getAdapter(Class<T> adapter) { + if (adapter.isInstance(fRunToLine)) { + return (T) fRunToLine; + } + if (adapter.isInstance(fMoveToLine)) { + return (T) fMoveToLine; + } + if (adapter.isInstance(fResumeAtLine)) { + return (T) fResumeAtLine; + } + return null; + } + + @Override + public boolean canResume() { + return false; + } - private final RunToLine fRunToLine; - private final MoveToLine fMoveToLine; - private final ResumeAtLine fResumeAtLine; - - SuspendResume(IExecutionDMContext execCtx) { - fRunToLine = new RunToLine(execCtx); - fMoveToLine = new MoveToLine(execCtx); - fResumeAtLine = new ResumeAtLine(execCtx); - } - - @SuppressWarnings("unchecked") @Override - public <T> T getAdapter(Class<T> adapter) { - if (adapter.isInstance(fRunToLine)) { - return (T)fRunToLine; - } - if (adapter.isInstance(fMoveToLine)) { - return (T)fMoveToLine; - } - if (adapter.isInstance(fResumeAtLine)) { - return (T)fResumeAtLine; - } - return null; - } + public boolean canSuspend() { + return false; + } - @Override - public boolean canResume() { return false; } - @Override - public boolean canSuspend() { return false; } - // This must return true because the platform - // RunToLineActionDelegate will only enable the - // action if we are suspended - @Override - public boolean isSuspended() { return true; } - @Override - public void resume() throws DebugException {} - @Override - public void suspend() throws DebugException {} - } - - @SuppressWarnings("unchecked") + // This must return true because the platform + // RunToLineActionDelegate will only enable the + // action if we are suspended + @Override + public boolean isSuspended() { + return true; + } + + @Override + public void resume() throws DebugException { + } + + @Override + public void suspend() throws DebugException { + } + } + + @SuppressWarnings("unchecked") @Override - public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { - if (ISuspendResume.class.equals(adapterType)) { - if (adaptableObject instanceof IDMVMContext) { - IExecutionDMContext execDmc = DMContexts.getAncestorOfType( - ((IDMVMContext)adaptableObject).getDMContext(), - IExecutionDMContext.class); - // It only makes sense to RunToLine, MoveToLine or - // ResumeAtLine if we are dealing with a thread, not a container - if (execDmc != null && !(execDmc instanceof IContainerDMContext)) { - return (T)new SuspendResume(execDmc); - } - } - } - return null; - } + public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { + if (ISuspendResume.class.equals(adapterType)) { + if (adaptableObject instanceof IDMVMContext) { + IExecutionDMContext execDmc = DMContexts + .getAncestorOfType(((IDMVMContext) adaptableObject).getDMContext(), IExecutionDMContext.class); + // It only makes sense to RunToLine, MoveToLine or + // ResumeAtLine if we are dealing with a thread, not a container + if (execDmc != null && !(execDmc instanceof IContainerDMContext)) { + return (T) new SuspendResume(execDmc); + } + } + } + return null; + } - @Override - public Class<?>[] getAdapterList() { - return new Class[] { ISuspendResume.class }; - } + @Override + public Class<?>[] getAdapterList() { + return new Class[] { ISuspendResume.class }; + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/ToggleBreakpointsTargetFactory.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/ToggleBreakpointsTargetFactory.java index 2e6648be19a..7d8b2bfe4e4 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/ToggleBreakpointsTargetFactory.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/ToggleBreakpointsTargetFactory.java @@ -52,7 +52,7 @@ public class ToggleBreakpointsTargetFactory implements IToggleBreakpointsTargetF * for the editor. */ public static final String TOGGLE_C_BREAKPOINT_TARGET_ID = CDebugUIPlugin.PLUGIN_ID + ".toggleCBreakpointTarget"; //$NON-NLS-1$ - + private static final Set<String> TOGGLE_TARGET_IDS = new HashSet<String>(1); static { TOGGLE_TARGET_IDS.add(TOGGLE_C_BREAKPOINT_TARGET_ID); @@ -63,7 +63,7 @@ public class ToggleBreakpointsTargetFactory implements IToggleBreakpointsTargetF public ToggleBreakpointsTargetFactory() { } - @Override + @Override public IToggleBreakpointsTarget createToggleTarget(String targetID) { if (TOGGLE_C_BREAKPOINT_TARGET_ID.equals(targetID)) { return fgDisassemblyToggleBreakpointsTarget; @@ -71,45 +71,43 @@ public class ToggleBreakpointsTargetFactory implements IToggleBreakpointsTargetF return null; } - @Override + @Override public String getDefaultToggleTarget(IWorkbenchPart part, ISelection selection) { if (part instanceof IDisassemblyPart) { - // Return the debug context as a default if the currently selected context - // is a CDT element. Otherwise return null. - Object element = getDebugContext(part).getFirstElement(); - if (element instanceof IAdaptable) { - IDebugModelProvider modelProvider = - ((IAdaptable)element).getAdapter(IDebugModelProvider.class); - if (modelProvider != null) { - String[] models = modelProvider.getModelIdentifiers(); - for (String model : models) { - if (CDIDebugModel.getPluginIdentifier().equals(model) || - ICBreakpoint.C_BREAKPOINTS_DEBUG_MODEL_ID.equals(model)) - { - return TOGGLE_C_BREAKPOINT_TARGET_ID; - } - } - } else if (element instanceof IDebugElement) { - if (CDIDebugModel.getPluginIdentifier().equals(((IDebugElement)element).getModelIdentifier()) ) { - return TOGGLE_C_BREAKPOINT_TARGET_ID; - } - } - } + // Return the debug context as a default if the currently selected context + // is a CDT element. Otherwise return null. + Object element = getDebugContext(part).getFirstElement(); + if (element instanceof IAdaptable) { + IDebugModelProvider modelProvider = ((IAdaptable) element).getAdapter(IDebugModelProvider.class); + if (modelProvider != null) { + String[] models = modelProvider.getModelIdentifiers(); + for (String model : models) { + if (CDIDebugModel.getPluginIdentifier().equals(model) + || ICBreakpoint.C_BREAKPOINTS_DEBUG_MODEL_ID.equals(model)) { + return TOGGLE_C_BREAKPOINT_TARGET_ID; + } + } + } else if (element instanceof IDebugElement) { + if (CDIDebugModel.getPluginIdentifier().equals(((IDebugElement) element).getModelIdentifier())) { + return TOGGLE_C_BREAKPOINT_TARGET_ID; + } + } + } } return null; } - @Override + @Override public String getToggleTargetDescription(String targetID) { return Messages.ToggleBreakpointsTargetFactory_description; } - @Override + @Override public String getToggleTargetName(String targetID) { return Messages.ToggleBreakpointsTargetFactory_name; } - @Override + @Override public Set<String> getToggleTargets(IWorkbenchPart part, ISelection selection) { if (part instanceof IDisassemblyPart) { return TOGGLE_TARGET_IDS; @@ -118,11 +116,11 @@ public class ToggleBreakpointsTargetFactory implements IToggleBreakpointsTargetF } private IStructuredSelection getDebugContext(IWorkbenchPart part) { - ISelection selection = DebugUITools.getDebugContextManager(). - getContextService(part.getSite().getWorkbenchWindow()).getActiveContext(); + ISelection selection = DebugUITools.getDebugContextManager() + .getContextService(part.getSite().getWorkbenchWindow()).getActiveContext(); if (selection instanceof IStructuredSelection) { - return (IStructuredSelection)selection; - } + return (IStructuredSelection) selection; + } return StructuredSelection.EMPTY; } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/AbstractDsfRegisterGroupActions.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/AbstractDsfRegisterGroupActions.java index 9c0f97370a3..4eeeadfa6c0 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/AbstractDsfRegisterGroupActions.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/AbstractDsfRegisterGroupActions.java @@ -176,24 +176,25 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { protected void addRegisterGroup(final IWorkbenchPart part, final IStructuredSelection selection) { try { - final SelectionDMContext selectionContext = new SelectionDMContext(selection); - selectionContext.fsession.getExecutor().execute(new DsfRunnable() { + final SelectionDMContext selectionContext = new SelectionDMContext(selection); + selectionContext.fsession.getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - final IRegisters2 registersService; - try { - registersService = selectionContext.resolveService(); - } catch (CoreException e) { - failed(e); - return; + @Override + public void run() { + final IRegisters2 registersService; + try { + registersService = selectionContext.resolveService(); + } catch (CoreException e) { + failed(e); + return; + } + + // continue to process + processAddRegisterGroup(part.getSite().getShell(), selectionContext, + resolveSelectedRegisters(selection), registersService); } + }); - // continue to process - processAddRegisterGroup(part.getSite().getShell(), selectionContext, - resolveSelectedRegisters(selection), registersService); - }}); - } catch (DebugException e) { } } @@ -234,27 +235,26 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { protected void editRegisterGroup(final IWorkbenchPart part, IStructuredSelection selection) { try { - final SelectionDMContext selectionContext = new SelectionDMContext(selection); - - selectionContext.fsession.getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - // Create a services tracker - final IRegisters2 registersService; - try { - registersService = selectionContext.resolveService(); - } catch (CoreException e) { - failed(e); - return; + final SelectionDMContext selectionContext = new SelectionDMContext(selection); + + selectionContext.fsession.getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + // Create a services tracker + final IRegisters2 registersService; + try { + registersService = selectionContext.resolveService(); + } catch (CoreException e) { + failed(e); + return; + } + + processEditRegisterGroup(part.getSite().getShell(), selectionContext, registersService); } - - processEditRegisterGroup(part.getSite().getShell(), selectionContext, - registersService); - } - - }); - } catch (DebugException e) { - } + + }); + } catch (DebugException e) { + } } protected boolean canEditRegisterGroup(IWorkbenchPart part, IStructuredSelection selection) { @@ -304,24 +304,25 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { */ protected void removeRegisterGroups(IWorkbenchPart part, IStructuredSelection selection) { try { - final SelectionDMContext selectionContext = new SelectionDMContext(selection); - - final IRegisterGroupDMContext[] groups = resolveSelectedGroups(selection); - selectionContext.fsession.getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - IRegisters2 registersService; - try { - registersService = selectionContext.resolveService(); - } catch (CoreException e) { - failed(e); - return; - } + final SelectionDMContext selectionContext = new SelectionDMContext(selection); - registersService.removeRegisterGroups(groups, new RequestMonitor(registersService.getExecutor(), null) { - }); - } - }); + final IRegisterGroupDMContext[] groups = resolveSelectedGroups(selection); + selectionContext.fsession.getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + IRegisters2 registersService; + try { + registersService = selectionContext.resolveService(); + } catch (CoreException e) { + failed(e); + return; + } + + registersService.removeRegisterGroups(groups, + new RequestMonitor(registersService.getExecutor(), null) { + }); + } + }); } catch (DebugException e) { } } @@ -337,13 +338,13 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { // No DM context present or group registers service found in the selection return false; } - + //resolve the selected groups final IRegisterGroupDMContext[] groups = resolveSelectedGroups(selection); - if (groups == null || groups.length < 1){ + if (groups == null || groups.length < 1) { return false; } - + //Prepare to Query the service and check if the selected groups can be removed Query<Boolean> query = new Query<Boolean>() { @Override @@ -357,11 +358,11 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { rm.done(); return; } - + regService.canRemoveRegisterGroups(groups, rm); } }; - + //Execute the query selectionContext.fsession.getExecutor().execute(query); @@ -371,7 +372,7 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { } catch (InterruptedException e) { } catch (ExecutionException e) { } - + // No positive answer from the service return false; } @@ -399,7 +400,8 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { } // no success handler needed - registersService.restoreDefaultGroups(null, new RequestMonitor(registersService.getExecutor(), null)); + registersService.restoreDefaultGroups(null, + new RequestMonitor(registersService.getExecutor(), null)); } }); } catch (DebugException e) { @@ -418,7 +420,7 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { // No DM context present or group registers service found in the selection return false; } - + //Prepare to Query the service Query<Boolean> query = new Query<Boolean>() { @Override @@ -432,11 +434,11 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { rm.done(); return; } - + regService.canRestoreDefaultGroups(selectionContext.fcontext, rm); } }; - + //Execute the query selectionContext.fsession.getExecutor().execute(query); @@ -446,100 +448,106 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { } catch (InterruptedException e) { } catch (ExecutionException e) { } - + // No positive answer from the service return false; } @ConfinedToDsfExecutor("selectionContext.fsession.getExecutor()") - private void processAddRegisterGroup(final Shell shell, final SelectionDMContext selectionContext, final IRegisterDMContext[] selectedRegisters, - final IRegisters2 regServiceManager) { + private void processAddRegisterGroup(final Shell shell, final SelectionDMContext selectionContext, + final IRegisterDMContext[] selectedRegisters, final IRegisters2 regServiceManager) { final DsfSession session = selectionContext.fsession; final DsfExecutor executor = session.getExecutor(); - final IContainerDMContext contDmc = DMContexts.getAncestorOfType(selectionContext.fcontext, IContainerDMContext.class); - // Using the container context to get all existing registers from the target instead of a limited set of registers for a selected group - regServiceManager.getRegisters(contDmc, new DataRequestMonitor<IRegisterDMContext[]>( - executor, null) { - + final IContainerDMContext contDmc = DMContexts.getAncestorOfType(selectionContext.fcontext, + IContainerDMContext.class); + // Using the container context to get all existing registers from the target instead of a limited set of registers for a selected group + regServiceManager.getRegisters(contDmc, new DataRequestMonitor<IRegisterDMContext[]>(executor, null) { + @Override protected void handleSuccess() { // Get Register Contexts final IRegisterDMContext[] rootRegisters = getData(); - + if (rootRegisters.length < 1) { //The target is expected to have registers, an error has happened ! assert false; noRegisterGroupFoundErr("Add Register Group", this); //$NON-NLS-1$ return; } - + //Find the root register group, containing all the registers associated to a target, from any of the root registers - final IRegisterGroupDMContext rootGroupDmc = DMContexts.getAncestorOfType(rootRegisters[0], IRegisterGroupDMContext.class); + final IRegisterGroupDMContext rootGroupDmc = DMContexts.getAncestorOfType(rootRegisters[0], + IRegisterGroupDMContext.class); // Get data for all available registers - getRegistersData(rootRegisters, regServiceManager, new DataRequestMonitor<IRegisterDMData[]>(executor, null) { - @Override - protected void handleSuccess() { - final IRegisterDMData[] rootRegistersData = getData(); - - getRegistersData(selectedRegisters, regServiceManager, new DataRequestMonitor<IRegisterDMData[]>(executor, null) { + getRegistersData(rootRegisters, regServiceManager, + new DataRequestMonitor<IRegisterDMData[]>(executor, null) { @Override protected void handleSuccess() { - // Get data for all selected registers i.e. selected for the new group - final IRegisterDMData[] selectedRegistersData = getData(); - - //Need the root group name to build register descriptors - regServiceManager.getRegisterGroupData(rootGroupDmc, - new DataRequestMonitor<IRegisterGroupDMData>(executor, null) { + final IRegisterDMData[] rootRegistersData = getData(); + + getRegistersData(selectedRegisters, regServiceManager, + new DataRequestMonitor<IRegisterDMData[]>(executor, null) { @Override protected void handleSuccess() { - final IRegisterGroupDMData rootGroupData = getData(); - // request for the next unused group name to propose it to the user - proposeGroupName(rootRegisters, regServiceManager, new DataRequestMonitor<String>(executor, null) { + // Get data for all selected registers i.e. selected for the new group + final IRegisterDMData[] selectedRegistersData = getData(); + + //Need the root group name to build register descriptors + regServiceManager.getRegisterGroupData(rootGroupDmc, + new DataRequestMonitor<IRegisterGroupDMData>(executor, null) { @Override protected void handleSuccess() { - String proposedGroupName = getData(); - - String rootGroupName = (rootGroupData == null) ? BLANK_STRING - : rootGroupData.getName(); - // Create the Register descriptors - DialogRegisterProvider descriptors = buildDescriptors( - rootGroupName, rootRegisters, - rootRegistersData, - selectedRegistersData); - // Create Dialog Resolve selection to DSF - // Registers - getDialogSelection( - shell, - proposedGroupName, - descriptors.getAllRegisters(), - descriptors.getcheckedRegisters(), - new DataRequestMonitor<IRegisterGroupDescriptor>( - executor, null) { + final IRegisterGroupDMData rootGroupData = getData(); + // request for the next unused group name to propose it to the user + proposeGroupName(rootRegisters, regServiceManager, + new DataRequestMonitor<String>(executor, null) { @Override protected void handleSuccess() { - try { - addRegisterGroup( - regServiceManager, - getData(), contDmc); - } catch (CoreException e) { - failed(e); - } - }; + String proposedGroupName = getData(); + + String rootGroupName = (rootGroupData == null) + ? BLANK_STRING + : rootGroupData.getName(); + // Create the Register descriptors + DialogRegisterProvider descriptors = buildDescriptors( + rootGroupName, rootRegisters, + rootRegistersData, + selectedRegistersData); + // Create Dialog Resolve selection to DSF + // Registers + getDialogSelection(shell, + proposedGroupName, + descriptors.getAllRegisters(), + descriptors + .getcheckedRegisters(), + new DataRequestMonitor<IRegisterGroupDescriptor>( + executor, null) { + @Override + protected void handleSuccess() { + try { + addRegisterGroup( + regServiceManager, + getData(), + contDmc); + } catch (CoreException e) { + failed(e); + } + }; + }); + } }); + } }); - } }); } }); - } - }); } - + }); } @@ -552,53 +560,57 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { rm.done(); } - private void proposeGroupName(IRegisterDMContext[] registers, final IRegisters2 regServiceManager, final DataRequestMonitor<String> rm) { - assert(registers != null && registers.length > 0); - + private void proposeGroupName(IRegisterDMContext[] registers, final IRegisters2 regServiceManager, + final DataRequestMonitor<String> rm) { + assert (registers != null && registers.length > 0); + final DsfExecutor executor = regServiceManager.getExecutor(); if (registers != null && registers.length > 0) { //First get all register group contexts, any register context can be used to resolve the container context - regServiceManager.getRegisterGroups(registers[0], new DataRequestMonitor<IRegisterGroupDMContext[]>(executor, null) { - @Override - protected void handleSuccess() { - IRegisterGroupDMContext[] groupsCtx = getData(); - assert (groupsCtx != null); - - final IRegisterGroupDMData[] groupsData = new IRegisterGroupDMData[groupsCtx.length]; - - final CountingRequestMonitor crm = new CountingRequestMonitor(executor, rm) { + regServiceManager.getRegisterGroups(registers[0], + new DataRequestMonitor<IRegisterGroupDMContext[]>(executor, null) { @Override - protected void handleCompleted() { - //GroupsData is resolved now - //Select an unused name - String unusedGroupName = Messages.ProposeGroupNameRoot + (resolveGroupNameWaterMark(groupsData) + 1); - rm.setData(unusedGroupName); - rm.done(); - } - }; - - //Resolve all register group data - for (int i=0; i < groupsCtx.length; i++) { - final int index = i; - regServiceManager.getRegisterGroupData(groupsCtx[index], new DataRequestMonitor<IRegisterGroupDMData>(executor, crm){ - @Override - protected void handleSuccess() { - groupsData[index] = getData(); - crm.done(); + protected void handleSuccess() { + IRegisterGroupDMContext[] groupsCtx = getData(); + assert (groupsCtx != null); + + final IRegisterGroupDMData[] groupsData = new IRegisterGroupDMData[groupsCtx.length]; + + final CountingRequestMonitor crm = new CountingRequestMonitor(executor, rm) { + @Override + protected void handleCompleted() { + //GroupsData is resolved now + //Select an unused name + String unusedGroupName = Messages.ProposeGroupNameRoot + + (resolveGroupNameWaterMark(groupsData) + 1); + rm.setData(unusedGroupName); + rm.done(); + } + }; + + //Resolve all register group data + for (int i = 0; i < groupsCtx.length; i++) { + final int index = i; + regServiceManager.getRegisterGroupData(groupsCtx[index], + new DataRequestMonitor<IRegisterGroupDMData>(executor, crm) { + @Override + protected void handleSuccess() { + groupsData[index] = getData(); + crm.done(); + } + }); } - }); - } - - crm.setDoneCount(groupsCtx.length); - } - }); + + crm.setDoneCount(groupsCtx.length); + } + }); } else { //Should not happen rm.setData(Messages.DefaultRegistersGroupName); rm.done(); } } - + // Adjust water mark suffix used to suggest register group names private Integer resolveGroupNameWaterMark(IRegisterGroupDMData[] groupsData) { // check only for this name pattern @@ -623,14 +635,15 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { // Quite unlikely and only causing a possibility to // propose a group name that already exists. } - } + } } - + return Integer.valueOf(water_mark); } - + @ConfinedToDsfExecutor("selectionContext.fsession.getExecutor()") - private void processEditRegisterGroup(final Shell shell, final SelectionDMContext selectionContext, final IRegisters2 regServiceManager) { + private void processEditRegisterGroup(final Shell shell, final SelectionDMContext selectionContext, + final IRegisters2 regServiceManager) { final DsfSession session = selectionContext.fsession; final DsfExecutor executor = session.getExecutor(); @@ -646,94 +659,110 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { protected void handleSuccess() { // Get children Register Contexts final IRegisterDMContext[] childRegisters = getData(); - - final IContainerDMContext contDmc = DMContexts.getAncestorOfType(selectionContext.fcontext, IContainerDMContext.class); - // Using the container context to get all existing registers from the target instead of a limited set of registers for a selected group + + final IContainerDMContext contDmc = DMContexts.getAncestorOfType(selectionContext.fcontext, + IContainerDMContext.class); + // Using the container context to get all existing registers from the target instead of a limited set of registers for a selected group // This is needed to populate the dialog with all available registers to pick from - regServiceManager.getRegisters(contDmc, new DataRequestMonitor<IRegisterDMContext[]>( - executor, null) { - @Override - protected void handleSuccess() { - final IRegisterDMContext[] rootRegisters = getData(); - - if (rootRegisters.length < 1) { - //The target is expected to have a root register group and associated registers, an error has happened ! - assert false; - noRegisterGroupFoundErr("Edit Register Group", this); //$NON-NLS-1$ - return; - } - - // We need to resolve the names for all root registers - getRegistersData(rootRegisters, regServiceManager, new DataRequestMonitor<IRegisterDMData[]>(executor, null) { + regServiceManager.getRegisters(contDmc, + new DataRequestMonitor<IRegisterDMContext[]>(executor, null) { @Override protected void handleSuccess() { - final IRegisterDMData[] rootRegistersData = getData(); - - getRegistersData(childRegisters, regServiceManager, new DataRequestMonitor<IRegisterDMData[]>(executor, null) { - @Override - protected void handleSuccess() { - // Get register data for all selected registers i.e. selected for the new group - final IRegisterDMData[] childRegisterData = getData(); - - // Need to get the parent group name. Used on the register descriptors - final IRegisterGroupDMContext rootGroupDmc = DMContexts.getAncestorOfType(rootRegisters[0], IRegisterGroupDMContext.class); - regServiceManager.getRegisterGroupData(rootGroupDmc, - new DataRequestMonitor<IRegisterGroupDMData>( - executor, null) { - @Override - protected void handleSuccess() { - IRegisterGroupDMData rootGroupData = getData(); - final String rootGroupName = (rootGroupData == null) ? BLANK_STRING - : rootGroupData.getName(); - - regServiceManager.getRegisterGroupData(groupDmc, - new DataRequestMonitor<IRegisterGroupDMData>( - executor, null) { - @Override - protected void handleSuccess() { - // Resolve the name of the selected group being edited - String selGroupName = getData().getName(); - // Create the Register descriptors to - // access all children registers - DialogRegisterProvider descriptors = buildDescriptors( - rootGroupName, rootRegisters, - rootRegistersData, - childRegisterData); - - // Create Dialog to Resolve new user - // selection of group name and registers - getDialogSelection( - shell, - selGroupName, - descriptors.getAllRegisters(), - descriptors - .getcheckedRegisters(), - new DataRequestMonitor<IRegisterGroupDescriptor>( - executor, null) { - @Override - protected void handleSuccess() { - try { - editRegisterGroup( - groupDmc, - regServiceManager, - getData()); - } catch (CoreException e) { - failed(e); - } - }; - }); - } - }); - }; - - }); - } - }); - + final IRegisterDMContext[] rootRegisters = getData(); + + if (rootRegisters.length < 1) { + //The target is expected to have a root register group and associated registers, an error has happened ! + assert false; + noRegisterGroupFoundErr("Edit Register Group", this); //$NON-NLS-1$ + return; + } + + // We need to resolve the names for all root registers + getRegistersData(rootRegisters, regServiceManager, + new DataRequestMonitor<IRegisterDMData[]>(executor, null) { + @Override + protected void handleSuccess() { + final IRegisterDMData[] rootRegistersData = getData(); + + getRegistersData(childRegisters, regServiceManager, + new DataRequestMonitor<IRegisterDMData[]>(executor, + null) { + @Override + protected void handleSuccess() { + // Get register data for all selected registers i.e. selected for the new group + final IRegisterDMData[] childRegisterData = getData(); + + // Need to get the parent group name. Used on the register descriptors + final IRegisterGroupDMContext rootGroupDmc = DMContexts + .getAncestorOfType(rootRegisters[0], + IRegisterGroupDMContext.class); + regServiceManager.getRegisterGroupData( + rootGroupDmc, + new DataRequestMonitor<IRegisterGroupDMData>( + executor, null) { + @Override + protected void handleSuccess() { + IRegisterGroupDMData rootGroupData = getData(); + final String rootGroupName = (rootGroupData == null) + ? BLANK_STRING + : rootGroupData + .getName(); + + regServiceManager + .getRegisterGroupData( + groupDmc, + new DataRequestMonitor<IRegisterGroupDMData>( + executor, + null) { + @Override + protected void handleSuccess() { + // Resolve the name of the selected group being edited + String selGroupName = getData() + .getName(); + // Create the Register descriptors to + // access all children registers + DialogRegisterProvider descriptors = buildDescriptors( + rootGroupName, + rootRegisters, + rootRegistersData, + childRegisterData); + + // Create Dialog to Resolve new user + // selection of group name and registers + getDialogSelection( + shell, + selGroupName, + descriptors + .getAllRegisters(), + descriptors + .getcheckedRegisters(), + new DataRequestMonitor<IRegisterGroupDescriptor>( + executor, + null) { + @Override + protected void handleSuccess() { + try { + editRegisterGroup( + groupDmc, + regServiceManager, + getData()); + } catch (CoreException e) { + failed(e); + } + }; + }); + } + }); + }; + + }); + } + }); + + } + }); } }); - } - }); } }); } @@ -799,9 +828,8 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { } @ConfinedToDsfExecutor("selectionContext.fsession.getExecutor()") - private void getDialogSelection(Shell shell, String originalGroupName, - IRegisterDescriptor[] allRegisters, IRegisterDescriptor[] checkedRegisters, - DataRequestMonitor<IRegisterGroupDescriptor> rm) { + private void getDialogSelection(Shell shell, String originalGroupName, IRegisterDescriptor[] allRegisters, + IRegisterDescriptor[] checkedRegisters, DataRequestMonitor<IRegisterGroupDescriptor> rm) { RegisterGroupDialogRunnable dialog = new RegisterGroupDialogRunnable(shell, originalGroupName, allRegisters, checkedRegisters, rm); shell.getDisplay().asyncExec(dialog); @@ -833,7 +861,7 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { /** * Build descriptor adapters to dialog interface both all registers as well as registers to be pre-selected on the * dialog - * + * * @param checkedRegistersData */ @ConfinedToDsfExecutor("selectionContext.fsession.getExecutor()") @@ -885,24 +913,24 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { } @ConfinedToDsfExecutor("selectionContext.fsession.getExecutor()") - private void addRegisterGroup(IRegisters2 regServiceManager, - IRegisterGroupDescriptor groupDescriptor, IContainerDMContext contDmc) throws CoreException { + private void addRegisterGroup(IRegisters2 regServiceManager, IRegisterGroupDescriptor groupDescriptor, + IContainerDMContext contDmc) throws CoreException { IRegisterDescriptor[] selectedRegisters = groupDescriptor.getChildren(); if (selectedRegisters != null) { String groupName = groupDescriptor.getName(); // Register the addition of the group and notify the change IRegisterDMContext[] registers = getRegisterContexts(selectedRegisters); - regServiceManager.addRegisterGroup(contDmc, groupName, registers, new RequestMonitor( - regServiceManager.getSession().getExecutor(), null) { - @Override - protected void handleCompleted() { - if (getStatus() != null && getStatus().getCode() == IDsfStatusConstants.NOT_SUPPORTED) { - // This user request is not supported, notify the user - notifyUser(getStatus().getMessage()); - } + regServiceManager.addRegisterGroup(contDmc, groupName, registers, + new RequestMonitor(regServiceManager.getSession().getExecutor(), null) { + @Override + protected void handleCompleted() { + if (getStatus() != null && getStatus().getCode() == IDsfStatusConstants.NOT_SUPPORTED) { + // This user request is not supported, notify the user + notifyUser(getStatus().getMessage()); + } - }; - }); + }; + }); } } @@ -915,15 +943,15 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { // Register the addition of the group and notify the change regServiceManager.editRegisterGroup(group, groupName, getRegisterContexts(selectedRegisters), new RequestMonitor(regServiceManager.getSession().getExecutor(), null) { - @Override - protected void handleCompleted() { - if (getStatus() != null && getStatus().getCode() == IDsfStatusConstants.NOT_SUPPORTED) { - // This user request is not supported, notify the user - notifyUser(getStatus().getMessage()); - } - - }; - }); + @Override + protected void handleCompleted() { + if (getStatus() != null && getStatus().getCode() == IDsfStatusConstants.NOT_SUPPORTED) { + // This user request is not supported, notify the user + notifyUser(getStatus().getMessage()); + } + + }; + }); } } @@ -934,13 +962,14 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { } private void notifyUser(final String message) { - + Runnable runnable = new Runnable() { @Override public void run() { Shell parent = DsfUIPlugin.getActiveWorkbenchShell(); if (parent != null) { - MessageDialog.openInformation(parent, Messages.Information, Messages.RegisterGroupInfo + ": " + message); //$NON-NLS-1$ + MessageDialog.openInformation(parent, Messages.Information, + Messages.RegisterGroupInfo + ": " + message); //$NON-NLS-1$ } } }; @@ -948,47 +977,47 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { Display.getDefault().asyncExec(runnable); } - /** - * @return true - OK to restore - */ - private boolean restoreConfirmed() { - ConfirmRestoreDialog restoreDialog = new ConfirmRestoreDialog(); + /** + * @return true - OK to restore + */ + private boolean restoreConfirmed() { + ConfirmRestoreDialog restoreDialog = new ConfirmRestoreDialog(); Display.getDefault().syncExec(restoreDialog); - return restoreDialog.fRestore; - } - - private class ConfirmRestoreDialog implements Runnable { + return restoreDialog.fRestore; + } + + private class ConfirmRestoreDialog implements Runnable { + + private Boolean fRestore = false; - private Boolean fRestore = false; - @Override public void run() { Shell parent = DsfUIPlugin.getActiveWorkbenchShell(); if (parent != null) { - - String title = Messages.RegisterGroupConfirmRestoreTitle; - String message = Messages.RegisterGroupConfirmRestoreMessage; - String[] buttonLabels = new String[]{Messages.RegisterGroupRestore, Messages.RegisterGroupRestoreCancel, - }; - MessageDialog dialog = new MessageDialog(parent, title, null, message, MessageDialog.QUESTION, - buttonLabels, 0); - int res = dialog.open(); - if (res == 0) { // RESTORE - fRestore = true; - } else if (res == 1) { // CANCEL - fRestore = false; - } - } + + String title = Messages.RegisterGroupConfirmRestoreTitle; + String message = Messages.RegisterGroupConfirmRestoreMessage; + String[] buttonLabels = new String[] { Messages.RegisterGroupRestore, + Messages.RegisterGroupRestoreCancel, }; + MessageDialog dialog = new MessageDialog(parent, title, null, message, MessageDialog.QUESTION, + buttonLabels, 0); + int res = dialog.open(); + if (res == 0) { // RESTORE + fRestore = true; + } else if (res == 1) { // CANCEL + fRestore = false; + } + } } - - } - - - private void getRegistersData(IRegisterDMContext[] regDMCs, IRegisters2 regService, final DataRequestMonitor<IRegisterDMData[]> rm) { + + } + + private void getRegistersData(IRegisterDMContext[] regDMCs, IRegisters2 regService, + final DataRequestMonitor<IRegisterDMData[]> rm) { final IRegisterDMData[] regDataArray = new IRegisterDMData[regDMCs.length]; final DsfExecutor executor = regService.getExecutor(); - + final CountingRequestMonitor crm = new CountingRequestMonitor(executor, rm) { @Override protected void handleSuccess() { @@ -996,7 +1025,7 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { rm.done(); } }; - + for (int i = 0; i < regDMCs.length; i++) { final int index = i; regService.getRegisterData(regDMCs[index], new DataRequestMonitor<IRegisterDMData>(executor, crm) { @@ -1007,7 +1036,7 @@ public abstract class AbstractDsfRegisterGroupActions extends AbstractHandler { } }); } - + crm.setDoneCount(regDMCs.length); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DisassemblyMoveToLineAdapter.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DisassemblyMoveToLineAdapter.java index 4ee134cb34a..813ec81f035 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DisassemblyMoveToLineAdapter.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DisassemblyMoveToLineAdapter.java @@ -35,7 +35,7 @@ import org.eclipse.ui.IWorkbenchPart; /** * Move to line target adapter for the DSF Disassembly view - * + * * @since 2.1 */ public class DisassemblyMoveToLineAdapter implements IMoveToLineTarget { @@ -44,37 +44,36 @@ public class DisassemblyMoveToLineAdapter implements IMoveToLineTarget { public void moveToLine(IWorkbenchPart part, ISelection selection, ISuspendResume target) throws CoreException { if (part instanceof IDisassemblyPart && selection instanceof ITextSelection) { if (!(selection instanceof IDisassemblySelection)) { - selection = new DisassemblySelection((ITextSelection)selection, (IDisassemblyPart)part); + selection = new DisassemblySelection((ITextSelection) selection, (IDisassemblyPart) part); } - IDisassemblySelection disassemblySelection = (IDisassemblySelection)selection; + IDisassemblySelection disassemblySelection = (IDisassemblySelection) selection; final IAddress address = disassemblySelection.getStartAddress(); - - if (address != null && target instanceof IAdaptable) { - final IMoveToAddress moveToAddress = ((IAdaptable)target).getAdapter(IMoveToAddress.class); - if (moveToAddress != null && moveToAddress.canMoveToAddress(address)) { - try { - moveToAddress.moveToAddress(address); - } - catch(DebugException e) { - failed(e); - } - } - } + + if (address != null && target instanceof IAdaptable) { + final IMoveToAddress moveToAddress = ((IAdaptable) target).getAdapter(IMoveToAddress.class); + if (moveToAddress != null && moveToAddress.canMoveToAddress(address)) { + try { + moveToAddress.moveToAddress(address); + } catch (DebugException e) { + failed(e); + } + } + } } } @Override public boolean canMoveToLine(IWorkbenchPart part, ISelection selection, ISuspendResume target) { if (target instanceof IAdaptable && part instanceof IDisassemblyPart && selection instanceof ITextSelection) { - IMoveToAddress moveToAddress = ((IAdaptable)target).getAdapter(IMoveToAddress.class); + IMoveToAddress moveToAddress = ((IAdaptable) target).getAdapter(IMoveToAddress.class); if (moveToAddress == null) { return false; } - + if (!(selection instanceof IDisassemblySelection)) { - selection = new DisassemblySelection((ITextSelection)selection, (IDisassemblyPart)part); + selection = new DisassemblySelection((ITextSelection) selection, (IDisassemblyPart) part); } - IDisassemblySelection disassemblySelection = (IDisassemblySelection)selection; + IDisassemblySelection disassemblySelection = (IDisassemblySelection) selection; final IAddress address = disassemblySelection.getStartAddress(); if (address == null) { return false; @@ -86,9 +85,11 @@ public class DisassemblyMoveToLineAdapter implements IMoveToLineTarget { return false; } - protected void failed( Throwable e ) { - MultiStatus ms = new MultiStatus(CDIDebugModel.getPluginIdentifier(), IDsfStatusConstants.REQUEST_FAILED, "MoveToLine failed", null); //$NON-NLS-1$ - ms.add( new Status(IStatus.ERROR, CDIDebugModel.getPluginIdentifier(), IDsfStatusConstants.REQUEST_FAILED, e.getMessage(), e)); + protected void failed(Throwable e) { + MultiStatus ms = new MultiStatus(CDIDebugModel.getPluginIdentifier(), IDsfStatusConstants.REQUEST_FAILED, + "MoveToLine failed", null); //$NON-NLS-1$ + ms.add(new Status(IStatus.ERROR, CDIDebugModel.getPluginIdentifier(), IDsfStatusConstants.REQUEST_FAILED, + e.getMessage(), e)); DsfUIPlugin.log(ms); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DisassemblyResumeAtLineAdapter.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DisassemblyResumeAtLineAdapter.java index cc6a828a37f..dd03333db71 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DisassemblyResumeAtLineAdapter.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DisassemblyResumeAtLineAdapter.java @@ -35,46 +35,45 @@ import org.eclipse.ui.IWorkbenchPart; /** * Resume at line target adapter for the DSF Disassembly view - * + * * @since 2.1 */ public class DisassemblyResumeAtLineAdapter implements IResumeAtLineTarget { @Override - public void resumeAtLine(IWorkbenchPart part, ISelection selection, ISuspendResume target) throws CoreException { + public void resumeAtLine(IWorkbenchPart part, ISelection selection, ISuspendResume target) throws CoreException { if (part instanceof IDisassemblyPart && selection instanceof ITextSelection) { if (!(selection instanceof IDisassemblySelection)) { - selection = new DisassemblySelection((ITextSelection)selection, (IDisassemblyPart)part); + selection = new DisassemblySelection((ITextSelection) selection, (IDisassemblyPart) part); } - IDisassemblySelection disassemblySelection = (IDisassemblySelection)selection; + IDisassemblySelection disassemblySelection = (IDisassemblySelection) selection; final IAddress address = disassemblySelection.getStartAddress(); - if (address != null && target instanceof IAdaptable) { - final IResumeAtAddress resumeAtAddress = ((IAdaptable)target).getAdapter(IResumeAtAddress.class); - if (resumeAtAddress != null && resumeAtAddress.canResumeAtAddress(address)) { - try { - resumeAtAddress.resumeAtAddress(address); - } - catch(DebugException e) { - failed(e); - } - } - } + if (address != null && target instanceof IAdaptable) { + final IResumeAtAddress resumeAtAddress = ((IAdaptable) target).getAdapter(IResumeAtAddress.class); + if (resumeAtAddress != null && resumeAtAddress.canResumeAtAddress(address)) { + try { + resumeAtAddress.resumeAtAddress(address); + } catch (DebugException e) { + failed(e); + } + } + } } } @Override public boolean canResumeAtLine(IWorkbenchPart part, ISelection selection, ISuspendResume target) { if (target instanceof IAdaptable && part instanceof IDisassemblyPart && selection instanceof ITextSelection) { - IResumeAtAddress resumeAtAddress = ((IAdaptable)target).getAdapter(IResumeAtAddress.class); + IResumeAtAddress resumeAtAddress = ((IAdaptable) target).getAdapter(IResumeAtAddress.class); if (resumeAtAddress == null) { return false; } - + if (!(selection instanceof IDisassemblySelection)) { - selection = new DisassemblySelection((ITextSelection)selection, (IDisassemblyPart)part); + selection = new DisassemblySelection((ITextSelection) selection, (IDisassemblyPart) part); } - IDisassemblySelection disassemblySelection = (IDisassemblySelection)selection; + IDisassemblySelection disassemblySelection = (IDisassemblySelection) selection; final IAddress address = disassemblySelection.getStartAddress(); if (address == null) { return false; @@ -86,9 +85,11 @@ public class DisassemblyResumeAtLineAdapter implements IResumeAtLineTarget { return false; } - protected void failed( Throwable e ) { - MultiStatus ms = new MultiStatus(CDIDebugModel.getPluginIdentifier(), IDsfStatusConstants.REQUEST_FAILED, "Resume At Line failed", null); //$NON-NLS-1$ - ms.add( new Status(IStatus.ERROR, CDIDebugModel.getPluginIdentifier(), IDsfStatusConstants.REQUEST_FAILED, e.getMessage(), e)); + protected void failed(Throwable e) { + MultiStatus ms = new MultiStatus(CDIDebugModel.getPluginIdentifier(), IDsfStatusConstants.REQUEST_FAILED, + "Resume At Line failed", null); //$NON-NLS-1$ + ms.add(new Status(IStatus.ERROR, CDIDebugModel.getPluginIdentifier(), IDsfStatusConstants.REQUEST_FAILED, + e.getMessage(), e)); DsfUIPlugin.log(ms); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DisassemblyRunToLineAdapter.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DisassemblyRunToLineAdapter.java index 73100505ae3..86f6cfe1964 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DisassemblyRunToLineAdapter.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DisassemblyRunToLineAdapter.java @@ -37,7 +37,7 @@ import org.eclipse.ui.IWorkbenchPart; /** * Run to line target adapter for the DSF Disassembly view - * + * * @since 2.1 */ public class DisassemblyRunToLineAdapter implements IRunToLineTarget { @@ -49,21 +49,21 @@ public class DisassemblyRunToLineAdapter implements IRunToLineTarget { public void runToLine(IWorkbenchPart part, ISelection selection, ISuspendResume target) throws CoreException { if (part instanceof IDisassemblyPart && selection instanceof ITextSelection) { if (!(selection instanceof IDisassemblySelection)) { - selection = new DisassemblySelection((ITextSelection)selection, (IDisassemblyPart)part); + selection = new DisassemblySelection((ITextSelection) selection, (IDisassemblyPart) part); } - IDisassemblySelection disassemblySelection = (IDisassemblySelection)selection; + IDisassemblySelection disassemblySelection = (IDisassemblySelection) selection; final IAddress address = disassemblySelection.getStartAddress(); if (address != null && target instanceof IAdaptable) { - final IRunToAddress runToAddress = ((IAdaptable)target).getAdapter(IRunToAddress.class); + final IRunToAddress runToAddress = ((IAdaptable) target).getAdapter(IRunToAddress.class); if (runToAddress != null && runToAddress.canRunToAddress(address)) { try { - boolean skipBreakpoints = DebugUITools.getPreferenceStore().getBoolean(IDebugUIConstants.PREF_SKIP_BREAKPOINTS_DURING_RUN_TO_LINE); - runToAddress.runToAddress(address, skipBreakpoints); - } - catch(DebugException e) { + boolean skipBreakpoints = DebugUITools.getPreferenceStore() + .getBoolean(IDebugUIConstants.PREF_SKIP_BREAKPOINTS_DURING_RUN_TO_LINE); + runToAddress.runToAddress(address, skipBreakpoints); + } catch (DebugException e) { failed(e); - } + } } } } @@ -75,15 +75,15 @@ public class DisassemblyRunToLineAdapter implements IRunToLineTarget { @Override public boolean canRunToLine(IWorkbenchPart part, ISelection selection, ISuspendResume target) { if (target instanceof IAdaptable && part instanceof IDisassemblyPart && selection instanceof ITextSelection) { - IRunToAddress runToAddress = ((IAdaptable)target).getAdapter(IRunToAddress.class); + IRunToAddress runToAddress = ((IAdaptable) target).getAdapter(IRunToAddress.class); if (runToAddress == null) { return false; } - + if (!(selection instanceof IDisassemblySelection)) { - selection = new DisassemblySelection((ITextSelection)selection, (IDisassemblyPart)part); + selection = new DisassemblySelection((ITextSelection) selection, (IDisassemblyPart) part); } - IDisassemblySelection disassemblySelection = (IDisassemblySelection)selection; + IDisassemblySelection disassemblySelection = (IDisassemblySelection) selection; final IAddress address = disassemblySelection.getStartAddress(); if (address == null) { return false; @@ -95,9 +95,11 @@ public class DisassemblyRunToLineAdapter implements IRunToLineTarget { return false; } - protected void failed( Throwable e ) { - MultiStatus ms = new MultiStatus( CDIDebugModel.getPluginIdentifier(), IDsfStatusConstants.REQUEST_FAILED, "RunToLine failed", null ); //$NON-NLS-1$ - ms.add( new Status( IStatus.ERROR, CDIDebugModel.getPluginIdentifier(), IDsfStatusConstants.REQUEST_FAILED, e.getMessage(), e ) ); + protected void failed(Throwable e) { + MultiStatus ms = new MultiStatus(CDIDebugModel.getPluginIdentifier(), IDsfStatusConstants.REQUEST_FAILED, + "RunToLine failed", null); //$NON-NLS-1$ + ms.add(new Status(IStatus.ERROR, CDIDebugModel.getPluginIdentifier(), IDsfStatusConstants.REQUEST_FAILED, + e.getMessage(), e)); DsfUIPlugin.log(ms); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfAddRegisterGroupCommand.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfAddRegisterGroupCommand.java index bf382377a4a..c53761dcf17 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfAddRegisterGroupCommand.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfAddRegisterGroupCommand.java @@ -29,23 +29,23 @@ public class DsfAddRegisterGroupCommand extends AbstractDsfRegisterGroupActions @Override public void setEnabled(Object evaluationContext) { boolean state = false; - if (evaluationContext instanceof IEvaluationContext) { - Object s = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_MENU_SELECTION_NAME); - Object p = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_PART_NAME); - if (s instanceof IStructuredSelection && p instanceof IWorkbenchPart) { - state = canAddRegisterGroup((IWorkbenchPart)p, (IStructuredSelection)s); - } - } + if (evaluationContext instanceof IEvaluationContext) { + Object s = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_MENU_SELECTION_NAME); + Object p = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_PART_NAME); + if (s instanceof IStructuredSelection && p instanceof IWorkbenchPart) { + state = canAddRegisterGroup((IWorkbenchPart) p, (IStructuredSelection) s); + } + } setBaseEnabled(state); } - + @Override public Object execute(ExecutionEvent event) { ISelection selection = HandlerUtil.getCurrentSelection(event); IWorkbenchPart part = HandlerUtil.getActivePart(event); if (selection instanceof IStructuredSelection) { - addRegisterGroup(part, (IStructuredSelection)selection); + addRegisterGroup(part, (IStructuredSelection) selection); } - return null; - } + return null; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfEditRegisterGroupCommand.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfEditRegisterGroupCommand.java index c9cb7b10c13..656b80c268d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfEditRegisterGroupCommand.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfEditRegisterGroupCommand.java @@ -29,23 +29,23 @@ public class DsfEditRegisterGroupCommand extends AbstractDsfRegisterGroupActions @Override public void setEnabled(Object evaluationContext) { boolean state = false; - if (evaluationContext instanceof IEvaluationContext) { - Object s = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_MENU_SELECTION_NAME); - Object p = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_PART_NAME); - if (s instanceof IStructuredSelection && p instanceof IWorkbenchPart) { - state = canEditRegisterGroup((IWorkbenchPart)p, (IStructuredSelection)s); - } - } + if (evaluationContext instanceof IEvaluationContext) { + Object s = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_MENU_SELECTION_NAME); + Object p = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_PART_NAME); + if (s instanceof IStructuredSelection && p instanceof IWorkbenchPart) { + state = canEditRegisterGroup((IWorkbenchPart) p, (IStructuredSelection) s); + } + } setBaseEnabled(state); } - + @Override public Object execute(ExecutionEvent event) { ISelection selection = HandlerUtil.getCurrentSelection(event); IWorkbenchPart part = HandlerUtil.getActivePart(event); if (selection instanceof IStructuredSelection) { - editRegisterGroup(part, (IStructuredSelection)selection); + editRegisterGroup(part, (IStructuredSelection) selection); } - return null; - } + return null; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfRemoveRegisterGroupsCommand.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfRemoveRegisterGroupsCommand.java index f1766f7416f..bac37622572 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfRemoveRegisterGroupsCommand.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfRemoveRegisterGroupsCommand.java @@ -29,23 +29,23 @@ public class DsfRemoveRegisterGroupsCommand extends AbstractDsfRegisterGroupActi @Override public void setEnabled(Object evaluationContext) { boolean state = false; - if (evaluationContext instanceof IEvaluationContext) { - Object s = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_MENU_SELECTION_NAME); - Object p = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_PART_NAME); - if (s instanceof IStructuredSelection && p instanceof IWorkbenchPart) { - state = canRemoveRegisterGroups((IWorkbenchPart)p, (IStructuredSelection)s); - } - } + if (evaluationContext instanceof IEvaluationContext) { + Object s = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_MENU_SELECTION_NAME); + Object p = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_PART_NAME); + if (s instanceof IStructuredSelection && p instanceof IWorkbenchPart) { + state = canRemoveRegisterGroups((IWorkbenchPart) p, (IStructuredSelection) s); + } + } setBaseEnabled(state); } - + @Override public Object execute(ExecutionEvent event) { ISelection selection = HandlerUtil.getCurrentSelection(event); IWorkbenchPart part = HandlerUtil.getActivePart(event); if (selection instanceof IStructuredSelection) { - removeRegisterGroups(part, (IStructuredSelection)selection); + removeRegisterGroups(part, (IStructuredSelection) selection); } - return null; - } + return null; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfRestoreRegisterGroupsCommand.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfRestoreRegisterGroupsCommand.java index 145cf4788f1..d075f8092ed 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfRestoreRegisterGroupsCommand.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/DsfRestoreRegisterGroupsCommand.java @@ -29,23 +29,23 @@ public class DsfRestoreRegisterGroupsCommand extends AbstractDsfRegisterGroupAct @Override public void setEnabled(Object evaluationContext) { boolean state = false; - if (evaluationContext instanceof IEvaluationContext) { - Object s = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_MENU_SELECTION_NAME); - Object p = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_PART_NAME); - if (s instanceof IStructuredSelection && p instanceof IWorkbenchPart) { - state = canRestoreDefaultGroups((IWorkbenchPart)p, (IStructuredSelection)s); - } - } + if (evaluationContext instanceof IEvaluationContext) { + Object s = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_MENU_SELECTION_NAME); + Object p = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_PART_NAME); + if (s instanceof IStructuredSelection && p instanceof IWorkbenchPart) { + state = canRestoreDefaultGroups((IWorkbenchPart) p, (IStructuredSelection) s); + } + } setBaseEnabled(state); } - + @Override public Object execute(ExecutionEvent event) { ISelection selection = HandlerUtil.getCurrentSelection(event); IWorkbenchPart part = HandlerUtil.getActivePart(event); if (selection instanceof IStructuredSelection) { - restoreDefaultGroups(part, (IStructuredSelection)selection); + restoreDefaultGroups(part, (IStructuredSelection) selection); } - return null; - } + return null; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/IDsfActionsConstants.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/IDsfActionsConstants.java index d5c519fe163..ad3dd7c4b7c 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/IDsfActionsConstants.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/IDsfActionsConstants.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IAR Systems - initial API and implementation *******************************************************************************/ @@ -15,16 +15,15 @@ package org.eclipse.cdt.dsf.debug.internal.ui.actions; /** * Constants used by the DSF UI action adapters - * + * * @noimplement This interface is not intended to be implemented by clients. */ interface IDsfActionsConstants { /** - * The timeout in ms which action adapters will wait before disabling + * The timeout in ms which action adapters will wait before disabling * the action itself, in order to avoid blocking the UI thread while * waiting for the DSF thread to service a blocking query. */ static final int ACTION_ADAPTERS_TIMEOUT_MS = 500; } - diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/MoveToLine.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/MoveToLine.java index c71a1262cf6..351438eb986 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/MoveToLine.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/MoveToLine.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Ericsson - initial API and implementation *******************************************************************************/ @@ -35,158 +35,162 @@ import org.eclipse.debug.core.DebugException; /** * Implements the CDT's move to line interface. - * + * * @since 2.1 */ public class MoveToLine implements IMoveToLine, IMoveToAddress { - private final IExecutionDMContext fContext; + private final IExecutionDMContext fContext; - public MoveToLine(IExecutionDMContext context) { - fContext = context; - } + public MoveToLine(IExecutionDMContext context) { + fContext = context; + } - @Override + @Override public boolean canMoveToLine(final String fileName, final int lineNumber) { - DsfSession session = DsfSession.getSession(fContext.getSessionId()); - if (session != null && session.isActive()) { - try { - Query<Boolean> query = new Query<Boolean>() { - @Override - protected void execute(DataRequestMonitor<Boolean> rm) { - DsfServicesTracker tracker = - new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fContext.getSessionId()); - - IRunControl2 runControl = tracker.getService(IRunControl2.class); - if (runControl != null) { - runControl.canMoveToLine(fContext, fileName, lineNumber, false, rm); - } else { - rm.setData(false); - rm.done(); - } - tracker.dispose(); - } - }; - session.getExecutor().execute(query); - return query.get(IDsfActionsConstants.ACTION_ADAPTERS_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } catch (RejectedExecutionException e) { - } catch (InterruptedException e) { - } catch (ExecutionException e) { - } catch (TimeoutException e) { - } - } - return false; - } + DsfSession session = DsfSession.getSession(fContext.getSessionId()); + if (session != null && session.isActive()) { + try { + Query<Boolean> query = new Query<Boolean>() { + @Override + protected void execute(DataRequestMonitor<Boolean> rm) { + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + fContext.getSessionId()); - @Override + IRunControl2 runControl = tracker.getService(IRunControl2.class); + if (runControl != null) { + runControl.canMoveToLine(fContext, fileName, lineNumber, false, rm); + } else { + rm.setData(false); + rm.done(); + } + tracker.dispose(); + } + }; + session.getExecutor().execute(query); + return query.get(IDsfActionsConstants.ACTION_ADAPTERS_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException e) { + } catch (InterruptedException e) { + } catch (ExecutionException e) { + } catch (TimeoutException e) { + } + } + return false; + } + + @Override public void moveToLine(final String fileName, final int lineNumber) throws DebugException { - DsfSession session = DsfSession.getSession(fContext.getSessionId()); - if (session != null && session.isActive()) { - Throwable exception = null; - try { - Query<Object> query = new Query<Object>() { - @Override - protected void execute(final DataRequestMonitor<Object> rm) { - DsfServicesTracker tracker = - new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fContext.getSessionId()); - - IRunControl2 runControl = tracker.getService(IRunControl2.class); - if (runControl != null) { - runControl.moveToLine( - fContext, fileName, lineNumber, false, rm); - } else { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "IRunControl2 service not available", null)); //$NON-NLS-1$ - rm.done(); - } - tracker.dispose(); - } - }; - session.getExecutor().execute(query); - query.get(); - } catch (RejectedExecutionException e) { - exception = e; - } catch (InterruptedException e) { - exception = e; - } catch (ExecutionException e) { - exception = e; - } - if (exception != null) { - throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Failed executing move to line", exception)); //$NON-NLS-1$ - } - } else { - throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Debug session is not active", null)); //$NON-NLS-1$ - } - } - - @Override + DsfSession session = DsfSession.getSession(fContext.getSessionId()); + if (session != null && session.isActive()) { + Throwable exception = null; + try { + Query<Object> query = new Query<Object>() { + @Override + protected void execute(final DataRequestMonitor<Object> rm) { + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + fContext.getSessionId()); + + IRunControl2 runControl = tracker.getService(IRunControl2.class); + if (runControl != null) { + runControl.moveToLine(fContext, fileName, lineNumber, false, rm); + } else { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.NOT_SUPPORTED, "IRunControl2 service not available", null)); //$NON-NLS-1$ + rm.done(); + } + tracker.dispose(); + } + }; + session.getExecutor().execute(query); + query.get(); + } catch (RejectedExecutionException e) { + exception = e; + } catch (InterruptedException e) { + exception = e; + } catch (ExecutionException e) { + exception = e; + } + if (exception != null) { + throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, + "Failed executing move to line", exception)); //$NON-NLS-1$ + } + } else { + throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, + "Debug session is not active", null)); //$NON-NLS-1$ + } + } + + @Override public boolean canMoveToAddress(final IAddress address) { - DsfSession session = DsfSession.getSession(fContext.getSessionId()); - if (session != null && session.isActive()) { - try { - Query<Boolean> query = new Query<Boolean>() { - @Override - protected void execute(DataRequestMonitor<Boolean> rm) { - DsfServicesTracker tracker = - new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fContext.getSessionId()); - - IRunControl2 runControl = tracker.getService(IRunControl2.class); - if (runControl != null) { - runControl.canMoveToAddress(fContext, address, false, rm); - } else { - rm.setData(false); - rm.done(); - } - tracker.dispose(); - } - }; - session.getExecutor().execute(query); - return query.get(IDsfActionsConstants.ACTION_ADAPTERS_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } catch (RejectedExecutionException e) { - } catch (InterruptedException e) { - } catch (ExecutionException e) { - } catch (TimeoutException e) { - } - } - return false; - } + DsfSession session = DsfSession.getSession(fContext.getSessionId()); + if (session != null && session.isActive()) { + try { + Query<Boolean> query = new Query<Boolean>() { + @Override + protected void execute(DataRequestMonitor<Boolean> rm) { + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + fContext.getSessionId()); + + IRunControl2 runControl = tracker.getService(IRunControl2.class); + if (runControl != null) { + runControl.canMoveToAddress(fContext, address, false, rm); + } else { + rm.setData(false); + rm.done(); + } + tracker.dispose(); + } + }; + session.getExecutor().execute(query); + return query.get(IDsfActionsConstants.ACTION_ADAPTERS_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException e) { + } catch (InterruptedException e) { + } catch (ExecutionException e) { + } catch (TimeoutException e) { + } + } + return false; + } - @Override + @Override public void moveToAddress(final IAddress address) throws DebugException { - DsfSession session = DsfSession.getSession(fContext.getSessionId()); - if (session != null && session.isActive()) { - Throwable exception = null; - try { - Query<Object> query = new Query<Object>() { - @Override - protected void execute(final DataRequestMonitor<Object> rm) { - DsfServicesTracker tracker = - new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fContext.getSessionId()); - - IRunControl2 runControl = tracker.getService(IRunControl2.class); - if (runControl != null) { - runControl.moveToAddress( - fContext, address, false, rm); - } else { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "IRunControl2 service not available", null)); //$NON-NLS-1$ - rm.done(); - } - tracker.dispose(); - } - }; - session.getExecutor().execute(query); - query.get(); - } catch (RejectedExecutionException e) { - exception = e; - } catch (InterruptedException e) { - exception = e; - } catch (ExecutionException e) { - exception = e; - } - if (exception != null) { - throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Failed executing move to line", exception)); //$NON-NLS-1$ - } - } else { - throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Debug session is not active", null)); //$NON-NLS-1$ - } - } + DsfSession session = DsfSession.getSession(fContext.getSessionId()); + if (session != null && session.isActive()) { + Throwable exception = null; + try { + Query<Object> query = new Query<Object>() { + @Override + protected void execute(final DataRequestMonitor<Object> rm) { + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + fContext.getSessionId()); + + IRunControl2 runControl = tracker.getService(IRunControl2.class); + if (runControl != null) { + runControl.moveToAddress(fContext, address, false, rm); + } else { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.NOT_SUPPORTED, "IRunControl2 service not available", null)); //$NON-NLS-1$ + rm.done(); + } + tracker.dispose(); + } + }; + session.getExecutor().execute(query); + query.get(); + } catch (RejectedExecutionException e) { + exception = e; + } catch (InterruptedException e) { + exception = e; + } catch (ExecutionException e) { + exception = e; + } + if (exception != null) { + throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, + "Failed executing move to line", exception)); //$NON-NLS-1$ + } + } else { + throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, + "Debug session is not active", null)); //$NON-NLS-1$ + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/ResumeAtLine.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/ResumeAtLine.java index f82399a734f..d08c8d3f5e5 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/ResumeAtLine.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/ResumeAtLine.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Ericsson - initial API and implementation *******************************************************************************/ @@ -36,16 +36,16 @@ import org.eclipse.debug.core.DebugException; /** * Implements the CDT's resume at line interface. - * + * * @since 2.1 */ public class ResumeAtLine implements IResumeAtLine, IResumeAtAddress { - private final IExecutionDMContext fContext; + private final IExecutionDMContext fContext; - public ResumeAtLine(IExecutionDMContext context) { - fContext = context; - } + public ResumeAtLine(IExecutionDMContext context) { + fContext = context; + } @Override public boolean canResumeAtLine(IFile file, final int lineNumber) { @@ -54,151 +54,155 @@ public class ResumeAtLine implements IResumeAtLine, IResumeAtAddress { @Override public boolean canResumeAtLine(final String fileName, final int lineNumber) { - DsfSession session = DsfSession.getSession(fContext.getSessionId()); - if (session != null && session.isActive()) { - try { - Query<Boolean> query = new Query<Boolean>() { - @Override - protected void execute(DataRequestMonitor<Boolean> rm) { - DsfServicesTracker tracker = - new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fContext.getSessionId()); - - IRunControl2 runControl = tracker.getService(IRunControl2.class); - if (runControl != null) { - runControl.canMoveToLine(fContext, fileName, lineNumber, true, rm); - } else { - rm.setData(false); - rm.done(); - } - tracker.dispose(); - } - }; - session.getExecutor().execute(query); - return query.get(IDsfActionsConstants.ACTION_ADAPTERS_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } catch (RejectedExecutionException e) { - } catch (InterruptedException e) { - } catch (ExecutionException e) { - } catch (TimeoutException e) { - } - } - return false; - } - + DsfSession session = DsfSession.getSession(fContext.getSessionId()); + if (session != null && session.isActive()) { + try { + Query<Boolean> query = new Query<Boolean>() { + @Override + protected void execute(DataRequestMonitor<Boolean> rm) { + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + fContext.getSessionId()); + + IRunControl2 runControl = tracker.getService(IRunControl2.class); + if (runControl != null) { + runControl.canMoveToLine(fContext, fileName, lineNumber, true, rm); + } else { + rm.setData(false); + rm.done(); + } + tracker.dispose(); + } + }; + session.getExecutor().execute(query); + return query.get(IDsfActionsConstants.ACTION_ADAPTERS_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException e) { + } catch (InterruptedException e) { + } catch (ExecutionException e) { + } catch (TimeoutException e) { + } + } + return false; + } + @Override public void resumeAtLine(IFile file, int lineNumber) throws DebugException { resumeAtLine(file.getLocation().makeAbsolute().toOSString(), lineNumber); } - + @Override public void resumeAtLine(final String fileName, final int lineNumber) throws DebugException { - DsfSession session = DsfSession.getSession(fContext.getSessionId()); - if (session != null && session.isActive()) { - Throwable exception = null; - try { - Query<Object> query = new Query<Object>() { - @Override - protected void execute(final DataRequestMonitor<Object> rm) { - DsfServicesTracker tracker = - new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fContext.getSessionId()); - - IRunControl2 runControl = tracker.getService(IRunControl2.class); - if (runControl != null) { - runControl.moveToLine( - fContext, fileName, lineNumber, true, rm); - } else { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "IRunControl2 service not available", null)); //$NON-NLS-1$ - rm.done(); - } - tracker.dispose(); - } - }; - session.getExecutor().execute(query); - query.get(); - } catch (RejectedExecutionException e) { - exception = e; - } catch (InterruptedException e) { - exception = e; - } catch (ExecutionException e) { - exception = e; - } - if (exception != null) { - throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Failed executing move to line", exception)); //$NON-NLS-1$ - } - } else { - throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Debug session is not active", null)); //$NON-NLS-1$ - } - } - + DsfSession session = DsfSession.getSession(fContext.getSessionId()); + if (session != null && session.isActive()) { + Throwable exception = null; + try { + Query<Object> query = new Query<Object>() { + @Override + protected void execute(final DataRequestMonitor<Object> rm) { + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + fContext.getSessionId()); + + IRunControl2 runControl = tracker.getService(IRunControl2.class); + if (runControl != null) { + runControl.moveToLine(fContext, fileName, lineNumber, true, rm); + } else { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.NOT_SUPPORTED, "IRunControl2 service not available", null)); //$NON-NLS-1$ + rm.done(); + } + tracker.dispose(); + } + }; + session.getExecutor().execute(query); + query.get(); + } catch (RejectedExecutionException e) { + exception = e; + } catch (InterruptedException e) { + exception = e; + } catch (ExecutionException e) { + exception = e; + } + if (exception != null) { + throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, + "Failed executing move to line", exception)); //$NON-NLS-1$ + } + } else { + throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, + "Debug session is not active", null)); //$NON-NLS-1$ + } + } + @Override public boolean canResumeAtAddress(final IAddress address) { - DsfSession session = DsfSession.getSession(fContext.getSessionId()); - if (session != null && session.isActive()) { - try { - Query<Boolean> query = new Query<Boolean>() { - @Override - protected void execute(DataRequestMonitor<Boolean> rm) { - DsfServicesTracker tracker = - new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fContext.getSessionId()); - - IRunControl2 runControl = tracker.getService(IRunControl2.class); - if (runControl != null) { - runControl.canMoveToAddress(fContext, address, true, rm); - } else { - rm.setData(false); - rm.done(); - } - tracker.dispose(); - } - }; - session.getExecutor().execute(query); - return query.get(IDsfActionsConstants.ACTION_ADAPTERS_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } catch (RejectedExecutionException e) { - } catch (InterruptedException e) { - } catch (ExecutionException e) { - } catch (TimeoutException e) { - } - } - return false; - } + DsfSession session = DsfSession.getSession(fContext.getSessionId()); + if (session != null && session.isActive()) { + try { + Query<Boolean> query = new Query<Boolean>() { + @Override + protected void execute(DataRequestMonitor<Boolean> rm) { + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + fContext.getSessionId()); + + IRunControl2 runControl = tracker.getService(IRunControl2.class); + if (runControl != null) { + runControl.canMoveToAddress(fContext, address, true, rm); + } else { + rm.setData(false); + rm.done(); + } + tracker.dispose(); + } + }; + session.getExecutor().execute(query); + return query.get(IDsfActionsConstants.ACTION_ADAPTERS_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException e) { + } catch (InterruptedException e) { + } catch (ExecutionException e) { + } catch (TimeoutException e) { + } + } + return false; + } @Override public void resumeAtAddress(final IAddress address) throws DebugException { - DsfSession session = DsfSession.getSession(fContext.getSessionId()); - if (session != null && session.isActive()) { - Throwable exception = null; - try { - Query<Object> query = new Query<Object>() { - @Override - protected void execute(final DataRequestMonitor<Object> rm) { - DsfServicesTracker tracker = - new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fContext.getSessionId()); - - IRunControl2 runControl = tracker.getService(IRunControl2.class); - if (runControl != null) { - runControl.moveToAddress( - fContext, address, true, rm); - } else { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "IRunControl2 service not available", null)); //$NON-NLS-1$ - rm.done(); - } - tracker.dispose(); - } - }; - session.getExecutor().execute(query); - query.get(); - } catch (RejectedExecutionException e) { - exception = e; - } catch (InterruptedException e) { - exception = e; - } catch (ExecutionException e) { - exception = e; - } - if (exception != null) { - throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Failed executing move to line", exception)); //$NON-NLS-1$ - } - } else { - throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Debug session is not active", null)); //$NON-NLS-1$ - } - } - + DsfSession session = DsfSession.getSession(fContext.getSessionId()); + if (session != null && session.isActive()) { + Throwable exception = null; + try { + Query<Object> query = new Query<Object>() { + @Override + protected void execute(final DataRequestMonitor<Object> rm) { + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + fContext.getSessionId()); + + IRunControl2 runControl = tracker.getService(IRunControl2.class); + if (runControl != null) { + runControl.moveToAddress(fContext, address, true, rm); + } else { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.NOT_SUPPORTED, "IRunControl2 service not available", null)); //$NON-NLS-1$ + rm.done(); + } + tracker.dispose(); + } + }; + session.getExecutor().execute(query); + query.get(); + } catch (RejectedExecutionException e) { + exception = e; + } catch (InterruptedException e) { + exception = e; + } catch (ExecutionException e) { + exception = e; + } + if (exception != null) { + throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, + "Failed executing move to line", exception)); //$NON-NLS-1$ + } + } else { + throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, + "Debug session is not active", null)); //$NON-NLS-1$ + } + } + } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/RetargettableActionAdapterFactory.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/RetargettableActionAdapterFactory.java index 1f18ec28f7e..431c06ba4b7 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/RetargettableActionAdapterFactory.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/RetargettableActionAdapterFactory.java @@ -20,7 +20,7 @@ import org.eclipse.debug.ui.actions.IRunToLineTarget; /** * Retargettable Action Adapter Factory for the DSF Disassembly view - * + * * @since 2.1 */ public class RetargettableActionAdapterFactory implements IAdapterFactory { @@ -32,13 +32,13 @@ public class RetargettableActionAdapterFactory implements IAdapterFactory { @SuppressWarnings("unchecked") public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { if (adapterType == IRunToLineTarget.class) { - return (T)new DisassemblyRunToLineAdapter(); - } + return (T) new DisassemblyRunToLineAdapter(); + } if (adapterType == IMoveToLineTarget.class) { - return (T)new DisassemblyMoveToLineAdapter(); - } + return (T) new DisassemblyMoveToLineAdapter(); + } if (adapterType == IResumeAtLineTarget.class) { - return (T)new DisassemblyResumeAtLineAdapter(); + return (T) new DisassemblyResumeAtLineAdapter(); } return null; } @@ -48,6 +48,6 @@ public class RetargettableActionAdapterFactory implements IAdapterFactory { */ @Override public Class<?>[] getAdapterList() { - return new Class[]{ IRunToLineTarget.class, IResumeAtLineTarget.class, IMoveToLineTarget.class }; + return new Class[] { IRunToLineTarget.class, IResumeAtLineTarget.class, IMoveToLineTarget.class }; } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/RunToLine.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/RunToLine.java index 38ffb06b6a4..956f40ee29a 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/RunToLine.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/actions/RunToLine.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Ericsson - Added support for IRunToAddress for DSF DisassemblyView (302324) @@ -39,167 +39,173 @@ import org.eclipse.debug.ui.actions.IRunToLineTarget; /** * Implements the CDT's run to line interface. This interface is called by CDT's * {@link IRunToLineTarget} implementation. - * + * * @since 2.1 */ public class RunToLine implements IRunToLine, IRunToAddress { - private final IExecutionDMContext fContext; + private final IExecutionDMContext fContext; - public RunToLine(IExecutionDMContext context) { - fContext = context; - } - - @Override + public RunToLine(IExecutionDMContext context) { + fContext = context; + } + + @Override public boolean canRunToLine(final IFile file, final int lineNumber) { - return canRunToLine(file.getLocation().makeAbsolute().toOSString(), lineNumber); - } + return canRunToLine(file.getLocation().makeAbsolute().toOSString(), lineNumber); + } - @Override + @Override public boolean canRunToLine(final String fileName, final int lineNumber) { - DsfSession session = DsfSession.getSession(fContext.getSessionId()); - if (session != null && session.isActive()) { - try { - Query<Boolean> query = new Query<Boolean>() { - @Override - protected void execute(DataRequestMonitor<Boolean> rm) { - DsfServicesTracker tracker = - new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fContext.getSessionId()); - - IRunControl2 runControl = tracker.getService(IRunControl2.class); - if (runControl != null) { - runControl.canRunToLine(fContext, fileName, lineNumber, rm); - } else { - rm.setData(false); - rm.done(); - } - tracker.dispose(); - } - }; - session.getExecutor().execute(query); - return query.get(IDsfActionsConstants.ACTION_ADAPTERS_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } catch (RejectedExecutionException e) { - } catch (InterruptedException e) { - } catch (ExecutionException e) { - } catch (TimeoutException e) { - } - } - return false; - } + DsfSession session = DsfSession.getSession(fContext.getSessionId()); + if (session != null && session.isActive()) { + try { + Query<Boolean> query = new Query<Boolean>() { + @Override + protected void execute(DataRequestMonitor<Boolean> rm) { + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + fContext.getSessionId()); + + IRunControl2 runControl = tracker.getService(IRunControl2.class); + if (runControl != null) { + runControl.canRunToLine(fContext, fileName, lineNumber, rm); + } else { + rm.setData(false); + rm.done(); + } + tracker.dispose(); + } + }; + session.getExecutor().execute(query); + return query.get(IDsfActionsConstants.ACTION_ADAPTERS_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException e) { + } catch (InterruptedException e) { + } catch (ExecutionException e) { + } catch (TimeoutException e) { + } + } + return false; + } - @Override + @Override public void runToLine(IFile file, int lineNumber, boolean skipBreakpoints) throws DebugException { - runToLine(file.getLocation().makeAbsolute().toOSString(), lineNumber, skipBreakpoints); - } - - @Override - public void runToLine(final String fileName, final int lineNumber, final boolean skipBreakpoints) throws DebugException { - DsfSession session = DsfSession.getSession(fContext.getSessionId()); - if (session != null && session.isActive()) { - Throwable exception = null; - try { - Query<Object> query = new Query<Object>() { - @Override - protected void execute(final DataRequestMonitor<Object> rm) { - DsfServicesTracker tracker = - new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fContext.getSessionId()); - - IRunControl2 runControl = tracker.getService(IRunControl2.class); - if (runControl != null) { - runControl.runToLine( - fContext, fileName, lineNumber, skipBreakpoints, rm); - } else { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "IRunControl2 service not available", null)); //$NON-NLS-1$ - rm.done(); - } - tracker.dispose(); - } - }; - session.getExecutor().execute(query); - query.get(); - } catch (RejectedExecutionException e) { - exception = e; - } catch (InterruptedException e) { - exception = e; - } catch (ExecutionException e) { - exception = e; - } - if (exception != null) { - throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Failed executing run to line", exception)); //$NON-NLS-1$ - } - } else { - throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Debug session is not active", null)); //$NON-NLS-1$ - } - } - + runToLine(file.getLocation().makeAbsolute().toOSString(), lineNumber, skipBreakpoints); + } + + @Override + public void runToLine(final String fileName, final int lineNumber, final boolean skipBreakpoints) + throws DebugException { + DsfSession session = DsfSession.getSession(fContext.getSessionId()); + if (session != null && session.isActive()) { + Throwable exception = null; + try { + Query<Object> query = new Query<Object>() { + @Override + protected void execute(final DataRequestMonitor<Object> rm) { + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + fContext.getSessionId()); + + IRunControl2 runControl = tracker.getService(IRunControl2.class); + if (runControl != null) { + runControl.runToLine(fContext, fileName, lineNumber, skipBreakpoints, rm); + } else { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.NOT_SUPPORTED, "IRunControl2 service not available", null)); //$NON-NLS-1$ + rm.done(); + } + tracker.dispose(); + } + }; + session.getExecutor().execute(query); + query.get(); + } catch (RejectedExecutionException e) { + exception = e; + } catch (InterruptedException e) { + exception = e; + } catch (ExecutionException e) { + exception = e; + } + if (exception != null) { + throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, + "Failed executing run to line", exception)); //$NON-NLS-1$ + } + } else { + throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, + "Debug session is not active", null)); //$NON-NLS-1$ + } + } + @Override public boolean canRunToAddress(final IAddress address) { - DsfSession session = DsfSession.getSession(fContext.getSessionId()); - if (session != null && session.isActive()) { - try { - Query<Boolean> query = new Query<Boolean>() { - @Override - protected void execute(DataRequestMonitor<Boolean> rm) { - DsfServicesTracker tracker = - new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fContext.getSessionId()); - - IRunControl2 runControl = tracker.getService(IRunControl2.class); - if (runControl != null) { - runControl.canRunToAddress(fContext, address, rm); - } else { - rm.setData(false); - rm.done(); - } - tracker.dispose(); - } - }; - session.getExecutor().execute(query); - return query.get(IDsfActionsConstants.ACTION_ADAPTERS_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } catch (RejectedExecutionException e) { - } catch (InterruptedException e) { - } catch (ExecutionException e) { - } catch (TimeoutException e) { - } - } - return false; - } + DsfSession session = DsfSession.getSession(fContext.getSessionId()); + if (session != null && session.isActive()) { + try { + Query<Boolean> query = new Query<Boolean>() { + @Override + protected void execute(DataRequestMonitor<Boolean> rm) { + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + fContext.getSessionId()); + + IRunControl2 runControl = tracker.getService(IRunControl2.class); + if (runControl != null) { + runControl.canRunToAddress(fContext, address, rm); + } else { + rm.setData(false); + rm.done(); + } + tracker.dispose(); + } + }; + session.getExecutor().execute(query); + return query.get(IDsfActionsConstants.ACTION_ADAPTERS_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException e) { + } catch (InterruptedException e) { + } catch (ExecutionException e) { + } catch (TimeoutException e) { + } + } + return false; + } @Override public void runToAddress(final IAddress address, final boolean skipBreakpoints) throws DebugException { - DsfSession session = DsfSession.getSession(fContext.getSessionId()); - if (session != null && session.isActive()) { - Throwable exception = null; - try { - Query<Object> query = new Query<Object>() { - @Override - protected void execute(final DataRequestMonitor<Object> rm) { - DsfServicesTracker tracker = - new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fContext.getSessionId()); - - IRunControl2 runControl = tracker.getService(IRunControl2.class); - if (runControl != null) { - runControl.runToAddress(fContext, address, skipBreakpoints, rm); - } else { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "IRunControl2 service not available", null)); //$NON-NLS-1$ - rm.done(); - } - tracker.dispose(); - } - }; - session.getExecutor().execute(query); - query.get(); - } catch (RejectedExecutionException e) { - exception = e; - } catch (InterruptedException e) { - exception = e; - } catch (ExecutionException e) { - exception = e; - } - if (exception != null) { - throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Failed executing run to line", exception)); //$NON-NLS-1$ - } - } else { - throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Debug session is not active", null)); //$NON-NLS-1$ - } - } - } + DsfSession session = DsfSession.getSession(fContext.getSessionId()); + if (session != null && session.isActive()) { + Throwable exception = null; + try { + Query<Object> query = new Query<Object>() { + @Override + protected void execute(final DataRequestMonitor<Object> rm) { + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + fContext.getSessionId()); + + IRunControl2 runControl = tracker.getService(IRunControl2.class); + if (runControl != null) { + runControl.runToAddress(fContext, address, skipBreakpoints, rm); + } else { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.NOT_SUPPORTED, "IRunControl2 service not available", null)); //$NON-NLS-1$ + rm.done(); + } + tracker.dispose(); + } + }; + session.getExecutor().execute(query); + query.get(); + } catch (RejectedExecutionException e) { + exception = e; + } catch (InterruptedException e) { + exception = e; + } catch (ExecutionException e) { + exception = e; + } + if (exception != null) { + throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, + "Failed executing run to line", exception)); //$NON-NLS-1$ + } + } else { + throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, + "Debug session is not active", null)); //$NON-NLS-1$ + } + } +} diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/DebugViewLayoutTester.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/DebugViewLayoutTester.java index 04f44bf89d5..b33f5d334df 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/DebugViewLayoutTester.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/DebugViewLayoutTester.java @@ -18,32 +18,32 @@ import org.eclipse.cdt.dsf.ui.viewmodel.datamodel.IDMVMContext; import org.eclipse.core.expressions.PropertyTester; /** - * Property tester for debug view related commands - group, ungroup, hide, etc. - * + * Property tester for debug view related commands - group, ungroup, hide, etc. + * * @since 2.2 */ -public class DebugViewLayoutTester extends PropertyTester{ - +public class DebugViewLayoutTester extends PropertyTester { + public DebugViewLayoutTester() { } protected static final String IS_GROUP_VISIBLE = "isGroupDebugContextsVisible"; //$NON-NLS-1$ protected static final String IS_UNGROUP_VISIBLE = "isUngroupDebugContextsVisible"; //$NON-NLS-1$ - + @Override public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { - if( IS_GROUP_VISIBLE.equals(property) || IS_UNGROUP_VISIBLE.equals(property)) { - if (receiver instanceof IDMVMContext) { - return test((IDMVMContext)receiver); - } - } - return false; - } - - private boolean test(IDMVMContext dmContext) { + if (IS_GROUP_VISIBLE.equals(property) || IS_UNGROUP_VISIBLE.equals(property)) { + if (receiver instanceof IDMVMContext) { + return test((IDMVMContext) receiver); + } + } + return false; + } + + private boolean test(IDMVMContext dmContext) { String sessionId = dmContext.getDMContext().getSessionId(); return DsfSession.isSessionActive(sessionId); - } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/actions/DsfDebugViewLayoutCommand.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/actions/DsfDebugViewLayoutCommand.java index 3ee859c9acb..b8e84e5438c 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/actions/DsfDebugViewLayoutCommand.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/actions/DsfDebugViewLayoutCommand.java @@ -35,86 +35,84 @@ import org.eclipse.debug.core.commands.IEnabledStateRequest; /** * @since 2.2 */ -public abstract class DsfDebugViewLayoutCommand implements IDebugCommandHandler{ - - protected final DsfExecutor fExecutor; - protected final DsfServicesTracker fTracker; - protected static IExecutionDMContext[] EMPTY_ARRAY = new IExecutionDMContext[0]; - - public DsfDebugViewLayoutCommand(DsfSession session) { - fExecutor = session.getExecutor(); - fTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); - } - - public void dispose() { - fTracker.dispose(); - } - - /** - * - * @param request - * @return set of IExecutionDMContext if: - * - all elements are from a DSF session. - * - all elements are from the same DSF session. - */ - protected IExecutionDMContext[] getDMContexts(IDebugCommandRequest request) { - - HashSet<IExecutionDMContext> ret = new HashSet<>(); - String sessionId = null; - - for (Object obj : request.getElements()) { - if (!(obj instanceof IDMVMContext)) { - return EMPTY_ARRAY; - } - - IDMContext dmContext = ((IDMVMContext)obj).getDMContext(); - IExecutionDMContext exeContext = DMContexts.getAncestorOfType(dmContext, IExecutionDMContext.class); - - if (exeContext == null) { - return EMPTY_ARRAY; - } - - // make sure all elements are from the same DSF session. - if (sessionId == null) { - sessionId = dmContext.getSessionId(); - } - else { - if (!sessionId.equals(dmContext.getSessionId())) { - return EMPTY_ARRAY; - } - } - - ret.add(exeContext); - } - return ret.toArray(new IExecutionDMContext[ret.size()]); - } - +public abstract class DsfDebugViewLayoutCommand implements IDebugCommandHandler { + + protected final DsfExecutor fExecutor; + protected final DsfServicesTracker fTracker; + protected static IExecutionDMContext[] EMPTY_ARRAY = new IExecutionDMContext[0]; + + public DsfDebugViewLayoutCommand(DsfSession session) { + fExecutor = session.getExecutor(); + fTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); + } + + public void dispose() { + fTracker.dispose(); + } + + /** + * + * @param request + * @return set of IExecutionDMContext if: + * - all elements are from a DSF session. + * - all elements are from the same DSF session. + */ + protected IExecutionDMContext[] getDMContexts(IDebugCommandRequest request) { + + HashSet<IExecutionDMContext> ret = new HashSet<>(); + String sessionId = null; + + for (Object obj : request.getElements()) { + if (!(obj instanceof IDMVMContext)) { + return EMPTY_ARRAY; + } + + IDMContext dmContext = ((IDMVMContext) obj).getDMContext(); + IExecutionDMContext exeContext = DMContexts.getAncestorOfType(dmContext, IExecutionDMContext.class); + + if (exeContext == null) { + return EMPTY_ARRAY; + } + + // make sure all elements are from the same DSF session. + if (sessionId == null) { + sessionId = dmContext.getSessionId(); + } else { + if (!sessionId.equals(dmContext.getSessionId())) { + return EMPTY_ARRAY; + } + } + + ret.add(exeContext); + } + return ret.toArray(new IExecutionDMContext[ret.size()]); + } + @Override public void canExecute(final IEnabledStateRequest request) { final IExecutionDMContext[] executionContexts = getDMContexts(request); if (executionContexts.length > 0 && !fExecutor.isTerminated()) { - fExecutor.submit(new DsfRunnable() { + fExecutor.submit(new DsfRunnable() { @Override public void run() { IExecutionContextTranslator translator = fTracker.getService(IExecutionContextTranslator.class); if (translator != null) { - canExecuteOnDsfThread(translator, executionContexts, - new DataRequestMonitor<Boolean>(fExecutor, null) { - @Override - protected void handleCompleted() { - boolean canExecute = isSuccess() && getData(); - request.setEnabled(canExecute); - request.done(); - } - }); + canExecuteOnDsfThread(translator, executionContexts, + new DataRequestMonitor<Boolean>(fExecutor, null) { + @Override + protected void handleCompleted() { + boolean canExecute = isSuccess() && getData(); + request.setEnabled(canExecute); + request.done(); + } + }); } else { request.setEnabled(false); request.done(); } - } - }); - } - else { + } + }); + } else { request.setEnabled(false); request.done(); } @@ -124,30 +122,31 @@ public abstract class DsfDebugViewLayoutCommand implements IDebugCommandHandler{ public boolean execute(final IDebugCommandRequest request) { final IExecutionDMContext[] executionContexts = getDMContexts(request); if (executionContexts.length > 0 && !fExecutor.isTerminated()) { - fExecutor.submit(new DsfRunnable() { + fExecutor.submit(new DsfRunnable() { @Override public void run() { IExecutionContextTranslator translator = fTracker.getService(IExecutionContextTranslator.class); if (translator != null) { - executeOnDsfThread(translator, executionContexts, - new RequestMonitor(fExecutor, null) { - @Override - protected void handleCompleted() { - request.done(); - } - }); - } - else { + executeOnDsfThread(translator, executionContexts, new RequestMonitor(fExecutor, null) { + @Override + protected void handleCompleted() { + request.done(); + } + }); + } else { request.done(); } - } - }); + } + }); return false; } - request.done(); + request.done(); return true; } - - abstract void executeOnDsfThread(IExecutionContextTranslator translator, IExecutionDMContext[] contexts, RequestMonitor rm); - abstract void canExecuteOnDsfThread(IExecutionContextTranslator translator, IExecutionDMContext[] contexts, DataRequestMonitor<Boolean> rm); + + abstract void executeOnDsfThread(IExecutionContextTranslator translator, IExecutionDMContext[] contexts, + RequestMonitor rm); + + abstract void canExecuteOnDsfThread(IExecutionContextTranslator translator, IExecutionDMContext[] contexts, + DataRequestMonitor<Boolean> rm); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/actions/DsfGroupDebugContextsCommand.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/actions/DsfGroupDebugContextsCommand.java index 0888385f121..6bd15348ef5 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/actions/DsfGroupDebugContextsCommand.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/actions/DsfGroupDebugContextsCommand.java @@ -24,18 +24,19 @@ import org.eclipse.debug.core.commands.IDebugCommandHandler; * @since 2.2 */ public class DsfGroupDebugContextsCommand extends DsfDebugViewLayoutCommand implements IDebugCommandHandler { - + public DsfGroupDebugContextsCommand(DsfSession session) { super(session); - } + } @Override void executeOnDsfThread(IExecutionContextTranslator translator, IExecutionDMContext[] contexts, RequestMonitor rm) { translator.group(contexts, rm); } - + @Override - void canExecuteOnDsfThread(IExecutionContextTranslator translator, IExecutionDMContext[] contexts, DataRequestMonitor<Boolean> rm) { + void canExecuteOnDsfThread(IExecutionContextTranslator translator, IExecutionDMContext[] contexts, + DataRequestMonitor<Boolean> rm) { translator.canGroup(contexts, rm); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/actions/DsfUngroupDebugContextsCommand.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/actions/DsfUngroupDebugContextsCommand.java index c5943f9bde2..86eff45aac5 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/actions/DsfUngroupDebugContextsCommand.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/debugview/layout/actions/DsfUngroupDebugContextsCommand.java @@ -24,10 +24,10 @@ import org.eclipse.debug.core.commands.IDebugCommandHandler; * @since 2.2 */ public class DsfUngroupDebugContextsCommand extends DsfDebugViewLayoutCommand implements IDebugCommandHandler { - - public DsfUngroupDebugContextsCommand(DsfSession session) { - super(session); - } + + public DsfUngroupDebugContextsCommand(DsfSession session) { + super(session); + } @Override void executeOnDsfThread(IExecutionContextTranslator translator, IExecutionDMContext[] contexts, RequestMonitor rm) { @@ -35,7 +35,8 @@ public class DsfUngroupDebugContextsCommand extends DsfDebugViewLayoutCommand im } @Override - void canExecuteOnDsfThread(IExecutionContextTranslator translator, IExecutionDMContext[] contexts, DataRequestMonitor<Boolean> rm) { + void canExecuteOnDsfThread(IExecutionContextTranslator translator, IExecutionDMContext[] contexts, + DataRequestMonitor<Boolean> rm) { translator.canUngroup(contexts, rm); - } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/AbstractImageRegistry.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/AbstractImageRegistry.java index f124e57cb4f..186733f8d8a 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/AbstractImageRegistry.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/AbstractImageRegistry.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -28,7 +28,6 @@ import org.eclipse.swt.SWTException; import org.eclipse.swt.graphics.Image; import org.osgi.framework.Bundle; - /** * Abstract image registry that allows for defining fallback paths for images. */ @@ -36,13 +35,13 @@ public abstract class AbstractImageRegistry { private HashMap<String, String> fPlugins = new HashMap<String, String>(); private HashMap<String, String[]> fLocations = new HashMap<String, String[]>(); private URL fBaseUrl; - private final ImageRegistry fRegistry; + private final ImageRegistry fRegistry; protected AbstractImageRegistry(Plugin plugin) { - fRegistry = new ImageRegistry(); + fRegistry = new ImageRegistry(); fBaseUrl = plugin.getBundle().getEntry("/"); //$NON-NLS-1$ } - + /** * Defines the key for a local image, that must be found below the icons directory * in the plugin. @@ -52,10 +51,10 @@ public abstract class AbstractImageRegistry { * key. */ protected void localImage(String key, String dir, String name) { - if (dir== null || dir.isEmpty()) - fLocations.put(key, new String[] {"icons/" + name}); //$NON-NLS-1$ + if (dir == null || dir.isEmpty()) + fLocations.put(key, new String[] { "icons/" + name }); //$NON-NLS-1$ else - fLocations.put(key, new String[] {"icons/" + dir + "/" + name}); //$NON-NLS-1$ //$NON-NLS-2$ + fLocations.put(key, new String[] { "icons/" + dir + "/" + name }); //$NON-NLS-1$ //$NON-NLS-2$ } /** @@ -69,58 +68,58 @@ public abstract class AbstractImageRegistry { * key. */ protected void externalImage(String key, String plugin, String[] dirs, String name) { - if (plugin != null) { - fPlugins.put(key, plugin); - } - String[] locations = new String[dirs.length]; - for (int i = 0; i < dirs.length; i++) { + if (plugin != null) { + fPlugins.put(key, plugin); + } + String[] locations = new String[dirs.length]; + for (int i = 0; i < dirs.length; i++) { String dir = dirs[i]; - if (dir== null || dir.isEmpty()) + if (dir == null || dir.isEmpty()) locations[i] = "icons/" + name; //$NON-NLS-1$ else locations[i] = "icons/" + dir + "/" + name; //$NON-NLS-1$ //$NON-NLS-2$ - } - fLocations.put(key, locations); + } + fLocations.put(key, locations); } - + final public Image get(String key) { - Image i = fRegistry.get(key); - if (i != null) { - return i; - } - - ImageDescriptor d = createFileImageDescriptor(key); - if (d != null) { - fRegistry.put(key, d); - return fRegistry.get(key); - } - return null; + Image i = fRegistry.get(key); + if (i != null) { + return i; + } + + ImageDescriptor d = createFileImageDescriptor(key); + if (d != null) { + fRegistry.put(key, d); + return fRegistry.get(key); + } + return null; } final public ImageDescriptor getDescriptor(String key) { - ImageDescriptor d = fRegistry.getDescriptor(key); - if (d != null) { - return d; - } - - d = createFileImageDescriptor(key); - if (d != null) { - fRegistry.put(key, d); - return d; - } - return null; + ImageDescriptor d = fRegistry.getDescriptor(key); + if (d != null) { + return d; + } + + d = createFileImageDescriptor(key); + if (d != null) { + fRegistry.put(key, d); + return d; + } + return null; } private ImageDescriptor createFileImageDescriptor(String key) { URL url = fBaseUrl; String pluginId = fPlugins.get(key); if (pluginId != null) { - Bundle bundle= Platform.getBundle(pluginId); + Bundle bundle = Platform.getBundle(pluginId); if (bundle != null) { url = bundle.getEntry("/"); //$NON-NLS-1$ } } - String[] locations= fLocations.get(key); + String[] locations = fLocations.get(key); if (locations != null) { for (int i = 0; i < locations.length; i++) { String loc = locations[i]; @@ -132,13 +131,14 @@ public abstract class AbstractImageRegistry { return candidate; } } catch (MalformedURLException e) { - DsfUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, "Malformed Icon URL", e)); //$NON-NLS-1$ + DsfUIPlugin.getDefault().getLog() + .log(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, "Malformed Icon URL", e)); //$NON-NLS-1$ } catch (SWTException e) { // try the next one. } } } - return null; + return null; } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/AddressRulerColumn.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/AddressRulerColumn.java index e74c1500334..7c4263ded50 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/AddressRulerColumn.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/AddressRulerColumn.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -34,10 +34,11 @@ import org.eclipse.swt.SWT; /** * A vertical ruler column to display the instruction address. */ -public class AddressRulerColumn extends DisassemblyRulerColumn implements IVerticalRulerInfo, IVerticalRulerInfoExtension, IAnnotationHover { +public class AddressRulerColumn extends DisassemblyRulerColumn + implements IVerticalRulerInfo, IVerticalRulerInfoExtension, IAnnotationHover { public static final String ID = "org.eclipse.cdt.dsf.ui.disassemblyColumn.address"; //$NON-NLS-1$ - + private int fRadix; private boolean fShowRadixPrefix; private String fRadixPrefix; @@ -58,7 +59,7 @@ public class AddressRulerColumn extends DisassemblyRulerColumn implements IVerti @Override protected String createDisplayString(int line) { - DisassemblyDocument doc = (DisassemblyDocument)getParentRuler().getTextViewer().getDocument(); + DisassemblyDocument doc = (DisassemblyDocument) getParentRuler().getTextViewer().getDocument(); int offset; try { offset = doc.getLineOffset(line); @@ -76,16 +77,16 @@ public class AddressRulerColumn extends DisassemblyRulerColumn implements IVerti int nLines; if (srcPos.fFileInfo.fSource == null) { srcLine = srcPos.fLine; - nLines = srcLine+1; + nLines = srcLine + 1; } else { - int delta = offset-srcPos.offset; - int baseOffset = srcPos.fFileInfo.fSource.getLineOffset(srcPos.fLine); - srcLine = srcPos.fFileInfo.fSource.getLineOfOffset(baseOffset+delta); + int delta = offset - srcPos.offset; + int baseOffset = srcPos.fFileInfo.fSource.getLineOffset(srcPos.fLine); + srcLine = srcPos.fFileInfo.fSource.getLineOfOffset(baseOffset + delta); nLines = srcPos.fFileInfo.fSource.getNumberOfLines(); } - String digitStr = Integer.toString(srcLine+1); - int maxDigits = (int)(Math.log(nLines)/Math.log(10))+1; - return SPACES.substring(0, maxDigits-digitStr.length())+digitStr; + String digitStr = Integer.toString(srcLine + 1); + int maxDigits = (int) (Math.log(nLines) / Math.log(10)) + 1; + return SPACES.substring(0, maxDigits - digitStr.length()) + digitStr; } } catch (BadLocationException e) { // silently ignored @@ -99,20 +100,20 @@ public class AddressRulerColumn extends DisassemblyRulerColumn implements IVerti } public void setAddressSize(int bits) { - fAddressSize= bits; + fAddressSize = bits; calculateNumberOfDigits(); } public void setRadix(int radix) { - fRadix= radix; + fRadix = radix; calculateNumberOfDigits(); setShowRadixPrefix(fShowRadixPrefix); } private void calculateNumberOfDigits() { - fNumberOfDigits= BigInteger.ONE.shiftLeft(fAddressSize).subtract(BigInteger.ONE).toString(fRadix).length(); + fNumberOfDigits = BigInteger.ONE.shiftLeft(fAddressSize).subtract(BigInteger.ONE).toString(fRadix).length(); } - + public void setShowRadixPrefix(boolean showRadixPrefix) { fShowRadixPrefix = showRadixPrefix; if (!fShowRadixPrefix) { @@ -132,7 +133,7 @@ public class AddressRulerColumn extends DisassemblyRulerColumn implements IVerti buf.append(fRadixPrefix); } String str = address.toString(fRadix); - for (int i=str.length(); i<fNumberOfDigits; ++i) + for (int i = str.length(); i < fNumberOfDigits; ++i) buf.append('0'); buf.append(str); buf.append(':'); @@ -169,7 +170,7 @@ public class AddressRulerColumn extends DisassemblyRulerColumn implements IVerti @Override public String getHoverInfo(ISourceViewer sourceViewer, int line) { - DisassemblyDocument doc = (DisassemblyDocument)getParentRuler().getTextViewer().getDocument(); + DisassemblyDocument doc = (DisassemblyDocument) getParentRuler().getTextViewer().getDocument(); BigInteger address = doc.getAddressOfLine(line); SourceFileInfo info = doc.getSourceInfo(address); if (info != null) { @@ -180,7 +181,7 @@ public class AddressRulerColumn extends DisassemblyRulerColumn implements IVerti @Override public void propertyChange(PropertyChangeEvent event) { - String property = event.getProperty(); + String property = event.getProperty(); IPreferenceStore store = getPreferenceStore(); boolean needRedraw = false; if (DisassemblyPreferenceConstants.ADDRESS_COLOR.equals(property)) { diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyBackendDsf.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyBackendDsf.java index b0db007bfb4..39951bb03e1 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyBackendDsf.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyBackendDsf.java @@ -97,7 +97,7 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements */ public DisassemblyBackendDsf() { } - + /* (non-Javadoc) * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyBackend#init(org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyPartCallback) */ @@ -115,43 +115,43 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements DsfSession.removeSessionEndedListener(this); } - public static boolean supportsDebugContext_(IAdaptable context) { - IDMVMContext dmvmContext = context.getAdapter(IDMVMContext.class); - return dmvmContext != null && hasDisassemblyService(dmvmContext.getDMContext()); - } - - private static boolean hasDisassemblyService(final IDMContext dmContext) { - DsfSession session = DsfSession.getSession(dmContext.getSessionId()); - if (session == null || !session.isActive()) { - return false; - } - if (session.getExecutor().isInExecutorThread()) { - DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); - IDisassembly disassSvc = tracker.getService(IDisassembly.class); - tracker.dispose(); - return disassSvc != null; - } - Query<Boolean> query = new Query<Boolean>() { - @Override - protected void execute(DataRequestMonitor<Boolean> rm) { - try { - rm.setData(hasDisassemblyService(dmContext)); - } finally { - rm.done(); - } - } - }; - try { - session.getExecutor().execute(query); - Boolean result = query.get(1, TimeUnit.SECONDS); - return result != null && result.booleanValue(); - } catch (Exception exc) { - // ignored on purpose - } - return false; - } - - /* (non-Javadoc) + public static boolean supportsDebugContext_(IAdaptable context) { + IDMVMContext dmvmContext = context.getAdapter(IDMVMContext.class); + return dmvmContext != null && hasDisassemblyService(dmvmContext.getDMContext()); + } + + private static boolean hasDisassemblyService(final IDMContext dmContext) { + DsfSession session = DsfSession.getSession(dmContext.getSessionId()); + if (session == null || !session.isActive()) { + return false; + } + if (session.getExecutor().isInExecutorThread()) { + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); + IDisassembly disassSvc = tracker.getService(IDisassembly.class); + tracker.dispose(); + return disassSvc != null; + } + Query<Boolean> query = new Query<Boolean>() { + @Override + protected void execute(DataRequestMonitor<Boolean> rm) { + try { + rm.setData(hasDisassemblyService(dmContext)); + } finally { + rm.done(); + } + } + }; + try { + session.getExecutor().execute(query); + Boolean result = query.get(1, TimeUnit.SECONDS); + return result != null && result.booleanValue(); + } catch (Exception exc) { + // ignored on purpose + } + return false; + } + + /* (non-Javadoc) * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyBackend#supportsDebugContext(org.eclipse.core.runtime.IAdaptable) */ @Override @@ -175,18 +175,19 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements assert supportsDebugContext(context) : "caller should not have invoked us"; //$NON-NLS-1$ IDMVMContext vmContext = context.getAdapter(IDMVMContext.class); IDMContext dmContext = vmContext.getDMContext(); - + SetDebugContextResult result = new SetDebugContextResult(); - + String dsfSessionId = dmContext.getSessionId(); - + if (!dsfSessionId.equals(fDsfSessionId)) { // switch to different session or initiate session if (DEBUG) { - System.out.println(MessageFormat.format("DisassemblyBackendDsf: switch session [{0}<<{1}]. Input context={2}", dsfSessionId, //$NON-NLS-1$ - fDsfSessionId, dmContext)); + System.out.println(MessageFormat.format( + "DisassemblyBackendDsf: switch session [{0}<<{1}]. Input context={2}", dsfSessionId, //$NON-NLS-1$ + fDsfSessionId, dmContext)); } - fTargetContext= null; + fTargetContext = null; fTargetFrameContext = null; result.contextChanged = true; @@ -194,29 +195,30 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements if (dmContext instanceof IFrameDMContext) { fTargetFrameContext = (IFrameDMContext) dmContext; } - IExecutionDMContext executionContext= DMContexts.getAncestorOfType(dmContext, IExecutionDMContext.class); + IExecutionDMContext executionContext = DMContexts.getAncestorOfType(dmContext, + IExecutionDMContext.class); if (executionContext != null) { - fTargetContext= executionContext; + fTargetContext = executionContext; } } if (fTargetContext != null) { - + // remove ourselves as a listener with the previous session (context) - if (fDsfSessionId != null) { - final DsfSession prevSession = DsfSession.getSession(fDsfSessionId); - if (prevSession != null) { - try { - prevSession.getExecutor().execute(new DsfRunnable() { - @Override + if (fDsfSessionId != null) { + final DsfSession prevSession = DsfSession.getSession(fDsfSessionId); + if (prevSession != null) { + try { + prevSession.getExecutor().execute(new DsfRunnable() { + @Override public void run() { - prevSession.removeServiceEventListener(DisassemblyBackendDsf.this); - } - }); - } catch (RejectedExecutionException e) { - // Session is shut down. - } + prevSession.removeServiceEventListener(DisassemblyBackendDsf.this); + } + }); + } catch (RejectedExecutionException e) { + // Session is shut down. + } } - } + } // Ensures the view will display 'No Debug Context' if (fTargetFrameContext != null) { result.sessionId = fDsfSessionId = dsfSessionId; @@ -227,27 +229,27 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements if (fServicesTracker != null) { fServicesTracker.dispose(); } - fServicesTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fDsfSessionId); - + fServicesTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fDsfSessionId); + // add ourselves as a listener with the new session (context) - final DsfSession newSession = DsfSession.getSession(dsfSessionId); - if (newSession != null) { - try { - newSession.getExecutor().execute(new DsfRunnable() { - @Override + final DsfSession newSession = DsfSession.getSession(dsfSessionId); + if (newSession != null) { + try { + newSession.getExecutor().execute(new DsfRunnable() { + @Override public void run() { - newSession.addServiceEventListener(DisassemblyBackendDsf.this, null); - } - }); - } catch (RejectedExecutionException e) { - // Session is shut down. - } + newSession.addServiceEventListener(DisassemblyBackendDsf.this, null); + } + }); + } catch (RejectedExecutionException e) { + // Session is shut down. + } } } } else if (dmContext instanceof IFrameDMContext) { result.sessionId = fDsfSessionId; // switch to different frame - IFrameDMContext frame= (IFrameDMContext) dmContext; + IFrameDMContext frame = (IFrameDMContext) dmContext; IExecutionDMContext newExeDmc = DMContexts.getAncestorOfType(frame, IExecutionDMContext.class); if (newExeDmc != null) { if (fTargetFrameContext != null) { @@ -260,12 +262,12 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements // If switching from a thread node to a frame node result.contextChanged = true; } - fTargetContext= newExeDmc; - fTargetFrameContext= frame; + fTargetContext = newExeDmc; + fTargetFrameContext = frame; if (!result.contextChanged) { fCallback.gotoFrameIfActive(frame.getLevel()); } - } else { + } else { fTargetContext = null; fTargetFrameContext = null; result.contextChanged = true; @@ -279,15 +281,15 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements } else if (dmContext.equals(fTargetContext) && canDisassemble()) { result.contextChanged = false; result.sessionId = fDsfSessionId; - } else { + } else { fTargetContext = null; fTargetFrameContext = null; result.contextChanged = true; } if (DEBUG) { System.out.println(MessageFormat.format( - "DisassemblyBackendDsf: switch session done [id={0};context={1};\n\t\t\tframe={2}].\n\t\t\tInput context={3}", //$NON-NLS-1$ - fDsfSessionId, fTargetContext, fTargetFrameContext, dmContext)); + "DisassemblyBackendDsf: switch session done [id={0};context={1};\n\t\t\tframe={2}].\n\t\t\tInput context={3}", //$NON-NLS-1$ + fDsfSessionId, fTargetContext, fTargetFrameContext, dmContext)); } return result; } @@ -306,14 +308,14 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements session.removeServiceEventListener(DisassemblyBackendDsf.this); } }); - } catch (RejectedExecutionException e) { - // Session is shut down. - } + } catch (RejectedExecutionException e) { + // Session is shut down. + } } - fTargetContext= null; + fTargetContext = null; if (fServicesTracker != null) { - fServicesTracker.dispose(); - fServicesTracker= null; + fServicesTracker.dispose(); + fServicesTracker = null; } } @@ -322,17 +324,18 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements */ @Override public void retrieveFrameAddress(final int frame) { - final DsfExecutor executor= getSession().getExecutor(); + final DsfExecutor executor = getSession().getExecutor(); executor.execute(new DsfRunnable() { @Override public void run() { retrieveFrameAddressInSessionThread(frame); - }}); + } + }); } void retrieveFrameAddressInSessionThread(final int frame) { - final IStack stack= fServicesTracker.getService(IStack.class); - final DsfExecutor executor= getSession().getExecutor(); + final IStack stack = fServicesTracker.getService(IStack.class); + final DsfExecutor executor = getSession().getExecutor(); // Our frame context is currently either un-set or it's set to the frame // our caller is specifying. If un-set, then set it and reinvoke this @@ -342,7 +345,7 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements stack.getTopFrame(fTargetContext, new DataRequestMonitor<IFrameDMContext>(executor, null) { @Override protected void handleCompleted() { - fTargetFrameContext= getData(); + fTargetFrameContext = getData(); if (fTargetFrameContext != null) { retrieveFrameAddressInSessionThread(frame); } else { @@ -363,26 +366,27 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements }); } else { // TODO retrieve other stack frame - fCallback.setUpdatePending(false); + fCallback.setUpdatePending(false); } return; - } - else if (frame != fTargetFrameContext.getLevel()) { - // frame context has changed in the meantime - reinvoke - retrieveFrameAddressInSessionThread(fTargetFrameContext.getLevel()); + } else if (frame != fTargetFrameContext.getLevel()) { + // frame context has changed in the meantime - reinvoke + retrieveFrameAddressInSessionThread(fTargetFrameContext.getLevel()); return; } - + stack.getFrameData(fTargetFrameContext, new DataRequestMonitor<IFrameDMData>(executor, null) { @Override protected void handleCompleted() { fCallback.setUpdatePending(false); - IFrameDMData frameData= getData(); - fTargetFrameData= frameData; + IFrameDMData frameData = getData(); + fTargetFrameData = frameData; if (!isCanceled() && frameData != null) { - final IAddress address= frameData.getAddress(); - final BigInteger addressValue= address.getValue(); - if (DEBUG) System.out.println("retrieveFrameAddress done "+ DisassemblyUtils.getAddressText(addressValue)); //$NON-NLS-1$ + final IAddress address = frameData.getAddress(); + final BigInteger addressValue = address.getValue(); + if (DEBUG) + System.out + .println("retrieveFrameAddress done " + DisassemblyUtils.getAddressText(addressValue)); //$NON-NLS-1$ fCallback.asyncExec(new Runnable() { @Override public void run() { @@ -397,7 +401,7 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements } }); } else { - final IStatus status= getStatus(); + final IStatus status = getStatus(); if (status != null && !status.isOK()) { DisassemblyBackendDsf.this.handleError(getStatus()); } @@ -444,7 +448,7 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements } catch (InterruptedException exc) { } catch (ExecutionException exc) { } - + return false; } @@ -455,29 +459,27 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements private IRunControl getRunControl() { return getService(IRunControl.class); } - + private <V> V getService(Class<V> serviceClass) { if (fServicesTracker != null) { return fServicesTracker.getService(serviceClass); } return null; } - - @DsfServiceEventHandler public void handleEvent(IExitedDMEvent event) { if (fTargetContext == null) { return; } - final IExecutionDMContext context= event.getDMContext(); - if (context.equals(fTargetContext) - || DMContexts.isAncestorOf(fTargetContext, context)) { + final IExecutionDMContext context = event.getDMContext(); + if (context.equals(fTargetContext) || DMContexts.isAncestorOf(fTargetContext, context)) { fCallback.asyncExec(new Runnable() { @Override public void run() { fCallback.handleTargetEnded(); - }}); + } + }); } } @@ -486,9 +488,8 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements if (fTargetContext == null) { return; } - final IExecutionDMContext context= event.getDMContext(); - if (context.equals(fTargetContext) - || DMContexts.isAncestorOf(fTargetContext, context)) { + final IExecutionDMContext context = event.getDMContext(); + if (context.equals(fTargetContext) || DMContexts.isAncestorOf(fTargetContext, context)) { fCallback.handleTargetSuspended(); } } @@ -498,9 +499,8 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements if (fTargetContext == null) { return; } - final IExecutionDMContext context= event.getDMContext(); - if (context.equals(fTargetContext) - || DMContexts.isAncestorOf(fTargetContext, context)) { + final IExecutionDMContext context = event.getDMContext(); + if (context.equals(fTargetContext) || DMContexts.isAncestorOf(fTargetContext, context)) { fCallback.handleTargetResumed(); } } @@ -526,7 +526,7 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements } return -1; } - + /* (non-Javadoc) * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyBackend#hasFrameContext() */ @@ -534,7 +534,6 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements public boolean hasFrameContext() { return fTargetFrameContext != null; } - /* (non-Javadoc) * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyBackend#getFrameFile() @@ -556,64 +555,72 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements * @see org.eclipse.cdt.dsf.debug.internal.ui.disassembly.IDisassemblyBackend#retrieveDisassembly(java.math.BigInteger, java.math.BigInteger, java.lang.String, int, int, boolean, boolean, boolean, int) */ @Override - public void retrieveDisassembly(final BigInteger startAddress, BigInteger endAddress, final String file, final int lineNumber, final int lines, final boolean mixed, final boolean showSymbols, final boolean showDisassembly, final int linesHint) { + public void retrieveDisassembly(final BigInteger startAddress, BigInteger endAddress, final String file, + final int lineNumber, final int lines, final boolean mixed, final boolean showSymbols, + final boolean showDisassembly, final int linesHint) { // make sure address range is no less than 32 bytes // this is an attempt to get better a response from the backend (bug 302505) - final BigInteger finalEndAddress= startAddress.add(BigInteger.valueOf(32)).max(endAddress); + final BigInteger finalEndAddress = startAddress.add(BigInteger.valueOf(32)).max(endAddress); DsfSession session = getSession(); if (session == null) { - return; // can happen during session termination + return; // can happen during session termination } - - final DsfExecutor executor= session.getExecutor(); - final IDisassemblyDMContext context= DMContexts.getAncestorOfType(fTargetContext, IDisassemblyDMContext.class); - + final DsfExecutor executor = session.getExecutor(); + final IDisassemblyDMContext context = DMContexts.getAncestorOfType(fTargetContext, IDisassemblyDMContext.class); + // align the start address first (bug 328168) - executor.execute(new Runnable() { + executor.execute(new Runnable() { @Override public void run() { alignOpCodeAddress(startAddress, new DataRequestMonitor<BigInteger>(executor, null) { - + @Override public void handleCompleted() { final BigInteger finalStartAddress = getData(); if (mixed) { - final DataRequestMonitor<IMixedInstruction[]> disassemblyRequest= new DataRequestMonitor<IMixedInstruction[]>(executor, null) { + final DataRequestMonitor<IMixedInstruction[]> disassemblyRequest = new DataRequestMonitor<IMixedInstruction[]>( + executor, null) { @Override public void handleCompleted() { - final IMixedInstruction[] data= getData(); + final IMixedInstruction[] data = getData(); if (!isCanceled() && data != null) { fCallback.asyncExec(new Runnable() { @Override public void run() { - if (!insertDisassembly(finalStartAddress, finalEndAddress, data, showSymbols, showDisassembly)) { + if (!insertDisassembly(finalStartAddress, finalEndAddress, data, + showSymbols, showDisassembly)) { // retry in non-mixed mode - fCallback.retrieveDisassembly(finalStartAddress, finalEndAddress, linesHint, false, true); + fCallback.retrieveDisassembly(finalStartAddress, finalEndAddress, + linesHint, false, true); } - }}); + } + }); } else { - final IStatus status= getStatus(); + final IStatus status = getStatus(); if (status != null && !status.isOK()) { - if( file != null ) { + if (file != null) { fCallback.asyncExec(new Runnable() { @Override public void run() { - fCallback.retrieveDisassembly(finalStartAddress, finalEndAddress, linesHint, true, true); - }}); - } - else { + fCallback.retrieveDisassembly(finalStartAddress, + finalEndAddress, linesHint, true, true); + } + }); + } else { fCallback.asyncExec(new Runnable() { @Override public void run() { fCallback.doScrollLocked(new Runnable() { @Override public void run() { - fCallback.insertError(finalStartAddress, status.getMessage()); + fCallback.insertError(finalStartAddress, + status.getMessage()); } }); - }}); + } + }); } } fCallback.setUpdatePending(false); @@ -624,46 +631,56 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements executor.execute(new Runnable() { @Override public void run() { - final IDisassembly disassembly= fServicesTracker.getService(IDisassembly.class); + final IDisassembly disassembly = fServicesTracker + .getService(IDisassembly.class); if (disassembly == null) { disassemblyRequest.cancel(); disassemblyRequest.done(); return; } - disassembly.getMixedInstructions(context, file, lineNumber, lines*2, disassemblyRequest); - }}); + disassembly.getMixedInstructions(context, file, lineNumber, lines * 2, + disassemblyRequest); + } + }); } else { executor.execute(new Runnable() { @Override public void run() { - final IDisassembly disassembly= fServicesTracker.getService(IDisassembly.class); + final IDisassembly disassembly = fServicesTracker + .getService(IDisassembly.class); if (disassembly == null) { disassemblyRequest.cancel(); disassemblyRequest.done(); return; } - disassembly.getMixedInstructions(context, finalStartAddress, finalEndAddress, disassemblyRequest); - }}); + disassembly.getMixedInstructions(context, finalStartAddress, finalEndAddress, + disassemblyRequest); + } + }); } } else { - final DataRequestMonitor<IInstruction[]> disassemblyRequest= new DataRequestMonitor<IInstruction[]>(executor, null) { + final DataRequestMonitor<IInstruction[]> disassemblyRequest = new DataRequestMonitor<IInstruction[]>( + executor, null) { @Override public void handleCompleted() { if (!isCanceled() && getData() != null) { fCallback.asyncExec(new Runnable() { @Override public void run() { - if (!insertDisassembly(finalStartAddress, finalEndAddress, getData(), showSymbols, showDisassembly)) { + if (!insertDisassembly(finalStartAddress, finalEndAddress, getData(), + showSymbols, showDisassembly)) { fCallback.doScrollLocked(new Runnable() { @Override public void run() { - fCallback.insertError(finalStartAddress, DisassemblyMessages.DisassemblyBackendDsf_error_UnableToRetrieveData); + fCallback.insertError(finalStartAddress, + DisassemblyMessages.DisassemblyBackendDsf_error_UnableToRetrieveData); } }); } - }}); + } + }); } else { - final IStatus status= getStatus(); + final IStatus status = getStatus(); if (status != null && !status.isOK()) { fCallback.asyncExec(new Runnable() { @Override @@ -671,10 +688,12 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements fCallback.doScrollLocked(new Runnable() { @Override public void run() { - fCallback.insertError(finalStartAddress, status.getMessage()); + fCallback.insertError(finalStartAddress, + status.getMessage()); } }); - }}); + } + }); } fCallback.setUpdatePending(false); } @@ -683,14 +702,16 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements executor.execute(new Runnable() { @Override public void run() { - final IDisassembly disassembly= fServicesTracker.getService(IDisassembly.class); + final IDisassembly disassembly = fServicesTracker.getService(IDisassembly.class); if (disassembly == null) { disassemblyRequest.cancel(); disassemblyRequest.done(); return; } - disassembly.getInstructions(context, finalStartAddress, finalEndAddress, disassemblyRequest); - }}); + disassembly.getInstructions(context, finalStartAddress, finalEndAddress, + disassemblyRequest); + } + }); } } }); @@ -698,20 +719,22 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements }); } - private boolean insertDisassembly(BigInteger startAddress, BigInteger endAddress, IInstruction[] instructions, boolean showSymbols, boolean showDisassembly) { - if (!fCallback.hasViewer() || fDsfSessionId == null || fTargetContext == null) { - if (DEBUG) { - System.out.println(MessageFormat.format( + private boolean insertDisassembly(BigInteger startAddress, BigInteger endAddress, IInstruction[] instructions, + boolean showSymbols, boolean showDisassembly) { + if (!fCallback.hasViewer() || fDsfSessionId == null || fTargetContext == null) { + if (DEBUG) { + System.out.println(MessageFormat.format( "insertDisassembly ignored at {0} due to missing context: [fDsfSessionId={1};fTargetContext={2}]", //$NON-NLS-1$ DisassemblyUtils.getAddressText(startAddress), fDsfSessionId, fTargetContext)); - } - if (fTargetContext == null) { - fCallback.setUpdatePending(false); - } + } + if (fTargetContext == null) { + fCallback.setUpdatePending(false); + } // return true to avoid a retry return true; } - if (DEBUG) System.out.println("insertDisassembly "+ DisassemblyUtils.getAddressText(startAddress)); //$NON-NLS-1$ + if (DEBUG) + System.out.println("insertDisassembly " + DisassemblyUtils.getAddressText(startAddress)); //$NON-NLS-1$ assert fCallback.getUpdatePending(); if (!fCallback.getUpdatePending()) { // safe-guard in case something weird is going on @@ -723,11 +746,11 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements try { fCallback.lockScroller(); - - AddressRangePosition p= null; + + AddressRangePosition p = null; for (int j = 0; j < instructions.length; j++) { IInstruction instruction = instructions[j]; - BigInteger address= instruction.getAdress(); + BigInteger address = instruction.getAdress(); if (startAddress == null || startAddress.compareTo(BigInteger.ZERO) < 0) { startAddress = address; fCallback.setGotoAddressPending(address); @@ -739,10 +762,12 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements p.fValid = false; fCallback.getDocument().addInvalidAddressRange(p); } else if (p == null || address.compareTo(endAddress) > 0) { - if (DEBUG) System.out.println("Excess disassembly lines at " + DisassemblyUtils.getAddressText(address)); //$NON-NLS-1$ + if (DEBUG) + System.out.println("Excess disassembly lines at " + DisassemblyUtils.getAddressText(address)); //$NON-NLS-1$ return insertedAnyAddress; } else if (p.fValid) { - if (DEBUG) System.out.println("Excess disassembly lines at " + DisassemblyUtils.getAddressText(address)); //$NON-NLS-1$ + if (DEBUG) + System.out.println("Excess disassembly lines at " + DisassemblyUtils.getAddressText(address)); //$NON-NLS-1$ if (!p.fAddressOffset.equals(address)) { // override probably unaligned disassembly p.fValid = false; @@ -751,21 +776,22 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements continue; } } - boolean hasSource= false; - String compilationPath= null; + boolean hasSource = false; + String compilationPath = null; // insert symbol label - final String functionName= instruction.getFuntionName(); + final String functionName = instruction.getFuntionName(); if (functionName != null && !functionName.isEmpty() && instruction.getOffset() == 0) { - p = fCallback.getDocument().insertLabel(p, address, functionName, showSymbols && (!hasSource || showDisassembly)); + p = fCallback.getDocument().insertLabel(p, address, functionName, + showSymbols && (!hasSource || showDisassembly)); } // determine instruction byte length - BigInteger instrLength= null; + BigInteger instrLength = null; if (instruction instanceof IInstructionWithSize - && ((IInstructionWithSize)instruction).getSize() != null) { - instrLength= new BigInteger(((IInstructionWithSize)instruction).getSize().toString()); + && ((IInstructionWithSize) instruction).getSize() != null) { + instrLength = new BigInteger(((IInstructionWithSize) instruction).getSize().toString()); } else { if (j < instructions.length - 1) { - instrLength= instructions[j+1].getAdress().subtract(instruction.getAdress()).abs(); + instrLength = instructions[j + 1].getAdress().subtract(instruction.getAdress()).abs(); } if (instrLength == null) { // cannot determine length of last instruction @@ -775,18 +801,19 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements final String functionOffset; // Renamed from opCode to avoid confusion // insert function name+offset instead of opcode bytes if (functionName != null && !functionName.isEmpty()) { - functionOffset= functionName + '+' + instruction.getOffset(); + functionOffset = functionName + '+' + instruction.getOffset(); } else { - functionOffset= ""; //$NON-NLS-1$ + functionOffset = ""; //$NON-NLS-1$ } - + BigInteger opCodes = null; // Get raw Opcodes if available - if(instruction instanceof IInstructionWithRawOpcodes){ - opCodes = ((IInstructionWithRawOpcodes)instruction).getRawOpcodes(); + if (instruction instanceof IInstructionWithRawOpcodes) { + opCodes = ((IInstructionWithRawOpcodes) instruction).getRawOpcodes(); } - p = fCallback.getDocument().insertDisassemblyLine(p, address, instrLength.intValue(), functionOffset, opCodes, instruction.getInstruction(), compilationPath, -1); + p = fCallback.getDocument().insertDisassemblyLine(p, address, instrLength.intValue(), functionOffset, + opCodes, instruction.getInstruction(), compilationPath, -1); if (p == null) { break; } @@ -814,7 +841,7 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements * an address the caller is hoping will be covered by this * insertion. I.e., [mixedInstructions] may or may not contain * that address; the caller wants to know if it does, and so we - * indicate that via our return value. Can be null to indicate n/a, + * indicate that via our return value. Can be null to indicate n/a, * in which case we return true as long as any instruction was inserted * as long as any instruction was inserted * @param endAddress @@ -825,20 +852,22 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements * @param showDisassembly * @return whether [startAddress] was inserted */ - private boolean insertDisassembly(BigInteger startAddress, BigInteger endAddress, IMixedInstruction[] mixedInstructions, boolean showSymbols, boolean showDisassembly) { - if (!fCallback.hasViewer() || fDsfSessionId == null || fTargetContext == null) { - if (DEBUG) { - System.out.println(MessageFormat.format( + private boolean insertDisassembly(BigInteger startAddress, BigInteger endAddress, + IMixedInstruction[] mixedInstructions, boolean showSymbols, boolean showDisassembly) { + if (!fCallback.hasViewer() || fDsfSessionId == null || fTargetContext == null) { + if (DEBUG) { + System.out.println(MessageFormat.format( "insertDisassembly ignored at {0} : missing context: [fDsfSessionId={1};fTargetContext={2}]", //$NON-NLS-1$ DisassemblyUtils.getAddressText(startAddress), fDsfSessionId, fTargetContext)); - } - if (fTargetContext == null) { - fCallback.setUpdatePending(false); - } + } + if (fTargetContext == null) { + fCallback.setUpdatePending(false); + } // return true to avoid a retry return true; } - if (DEBUG) System.out.println("insertDisassembly "+ DisassemblyUtils.getAddressText(startAddress)); //$NON-NLS-1$ + if (DEBUG) + System.out.println("insertDisassembly " + DisassemblyUtils.getAddressText(startAddress)); //$NON-NLS-1$ boolean updatePending = fCallback.getUpdatePending(); assert updatePending; if (!updatePending) { @@ -850,16 +879,16 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements boolean insertedAnyAddress = false; try { fCallback.lockScroller(); - - AddressRangePosition p= null; + + AddressRangePosition p = null; for (int i = 0; i < mixedInstructions.length; ++i) { - IMixedInstruction mixedInstruction= mixedInstructions[i]; - final String file= mixedInstruction.getFileName(); - int lineNumber= mixedInstruction.getLineNumber() - 1; - IInstruction[] instructions= mixedInstruction.getInstructions(); + IMixedInstruction mixedInstruction = mixedInstructions[i]; + final String file = mixedInstruction.getFileName(); + int lineNumber = mixedInstruction.getLineNumber() - 1; + IInstruction[] instructions = mixedInstruction.getInstructions(); for (int j = 0; j < instructions.length; ++j) { IInstruction instruction = instructions[j]; - BigInteger address= instruction.getAdress(); + BigInteger address = instruction.getAdress(); if (startAddress == null) { startAddress = address; fCallback.setGotoAddressPending(address); @@ -871,10 +900,14 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements p.fValid = false; fCallback.getDocument().addInvalidAddressRange(p); } else if (p == null || address.compareTo(endAddress) > 0) { - if (DEBUG) System.out.println("Excess disassembly lines at " + DisassemblyUtils.getAddressText(address)); //$NON-NLS-1$ + if (DEBUG) + System.out + .println("Excess disassembly lines at " + DisassemblyUtils.getAddressText(address)); //$NON-NLS-1$ return insertedAnyAddress; } else if (p.fValid) { - if (DEBUG) System.out.println("Excess disassembly lines at " + DisassemblyUtils.getAddressText(address)); //$NON-NLS-1$ + if (DEBUG) + System.out + .println("Excess disassembly lines at " + DisassemblyUtils.getAddressText(address)); //$NON-NLS-1$ if (!p.fAddressOffset.equals(address)) { // override probably unaligned disassembly p.fValid = false; @@ -883,30 +916,31 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements continue; } } - boolean hasSource= false; + boolean hasSource = false; if (file != null && lineNumber >= 0) { p = fCallback.insertSource(p, address, file, lineNumber); hasSource = fCallback.getStorageForFile(file) != null; } // insert symbol label - final String functionName= instruction.getFuntionName(); + final String functionName = instruction.getFuntionName(); if (functionName != null && !functionName.isEmpty() && instruction.getOffset() == 0) { - p = fCallback.getDocument().insertLabel(p, address, functionName, showSymbols && (!hasSource || showDisassembly)); + p = fCallback.getDocument().insertLabel(p, address, functionName, + showSymbols && (!hasSource || showDisassembly)); } // determine instruction byte length - BigInteger instrLength= null; + BigInteger instrLength = null; if (instruction instanceof IInstructionWithSize - && ((IInstructionWithSize)instruction).getSize() != null) { - instrLength= new BigInteger(((IInstructionWithSize)instruction).getSize().toString()); + && ((IInstructionWithSize) instruction).getSize() != null) { + instrLength = new BigInteger(((IInstructionWithSize) instruction).getSize().toString()); } else { if (j < instructions.length - 1) { - instrLength= instructions[j+1].getAdress().subtract(instruction.getAdress()).abs(); + instrLength = instructions[j + 1].getAdress().subtract(instruction.getAdress()).abs(); } else if (i < mixedInstructions.length - 1) { - int nextSrcLineIdx= i+1; + int nextSrcLineIdx = i + 1; while (nextSrcLineIdx < mixedInstructions.length) { - IInstruction[] nextInstrs= mixedInstructions[nextSrcLineIdx].getInstructions(); + IInstruction[] nextInstrs = mixedInstructions[nextSrcLineIdx].getInstructions(); if (nextInstrs.length > 0) { - instrLength= nextInstrs[0].getAdress().subtract(instruction.getAdress()).abs(); + instrLength = nextInstrs[0].getAdress().subtract(instruction.getAdress()).abs(); break; } ++nextSrcLineIdx; @@ -923,24 +957,25 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements final String funcOffset; // insert function name+offset instead of opcode bytes if (functionName != null && !functionName.isEmpty()) { - funcOffset= functionName + '+' + instruction.getOffset(); + funcOffset = functionName + '+' + instruction.getOffset(); } else { - funcOffset= ""; //$NON-NLS-1$ + funcOffset = ""; //$NON-NLS-1$ } - + BigInteger opCodes = null; - if(instruction instanceof IInstructionWithRawOpcodes){ - opCodes = ((IInstructionWithRawOpcodes)instruction).getRawOpcodes(); + if (instruction instanceof IInstructionWithRawOpcodes) { + opCodes = ((IInstructionWithRawOpcodes) instruction).getRawOpcodes(); } - - p = fCallback.getDocument().insertDisassemblyLine(p, address, instrLength.intValue(), funcOffset, opCodes, instruction.getInstruction(), file, lineNumber); + + p = fCallback.getDocument().insertDisassemblyLine(p, address, instrLength.intValue(), funcOffset, + opCodes, instruction.getInstruction(), file, lineNumber); if (p == null) { break; } insertedAnyAddress = true; } } - + } catch (BadLocationException e) { // should not happen DisassemblyUtils.internalError(e); @@ -964,25 +999,25 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements @Override public Object insertSource(Position pos, BigInteger address, final String file, int lineNumber) { Object sourceElement = null; - final ISourceLookupDMContext ctx= DMContexts.getAncestorOfType(fTargetContext, ISourceLookupDMContext.class); - final DsfExecutor executor= getSession().getExecutor(); - Query<Object> query= new Query<Object>() { + final ISourceLookupDMContext ctx = DMContexts.getAncestorOfType(fTargetContext, ISourceLookupDMContext.class); + final DsfExecutor executor = getSession().getExecutor(); + Query<Object> query = new Query<Object>() { @Override protected void execute(final DataRequestMonitor<Object> rm) { - final DataRequestMonitor<Object> request= new DataRequestMonitor<Object>(executor, rm) { + final DataRequestMonitor<Object> request = new DataRequestMonitor<Object>(executor, rm) { @Override protected void handleSuccess() { rm.setData(getData()); rm.done(); } }; - final ISourceLookup lookup= getService(ISourceLookup.class); + final ISourceLookup lookup = getService(ISourceLookup.class); lookup.getSource(ctx, file, request); } }; try { getSession().getExecutor().execute(query); - sourceElement= query.get(); + sourceElement = query.get(); } catch (InterruptedException exc) { DisassemblyUtils.internalError(exc); } catch (ExecutionException exc) { @@ -999,7 +1034,7 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements if (!hasFrameContext()) { return; } - evaluateAddressExpression(symbol, false, new DataRequestMonitor<BigInteger>(getSession().getExecutor(), null) { + evaluateAddressExpression(symbol, false, new DataRequestMonitor<BigInteger>(getSession().getExecutor(), null) { @Override protected void handleSuccess() { final BigInteger address = getData(); @@ -1008,7 +1043,8 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements @Override public void run() { fCallback.gotoAddress(address); - }}); + } + }); } } }); @@ -1027,8 +1063,8 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements Query<BigInteger> query = new Query<BigInteger>() { @Override protected void execute(DataRequestMonitor<BigInteger> rm) { - evaluateAddressExpression(symbol, suppressError, rm); - } + evaluateAddressExpression(symbol, suppressError, rm); + } }; getSession().getExecutor().execute(query); try { @@ -1037,113 +1073,127 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements return null; } } - - private void evaluateAddressExpression(final String symbol, final boolean suppressError, final DataRequestMonitor<BigInteger> rm) { - final IExpressions expressions= getService(IExpressions.class); + + private void evaluateAddressExpression(final String symbol, final boolean suppressError, + final DataRequestMonitor<BigInteger> rm) { + final IExpressions expressions = getService(IExpressions.class); if (expressions == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "", null)); //$NON-NLS-1$ + rm.setStatus( + new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "", null)); //$NON-NLS-1$ rm.done(); return; } - - final IExpressionDMContext exprDmc= expressions.createExpression(fTargetContext, symbol); + + final IExpressionDMContext exprDmc = expressions.createExpression(fTargetContext, symbol); // first, try to get l-value address - expressions.getExpressionAddressData(exprDmc, new DataRequestMonitor<IExpressionDMAddress>(getSession().getExecutor(), null) { - @Override - protected void handleSuccess() { - IExpressionDMAddress data = getData(); - final IAddress address = data.getAddress(); - if (address != null && address != IExpressionDMLocation.INVALID_ADDRESS) { - final BigInteger addressValue = address.getValue(); - fCallback.asyncExec(new Runnable() { - @Override - public void run() { - fCallback.gotoAddress(addressValue); - } - }); - rm.setData(addressValue); - rm.done(); - } else { - handleError(); - } - } - @Override - protected void handleError() { - // not an l-value, evaluate expression - final FormattedValueDMContext valueDmc= expressions.getFormattedValueContext(exprDmc, IFormattedValues.HEX_FORMAT); - expressions.getFormattedExpressionValue(valueDmc, new DataRequestMonitor<FormattedValueDMData>(getSession().getExecutor(), null) { + expressions.getExpressionAddressData(exprDmc, + new DataRequestMonitor<IExpressionDMAddress>(getSession().getExecutor(), null) { @Override protected void handleSuccess() { - FormattedValueDMData data= getData(); - String value= data.getFormattedValue(); - BigInteger address= null; - try { - address = DisassemblyUtils.decodeAddress(value); - } catch (final Exception e) { - // "value" can be empty i.e *fooX, where fooX is a variable. - // Not sure if this is a bug or not. So, fail the request instead. - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "", null)); //$NON-NLS-1$ - - if (!suppressError) { - DisassemblyBackendDsf.this.handleError(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, - DisassemblyMessages.Disassembly_log_error_expression_eval + " (" + e.getMessage() + ")", null)); //$NON-NLS-1$ //$NON-NLS-2$ - } + IExpressionDMAddress data = getData(); + final IAddress address = data.getAddress(); + if (address != null && address != IExpressionDMLocation.INVALID_ADDRESS) { + final BigInteger addressValue = address.getValue(); + fCallback.asyncExec(new Runnable() { + @Override + public void run() { + fCallback.gotoAddress(addressValue); + } + }); + rm.setData(addressValue); + rm.done(); + } else { + handleError(); } - rm.setData(address); - rm.done(); } + @Override protected void handleError() { - if (!suppressError) { - DisassemblyBackendDsf.this.handleError(getStatus()); - } - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "", null)); //$NON-NLS-1$ - rm.done(); + // not an l-value, evaluate expression + final FormattedValueDMContext valueDmc = expressions.getFormattedValueContext(exprDmc, + IFormattedValues.HEX_FORMAT); + expressions.getFormattedExpressionValue(valueDmc, + new DataRequestMonitor<FormattedValueDMData>(getSession().getExecutor(), null) { + @Override + protected void handleSuccess() { + FormattedValueDMData data = getData(); + String value = data.getFormattedValue(); + BigInteger address = null; + try { + address = DisassemblyUtils.decodeAddress(value); + } catch (final Exception e) { + // "value" can be empty i.e *fooX, where fooX is a variable. + // Not sure if this is a bug or not. So, fail the request instead. + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.REQUEST_FAILED, "", null)); //$NON-NLS-1$ + + if (!suppressError) { + DisassemblyBackendDsf.this.handleError(new Status(IStatus.ERROR, + DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, + DisassemblyMessages.Disassembly_log_error_expression_eval + " (" //$NON-NLS-1$ + + e.getMessage() + ")", //$NON-NLS-1$ + null)); + } + } + rm.setData(address); + rm.done(); + } + + @Override + protected void handleError() { + if (!suppressError) { + DisassemblyBackendDsf.this.handleError(getStatus()); + } + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.REQUEST_FAILED, "", null)); //$NON-NLS-1$ + rm.done(); + } + }); } }); - } - }); } - + /* (non-Javadoc) * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyBackend#retrieveDisassembly(java.lang.String, int, java.math.BigInteger, boolean, boolean, boolean) */ @Override - public void retrieveDisassembly(final String file, final int lines, final BigInteger endAddress, boolean mixed, final boolean showSymbols, final boolean showDisassembly) { - String debuggerPath= file; + public void retrieveDisassembly(final String file, final int lines, final BigInteger endAddress, boolean mixed, + final boolean showSymbols, final boolean showDisassembly) { + String debuggerPath = file; // try reverse lookup - final ISourceLookupDMContext ctx= DMContexts.getAncestorOfType(fTargetContext, ISourceLookupDMContext.class); - final DsfExecutor executor= getSession().getExecutor(); - Query<String> query= new Query<String>() { + final ISourceLookupDMContext ctx = DMContexts.getAncestorOfType(fTargetContext, ISourceLookupDMContext.class); + final DsfExecutor executor = getSession().getExecutor(); + Query<String> query = new Query<String>() { @Override protected void execute(final DataRequestMonitor<String> rm) { - final DataRequestMonitor<String> request= new DataRequestMonitor<String>(executor, rm) { + final DataRequestMonitor<String> request = new DataRequestMonitor<String>(executor, rm) { @Override protected void handleSuccess() { rm.setData(getData()); rm.done(); } }; - final ISourceLookup lookup= getService(ISourceLookup.class); + final ISourceLookup lookup = getService(ISourceLookup.class); lookup.getDebuggerPath(ctx, file, request); } }; try { getSession().getExecutor().execute(query); - debuggerPath= query.get(); + debuggerPath = query.get(); } catch (InterruptedException exc) { internalError(exc); } catch (ExecutionException exc) { internalError(exc); } - final IDisassemblyDMContext context= DMContexts.getAncestorOfType(fTargetContext, IDisassemblyDMContext.class); + final IDisassemblyDMContext context = DMContexts.getAncestorOfType(fTargetContext, IDisassemblyDMContext.class); - final String finalFile= debuggerPath; - final DataRequestMonitor<IMixedInstruction[]> disassemblyRequest= new DataRequestMonitor<IMixedInstruction[]>(executor, null) { + final String finalFile = debuggerPath; + final DataRequestMonitor<IMixedInstruction[]> disassemblyRequest = new DataRequestMonitor<IMixedInstruction[]>( + executor, null) { @Override public void handleCompleted() { - final IMixedInstruction[] data= getData(); + final IMixedInstruction[] data = getData(); if (!isCanceled() && data != null) { fCallback.asyncExec(new Runnable() { @Override @@ -1152,9 +1202,10 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements // retry in non-mixed mode retrieveDisassembly(file, lines, endAddress, false, showSymbols, showDisassembly); } - }}); + } + }); } else { - final IStatus status= getStatus(); + final IStatus status = getStatus(); if (status != null && !status.isOK()) { DisassemblyBackendDsf.this.handleError(getStatus()); } @@ -1167,14 +1218,15 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements executor.execute(new Runnable() { @Override public void run() { - final IDisassembly disassembly= fServicesTracker.getService(IDisassembly.class); + final IDisassembly disassembly = fServicesTracker.getService(IDisassembly.class); if (disassembly == null) { disassemblyRequest.cancel(); disassemblyRequest.done(); return; } disassembly.getMixedInstructions(context, finalFile, 1, lines, disassemblyRequest); - }}); + } + }); } /* (non-Javadoc) @@ -1185,37 +1237,41 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements if (fTargetFrameContext == null) { return null; } - final DsfExecutor executor= DsfSession.getSession(fDsfSessionId).getExecutor(); - Query<FormattedValueDMData> query= new Query<FormattedValueDMData>() { + final DsfExecutor executor = DsfSession.getSession(fDsfSessionId).getExecutor(); + Query<FormattedValueDMData> query = new Query<FormattedValueDMData>() { @Override protected void execute(final DataRequestMonitor<FormattedValueDMData> rm) { - IExecutionDMContext exeCtx = DMContexts.getAncestorOfType(fTargetFrameContext, IExecutionDMContext.class); - final IRunControl rc= getService(IRunControl.class); + IExecutionDMContext exeCtx = DMContexts.getAncestorOfType(fTargetFrameContext, + IExecutionDMContext.class); + final IRunControl rc = getService(IRunControl.class); if (rc == null || !rc.isSuspended(exeCtx)) { rm.done(); return; } - final IExpressions expressions= getService(IExpressions.class); + final IExpressions expressions = getService(IExpressions.class); if (expressions == null) { rm.done(); return; } - IExpressionDMContext exprDmc= expressions.createExpression(fTargetFrameContext, expression); - final FormattedValueDMContext valueDmc= expressions.getFormattedValueContext(exprDmc, IFormattedValues.NATURAL_FORMAT); - expressions.getFormattedExpressionValue(valueDmc, new DataRequestMonitor<FormattedValueDMData>(executor, rm) { - @Override - protected void handleSuccess() { - FormattedValueDMData data= getData(); - rm.setData(data); - rm.done(); - } - }); - }}; - + IExpressionDMContext exprDmc = expressions.createExpression(fTargetFrameContext, expression); + final FormattedValueDMContext valueDmc = expressions.getFormattedValueContext(exprDmc, + IFormattedValues.NATURAL_FORMAT); + expressions.getFormattedExpressionValue(valueDmc, + new DataRequestMonitor<FormattedValueDMData>(executor, rm) { + @Override + protected void handleSuccess() { + FormattedValueDMData data = getData(); + rm.setData(data); + rm.done(); + } + }); + } + }; + executor.execute(query); - FormattedValueDMData data= null; + FormattedValueDMData data = null; try { - data= query.get(); + data = query.get(); } catch (InterruptedException exc) { } catch (ExecutionException exc) { } @@ -1223,9 +1279,9 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements return data.getFormattedValue(); } return null; - + } - + @Override public String evaluateRegister(final String potentialRegisterName) { if (fTargetFrameContext == null) { @@ -1236,7 +1292,8 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements Query<FormattedValueDMData> query = new Query<FormattedValueDMData>() { @Override protected void execute(final DataRequestMonitor<FormattedValueDMData> rm) { - IExecutionDMContext exeCtx = DMContexts.getAncestorOfType(fTargetFrameContext, IExecutionDMContext.class); + IExecutionDMContext exeCtx = DMContexts.getAncestorOfType(fTargetFrameContext, + IExecutionDMContext.class); final IRunControl rc = getService(IRunControl.class); if (rc == null || !rc.isSuspended(exeCtx)) { rm.done(); @@ -1247,71 +1304,74 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements rm.done(); return; } - + // find registers for current frame context - registersService.findRegister(fTargetFrameContext, potentialRegisterName, - new DataRequestMonitor<IRegisterDMContext>(executor, rm) - { - @Override - protected void handleSuccess() { - // handle to the register we're looking-for - final IRegisterDMContext theOne = getData(); - - FormattedValueDMContext fmtCtx = registersService.getFormattedValueContext(theOne, IFormattedValues.HEX_FORMAT); - registersService.getFormattedExpressionValue(fmtCtx, new DataRequestMonitor<FormattedValueDMData>(executor, rm) { - @Override - protected void handleSuccess() { - rm.done(getData()); - } - }); - } - }); - }}; - + registersService.findRegister(fTargetFrameContext, potentialRegisterName, + new DataRequestMonitor<IRegisterDMContext>(executor, rm) { + @Override + protected void handleSuccess() { + // handle to the register we're looking-for + final IRegisterDMContext theOne = getData(); + + FormattedValueDMContext fmtCtx = registersService.getFormattedValueContext(theOne, + IFormattedValues.HEX_FORMAT); + registersService.getFormattedExpressionValue(fmtCtx, + new DataRequestMonitor<FormattedValueDMData>(executor, rm) { + @Override + protected void handleSuccess() { + rm.done(getData()); + } + }); + } + }); + } + }; + executor.execute(query); String returnValue = null; try { - // set a query timeout, to help avoid potential deadlock - FormattedValueDMData data = query.get(500, TimeUnit.MILLISECONDS); - if (data != null) { - returnValue = data.getFormattedValue(); - } + // set a query timeout, to help avoid potential deadlock + FormattedValueDMData data = query.get(500, TimeUnit.MILLISECONDS); + if (data != null) { + returnValue = data.getFormattedValue(); + } } catch (InterruptedException exc) { } catch (ExecutionException exc) { } catch (TimeoutException exc) { - } + } - return returnValue; + return returnValue; } /** * Align the opCode of an address. - * + * * @param addr the address * @param rm the data request monitor */ @ConfinedToDsfExecutor("getSession().getExecutor()") - void alignOpCodeAddress(final BigInteger addr, final DataRequestMonitor<BigInteger> rm) { - IDisassembly2 disassembly = getService(IDisassembly2.class); - if (disassembly == null) { - rm.setData(addr); - rm.done(); - return; - } - - final IDisassemblyDMContext context = DMContexts.getAncestorOfType(fTargetContext, IDisassemblyDMContext.class); - disassembly.alignOpCodeAddress(context, addr, new ImmediateDataRequestMonitor<BigInteger>(rm) { - @Override - protected void handleFailure() { - rm.setData(addr); - rm.done(); - } - @Override - protected void handleSuccess() { - rm.setData(getData()); - rm.done(); - } - }); + void alignOpCodeAddress(final BigInteger addr, final DataRequestMonitor<BigInteger> rm) { + IDisassembly2 disassembly = getService(IDisassembly2.class); + if (disassembly == null) { + rm.setData(addr); + rm.done(); + return; + } + + final IDisassemblyDMContext context = DMContexts.getAncestorOfType(fTargetContext, IDisassemblyDMContext.class); + disassembly.alignOpCodeAddress(context, addr, new ImmediateDataRequestMonitor<BigInteger>(rm) { + @Override + protected void handleFailure() { + rm.setData(addr); + rm.done(); + } + + @Override + protected void handleSuccess() { + rm.setData(getData()); + rm.done(); + } + }); } /** @@ -1322,7 +1382,7 @@ public class DisassemblyBackendDsf extends AbstractDisassemblyBackend implements protected boolean canDisassembleContext(IDMContext context) { return DMContexts.getAncestorOfType(context, IExecutionDMContext.class) != null; } - + /** * Returns the target context for the current selected debug context. * @return diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyBackendDsfFactory.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyBackendDsfFactory.java index 81fbde9622b..70d71833631 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyBackendDsfFactory.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyBackendDsfFactory.java @@ -29,8 +29,9 @@ public class DisassemblyBackendDsfFactory implements IAdapterFactory { @Override @SuppressWarnings("unchecked") public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { - if (IDisassemblyBackend.class.equals(adapterType)) { - if (adaptableObject instanceof IAdaptable && DisassemblyBackendDsf.supportsDebugContext_((IAdaptable)adaptableObject)) { + if (IDisassemblyBackend.class.equals(adapterType)) { + if (adaptableObject instanceof IAdaptable + && DisassemblyBackendDsf.supportsDebugContext_((IAdaptable) adaptableObject)) { String sessionId = ((IDMVMContext) adaptableObject).getDMContext().getSessionId(); DsfSession session = DsfSession.getSession(sessionId); if (session.isActive()) { @@ -41,7 +42,7 @@ public class DisassemblyBackendDsfFactory implements IAdapterFactory { return adapter; } } - return (T)new DisassemblyBackendDsf(); + return (T) new DisassemblyBackendDsf(); } } return null; diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyColumnSupport.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyColumnSupport.java index a7a920938b9..1de8ce769f5 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyColumnSupport.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyColumnSupport.java @@ -49,9 +49,9 @@ class DisassemblyColumnSupport implements IColumnSupport { public DisassemblyColumnSupport(DisassemblyPart disassembly, RulerColumnRegistry registry) { Assert.isLegal(disassembly != null); Assert.isLegal(registry != null); - fDisassembly= disassembly; - fRegistry= registry; - fColumns= new ArrayList<IContributedRulerColumn>(); + fDisassembly = disassembly; + fRegistry = registry; + fColumns = new ArrayList<IContributedRulerColumn>(); } /* @@ -61,12 +61,12 @@ class DisassemblyColumnSupport implements IColumnSupport { public final void setColumnVisible(RulerColumnDescriptor descriptor, boolean visible) { Assert.isLegal(descriptor != null); - final CompositeRuler ruler= getRuler(); + final CompositeRuler ruler = getRuler(); if (ruler == null) return; if (!isColumnSupported(descriptor)) - visible= false; + visible = false; if (isColumnVisible(descriptor)) { if (!visible) @@ -79,12 +79,12 @@ class DisassemblyColumnSupport implements IColumnSupport { private void addColumn(final CompositeRuler ruler, final RulerColumnDescriptor descriptor) { - final int idx= computeIndex(ruler, descriptor); + final int idx = computeIndex(ruler, descriptor); - SafeRunnable runnable= new SafeRunnable() { + SafeRunnable runnable = new SafeRunnable() { @Override public void run() throws Exception { - IContributedRulerColumn column= descriptor.createColumn(fDisassembly); + IContributedRulerColumn column = descriptor.createColumn(fDisassembly); fColumns.add(column); initializeColumn(column); ruler.addDecorator(idx, column); @@ -109,7 +109,7 @@ class DisassemblyColumnSupport implements IColumnSupport { private void removeColumn(final CompositeRuler ruler, final IContributedRulerColumn rulerColumn) { if (rulerColumn != null) { - SafeRunnable runnable= new SafeRunnable() { + SafeRunnable runnable = new SafeRunnable() { @Override public void run() throws Exception { if (ruler != null) @@ -130,11 +130,11 @@ class DisassemblyColumnSupport implements IColumnSupport { * @return the matching column or <code>null</code> */ private IContributedRulerColumn getVisibleColumn(CompositeRuler ruler, RulerColumnDescriptor descriptor) { - for (Iterator<?> it= ruler.getDecoratorIterator(); it.hasNext();) { - IVerticalRulerColumn column= (IVerticalRulerColumn)it.next(); + for (Iterator<?> it = ruler.getDecoratorIterator(); it.hasNext();) { + IVerticalRulerColumn column = (IVerticalRulerColumn) it.next(); if (column instanceof IContributedRulerColumn) { - IContributedRulerColumn rulerColumn= (IContributedRulerColumn)column; - RulerColumnDescriptor rcd= rulerColumn.getDescriptor(); + IContributedRulerColumn rulerColumn = (IContributedRulerColumn) column; + RulerColumnDescriptor rcd = rulerColumn.getDescriptor(); if (descriptor.equals(rcd)) return rulerColumn; } @@ -150,13 +150,13 @@ class DisassemblyColumnSupport implements IColumnSupport { * @return the insertion index for a new column */ private int computeIndex(CompositeRuler ruler, RulerColumnDescriptor descriptor) { - int index= 0; - List<?> all= fRegistry.getColumnDescriptors(); - int newPos= all.indexOf(descriptor); - for (Iterator<?> it= ruler.getDecoratorIterator(); it.hasNext();) { - IVerticalRulerColumn column= (IVerticalRulerColumn) it.next(); + int index = 0; + List<?> all = fRegistry.getColumnDescriptors(); + int newPos = all.indexOf(descriptor); + for (Iterator<?> it = ruler.getDecoratorIterator(); it.hasNext();) { + IVerticalRulerColumn column = (IVerticalRulerColumn) it.next(); if (column instanceof IContributedRulerColumn) { - RulerColumnDescriptor rcd= ((IContributedRulerColumn)column).getDescriptor(); + RulerColumnDescriptor rcd = ((IContributedRulerColumn) column).getDescriptor(); if (rcd != null && all.indexOf(rcd) > newPos) break; } @@ -168,7 +168,7 @@ class DisassemblyColumnSupport implements IColumnSupport { @Override public final boolean isColumnVisible(RulerColumnDescriptor descriptor) { Assert.isLegal(descriptor != null); - CompositeRuler ruler= getRuler(); + CompositeRuler ruler = getRuler(); return ruler != null && getVisibleColumn(ruler, descriptor) != null; } @@ -188,7 +188,7 @@ class DisassemblyColumnSupport implements IColumnSupport { * @return the disassembly part's {@link CompositeRuler} or <code>null</code> */ private CompositeRuler getRuler() { - Object ruler= fDisassembly.getAdapter(IVerticalRulerInfo.class); + Object ruler = fDisassembly.getAdapter(IVerticalRulerInfo.class); if (ruler instanceof CompositeRuler) return (CompositeRuler) ruler; return null; @@ -202,7 +202,8 @@ class DisassemblyColumnSupport implements IColumnSupport { */ @Override public void dispose() { - for (Iterator<IContributedRulerColumn> iter= new ArrayList<IContributedRulerColumn>(fColumns).iterator(); iter.hasNext();) + for (Iterator<IContributedRulerColumn> iter = new ArrayList<IContributedRulerColumn>(fColumns).iterator(); iter + .hasNext();) removeColumn(getRuler(), iter.next()); fColumns.clear(); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyDropAdapter.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyDropAdapter.java index cbeee5b18aa..fa4487cc42e 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyDropAdapter.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyDropAdapter.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -21,7 +21,7 @@ import org.eclipse.swt.dnd.*; public class DisassemblyDropAdapter extends DropTargetAdapter { private DisassemblyPart fDisassembly; - + /** * New DisassemblyDropAdapter. */ @@ -39,12 +39,12 @@ public class DisassemblyDropAdapter extends DropTargetAdapter { if (isFileDataType(dataType)) { // event.data is an array of strings which represent the absolute file pathes assert event.data instanceof String[]; - String fileNames[] = (String[])event.data; + String fileNames[] = (String[]) event.data; dropFiles(fileNames); } else if (isTextDataType(dataType)) { // event.data is a string assert event.data instanceof String; - String text = (String)event.data; + String text = (String) event.data; if (text.indexOf('/') != -1 || text.indexOf('.') != -1) { dropFiles(new String[] { text }); } else { @@ -74,6 +74,7 @@ public class DisassemblyDropAdapter extends DropTargetAdapter { private static boolean isFileDataType(TransferData dataType) { return FileTransfer.getInstance().isSupportedType(dataType); } + private static boolean isTextDataType(TransferData dataType) { return TextTransfer.getInstance().isSupportedType(dataType); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyEditor.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyEditor.java index e0b174e2b46..433a778835f 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyEditor.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyEditor.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -37,7 +37,7 @@ public class DisassemblyEditor extends DisassemblyPart implements IEditorPart { private Label fContentDescriptionLabel; /** - * + * */ public DisassemblyEditor() { super(); @@ -70,7 +70,7 @@ public class DisassemblyEditor extends DisassemblyPart implements IEditorPart { inner.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); super.createPartControl(inner); } - + /* * @see org.eclipse.ui.part.WorkbenchPart#setContentDescription(java.lang.String) */ @@ -105,7 +105,7 @@ public class DisassemblyEditor extends DisassemblyPart implements IEditorPart { */ @Override public IEditorSite getEditorSite() { - return (IEditorSite)getSite(); + return (IEditorSite) getSite(); } /* diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyHyperlinkDetector.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyHyperlinkDetector.java index ba651e4fb1f..a83b61c6359 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyHyperlinkDetector.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyHyperlinkDetector.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -37,8 +37,8 @@ class DisassemblyHyperlinkDetector extends AbstractHyperlinkDetector { * @param region */ public DisassemblyHyperlink(String symbol, IRegion region) { - fSymbol= symbol; - fRegion= region; + fSymbol = symbol; + fRegion = region; } /* @@ -71,7 +71,7 @@ class DisassemblyHyperlinkDetector extends AbstractHyperlinkDetector { @Override public void open() { if (fPart != null) { - fPart.gotoSymbol(fSymbol); + fPart.gotoSymbol(fSymbol); } } @@ -80,16 +80,15 @@ class DisassemblyHyperlinkDetector extends AbstractHyperlinkDetector { private DisassemblyPart fPart; public DisassemblyHyperlinkDetector(DisassemblyPart part) { - fPart= part; + fPart = part; } /* * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion, boolean) */ @Override - public IHyperlink[] detectHyperlinks(ITextViewer textViewer, - IRegion region, boolean canShowMultipleHyperlinks) { - IDocument document= textViewer.getDocument(); + public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { + IDocument document = textViewer.getDocument(); if (document == null) { return null; } @@ -97,7 +96,7 @@ class DisassemblyHyperlinkDetector extends AbstractHyperlinkDetector { if (wordRegion != null && wordRegion.getLength() != 0) { String word; try { - word= document.get(wordRegion.getOffset(), wordRegion.getLength()); + word = document.get(wordRegion.getOffset(), wordRegion.getLength()); return new IHyperlink[] { new DisassemblyHyperlink(word, wordRegion) }; } catch (BadLocationException e) { } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyImageRegistry.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyImageRegistry.java index 94d445554f1..04bd4c92cbb 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyImageRegistry.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyImageRegistry.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Patrick Chuong (Texas Instruments) - Bug fix (326670) @@ -29,48 +29,57 @@ public class DisassemblyImageRegistry extends AbstractImageRegistry { private static List<Object[]> fStore = new ArrayList<Object[]>(); private static String add(String plugin, String[] dirs, String name) { - String key = plugin+'/'+dirs[0]+'/'+name; - fStore.add(new Object[] {key, plugin, dirs, name}); - return key; + String key = plugin + '/' + dirs[0] + '/' + name; + fStore.add(new Object[] { key, plugin, dirs, name }); + return key; } - private static final String ORG_ECLIPSE_DEBUG_UI_PLUGIN_ID = "org.eclipse.debug.ui"; //$NON-NLS-1$ - private static final String ORG_ECLIPSE_UI_PLUGIN_ID = "org.eclipse.ui"; //$NON-NLS-1$ - - public static final String ICON_ToggleBreakpoint = add(ORG_ECLIPSE_DEBUG_UI_PLUGIN_ID, new String[] { "full/obj16"}, "brkp_obj.png"); //$NON-NLS-1$ //$NON-NLS-2$ - public static final String ICON_Refresh_enabled = add(ORG_ECLIPSE_UI_PLUGIN_ID, new String[] {"full/elcl16"}, "refresh_nav.png"); //$NON-NLS-1$ //$NON-NLS-2$ - public static final String ICON_Refresh_disabled = add(ORG_ECLIPSE_UI_PLUGIN_ID, new String[] {"full/dlcl16"}, "refresh_nav.png"); //$NON-NLS-1$ //$NON-NLS-2$ - public static final String ICON_Copy_enabled = add(ORG_ECLIPSE_UI_PLUGIN_ID, new String[] {"full/etool16"}, "copy_edit.png"); //$NON-NLS-1$ //$NON-NLS-2$ - public static final String ICON_Copy_disabled = add(ORG_ECLIPSE_UI_PLUGIN_ID, new String[] {"full/dtool16"}, "copy_edit.png"); //$NON-NLS-1$ //$NON-NLS-2$ - public static final String ICON_Home_enabled = add(ORG_ECLIPSE_UI_PLUGIN_ID, new String[] {"full/elcl16"}, "home_nav.png"); //$NON-NLS-1$ //$NON-NLS-2$ - public static final String ICON_Home_disabled = add(ORG_ECLIPSE_UI_PLUGIN_ID, new String[] {"full/dlcl16"}, "home_nav.png"); //$NON-NLS-1$ //$NON-NLS-2$ - public static final String ICON_Sync_enabled = add(ORG_ECLIPSE_DEBUG_UI_PLUGIN_ID, new String[] {"full/elcl16"}, "synced.png"); //$NON-NLS-1$ //$NON-NLS-2$ - public static final String ICON_Sync_disabled = add(ORG_ECLIPSE_DEBUG_UI_PLUGIN_ID, new String[] {"full/dlcl16"}, "synced.png"); //$NON-NLS-1$ //$NON-NLS-2$ + private static final String ORG_ECLIPSE_DEBUG_UI_PLUGIN_ID = "org.eclipse.debug.ui"; //$NON-NLS-1$ + private static final String ORG_ECLIPSE_UI_PLUGIN_ID = "org.eclipse.ui"; //$NON-NLS-1$ + + public static final String ICON_ToggleBreakpoint = add(ORG_ECLIPSE_DEBUG_UI_PLUGIN_ID, + new String[] { "full/obj16" }, "brkp_obj.png"); //$NON-NLS-1$ //$NON-NLS-2$ + public static final String ICON_Refresh_enabled = add(ORG_ECLIPSE_UI_PLUGIN_ID, new String[] { "full/elcl16" }, //$NON-NLS-1$ + "refresh_nav.png"); //$NON-NLS-1$ + public static final String ICON_Refresh_disabled = add(ORG_ECLIPSE_UI_PLUGIN_ID, new String[] { "full/dlcl16" }, //$NON-NLS-1$ + "refresh_nav.png"); //$NON-NLS-1$ + public static final String ICON_Copy_enabled = add(ORG_ECLIPSE_UI_PLUGIN_ID, new String[] { "full/etool16" }, //$NON-NLS-1$ + "copy_edit.png"); //$NON-NLS-1$ + public static final String ICON_Copy_disabled = add(ORG_ECLIPSE_UI_PLUGIN_ID, new String[] { "full/dtool16" }, //$NON-NLS-1$ + "copy_edit.png"); //$NON-NLS-1$ + public static final String ICON_Home_enabled = add(ORG_ECLIPSE_UI_PLUGIN_ID, new String[] { "full/elcl16" }, //$NON-NLS-1$ + "home_nav.png"); //$NON-NLS-1$ + public static final String ICON_Home_disabled = add(ORG_ECLIPSE_UI_PLUGIN_ID, new String[] { "full/dlcl16" }, //$NON-NLS-1$ + "home_nav.png"); //$NON-NLS-1$ + public static final String ICON_Sync_enabled = add(ORG_ECLIPSE_DEBUG_UI_PLUGIN_ID, new String[] { "full/elcl16" }, //$NON-NLS-1$ + "synced.png"); //$NON-NLS-1$ + public static final String ICON_Sync_disabled = add(ORG_ECLIPSE_DEBUG_UI_PLUGIN_ID, new String[] { "full/dlcl16" }, //$NON-NLS-1$ + "synced.png"); //$NON-NLS-1$ - private static DisassemblyImageRegistry INSTANCE= new DisassemblyImageRegistry(DsfUIPlugin.getDefault()); - - DisassemblyImageRegistry(Plugin plugin) { + private static DisassemblyImageRegistry INSTANCE = new DisassemblyImageRegistry(DsfUIPlugin.getDefault()); + + DisassemblyImageRegistry(Plugin plugin) { super(plugin); initialize(); } - void initialize() { - for (Iterator<Object[]> iter = fStore.iterator(); iter.hasNext();) { - Object[] element = iter.next(); - if (element.length == 2) { - String dir= (String) element[0]; - String name= (String) element[1]; - localImage(name, dir, name); - } else { - String key = (String) element[0]; - String plugin= (String) element[1]; - String[] dirs= (String[]) element[2]; - String name= (String) element[3]; - externalImage(key, plugin, dirs, name); - } - } + void initialize() { + for (Iterator<Object[]> iter = fStore.iterator(); iter.hasNext();) { + Object[] element = iter.next(); + if (element.length == 2) { + String dir = (String) element[0]; + String name = (String) element[1]; + localImage(name, dir, name); + } else { + String key = (String) element[0]; + String plugin = (String) element[1]; + String[] dirs = (String[]) element[2]; + String name = (String) element[3]; + externalImage(key, plugin, dirs, name); + } + } } - + public static ImageDescriptor getImageDescriptor(String key) { return INSTANCE.getDescriptor(key); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyMessages.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyMessages.java index 8bc7818ae6f..b3a0a09d9d6 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyMessages.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyMessages.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Patrick Chuong (Texas Instruments) - Bug fix (326670) @@ -80,12 +80,11 @@ public final class DisassemblyMessages extends NLS { public static String Disassembly_Error_Dialog_title; public static String Disassembly_Error_Dialog_ok_button; public static String DisassemblyBackendDsf_error_UnableToRetrieveData; - public static String Disassembly_action_AddBreakpoint_label; - public static String Disassembly_action_AddBreakpoint_errorTitle; - public static String Disassembly_action_AddBreakpoint_errorMessage; - public static String Disassembly_action_ToggleBreakpoint_accelerator; + public static String Disassembly_action_AddBreakpoint_label; + public static String Disassembly_action_AddBreakpoint_errorTitle; + public static String Disassembly_action_AddBreakpoint_errorMessage; + public static String Disassembly_action_ToggleBreakpoint_accelerator; - static { NLS.initializeMessages(DisassemblyMessages.class.getName(), DisassemblyMessages.class); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyPart.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyPart.java index f0df59c4da9..2d112f14d3d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyPart.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyPart.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Patrick Chuong (Texas Instruments) - Bug 326670 @@ -197,15 +197,17 @@ import com.ibm.icu.text.MessageFormat; * DisassemblyPart */ @SuppressWarnings("restriction") -public abstract class DisassemblyPart extends WorkbenchPart implements IDisassemblyPart, IViewportListener, ITextPresentationListener, IDisassemblyPartCallback { +public abstract class DisassemblyPart extends WorkbenchPart + implements IDisassemblyPart, IViewportListener, ITextPresentationListener, IDisassemblyPartCallback { - final static boolean DEBUG = Boolean.parseBoolean(Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/disassembly")); //$NON-NLS-1$ + final static boolean DEBUG = Boolean + .parseBoolean(Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/disassembly")); //$NON-NLS-1$ /** * Annotation model attachment key for breakpoint annotations. */ - private final static String BREAKPOINT_ANNOTATIONS= "breakpoints"; //$NON-NLS-1$ - + private final static String BREAKPOINT_ANNOTATIONS = "breakpoints"; //$NON-NLS-1$ + /** * Annotation model attachment key for extended PC annotations. */ @@ -236,7 +238,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem /** * A named preference that controls the visible ruler column contributions. */ - public static final String PREFERENCE_RULER_CONTRIBUTIONS= "rulerContributions"; //$NON-NLS-1$ + public static final String PREFERENCE_RULER_CONTRIBUTIONS = "rulerContributions"; //$NON-NLS-1$ protected DisassemblyViewer fViewer; @@ -254,12 +256,12 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem private MarkerAnnotationPreferences fAnnotationPreferences; private IPreferenceStore fPreferenceStore; private IOverviewRuler fOverviewRuler; - private final ListenerList<IMenuListener> fRulerContextMenuListeners= new ListenerList<>(ListenerList.IDENTITY); + private final ListenerList<IMenuListener> fRulerContextMenuListeners = new ListenerList<>(ListenerList.IDENTITY); private SourceViewerDecorationSupport fDecorationSupport; private Font fFont; private IVerticalRuler fVerticalRuler; private IFindReplaceTarget fFindReplaceTarget; - private IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener(); + private IPropertyChangeListener fPropertyChangeListener = new PropertyChangeListener(); private Color fInstructionColor; private Color fErrorColor; private Color fSourceColor; @@ -275,13 +277,13 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem private BigInteger fStartAddress; private BigInteger fEndAddress; - private int fAddressSize= 32; + private int fAddressSize = 32; private volatile boolean fUpdatePending; - private volatile int fUpdateCount; + private volatile int fUpdateCount; private BigInteger fPCAddress; - private BigInteger fGotoAddressPending= PC_UNKNOWN; - private BigInteger fFocusAddress= PC_UNKNOWN; + private BigInteger fGotoAddressPending = PC_UNKNOWN; + private BigInteger fFocusAddress = PC_UNKNOWN; private int fBufferZone; private String fDebugSessionId; private int fTargetFrame; @@ -292,7 +294,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem private Position fScrollPos; private int fScrollLine; private Position fFocusPos; - private BigInteger fFrameAddress= PC_UNKNOWN; + private BigInteger fFrameAddress = PC_UNKNOWN; protected Map<String, Action> fGlobalActions = new HashMap<String, Action>(); private List<Action> fSelectionActions = new ArrayList<Action>(); private List<AbstractDisassemblyAction> fStateDependentActions = new ArrayList<AbstractDisassemblyAction>(); @@ -311,44 +313,50 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem private String fPCLastLocationTxt = DisassemblyMessages.Disassembly_GotoLocation_initial_text; private BigInteger fPCLastAddress = PC_UNKNOWN; private IAdaptable fDebugContext; - + private String fPCAnnotationColorKey; private ArrayList<Runnable> fRunnableQueue = new ArrayList<Runnable>(); - protected IPartListener2 fPartListener = - new IPartListener2() { - @Override - public void partActivated(IWorkbenchPartReference partRef) { - } - @Override - public void partBroughtToTop(IWorkbenchPartReference partRef) { - } - @Override - public void partClosed(IWorkbenchPartReference partRef) { - } - @Override - public void partDeactivated(IWorkbenchPartReference partRef) { - } - @Override - public void partOpened(IWorkbenchPartReference partRef) { - } - @Override - public void partHidden(IWorkbenchPartReference partRef) { - if (partRef.getPart(false) == DisassemblyPart.this) { - setActive(false); - } - } - @Override - public void partVisible(IWorkbenchPartReference partRef) { - if (partRef.getPart(false) == DisassemblyPart.this) { - setActive(true); - } + protected IPartListener2 fPartListener = new IPartListener2() { + @Override + public void partActivated(IWorkbenchPartReference partRef) { + } + + @Override + public void partBroughtToTop(IWorkbenchPartReference partRef) { + } + + @Override + public void partClosed(IWorkbenchPartReference partRef) { + } + + @Override + public void partDeactivated(IWorkbenchPartReference partRef) { + } + + @Override + public void partOpened(IWorkbenchPartReference partRef) { + } + + @Override + public void partHidden(IWorkbenchPartReference partRef) { + if (partRef.getPart(false) == DisassemblyPart.this) { + setActive(false); } - @Override - public void partInputChanged(IWorkbenchPartReference partRef) { + } + + @Override + public void partVisible(IWorkbenchPartReference partRef) { + if (partRef.getPart(false) == DisassemblyPart.this) { + setActive(true); } - }; + } + + @Override + public void partInputChanged(IWorkbenchPartReference partRef) { + } + }; private boolean fActive = true; private boolean fDoPendingPosted; @@ -362,66 +370,73 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem private ArrayList<IHandlerActivation> fHandlerActivations; private IContextActivation fContextActivation; - + private IDisassemblyBackend fBackend; - + private AddressBarContributionItem fAddressBar = null; private Action fJumpToAddressAction = new JumpToAddressAction(this); - private IDebugContextListener fDebugContextListener; - private DisassemblyAnnotationModel fExtPCAnnotationModel; + private IDebugContextListener fDebugContextListener; + private DisassemblyAnnotationModel fExtPCAnnotationModel; private IColumnSupport fColumnSupport; - private final class SyncActiveDebugContextAction extends Action { - public SyncActiveDebugContextAction() { - setChecked(DisassemblyPart.this.isSyncWithActiveDebugContext()); - setText(DisassemblyMessages.Disassembly_action_Sync_label); - setImageDescriptor(DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Sync_enabled)); - setDisabledImageDescriptor(DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Sync_disabled)); - } - - @Override - public void run() { - DisassemblyPart.this.setSyncWithDebugView(this.isChecked()); - } - } - - private final class TrackExpressionAction extends Action { - public TrackExpressionAction() { - setChecked(DisassemblyPart.this.isTrackExpression()); - setEnabled(!fSynchWithActiveDebugContext); - setText(DisassemblyMessages.Disassembly_action_TrackExpression_label); - } - - @Override - public void run() { - DisassemblyPart.this.setTrackExpression(this.isChecked()); - } - - } - - private final class ActionRefreshView extends AbstractDisassemblyAction { + private final class SyncActiveDebugContextAction extends Action { + public SyncActiveDebugContextAction() { + setChecked(DisassemblyPart.this.isSyncWithActiveDebugContext()); + setText(DisassemblyMessages.Disassembly_action_Sync_label); + setImageDescriptor(DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Sync_enabled)); + setDisabledImageDescriptor( + DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Sync_disabled)); + } + + @Override + public void run() { + DisassemblyPart.this.setSyncWithDebugView(this.isChecked()); + } + } + + private final class TrackExpressionAction extends Action { + public TrackExpressionAction() { + setChecked(DisassemblyPart.this.isTrackExpression()); + setEnabled(!fSynchWithActiveDebugContext); + setText(DisassemblyMessages.Disassembly_action_TrackExpression_label); + } + + @Override + public void run() { + DisassemblyPart.this.setTrackExpression(this.isChecked()); + } + + } + + private final class ActionRefreshView extends AbstractDisassemblyAction { public ActionRefreshView() { super(DisassemblyPart.this); setText(DisassemblyMessages.Disassembly_action_RefreshView_label); - setImageDescriptor(DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Refresh_enabled)); - setDisabledImageDescriptor(DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Refresh_disabled)); + setImageDescriptor( + DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Refresh_enabled)); + setDisabledImageDescriptor( + DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Refresh_disabled)); } + @Override public void run() { fPCLastAddress = getTopAddress(); refreshView(10); } } - + private final class ActionToggleBreakpointEnablement extends AbstractDisassemblyAction { private IBreakpoint fBreakpoint; + public ActionToggleBreakpointEnablement() { super(DisassemblyPart.this); - setText(DisassemblyMessages.Disassembly_action_EnableBreakpoint_label + "\t" + //$NON-NLS-1$ - CDebugUIUtils.formatKeyBindingString(SWT.MOD2, DisassemblyMessages.Disassembly_action_ToggleBreakpoint_accelerator)); + setText(DisassemblyMessages.Disassembly_action_EnableBreakpoint_label + "\t" + //$NON-NLS-1$ + CDebugUIUtils.formatKeyBindingString(SWT.MOD2, + DisassemblyMessages.Disassembly_action_ToggleBreakpoint_accelerator)); } + @Override public void run() { try { @@ -430,6 +445,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem internalError(e); } } + @Override public void update() { super.update(); @@ -442,11 +458,13 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem fBreakpoint = bps[0]; try { if (fBreakpoint.isEnabled()) { - setText(DisassemblyMessages.Disassembly_action_DisableBreakpoint_label + "\t" + //$NON-NLS-1$ - CDebugUIUtils.formatKeyBindingString(SWT.MOD2, DisassemblyMessages.Disassembly_action_ToggleBreakpoint_accelerator)); + setText(DisassemblyMessages.Disassembly_action_DisableBreakpoint_label + "\t" + //$NON-NLS-1$ + CDebugUIUtils.formatKeyBindingString(SWT.MOD2, + DisassemblyMessages.Disassembly_action_ToggleBreakpoint_accelerator)); } else { - setText(DisassemblyMessages.Disassembly_action_EnableBreakpoint_label + "\t" + //$NON-NLS-1$ - CDebugUIUtils.formatKeyBindingString(SWT.MOD2, DisassemblyMessages.Disassembly_action_ToggleBreakpoint_accelerator)); + setText(DisassemblyMessages.Disassembly_action_EnableBreakpoint_label + "\t" + //$NON-NLS-1$ + CDebugUIUtils.formatKeyBindingString(SWT.MOD2, + DisassemblyMessages.Disassembly_action_ToggleBreakpoint_accelerator)); } } catch (CoreException e) { setEnabled(false); @@ -461,11 +479,13 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem super(DisassemblyPart.this, IAction.AS_CHECK_BOX); setText(DisassemblyMessages.Disassembly_action_ShowSource_label); } + @Override public void run() { IPreferenceStore store = DsfUIPlugin.getDefault().getPreferenceStore(); store.setValue(DisassemblyPreferenceConstants.SHOW_SOURCE, !fShowSource); } + @Override public void update() { super.update(); @@ -481,11 +501,13 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem super(DisassemblyPart.this, IAction.AS_CHECK_BOX); setText(DisassemblyMessages.Disassembly_action_ShowSymbols_label); } + @Override public void run() { IPreferenceStore store = DsfUIPlugin.getDefault().getPreferenceStore(); store.setValue(DisassemblyPreferenceConstants.SHOW_SYMBOLS, !fShowSymbols); } + @Override public void update() { super.update(); @@ -507,23 +529,22 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } } - /** * The constructor. */ public DisassemblyPart() { fAnnotationPreferences = new MarkerAnnotationPreferences(); setPreferenceStore(new ChainedPreferenceStore(new IPreferenceStore[] { - DsfUIPlugin.getDefault().getPreferenceStore(), EditorsUI.getPreferenceStore() })); + DsfUIPlugin.getDefault().getPreferenceStore(), EditorsUI.getPreferenceStore() })); fPCAddress = fFrameAddress = PC_UNKNOWN; fTargetFrame = -1; fBufferZone = 32; fPCAnnotation = new DisassemblyIPAnnotation(true, 0); fSecondaryPCAnnotation = new DisassemblyIPAnnotation(false, 0); - IPreferenceStore prefs = getPreferenceStore(); + IPreferenceStore prefs = getPreferenceStore(); fStartAddress = new BigInteger(prefs.getString(DisassemblyPreferenceConstants.START_ADDRESS)); String endAddressString = prefs.getString(DisassemblyPreferenceConstants.END_ADDRESS); - if(endAddressString.startsWith("0x")) //$NON-NLS-1$ + if (endAddressString.startsWith("0x")) //$NON-NLS-1$ fEndAddress = new BigInteger(endAddressString.substring(2), 16); else fEndAddress = new BigInteger(endAddressString, 16); @@ -540,34 +561,35 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem /* * @see IAdaptable#getAdapter(java.lang.Class) */ - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") @Override public <T> T getAdapter(Class<T> required) { if (IVerticalRulerInfo.class.equals(required)) { if (fVerticalRuler != null) { - return (T)fVerticalRuler; + return (T) fVerticalRuler; } } else if (IDisassemblyPart.class.equals(required)) { - return (T)this; + return (T) this; } else if (IFindReplaceTarget.class.equals(required)) { if (fFindReplaceTarget == null) { fFindReplaceTarget = (fViewer == null ? null : fViewer.getFindReplaceTarget()); } - return (T)fFindReplaceTarget; + return (T) fFindReplaceTarget; } else if (ITextOperationTarget.class.equals(required)) { - return (fViewer == null ? null : (T)fViewer.getTextOperationTarget()); + return (fViewer == null ? null : (T) fViewer.getTextOperationTarget()); } else if (Control.class.equals(required)) { - return fViewer != null ? (T)fViewer.getTextWidget() : null; + return fViewer != null ? (T) fViewer.getTextWidget() : null; } else if (IGotoMarker.class.equals(required)) { - return (T)new IGotoMarker() { + return (T) new IGotoMarker() { @Override public void gotoMarker(IMarker marker) { DisassemblyPart.this.gotoMarker(marker); - }}; + } + }; } else if (IColumnSupport.class.equals(required)) { if (fColumnSupport == null) - fColumnSupport= createColumnSupport(); - return (T)fColumnSupport; + fColumnSupport = createColumnSupport(); + return (T) fColumnSupport; } return super.getAdapter(required); @@ -580,15 +602,17 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem */ private void addRulerContributionActions(IMenuManager menu) { // store directly in generic editor preferences - final IColumnSupport support= getAdapter(IColumnSupport.class); - IPreferenceStore store= DsfUIPlugin.getDefault().getPreferenceStore(); - final RulerColumnPreferenceAdapter adapter= new RulerColumnPreferenceAdapter(store, PREFERENCE_RULER_CONTRIBUTIONS); - List<RulerColumnDescriptor> descriptors= RulerColumnRegistry.getDefault().getColumnDescriptors(); + final IColumnSupport support = getAdapter(IColumnSupport.class); + IPreferenceStore store = DsfUIPlugin.getDefault().getPreferenceStore(); + final RulerColumnPreferenceAdapter adapter = new RulerColumnPreferenceAdapter(store, + PREFERENCE_RULER_CONTRIBUTIONS); + List<RulerColumnDescriptor> descriptors = RulerColumnRegistry.getDefault().getColumnDescriptors(); for (final RulerColumnDescriptor descriptor : descriptors) { if (!descriptor.isIncludedInMenu() || !support.isColumnSupported(descriptor)) continue; - final boolean isVisible= support.isColumnVisible(descriptor); - IAction action= new Action(MessageFormat.format(DisassemblyMessages.DisassemblyPart_showRulerColumn_label, new Object[] {descriptor.getName()}), IAction.AS_CHECK_BOX) { + final boolean isVisible = support.isColumnVisible(descriptor); + IAction action = new Action(MessageFormat.format(DisassemblyMessages.DisassemblyPart_showRulerColumn_label, + new Object[] { descriptor.getName() }), IAction.AS_CHECK_BOX) { @Override public void run() { if (descriptor.isGlobal()) @@ -611,16 +635,16 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem * @param ruler the composite ruler to add contributions to */ protected void updateContributedRulerColumns(CompositeRuler ruler) { - IColumnSupport support= getAdapter(IColumnSupport.class); + IColumnSupport support = getAdapter(IColumnSupport.class); if (support == null) return; - RulerColumnPreferenceAdapter adapter= null; + RulerColumnPreferenceAdapter adapter = null; if (fPreferenceStore != null) - adapter= new RulerColumnPreferenceAdapter(getPreferenceStore(), PREFERENCE_RULER_CONTRIBUTIONS); + adapter = new RulerColumnPreferenceAdapter(getPreferenceStore(), PREFERENCE_RULER_CONTRIBUTIONS); - RulerColumnRegistry registry= RulerColumnRegistry.getDefault(); - List<RulerColumnDescriptor> descriptors= registry.getColumnDescriptors(); + RulerColumnRegistry registry = RulerColumnRegistry.getDefault(); + List<RulerColumnDescriptor> descriptors = registry.getColumnDescriptors(); for (RulerColumnDescriptor descriptor : descriptors) { support.setColumnVisible(descriptor, adapter == null || adapter.isEnabled(descriptor)); } @@ -629,7 +653,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem protected IColumnSupport createColumnSupport() { return new DisassemblyColumnSupport(this, RulerColumnRegistry.getDefault()); } - + private void setPreferenceStore(IPreferenceStore store) { if (fPreferenceStore != null) { fPreferenceStore.removePropertyChangeListener(fPropertyChangeListener); @@ -684,19 +708,20 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } else if (property.equals(fPCAnnotationColorKey)) { fPCAnnotationRGB = PreferenceConverter.getColor(store, fPCAnnotationColorKey); // redraw - for (Iterator<AddressRangePosition> it=fPCHistory.iterator(); it.hasNext();) { + for (Iterator<AddressRangePosition> it = fPCHistory.iterator(); it.hasNext();) { AddressRangePosition pos = it.next(); fViewer.invalidateTextPresentation(pos.offset, pos.length); } } else if (property.equals(DisassemblyPreferenceConstants.PC_HISTORY_SIZE)) { fPCHistorySizeMax = store.getInt(property); } else if (PREFERENCE_RULER_CONTRIBUTIONS.equals(property)) { - String[] difference= StringSetSerializer.getDifference((String) event.getOldValue(), (String) event.getNewValue()); - IColumnSupport support= getAdapter(IColumnSupport.class); - for (int i= 0; i < difference.length; i++) { - RulerColumnDescriptor desc= RulerColumnRegistry.getDefault().getColumnDescriptor(difference[i]); - if (desc != null && support.isColumnSupported(desc)) { - boolean newState= !support.isColumnVisible(desc); + String[] difference = StringSetSerializer.getDifference((String) event.getOldValue(), + (String) event.getNewValue()); + IColumnSupport support = getAdapter(IColumnSupport.class); + for (int i = 0; i < difference.length; i++) { + RulerColumnDescriptor desc = RulerColumnRegistry.getDefault().getColumnDescriptor(difference[i]); + if (desc != null && support.isColumnSupported(desc)) { + boolean newState = !support.isColumnVisible(desc); support.setColumnVisible(desc, newState); } } @@ -721,7 +746,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem fViewer.addTextPresentationListener(this); fViewer.configure(sourceViewerConfig); fDecorationSupport = new SourceViewerDecorationSupport(fViewer, getOverviewRuler(), getAnnotationAccess(), - getSharedColors()); + getSharedColors()); configureSourceViewerDecorationSupport(fDecorationSupport); fDecorationSupport.install(getPreferenceStore()); if (fPCAnnotationColorKey != null) { @@ -739,7 +764,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem hookRulerContextMenu(); hookContextMenu(); contributeToActionBars(); - + fViewer.getTextWidget().addVerifyKeyListener(new VerifyKeyListener() { @Override public void verifyKey(VerifyEvent event) { @@ -765,16 +790,17 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem fSourceColor = getSharedColors().getColor(new RGB(64, 0, 80)); fLabelColor = getSharedColors().getColor(new RGB(0, 0, 96)); - IVerticalRuler ruler= getVerticalRuler(); + IVerticalRuler ruler = getVerticalRuler(); if (ruler instanceof CompositeRuler) { updateContributedRulerColumns((CompositeRuler) ruler); } initDragAndDrop(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(fViewer.getControl(), IDisassemblyHelpContextIds.DISASSEMBLY_VIEW); + PlatformUI.getWorkbench().getHelpSystem().setHelp(fViewer.getControl(), + IDisassemblyHelpContextIds.DISASSEMBLY_VIEW); updateTitle(); updateStateDependentActions(); - + if (fDebugSessionId != null) { debugContextChanged(); } else { @@ -788,16 +814,16 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem @Override protected void setSite(IWorkbenchPartSite site) { super.setSite(site); - site.getPage().addPartListener(fPartListener); - fDebugContextListener = new IDebugContextListener() { - @Override + site.getPage().addPartListener(fPartListener); + fDebugContextListener = new IDebugContextListener() { + @Override public void debugContextChanged(DebugContextEvent event) { - if ((event.getFlags() & DebugContextEvent.ACTIVATED) != 0) { - updateDebugContext(); - } - } - }; - DebugUITools.addPartDebugContextListener(site, fDebugContextListener); + if ((event.getFlags() & DebugContextEvent.ACTIVATED) != 0) { + updateDebugContext(); + } + } + }; + DebugUITools.addPartDebugContextListener(site, fDebugContextListener); } private DisassemblyDocument createDocument() { @@ -814,25 +840,25 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem IWorkbenchPartSite site = getSite(); site.setSelectionProvider(null); site.getPage().removePartListener(fPartListener); - if (fDebugContextListener != null) { - DebugUITools.removePartDebugContextListener(site, fDebugContextListener); - fDebugContextListener = null; - } + if (fDebugContextListener != null) { + DebugUITools.removePartDebugContextListener(site, fDebugContextListener); + fDebugContextListener = null; + } if (fHandlerActivations != null) { IHandlerService handlerService = site.getService(IHandlerService.class); handlerService.deactivateHandlers(fHandlerActivations); fHandlerActivations = null; } - + deactivateDisassemblyContext(); - + fViewer = null; if (fBackend != null) { fBackend.clearDebugContext(); fBackend.dispose(); fBackend = null; } - + fAnnotationAccess = null; fAnnotationPreferences = null; fAnnotationRulerColumn = null; @@ -860,7 +886,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } if (fColumnSupport != null) { fColumnSupport.dispose(); - fColumnSupport= null; + fColumnSupport = null; } fDocument.dispose(); @@ -896,7 +922,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) { Iterator<?> e = fAnnotationPreferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { - AnnotationPreference pref = (AnnotationPreference)e.next(); + AnnotationPreference pref = (AnnotationPreference) e.next(); support.setAnnotationPreference(pref); if (pref.getAnnotationType().equals(fPCAnnotation.getType())) { fPCAnnotationColorKey = pref.getColorPreferenceKey(); @@ -945,7 +971,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem else if (fPreferenceStore != null) { // Backward compatibility if (fPreferenceStore.contains(JFaceResources.TEXT_FONT) - && !fPreferenceStore.isDefault(JFaceResources.TEXT_FONT)) { + && !fPreferenceStore.isDefault(JFaceResources.TEXT_FONT)) { FontData data = PreferenceConverter.getFontData(fPreferenceStore, JFaceResources.TEXT_FONT); if (data != null) { @@ -1029,7 +1055,8 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem IVerticalRulerColumn column = (IVerticalRulerColumn) iter.next(); if (column instanceof AnnotationRulerColumn) { fAnnotationRulerColumn = (AnnotationRulerColumn) column; - for (Iterator<?> iter2 = fAnnotationPreferences.getAnnotationPreferences().iterator(); iter2.hasNext();) { + for (Iterator<?> iter2 = fAnnotationPreferences.getAnnotationPreferences().iterator(); iter2 + .hasNext();) { AnnotationPreference preference = (AnnotationPreference) iter2.next(); String key = preference.getVerticalRulerPreferenceKey(); boolean showAnnotation = true; @@ -1087,29 +1114,28 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem * @param rulerColumn the ruler column to be initialized */ protected void initializeRulerColumn(DisassemblyRulerColumn rulerColumn, String colorPrefKey) { - ISharedTextColors sharedColors= getSharedColors(); - IPreferenceStore store= getPreferenceStore(); + ISharedTextColors sharedColors = getSharedColors(); + IPreferenceStore store = getPreferenceStore(); if (store != null) { - RGB rgb= null; + RGB rgb = null; // foreground color if (store.contains(colorPrefKey)) { if (store.isDefault(colorPrefKey)) - rgb= PreferenceConverter.getDefaultColor(store, colorPrefKey); + rgb = PreferenceConverter.getDefaultColor(store, colorPrefKey); else - rgb= PreferenceConverter.getColor(store, colorPrefKey); + rgb = PreferenceConverter.getColor(store, colorPrefKey); } if (rgb == null) - rgb= new RGB(0, 0, 0); + rgb = new RGB(0, 0, 0); rulerColumn.setForeground(sharedColors.getColor(rgb)); - rgb= null; + rgb = null; rulerColumn.redraw(); } } - /** * @return the preference store */ @@ -1195,7 +1221,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem bars.setGlobalActionHandler(key, action); } IMenuManager menu = bars.getMenuManager(); - IMenuManager navigateMenu= menu.findMenuUsingPath(IWorkbenchActionConstants.M_NAVIGATE); + IMenuManager navigateMenu = menu.findMenuUsingPath(IWorkbenchActionConstants.M_NAVIGATE); if (navigateMenu != null) { navigateMenu.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, fActionGotoPC); navigateMenu.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, fActionGotoAddress); @@ -1212,8 +1238,10 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem manager.add(new Separator("group.breakpoints")); //$NON-NLS-1$ manager.add(new Separator("group.debug")); //$NON-NLS-1$ manager.add(new Separator(ITextEditorActionConstants.GROUP_EDIT)); - manager.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, fGlobalActions.get(ITextEditorActionConstants.COPY)); - manager.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL)); + manager.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, + fGlobalActions.get(ITextEditorActionConstants.COPY)); + manager.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, + fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL)); manager.add(new Separator(ITextEditorActionConstants.GROUP_SETTINGS)); manager.add(fActionToggleSource); manager.add(fActionToggleSymbols); @@ -1241,36 +1269,39 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem listener.menuAboutToShow(manager); manager.add(new Separator(ITextEditorActionConstants.GROUP_EDIT)); - manager.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, fGlobalActions.get(ITextEditorActionConstants.COPY)); + manager.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, + fGlobalActions.get(ITextEditorActionConstants.COPY)); } protected void fillLocalToolBar(IToolBarManager manager) { final int ADDRESS_BAR_WIDTH = 190; - ToolBar toolbar = ((ToolBarManager)manager).getControl(); + ToolBar toolbar = ((ToolBarManager) manager).getControl(); fAddressBar = new AddressBarContributionItem(fJumpToAddressAction); - fAddressBar.createAddressBox(toolbar, ADDRESS_BAR_WIDTH, DisassemblyMessages.Disassembly_GotoLocation_initial_text, DisassemblyMessages.Disassembly_GotoLocation_warning); + fAddressBar.createAddressBox(toolbar, ADDRESS_BAR_WIDTH, + DisassemblyMessages.Disassembly_GotoLocation_initial_text, + DisassemblyMessages.Disassembly_GotoLocation_warning); manager.add(fAddressBar); - fJumpToAddressAction.setEnabled(fDebugSessionId!=null); - + fJumpToAddressAction.setEnabled(fDebugSessionId != null); + manager.add(new Separator()); manager.add(fActionRefreshView); manager.add(fActionGotoPC); manager.add(fSyncAction); manager.add(fActionToggleSource); - // Other plug-ins can contribute their actions here - manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); + // Other plug-ins can contribute their actions here + manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } protected void updateSelectionDependentActions() { - Iterator<Action> iterator= fSelectionActions.iterator(); + Iterator<Action> iterator = fSelectionActions.iterator(); while (iterator.hasNext()) { - IUpdate action = (IUpdate)iterator.next(); + IUpdate action = (IUpdate) iterator.next(); action.update(); } } protected void updateStateDependentActions() { - Iterator<AbstractDisassemblyAction> iterator= fStateDependentActions.iterator(); + Iterator<AbstractDisassemblyAction> iterator = fStateDependentActions.iterator(); while (iterator.hasNext()) { IUpdate action = iterator.next(); action.update(); @@ -1279,35 +1310,39 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem protected void createActions() { Action action; - action= new TextOperationAction(fViewer, ITextOperationTarget.COPY); + action = new TextOperationAction(fViewer, ITextOperationTarget.COPY); action.setText(DisassemblyMessages.Disassembly_action_Copy_label); - action.setImageDescriptor(DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Copy_enabled)); - action.setDisabledImageDescriptor(DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Copy_disabled)); + action.setImageDescriptor( + DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Copy_enabled)); + action.setDisabledImageDescriptor( + DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Copy_disabled)); action.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_COPY); fGlobalActions.put(ITextEditorActionConstants.COPY, action); fSelectionActions.add(action); - action= new TextOperationAction(fViewer, ITextOperationTarget.SELECT_ALL); + action = new TextOperationAction(fViewer, ITextOperationTarget.SELECT_ALL); action.setText(DisassemblyMessages.Disassembly_action_SelectAll_label); action.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_SELECT_ALL); fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action); - action= new TextOperationAction(fViewer, ITextOperationTarget.PRINT); + action = new TextOperationAction(fViewer, ITextOperationTarget.PRINT); action.setActionDefinitionId(IWorkbenchCommandConstants.FILE_PRINT); fGlobalActions.put(ITextEditorActionConstants.PRINT, action); - action= new FindReplaceAction(DisassemblyMessages.getBundleForConstructedKeys(), "FindReplaceAction.", this); //$NON-NLS-1$ + action = new FindReplaceAction(DisassemblyMessages.getBundleForConstructedKeys(), "FindReplaceAction.", this); //$NON-NLS-1$ action.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_FIND_AND_REPLACE); fGlobalActions.put(ActionFactory.FIND.getId(), action); fSelectionActions.add(action); fActionGotoPC = new ActionGotoProgramCounter(this); fActionGotoPC.setActionDefinitionId(COMMAND_ID_GOTO_PC); - fActionGotoPC.setImageDescriptor(DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Home_enabled)); - fActionGotoPC.setDisabledImageDescriptor(DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Home_disabled)); + fActionGotoPC.setImageDescriptor( + DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Home_enabled)); + fActionGotoPC.setDisabledImageDescriptor( + DisassemblyImageRegistry.getImageDescriptor(DisassemblyImageRegistry.ICON_Home_disabled)); fStateDependentActions.add(fActionGotoPC); registerWithHandlerService(fActionGotoPC); - + fActionGotoAddress = new ActionGotoAddress(this); fActionGotoAddress.setActionDefinitionId(COMMAND_ID_GOTO_ADDRESS); fStateDependentActions.add(fActionGotoAddress); @@ -1315,7 +1350,8 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem fActionToggleSource = new ActionToggleSource(); fStateDependentActions.add(fActionToggleSource); - fActionToggleSource.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(DsfUIPlugin.PLUGIN_ID, "icons/source.gif")); //$NON-NLS-1$ + fActionToggleSource.setImageDescriptor( + AbstractUIPlugin.imageDescriptorFromPlugin(DsfUIPlugin.PLUGIN_ID, "icons/source.gif")); //$NON-NLS-1$ fVerticalRuler.getControl().addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(final MouseEvent e) { @@ -1323,17 +1359,17 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem IHandlerService handlerService = getSite().getService(IHandlerService.class); if (handlerService != null) { try { - Event event= new Event(); - event.display = e.display; - event.widget = e.widget; - event.time = e.time; - event.data = e.data; - event.x = e.x; - event.y = e.y; - event.button = e.button; - event.stateMask = e.stateMask; - event.count = e.count; - + Event event = new Event(); + event.display = e.display; + event.widget = e.widget; + event.time = e.time; + event.data = e.data; + event.x = e.x; + event.y = e.y; + event.button = e.button; + event.stateMask = e.stateMask; + event.count = e.count; + handlerService.executeCommand(COMMAND_ID_TOGGLE_BREAKPOINT, event); } catch (org.eclipse.core.commands.ExecutionException exc) { DsfUIPlugin.log(exc); @@ -1356,7 +1392,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem /** * Register given action with the handler service for key bindings. - * + * * @param action */ private void registerWithHandlerService(IAction action) { @@ -1364,7 +1400,8 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem fHandlerActivations = new ArrayList<IHandlerActivation>(5); } IHandlerService handlerService = getSite().getService(IHandlerService.class); - fHandlerActivations.add(handlerService.activateHandler(action.getActionDefinitionId(), new ActionHandler(action))); + fHandlerActivations + .add(handlerService.activateHandler(action.getActionDefinitionId(), new ActionHandler(action))); } /* @@ -1396,17 +1433,17 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem }); } } - + public final void gotoLocationByUser(BigInteger address, String locationTxt) { fPCLastAddress = address; fPCLastLocationTxt = locationTxt; gotoAddress(address); } - + public final void gotoActiveFrameByUser() { gotoFrame(getActiveStackFrame()); } - + /* * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyPartCallback#gotoAddress(java.math.BigInteger) */ @@ -1415,7 +1452,8 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem if (fDebugSessionId == null) { return; } - if (DEBUG) System.out.println("gotoAddress " + getAddressText(address)); //$NON-NLS-1$ + if (DEBUG) + System.out.println("gotoAddress " + getAddressText(address)); //$NON-NLS-1$ fFocusAddress = address; BigInteger previousAddress = fGotoAddressPending; if (fGotoAddressPending == PC_UNKNOWN) { @@ -1427,21 +1465,22 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem AddressRangePosition pos = getPositionOfAddress(address); if (pos != null) { if (pos.fValid) { - if ((pos instanceof ErrorPosition || !pos.fAddressOffset.equals(address)) && !previousAddress.equals(address)) { - // address is within a disassembled instruction or error - need to invalidate - pos.fValid = false; - fDocument.addInvalidAddressRange(pos); - } else { - if (fGotoAddressPending.equals(address)) { - fGotoAddressPending = PC_UNKNOWN; - } - gotoPosition(pos, !address.equals(fFrameAddress)); - return; - } - } - int lines = fBufferZone+3; - BigInteger endAddress = pos.fAddressOffset.add(pos.fAddressLength).min( - address.add(BigInteger.valueOf(lines * fDocument.getMeanSizeOfInstructions()))); + if ((pos instanceof ErrorPosition || !pos.fAddressOffset.equals(address)) + && !previousAddress.equals(address)) { + // address is within a disassembled instruction or error - need to invalidate + pos.fValid = false; + fDocument.addInvalidAddressRange(pos); + } else { + if (fGotoAddressPending.equals(address)) { + fGotoAddressPending = PC_UNKNOWN; + } + gotoPosition(pos, !address.equals(fFrameAddress)); + return; + } + } + int lines = fBufferZone + 3; + BigInteger endAddress = pos.fAddressOffset.add(pos.fAddressLength) + .min(address.add(BigInteger.valueOf(lines * fDocument.getMeanSizeOfInstructions()))); retrieveDisassembly(address, endAddress, lines); } } @@ -1498,28 +1537,28 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem */ @Override public void viewportChanged(int verticalOffset) { - if (fDebugSessionId != null && fGotoAddressPending == PC_UNKNOWN && fScrollPos == null && !fUpdatePending && !fRefreshViewPending - && fFocusAddress != PC_UNKNOWN) { + if (fDebugSessionId != null && fGotoAddressPending == PC_UNKNOWN && fScrollPos == null && !fUpdatePending + && !fRefreshViewPending && fFocusAddress != PC_UNKNOWN) { fUpdatePending = true; - final int updateCount = fUpdateCount; - invokeLater(new Runnable() { - @Override + final int updateCount = fUpdateCount; + invokeLater(new Runnable() { + @Override public void run() { - if (updateCount == fUpdateCount) { - assert fUpdatePending; - if (fUpdatePending) { - fUpdatePending = false; - updateVisibleArea(); - } - } - } - }); + if (updateCount == fUpdateCount) { + assert fUpdatePending; + if (fUpdatePending) { + fUpdatePending = false; + updateVisibleArea(); + } + } + } + }); } } /** * Update lines of currently visible area + one page buffer zone below. - * + * * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyPartCallback#updateVisibleArea() */ @Override @@ -1539,7 +1578,8 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem int bottomIndex = fViewer.getBottomIndex(); int focusIndex = -1; boolean focusVisible = false; - boolean isScrollingUp = fViewer.isUserTriggeredScrolling() && fViewer.getLastTopPixel() >= styledText.getTopPixel(); + boolean isScrollingUp = fViewer.isUserTriggeredScrolling() + && fViewer.getLastTopPixel() >= styledText.getTopPixel(); if (fFocusPos != null) { try { int focusOffset = fFocusPos.offset; @@ -1565,16 +1605,17 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem AddressRangePosition bestPosition = null; int bestLine = -1; BigInteger bestDistance = null; - if (DEBUG) System.out.println("DisassemblyPart.updateVisibleArea() called. There are " + fDocument.getInvalidAddressRanges().length + " invalid ranges to consider updating"); //$NON-NLS-1$ //$NON-NLS-2$ + if (DEBUG) + System.out.println("DisassemblyPart.updateVisibleArea() called. There are " //$NON-NLS-1$ + + fDocument.getInvalidAddressRanges().length + " invalid ranges to consider updating"); //$NON-NLS-1$ for (AddressRangePosition p : fDocument.getInvalidAddressRanges()) { try { int line = fDocument.getLineOfOffset(p.offset); if (line >= topIndex && line <= bottomIndex) { - if (p instanceof DisassemblyPosition || p.fAddressLength.compareTo( - BigInteger.valueOf(fBufferZone * 2)) <= 0) { + if (p instanceof DisassemblyPosition + || p.fAddressLength.compareTo(BigInteger.valueOf(fBufferZone * 2)) <= 0) { // small areas and known areas are OK to update - } else if (!isScrollingUp && !fUpdateBeforeFocus - && p.fAddressOffset.compareTo(focusAddress) < 0) { + } else if (!isScrollingUp && !fUpdateBeforeFocus && p.fAddressOffset.compareTo(focusAddress) < 0) { continue; } BigInteger distance = p.fAddressOffset.subtract(focusAddress).abs(); @@ -1592,8 +1633,9 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } } if (bestPosition != null) { - if (DEBUG) System.out.println("...and the best candidate is: " + bestPosition); //$NON-NLS-1$ - int lines = fBufferZone+3; + if (DEBUG) + System.out.println("...and the best candidate is: " + bestPosition); //$NON-NLS-1$ + int lines = fBufferZone + 3; BigInteger startAddress = bestPosition.fAddressOffset; BigInteger endAddress = bestPosition.fAddressOffset.add(bestPosition.fAddressLength); BigInteger addressRange = BigInteger.valueOf(lines * fDocument.getMeanSizeOfInstructions()); @@ -1603,7 +1645,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem // try to increase range to reduce number of requests Iterator<?> iter = fDocument.getModelPositionIterator(endAddress); while (iter.hasNext()) { - AddressRangePosition p = (AddressRangePosition)iter.next(); + AddressRangePosition p = (AddressRangePosition) iter.next(); if (p.fValid) { endAddress = endAddress.add(p.fAddressLength); if (endAddress.subtract(startAddress).compareTo(addressRange) >= 0) { @@ -1621,8 +1663,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem lines = endAddress.subtract(startAddress).intValue(); } retrieveDisassembly(startAddress, endAddress, lines); - } - else { + } else { if (DEBUG) { System.out.println("...but alas we didn't deem any of them worth updating. They are:"); //$NON-NLS-1$ int i = 0; @@ -1643,9 +1684,11 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem fViewer.getControl().getDisplay().asyncExec(runnable); } } + private void invokeLater(Runnable runnable) { invokeLater(10, runnable); } + private void invokeLater(int delay, Runnable runnable) { if (fViewer != null) { fViewer.getControl().getDisplay().timerExec(delay, runnable); @@ -1654,7 +1697,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem /** * Insert source lines if available. - * + * * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyPartCallback#updateInvalidSource() */ @Override @@ -1667,10 +1710,10 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem try { if (fScrollPos == null) { if (fUpdatePending) { - fUpdateSourcePending= true; + fUpdateSourcePending = true; return; } - fUpdateSourcePending= false; + fUpdateSourcePending = false; unlock = true; fUpdatePending = true; lockScroller(); @@ -1680,7 +1723,8 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem if (!p.fValid) { insertSource(p); } else if (DEBUG && fDocument.removeInvalidSourcePosition(p)) { - System.err.println("!!! valid source position in invalid source list at "+ getAddressText(p.fAddressOffset)); //$NON-NLS-1$ + System.err.println( + "!!! valid source position in invalid source list at " + getAddressText(p.fAddressOffset)); //$NON-NLS-1$ } } } finally { @@ -1696,7 +1740,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem * Show disassembly for given (source) file. Retrieves disassembly starting * at the beginning of the file, for as many lines as are specified. If * [lines] == -1, the entire file is disassembled. - * + * * @param file * @param lines */ @@ -1704,20 +1748,22 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem if (fDebugSessionId == null) { return; } - startUpdate(new Runnable() { - @Override + startUpdate(new Runnable() { + @Override public void run() { - if (DEBUG) System.out.println("retrieveDisassembly "+file); //$NON-NLS-1$ - fBackend.retrieveDisassembly(file, lines, fEndAddress, mixed, fShowSymbols, fShowDisassembly); - } - }); + if (DEBUG) + System.out.println("retrieveDisassembly " + file); //$NON-NLS-1$ + fBackend.retrieveDisassembly(file, lines, fEndAddress, mixed, fShowSymbols, fShowDisassembly); + } + }); } private void retrieveDisassembly(BigInteger startAddress, BigInteger endAddress, int lines) { if (fDebugSessionId == null) { return; } - if (DEBUG) System.out.println("retrieveDisassembly "+getAddressText(startAddress)+" "+lines+" lines"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (DEBUG) + System.out.println("retrieveDisassembly " + getAddressText(startAddress) + " " + lines + " lines"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retrieveDisassembly(startAddress, endAddress, lines, fShowSource, true); } @@ -1725,29 +1771,33 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyPartCallback#retrieveDisassembly(java.math.BigInteger, java.math.BigInteger, int, boolean, boolean) */ @Override - public void retrieveDisassembly(final BigInteger startAddress, BigInteger endAddress, final int linesHint, boolean mixed, boolean ignoreFile) { + public void retrieveDisassembly(final BigInteger startAddress, BigInteger endAddress, final int linesHint, + boolean mixed, boolean ignoreFile) { assert isGuiThread(); assert !fUpdatePending; fUpdatePending = true; - final int lines= linesHint + 2; - final BigInteger addressLength= BigInteger.valueOf(lines * 4); + final int lines = linesHint + 2; + final BigInteger addressLength = BigInteger.valueOf(lines * 4); if (endAddress.subtract(startAddress).compareTo(addressLength) > 0) { - endAddress= startAddress.add(addressLength); + endAddress = startAddress.add(addressLength); } - boolean insideActiveFrame= startAddress.equals(fFrameAddress); - String file= null; - int lineNumber= -1; + boolean insideActiveFrame = startAddress.equals(fFrameAddress); + String file = null; + int lineNumber = -1; if (!ignoreFile && insideActiveFrame && fBackend != null) { - file= fBackend.getFrameFile(); + file = fBackend.getFrameFile(); if (file != null && file.trim().length() == 0) { file = null; } if (file != null) { - lineNumber= fBackend.getFrameLine(); + lineNumber = fBackend.getFrameLine(); } } - if (DEBUG) System.out.println("Asking backend to retrieve disassembly: sa=0x" + startAddress.toString(16) + ",ea=0x" + endAddress.toString(16) + ",file=" + file + ",lineNumber=" + lineNumber + ",lines=" + lines); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ - fBackend.retrieveDisassembly(startAddress, endAddress, file, lineNumber, lines, mixed, fShowSymbols, fShowDisassembly, linesHint); + if (DEBUG) + System.out.println("Asking backend to retrieve disassembly: sa=0x" + startAddress.toString(16) + ",ea=0x" //$NON-NLS-1$//$NON-NLS-2$ + + endAddress.toString(16) + ",file=" + file + ",lineNumber=" + lineNumber + ",lines=" + lines); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + fBackend.retrieveDisassembly(startAddress, endAddress, file, lineNumber, lines, mixed, fShowSymbols, + fShowDisassembly, linesHint); } /* (non-Javadoc) @@ -1776,20 +1826,20 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem assert isGuiThread(); return fAddressSize; } - + /* (non-Javadoc) * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyPartCallback#addressSizeChanged(int) */ @Override public void addressSizeChanged(int addressSize) { assert isGuiThread(); - BigInteger oldEndAddress= fEndAddress; - fEndAddress= BigInteger.ONE.shiftLeft(addressSize); - int oldAddressSize= fAddressSize; - fAddressSize= addressSize; + BigInteger oldEndAddress = fEndAddress; + fEndAddress = BigInteger.ONE.shiftLeft(addressSize); + int oldAddressSize = fAddressSize; + fAddressSize = addressSize; if (addressSize < oldAddressSize) { fDocument.deleteDisassemblyRange(fEndAddress, oldEndAddress, true, true); - List<AddressRangePosition> toRemove= new ArrayList<AddressRangePosition>(); + List<AddressRangePosition> toRemove = new ArrayList<AddressRangePosition>(); for (AddressRangePosition position : fDocument.getInvalidAddressRanges()) { if (position.fAddressOffset.compareTo(fEndAddress) >= 0) { try { @@ -1799,8 +1849,8 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } catch (BadLocationException exc) { internalError(exc); } - } else if (position.containsAddress(fEndAddress)){ - position.fAddressLength= fEndAddress.subtract(position.fAddressOffset); + } else if (position.containsAddress(fEndAddress)) { + position.fAddressLength = fEndAddress.subtract(position.fAddressOffset); } } fDocument.removeInvalidAddressRanges(toRemove); @@ -1810,14 +1860,14 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem return; } AddressRulerColumn fAddressRulerColumn = (AddressRulerColumn) getRulerColumn(AddressRulerColumn.ID); - if (fAddressRulerColumn != null) { + if (fAddressRulerColumn != null) { fAddressRulerColumn.setAddressSize(addressSize); if (fComposite != null) { fComposite.layout(true); } } } - + private IContributedRulerColumn getRulerColumn(String id) { CompositeRuler compositeRuler = (CompositeRuler) getVerticalRuler(); for (Iterator<?> iter = compositeRuler.getDecoratorIterator(); iter.hasNext();) { @@ -1859,7 +1909,8 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } protected void setActive(boolean active) { - if (DEBUG) System.out.println("setActive("+ active +")"); //$NON-NLS-1$ //$NON-NLS-2$ + if (DEBUG) + System.out.println("setActive(" + active + ")"); //$NON-NLS-1$ //$NON-NLS-2$ fActive = active; if (fActive) { if (fRefreshAll) { @@ -1870,7 +1921,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem if (fBackend != null && fBackend.hasDebugContext()) { int frame = getActiveStackFrame(); if (frame < 0 && isSuspended()) { - frame= 0; + frame = 0; } if (frame != fTargetFrame) { gotoFrame(frame); @@ -1878,7 +1929,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } } } else { - fGotoAddressPending= fFocusAddress= PC_UNKNOWN; + fGotoAddressPending = fFocusAddress = PC_UNKNOWN; } firePropertyChange(PROP_ACTIVE); } @@ -1900,7 +1951,9 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem IDisassemblyBackend contextBackend = fDebugContext.getAdapter(IDisassemblyBackend.class); // Need to compare the backend classes to prevent reusing the same backend object. // sub class can overwrite the standard disassembly backend to provide its own customization. - if ((prevBackend != null) && (contextBackend != null) && prevBackend.getClass().equals(contextBackend.getClass()) && prevBackend.supportsDebugContext(fDebugContext)) { + if ((prevBackend != null) && (contextBackend != null) + && prevBackend.getClass().equals(contextBackend.getClass()) + && prevBackend.supportsDebugContext(fDebugContext)) { newBackend = prevBackend; } else { needUpdate = true; @@ -1949,6 +2002,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem public void run() { update.run(); } + @Override public void handleException(Throwable e) { internalError(e); @@ -1972,15 +2026,16 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } private void debugContextChanged() { - if (DEBUG) System.out.println("DisassemblyPart.debugContextChanged()"); //$NON-NLS-1$ - fUpdateCount++; + if (DEBUG) + System.out.println("DisassemblyPart.debugContextChanged()"); //$NON-NLS-1$ + fUpdateCount++; fRunnableQueue.clear(); fUpdatePending = false; resetViewer(); if (fDebugSessionId != null) { fJumpToAddressAction.setEnabled(true); if (fAddressBar != null) - fAddressBar.enableAddressBox(true); + fAddressBar.enableAddressBox(true); int activeFrame = getActiveStackFrame(); if (activeFrame > 0) { @@ -1989,20 +2044,20 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem updatePC(PC_UNKNOWN); } - if (fGotoAddressPending != PC_UNKNOWN) { - gotoAddress(fGotoAddressPending); - } - if (fGotoMarkerPending != null) { - gotoMarker(fGotoMarkerPending); - } + if (fGotoAddressPending != PC_UNKNOWN) { + gotoAddress(fGotoAddressPending); + } + if (fGotoMarkerPending != null) { + gotoMarker(fGotoMarkerPending); + } fViewer.addViewportListener(this); - } else { - fJumpToAddressAction.setEnabled(false); - if (fAddressBar != null) - fAddressBar.enableAddressBox(false); + } else { + fJumpToAddressAction.setEnabled(false); + if (fAddressBar != null) + fAddressBar.enableAddressBox(false); fViewer.removeViewportListener(this); - fGotoMarkerPending = null; - } + fGotoMarkerPending = null; + } updateTitle(); updateStateDependentActions(); firePropertyChange(PROP_CONNECTED); @@ -2012,16 +2067,16 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem private void attachExtendedPCAnnotationModel() { IAnnotationModel annotationModel = fViewer.getAnnotationModel(); if (annotationModel instanceof IAnnotationModelExtension) { - IAnnotationModelExtension ame= (IAnnotationModelExtension) annotationModel; + IAnnotationModelExtension ame = (IAnnotationModelExtension) annotationModel; fExtPCAnnotationModel = new DisassemblyAnnotationModel(); ame.addAnnotationModel(EXTENDED_PC_ANNOTATIONS, fExtPCAnnotationModel); } } - + private void attachBreakpointsAnnotationModel() { IAnnotationModel annotationModel = fViewer.getAnnotationModel(); if (annotationModel instanceof IAnnotationModelExtension) { - IAnnotationModelExtension ame= (IAnnotationModelExtension) annotationModel; + IAnnotationModelExtension ame = (IAnnotationModelExtension) annotationModel; ame.addAnnotationModel(BREAKPOINT_ANNOTATIONS, new BreakpointsAnnotationModel(fDebugContext)); } } @@ -2039,14 +2094,15 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem fRefreshViewPending = false; long now = System.currentTimeMillis(); if (now >= refreshViewScheduled) { - if (DEBUG) System.err.println("*** refreshing view ***"); //$NON-NLS-1$ - + if (DEBUG) + System.err.println("*** refreshing view ***"); //$NON-NLS-1$ + // save viewport position and frame info BigInteger topAddress = getTopAddress(); - int targetFrame= fTargetFrame; + int targetFrame = fTargetFrame; BigInteger frameAddress = fFrameAddress; BigInteger pcAddress = fPCAddress; - + // clear viewer resetViewer(); if (fScrollPos != null) { @@ -2060,15 +2116,17 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem fPCAddress = pcAddress; gotoAddress(topAddress); } else { - refreshView((int)(refreshViewScheduled - now)); + refreshView((int) (refreshViewScheduled - now)); } - }}; + } + }; if (delay > 0) { invokeLater(delay, new Runnable() { @Override public void run() { doScrollLocked(refresh); - }}); + } + }); } else { doScrollLocked(refresh); } @@ -2083,7 +2141,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem topAddress = getAddressOfLine(fViewer.getTopIndex() + 1); } return topAddress; - + } else { return PC_UNKNOWN; } @@ -2104,14 +2162,14 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem fFile2Storage.clear(); fDocument.clear(); fViewer.setDocument(fDocument, new AnnotationModel()); - if (fDebugSessionId != null) { - attachBreakpointsAnnotationModel(); - attachExtendedPCAnnotationModel(); + if (fDebugSessionId != null) { + attachBreakpointsAnnotationModel(); + attachExtendedPCAnnotationModel(); fDocument.insertInvalidAddressRange(0, 0, fStartAddress, fEndAddress); - } + } } - private AddressRangePosition getPCPosition(BigInteger address) { + private AddressRangePosition getPCPosition(BigInteger address) { if (address.compareTo(BigInteger.ZERO) < 0) { // invalid address return null; @@ -2129,7 +2187,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem if (!(pos instanceof DisassemblyPosition)) { return pos; } - String srcFile = ((DisassemblyPosition)pos).getFile(); + String srcFile = ((DisassemblyPosition) pos).getFile(); if (srcFile == null) { return pos; } @@ -2144,7 +2202,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } return null; } - int stmtLine = ((DisassemblyPosition)pos).getLine(); + int stmtLine = ((DisassemblyPosition) pos).getLine(); if (stmtLine < 0) { return pos; } @@ -2155,46 +2213,46 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem int offset = srcPos.offset; int length = srcPos.length; return new AddressRangePosition(offset, length, address, BigInteger.ZERO); - } + } - /** + /** * Update the annotation indicating the given address. * @return a position which denotes the documents position */ private AddressRangePosition updateAddressAnnotation(Annotation annotation, BigInteger address) { if (fViewer == null) { - return null; // can happen during session shutdown + return null; // can happen during session shutdown } IAnnotationModel annotationModel = fViewer.getAnnotationModel(); annotationModel.removeAnnotation(annotation); AddressRangePosition pos = getPCPosition(address); if (pos != null) { - annotationModel.addAnnotation(annotation, new Position(pos.offset, Math.max(0, pos.length-1))); + annotationModel.addAnnotation(annotation, new Position(pos.offset, Math.max(0, pos.length - 1))); } return pos; } public IBreakpoint[] getBreakpointsAtLine(int line) { - BreakpointsAnnotationModel bpModel= null; - IAnnotationModel am= fViewer.getAnnotationModel(); + BreakpointsAnnotationModel bpModel = null; + IAnnotationModel am = fViewer.getAnnotationModel(); if (am instanceof IAnnotationModelExtension) { - IAnnotationModelExtension ame= (IAnnotationModelExtension) am; - bpModel= (BreakpointsAnnotationModel) ame.getAnnotationModel(BREAKPOINT_ANNOTATIONS); + IAnnotationModelExtension ame = (IAnnotationModelExtension) am; + bpModel = (BreakpointsAnnotationModel) ame.getAnnotationModel(BREAKPOINT_ANNOTATIONS); if (bpModel != null) { IRegion lineRegion; try { - lineRegion= fDocument.getLineInformation(line); + lineRegion = fDocument.getLineInformation(line); } catch (BadLocationException exc) { return null; } - int offset= lineRegion.getOffset(); - int length= lineRegion.getLength(); - Iterator<Annotation> it= bpModel.getAnnotationIterator(offset, length, true, true); - List<IBreakpoint> bpList= new ArrayList<IBreakpoint>(5); - final IBreakpointManager bpMgr= DebugPlugin.getDefault().getBreakpointManager(); + int offset = lineRegion.getOffset(); + int length = lineRegion.getLength(); + Iterator<Annotation> it = bpModel.getAnnotationIterator(offset, length, true, true); + List<IBreakpoint> bpList = new ArrayList<IBreakpoint>(5); + final IBreakpointManager bpMgr = DebugPlugin.getDefault().getBreakpointManager(); while (it.hasNext()) { - final SimpleMarkerAnnotation annotation= (SimpleMarkerAnnotation) it.next(); - IBreakpoint bp= bpMgr.getBreakpoint(annotation.getMarker()); + final SimpleMarkerAnnotation annotation = (SimpleMarkerAnnotation) it.next(); + IBreakpoint bp = bpMgr.getBreakpoint(annotation.getMarker()); if (bp != null) { bpList.add(bp); } @@ -2213,7 +2271,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem @Override public void gotoFrame(int frame) { assert isGuiThread(); - fGotoAddressPending = PC_UNKNOWN; + fGotoAddressPending = PC_UNKNOWN; gotoFrame(frame, PC_UNKNOWN); } @@ -2237,8 +2295,9 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem @Override public void gotoFrame(int frame, BigInteger address) { assert isGuiThread(); - if (DEBUG) System.out.println("gotoFrame " + frame + " " + getAddressText(address)); //$NON-NLS-1$ //$NON-NLS-2$ - + if (DEBUG) + System.out.println("gotoFrame " + frame + " " + getAddressText(address)); //$NON-NLS-1$ //$NON-NLS-2$ + // cache the last PC address if (!isSyncWithActiveDebugContext()) { if (isTrackExpression()) { @@ -2248,26 +2307,26 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem if (fPCLastAddress != PC_UNKNOWN) { address = fPCLastAddress; } else if (address != PC_UNKNOWN) { - fPCLastAddress = address; + fPCLastAddress = address; } - + // need to get the frame address when the view first started. if (fPCLastAddress != PC_UNKNOWN) frame = -2; // clear the annotation } else { fPCLastAddress = address; } - - if (fGotoAddressPending == fFrameAddress) { - // cancel goto address from previous goto frame - fGotoAddressPending = PC_UNKNOWN; - } + + if (fGotoAddressPending == fFrameAddress) { + // cancel goto address from previous goto frame + fGotoAddressPending = PC_UNKNOWN; + } fTargetFrame = frame; fFrameAddress = address; if (fTargetFrame == -1) { fTargetFrame = getActiveStackFrame(); if (fTargetFrame < 0 && fBackend != null && fBackend.canDisassemble()) { - fTargetFrame= 0; + fTargetFrame = 0; } if (fTargetFrame == -1) { fGotoFramePending = false; @@ -2282,7 +2341,8 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem if (!fUpdatePending) { fGotoFramePending = false; if (fBackend != null && fBackend.hasDebugContext() && fBackend.canDisassemble()) { - if (DEBUG) System.out.println("retrieveFrameAddress "+frame); //$NON-NLS-1$ + if (DEBUG) + System.out.println("retrieveFrameAddress " + frame); //$NON-NLS-1$ fUpdatePending = true; fBackend.retrieveFrameAddress(fTargetFrame); } @@ -2319,7 +2379,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem public final boolean isActive() { return fActive; } - + /* * @see org.eclipse.cdt.dsf.debug.internal.ui.disassembly.IDisassemblyPart#isConnected() */ @@ -2328,7 +2388,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem if (fDebugSessionId == null) { return false; } - + return (fBackend != null) ? fBackend.hasDebugContext() : false; } @@ -2347,7 +2407,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem public final ISourceViewer getTextViewer() { return fViewer; } - + @Override public final boolean hasViewer() { return fViewer != null; @@ -2374,7 +2434,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem * Should return a <code>Long</code> object in case the value was computed, * another object to be waited on if the retrieval is in progress, <code>null</code> * if no time stamp could be retrieved. - * + * * @param address * @return Long, Object or <code>null</code> */ @@ -2421,7 +2481,8 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } private void addToPCHistory(AddressRangePosition pcPos) { - if (DEBUG) System.out.println("addToPCHistory "+getAddressText(pcPos.fAddressOffset)); //$NON-NLS-1$ + if (DEBUG) + System.out.println("addToPCHistory " + getAddressText(pcPos.fAddressOffset)); //$NON-NLS-1$ if (fPCHistorySizeMax <= 1) { return; } @@ -2452,7 +2513,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem fViewer.invalidateTextPresentation(last.offset, last.length); } // redraw - for (Iterator<AddressRangePosition> it=fPCHistory.iterator(); it.hasNext();) { + for (Iterator<AddressRangePosition> it = fPCHistory.iterator(); it.hasNext();) { AddressRangePosition pos = it.next(); fViewer.invalidateTextPresentation(pos.offset, pos.length); } @@ -2470,9 +2531,9 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem public void updatePC(BigInteger pc) { assert isGuiThread(); if (!fPendingPCUpdates.isEmpty()) { - BigInteger last = fPendingPCUpdates.get(fPendingPCUpdates.size()-1); + BigInteger last = fPendingPCUpdates.get(fPendingPCUpdates.size() - 1); if (last.compareTo(BigInteger.ZERO) < 0) { - fPendingPCUpdates.remove(fPendingPCUpdates.size()-1); + fPendingPCUpdates.remove(fPendingPCUpdates.size() - 1); } } fPendingPCUpdates.add(pc); @@ -2509,7 +2570,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem // set primary pos = updateAddressAnnotation(fPCAnnotation, fPCAddress); } else if (fTargetFrame < 0) { - // clear both + // clear both updateAddressAnnotation(fPCAnnotation, PC_UNKNOWN); updateAddressAnnotation(fSecondaryPCAnnotation, PC_UNKNOWN); } else { @@ -2519,11 +2580,11 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem pos = updateAddressAnnotation(fSecondaryPCAnnotation, fFrameAddress); } fPCAnnotationUpdatePending = pos == null && fFrameAddress.compareTo(BigInteger.ZERO) >= 0; - + if (fExtPCAnnotationModel != null) { fBackend.updateExtendedPCAnnotation(fExtPCAnnotationModel); } - + return pos; } @@ -2552,7 +2613,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem if (fUpdateSourcePending) { updateInvalidSource(); } - boolean sourceValid= !fDocument.hasInvalidSourcePositions(); + boolean sourceValid = !fDocument.hasInvalidSourcePositions(); if (sourceValid || fShowDisassembly) { if (fGotoFramePending) { gotoFrame(fTargetFrame, fFrameAddress); @@ -2588,49 +2649,50 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } if (!fActive) { // refresh all when becoming active again - fRefreshViewPending= false; + fRefreshViewPending = false; fRefreshAll = true; return; } if (doit != null) { fRunnableQueue.add(doit); } - final int updateCount = fUpdateCount; - if (fUpdatePending) { - if (fRunnableQueue.size() == 1) { - Runnable doitlater = new Runnable() { - @Override + final int updateCount = fUpdateCount; + if (fUpdatePending) { + if (fRunnableQueue.size() == 1) { + Runnable doitlater = new Runnable() { + @Override public void run() { - if (updateCount == fUpdateCount) { - doScrollLocked(null); - } - }}; - invokeLater(doitlater); - } - } else { - fUpdatePending = true; - lockScroller(); - try { - ArrayList<Runnable> copy = new ArrayList<Runnable>(fRunnableQueue); - fRunnableQueue.clear(); - for (Iterator<Runnable> iter = copy.iterator(); iter.hasNext();) { - if (updateCount != fUpdateCount) { - return; - } - Runnable doitnow = iter.next(); - try { - doitnow.run(); - } catch(Exception e) { - internalError(e); - } - } - } finally { - fUpdatePending = false; - unlockScroller(); - doPending(); - updateVisibleArea(); - } - } + if (updateCount == fUpdateCount) { + doScrollLocked(null); + } + } + }; + invokeLater(doitlater); + } + } else { + fUpdatePending = true; + lockScroller(); + try { + ArrayList<Runnable> copy = new ArrayList<Runnable>(fRunnableQueue); + fRunnableQueue.clear(); + for (Iterator<Runnable> iter = copy.iterator(); iter.hasNext();) { + if (updateCount != fUpdateCount) { + return; + } + Runnable doitnow = iter.next(); + try { + doitnow.run(); + } catch (Exception e) { + internalError(e); + } + } + } finally { + fUpdatePending = false; + unlockScroller(); + doPending(); + updateVisibleArea(); + } + } } /* (non-Javadoc) @@ -2661,7 +2723,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem AddressRangePosition pos = fDocument.getDisassemblyPosition(focusOffset); if (pos != null && !pos.fValid) { // don't lock position of invalid range - focusOffset = pos.offset+pos.length; + focusOffset = pos.offset + pos.length; focusLine = fDocument.getLineOfOffset(focusOffset); } } @@ -2700,10 +2762,10 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem int topLine = fDocument.getLineOfOffset(fScrollPos.offset) - fScrollLine; // limit text size int lineCount = fDocument.getNumberOfLines(); - if (lineCount > fgHighWaterMark*fBufferZone) { - int startLine = Math.max(0, topLine-fgLowWaterMark/2*fBufferZone); - int endLine = Math.min(lineCount-1, topLine+fgLowWaterMark/2*fBufferZone); - fDocument.deleteLineRange(endLine, lineCount-1); + if (lineCount > fgHighWaterMark * fBufferZone) { + int startLine = Math.max(0, topLine - fgLowWaterMark / 2 * fBufferZone); + int endLine = Math.min(lineCount - 1, topLine + fgLowWaterMark / 2 * fBufferZone); + fDocument.deleteLineRange(endLine, lineCount - 1); fDocument.deleteLineRange(0, startLine); } int lineHeight = fViewer.getTextWidget().getLineHeight(); @@ -2727,31 +2789,31 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } } - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyPartCallback#insertSource(org.eclipse.cdt.debug.internal.ui.disassembly.dsf.AddressRangePosition) - */ - @Override + /* (non-Javadoc) + * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyPartCallback#insertSource(org.eclipse.cdt.debug.internal.ui.disassembly.dsf.AddressRangePosition) + */ + @Override public void insertSource(AddressRangePosition _pos) { - assert isGuiThread(); + assert isGuiThread(); // IDisassemblyPartCallback does not have visibility to the // SourcePosition type, which is DSF-specific, so it uses the base type - if (!(_pos instanceof SourcePosition)) { - assert false : "Caller should have passed in a SourcePosition"; //$NON-NLS-1$ - return; - } - SourcePosition pos = (SourcePosition)_pos; - - if (!fShowSource) { - fDocument.insertSource(pos, "", pos.fLine, true); //$NON-NLS-1$ - return; - } - SourceFileInfo fi = pos.fFileInfo; + if (!(_pos instanceof SourcePosition)) { + assert false : "Caller should have passed in a SourcePosition"; //$NON-NLS-1$ + return; + } + SourcePosition pos = (SourcePosition) _pos; + + if (!fShowSource) { + fDocument.insertSource(pos, "", pos.fLine, true); //$NON-NLS-1$ + return; + } + SourceFileInfo fi = pos.fFileInfo; if (fi.fSource != null || fi.fError != null) { - int lineNr = pos.fLine; + int lineNr = pos.fLine; if (fi.fSource != null && lineNr >= 0 && lineNr < fi.fSource.getNumberOfLines()) { fi.fStartAddress = fi.fStartAddress.min(pos.fAddressOffset); fi.fEndAddress = fi.fEndAddress.max(pos.fAddressOffset.add(pos.fAddressLength)); - int last = pos.fLast > lineNr ? pos.fLast : lineNr; + int last = pos.fLast > lineNr ? pos.fLast : lineNr; final BigInteger lineAddr = fi.fLine2Addr[lineNr]; if (lineAddr == null) { fi.fLine2Addr[lineNr] = pos.fAddressOffset; @@ -2765,9 +2827,11 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem if (oldPos != null) { // test if source positions are consecutive try { - int index = fDocument.computeIndexInCategory(DisassemblyDocument.CATEGORY_SOURCE, pos.fAddressOffset); + int index = fDocument.computeIndexInCategory(DisassemblyDocument.CATEGORY_SOURCE, + pos.fAddressOffset); if (index >= 0) { - SourcePosition nextPos = (SourcePosition) fDocument.getPositionOfIndex(DisassemblyDocument.CATEGORY_SOURCE, index+1); + SourcePosition nextPos = (SourcePosition) fDocument + .getPositionOfIndex(DisassemblyDocument.CATEGORY_SOURCE, index + 1); if (nextPos.fFileInfo == fi && nextPos.fLine == lineNr) { fDocument.replace(oldPos, oldPos.length, ""); //$NON-NLS-1$ fDocument.removeSourcePosition(oldPos); @@ -2789,9 +2853,11 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem // new source position is after old position try { // test if source positions are consecutive - int index = fDocument.computeIndexInCategory(DisassemblyDocument.CATEGORY_SOURCE, pos.fAddressOffset); + int index = fDocument.computeIndexInCategory(DisassemblyDocument.CATEGORY_SOURCE, + pos.fAddressOffset); if (index > 0) { - SourcePosition prevPos = (SourcePosition) fDocument.getPositionOfIndex(DisassemblyDocument.CATEGORY_SOURCE, index-1); + SourcePosition prevPos = (SourcePosition) fDocument + .getPositionOfIndex(DisassemblyDocument.CATEGORY_SOURCE, index - 1); if (prevPos.fFileInfo == fi && prevPos.fLine == lineNr) { fDocument.insertSource(pos, "", lineNr, true); //$NON-NLS-1$ fDocument.removeSourcePosition(pos); @@ -2816,29 +2882,29 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } } - private void updateTitle() { - if (fDebugSessionId == null) { - String descr = DisassemblyMessages.Disassembly_message_notConnected; - String title = getConfigurationElement().getAttribute("name"); //$NON-NLS-1$ - setPartName(title); - setContentDescription(descr); - setTitleToolTip(title); - } else { - // TLETODO Proper content description - setContentDescription(""); //$NON-NLS-1$ - } - } + private void updateTitle() { + if (fDebugSessionId == null) { + String descr = DisassemblyMessages.Disassembly_message_notConnected; + String title = getConfigurationElement().getAttribute("name"); //$NON-NLS-1$ + setPartName(title); + setContentDescription(descr); + setTitleToolTip(title); + } else { + // TLETODO Proper content description + setContentDescription(""); //$NON-NLS-1$ + } + } - /** + /** * Close this part */ protected abstract void closePart(); @Override - public void applyTextPresentation(TextPresentation textPresentation) { + public void applyTextPresentation(TextPresentation textPresentation) { IRegion coverage = textPresentation.getExtent(); if (coverage == null) { - coverage= new Region(0, fDocument.getLength()); + coverage = new Region(0, fDocument.getLength()); } int startOffset = coverage.getOffset(); int length = coverage.getLength(); @@ -2858,27 +2924,28 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem return; } ArrayList<StyleRange> styleRanges = new ArrayList<StyleRange>(); - while(it.hasNext()) { - AddressRangePosition pos = (AddressRangePosition)it.next(); + while (it.hasNext()) { + AddressRangePosition pos = (AddressRangePosition) it.next(); if (pos.offset >= endOffset) { break; } - if (pos.offset+pos.length <= startOffset) { + if (pos.offset + pos.length <= startOffset) { continue; } if (pos.fValid && pos.length > 0) { if (pos instanceof DisassemblyPosition) { - DisassemblyPosition disPos = (DisassemblyPosition)pos; + DisassemblyPosition disPos = (DisassemblyPosition) pos; styleRanges.add(new StyleRange(pos.offset, disPos.length, fInstructionColor, null, SWT.NULL)); } else if (pos instanceof ErrorPosition) { styleRanges.add(new StyleRange(pos.offset, pos.length, fErrorColor, null, SWT.NULL)); } else if (pos instanceof LabelPosition) { styleRanges.add(new StyleRange(pos.offset, pos.length, fLabelColor, null, SWT.BOLD)); } else if (pos instanceof SourcePosition) { - SourcePosition srcPos = (SourcePosition)pos; + SourcePosition srcPos = (SourcePosition) pos; TextPresentation presentation = null; if (srcPos.fFileInfo.fSource != null) { - presentation = srcPos.fFileInfo.getPresentation(srcPos.fFileInfo.getRegion(srcPos.fLine, pos.length)); + presentation = srcPos.fFileInfo + .getPresentation(srcPos.fFileInfo.getRegion(srcPos.fLine, pos.length)); } if (presentation != null) { // clip result window to coverage @@ -2886,8 +2953,9 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem int end = Math.min(endOffset, srcPos.offset + srcPos.length); int srcOffset = srcPos.fFileInfo.getLineOffset(srcPos.fLine); int clipOffset = start - srcPos.offset; - presentation.setResultWindow(new Region(srcOffset + clipOffset, end-start)); - for (Iterator<StyleRange> iter = presentation.getNonDefaultStyleRangeIterator(); iter.hasNext();) { + presentation.setResultWindow(new Region(srcOffset + clipOffset, end - start)); + for (Iterator<StyleRange> iter = presentation.getNonDefaultStyleRangeIterator(); iter + .hasNext();) { StyleRange styleRange = iter.next(); styleRange.start += srcPos.offset + clipOffset; styleRanges.add(styleRange); @@ -2906,9 +2974,10 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem // update pc history trail if (fPCHistory.size() > 1) { HSL hsv = new HSL(fPCAnnotationRGB); - double luminanceStep = (1-hsv.luminance)/(fPCHistorySizeMax+1); + double luminanceStep = (1 - hsv.luminance) / (fPCHistorySizeMax + 1); hsv.luminance = 1 - luminanceStep * (fPCHistorySizeMax - fPCHistory.size()); - for (ListIterator<AddressRangePosition> listIt = fPCHistory.listIterator(fPCHistory.size()); listIt.hasPrevious();) { + for (ListIterator<AddressRangePosition> listIt = fPCHistory.listIterator(fPCHistory.size()); listIt + .hasPrevious();) { AddressRangePosition pcPos = listIt.previous(); hsv.luminance -= luminanceStep; if (pcPos.isDeleted) { @@ -2923,7 +2992,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem Color pcColor = getSharedColors().getColor(rgb); Color textColor = null; // experimental: if color is dark, use white (background) as text color -// Color textColor = hsv.luminance < 0.7 ? fViewer.getTextWidget().getBackground() : null; + // Color textColor = hsv.luminance < 0.7 ? fViewer.getTextWidget().getBackground() : null; textPresentation.mergeStyleRange(new StyleRange(pcPos.offset, pcPos.length, textColor, pcColor)); } } @@ -2931,11 +3000,14 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } @Override - public AddressRangePosition insertSource(AddressRangePosition pos, BigInteger address, final String file, int lineNumber) { + public AddressRangePosition insertSource(AddressRangePosition pos, BigInteger address, final String file, + int lineNumber) { return insertSource(pos, address, file, lineNumber, lineNumber); } + @Override - public AddressRangePosition insertSource(AddressRangePosition pos, BigInteger address, final String file, int firstLine, int lastLine) { + public AddressRangePosition insertSource(AddressRangePosition pos, BigInteger address, final String file, + int firstLine, int lastLine) { assert isGuiThread(); Object sourceElement = null; if (fFile2Storage.containsKey(file)) { @@ -2944,17 +3016,17 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem sourceElement = fBackend.insertSource(pos, address, file, firstLine); } if (sourceElement instanceof File) { - sourceElement = new LocalFileStorage((File)sourceElement); - } else if (sourceElement instanceof ITranslationUnit) { - IPath location = ((ITranslationUnit) sourceElement).getLocation(); - if (location != null) { - sourceElement = new LocalFileStorage(location.toFile()); - } + sourceElement = new LocalFileStorage((File) sourceElement); + } else if (sourceElement instanceof ITranslationUnit) { + IPath location = ((ITranslationUnit) sourceElement).getLocation(); + if (location != null) { + sourceElement = new LocalFileStorage(location.toFile()); + } } if (sourceElement instanceof IStorage) { if (!(sourceElement instanceof IFile)) { // try to resolve as resource - final IPath location= ((IStorage) sourceElement).getFullPath(); + final IPath location = ((IStorage) sourceElement).getFullPath(); if (location != null) { IFile iFile = ResourceLookup.selectFileForLocation(location, null); if (iFile != null && iFile.isAccessible()) { @@ -2965,18 +3037,18 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem fFile2Storage.put(file, sourceElement); } else if (sourceElement == null) { if (!fFile2Storage.containsKey(file)) { - logWarning(DisassemblyMessages.Disassembly_log_error_locateFile+file, null); - fFile2Storage.put(file, null); + logWarning(DisassemblyMessages.Disassembly_log_error_locateFile + file, null); + fFile2Storage.put(file, null); } } else { - fFile2Storage.put(file, null); - assert false : "missing support for source element of type " + sourceElement.getClass().toString(); //$NON-NLS-1$ + fFile2Storage.put(file, null); + assert false : "missing support for source element of type " + sourceElement.getClass().toString(); //$NON-NLS-1$ } - + if (sourceElement instanceof IStorage) { - SourceFileInfo fi = fDocument.getSourceInfo((IStorage)sourceElement); + SourceFileInfo fi = fDocument.getSourceInfo((IStorage) sourceElement); if (fi == null) { - IStorage storage = (IStorage)sourceElement; + IStorage storage = (IStorage) sourceElement; Display display = getSite().getShell().getDisplay(); Runnable done = new SourceColorerJob(display, storage, this); fi = fDocument.createSourceInfo(file, storage, done); @@ -2989,25 +3061,27 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } pos = fDocument.insertInvalidSource(pos, address, fi, firstLine, lastLine); } - + return pos; } - + public AddressBarContributionItem getAddressBar() { return fAddressBar; } - + public void generateErrorDialog(String message) { - MessageDialog messageDialog = new MessageDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(), DisassemblyMessages.Disassembly_Error_Dialog_title, null, message, MessageDialog.ERROR, new String[]{DisassemblyMessages.Disassembly_Error_Dialog_ok_button}, 0); + MessageDialog messageDialog = new MessageDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(), + DisassemblyMessages.Disassembly_Error_Dialog_title, null, message, MessageDialog.ERROR, + new String[] { DisassemblyMessages.Disassembly_Error_Dialog_ok_button }, 0); messageDialog.open(); } - + public void activateDisassemblyContext() { IContextService ctxService = getSite().getService(IContextService.class); - if (ctxService!=null) + if (ctxService != null) fContextActivation = ctxService.activateContext(KEY_BINDING_CONTEXT_DISASSEMBLY); } - + public void deactivateDisassemblyContext() { if (fContextActivation != null) { IContextService ctxService = getSite().getService(IContextService.class); @@ -3042,7 +3116,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } }); } - + /* (non-Javadoc) * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyPartCallback#handleTargetEnded() */ @@ -3052,16 +3126,16 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem @Override public void run() { fDebugSessionId = null; - startUpdate(new Runnable() { - @Override + startUpdate(new Runnable() { + @Override public void run() { - debugContextChanged(); - } - }); + debugContextChanged(); + } + }); } }); } - + /* (non-Javadoc) * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyPartCallback#setUpdatePending(boolean) */ @@ -3105,7 +3179,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem assert isGuiThread(); return fDocument; } - + /* (non-Javadoc) * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyPartCallback#getStorageForFile(java.lang.String) */ @@ -3119,7 +3193,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem * A pass through to process the text to populate into a text hover. */ public String getHoverInfoData(AddressRangePosition pos, String ident) { - if (fBackend != null ) { + if (fBackend != null) { return fBackend.getHoverInfoData(pos, ident); } return ""; //$NON-NLS-1$ @@ -3134,7 +3208,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } return ""; //$NON-NLS-1$ } - + /** * A passthru from the text hover code to the backend. */ @@ -3144,7 +3218,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } return ""; //$NON-NLS-1$ } - + public BigInteger eval(String expr, boolean suppressError) { if (fBackend != null) { BigInteger address = null; @@ -3175,29 +3249,29 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem private void setTrackExpression(boolean track) { fTrackExpression = track; } - + protected boolean isSyncWithActiveDebugContext() { return fSynchWithActiveDebugContext; } - + private void setSyncWithDebugView(boolean sync) { fSynchWithActiveDebugContext = sync; fTrackExpressionAction.setEnabled(!sync); - + if (sync) { gotoActiveFrameByUser(); } else { // redraw while (!fPCHistory.isEmpty()) { - AddressRangePosition pos = fPCHistory.removeFirst(); + AddressRangePosition pos = fPCHistory.removeFirst(); fViewer.invalidateTextPresentation(pos.offset, pos.length); } - + fTargetFrame = -2; // clear the annotation updatePCAnnotation(); } } - + /** * Most methods in IDisassemblyPartCallback require execution on the GUI thread. */ @@ -3231,13 +3305,13 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem scrollToAddress = bottomAddress.add(addressRange).min(bottomAddress); break; default: - assert false; // invalid keycode passed + assert false; // invalid keycode passed scrollToAddress = fFocusAddress; } AddressRangePosition pos = getPositionOfAddress(scrollToAddress); if (pos != null && pos.fValid) { if (SWT.ARROW_DOWN == keyCode && pos.fAddressOffset.compareTo(bottomAddress) <= 0 - || SWT.ARROW_UP == keyCode && pos.fAddressOffset.compareTo(topAddress) >= 0) { + || SWT.ARROW_UP == keyCode && pos.fAddressOffset.compareTo(topAddress) >= 0) { return false; } gotoPosition(pos, SWT.ARROW_DOWN != keyCode); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblySelectionProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblySelectionProvider.java index 64b6d77fab0..f2b12746c74 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblySelectionProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblySelectionProvider.java @@ -13,7 +13,6 @@ *******************************************************************************/ package org.eclipse.cdt.dsf.debug.internal.ui.disassembly; - import org.eclipse.cdt.dsf.debug.internal.ui.disassembly.provisional.DisassemblySelection; import org.eclipse.cdt.dsf.debug.internal.ui.disassembly.provisional.IDisassemblySelection; import org.eclipse.core.runtime.ListenerList; @@ -38,7 +37,7 @@ class DisassemblySelectionProvider implements ISelectionProvider { private final ListenerList<ISelectionChangedListener> fListenerList = new ListenerList<>(ListenerList.IDENTITY); private final ISelectionChangedListener fListener = event -> fireSelectionChanged(event); private final DisassemblyPart fPart; - + DisassemblySelectionProvider(DisassemblyPart disassemblyPart) { fPart = disassemblyPart; fPart.getTextViewer().getSelectionProvider().addSelectionChangedListener(fListener); @@ -53,12 +52,12 @@ class DisassemblySelectionProvider implements ISelectionProvider { @Override public void addSelectionChangedListener(ISelectionChangedListener listener) { - fListenerList.add(listener); + fListenerList.add(listener); } @Override public ISelection getSelection() { - final ISourceViewer textViewer= fPart.getTextViewer(); + final ISourceViewer textViewer = fPart.getTextViewer(); ISelectionProvider provider = textViewer.getSelectionProvider(); if (provider != null) { return new DisassemblySelection((ITextSelection) provider.getSelection(), fPart); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyTextHover.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyTextHover.java index 6bc2f4a1cc4..cdd4cd75327 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyTextHover.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyTextHover.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -38,13 +38,13 @@ public class DisassemblyTextHover implements ITextHover { * Create a new disassembly text hover. */ public DisassemblyTextHover(DisassemblyPart part) { - fDisassemblyPart= part; + fDisassemblyPart = part; } /* (non-Javadoc) * @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, int) */ - @Override + @Override public IRegion getHoverRegion(ITextViewer textViewer, int offset) { IDocument doc = textViewer.getDocument(); return CWordFinder.findWord(doc, offset); @@ -55,17 +55,17 @@ public class DisassemblyTextHover implements ITextHover { */ @Override public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { - DisassemblyDocument doc = (DisassemblyDocument)textViewer.getDocument(); + DisassemblyDocument doc = (DisassemblyDocument) textViewer.getDocument(); int offset = hoverRegion.getOffset(); AddressRangePosition pos; try { String ident = doc.get(offset, hoverRegion.getLength()); String value = null; pos = doc.getModelPosition(offset); - + value = fDisassemblyPart.getHoverInfoData(pos, ident); - // If returns null (or empty string), not implemented or something went wrong. + // If returns null (or empty string), not implemented or something went wrong. if (value == null || value.length() == 0) { if (pos instanceof SourcePosition) { value = evaluateExpression(ident); @@ -82,12 +82,12 @@ public class DisassemblyTextHover implements ITextHover { if (value != null) { return ident + " = " + value; //$NON-NLS-1$ } - } - else + } else return value; } catch (BadLocationException e) { if (DsfUIPlugin.getDefault().isDebugging()) { - DsfUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, "Internal Error", e)); //$NON-NLS-1$ + DsfUIPlugin.getDefault().getLog() + .log(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, "Internal Error", e)); //$NON-NLS-1$ } } return null; @@ -99,7 +99,7 @@ public class DisassemblyTextHover implements ITextHover { * @return register value or <code>null</code> */ private String evaluateRegister(String register) { - return fDisassemblyPart.evaluateRegister(register); + return fDisassemblyPart.evaluateRegister(register); } /** diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyToggleBreakpointTester.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyToggleBreakpointTester.java index bb0c10dfd06..4b5e6841670 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyToggleBreakpointTester.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyToggleBreakpointTester.java @@ -9,7 +9,7 @@ * SPDX-License-Identifier: EPL-2.0 * * Contributors: - * Patrick Chuong (Texas Instruments) - + * Patrick Chuong (Texas Instruments) - * Update CDT ToggleBreakpointTargetFactory enablement (340177 ) *****************************************************************/ package org.eclipse.cdt.dsf.debug.internal.ui.disassembly; @@ -26,7 +26,7 @@ import org.eclipse.debug.ui.DebugUITools; /** * Disassembly toggle breakpoint factory enablement tester. - * + * * @since 2.2 */ public class DisassemblyToggleBreakpointTester extends PropertyTester { @@ -40,25 +40,25 @@ public class DisassemblyToggleBreakpointTester extends PropertyTester { if ("isDisassemblyViewSupportsCBreakpoint".equals(property) && (receiver instanceof IDisassemblyPart)) { //$NON-NLS-1$ IDisassemblyPart view = ((IDisassemblyPart) receiver); if (!CDebugUtils.isCustomToggleBreakpointFactory()) - return true; - - IAdaptable element = DebugUITools.getPartDebugContext(view.getSite()); - if (element != null) { - IDebugModelProvider modelProvider = element.getAdapter(IDebugModelProvider.class); - if (modelProvider != null) { - String[] models = modelProvider.getModelIdentifiers(); - for (String model : models) { - if (CDIDebugModel.getPluginIdentifier().equals(model) || - ICBreakpoint.C_BREAKPOINTS_DEBUG_MODEL_ID.equals(model)) { - return true; - } - } - } else if (element instanceof IDebugElement) { - if (CDIDebugModel.getPluginIdentifier().equals(((IDebugElement)element).getModelIdentifier()) ) { - return true; - } - } - } + return true; + + IAdaptable element = DebugUITools.getPartDebugContext(view.getSite()); + if (element != null) { + IDebugModelProvider modelProvider = element.getAdapter(IDebugModelProvider.class); + if (modelProvider != null) { + String[] models = modelProvider.getModelIdentifiers(); + for (String model : models) { + if (CDIDebugModel.getPluginIdentifier().equals(model) + || ICBreakpoint.C_BREAKPOINTS_DEBUG_MODEL_ID.equals(model)) { + return true; + } + } + } else if (element instanceof IDebugElement) { + if (CDIDebugModel.getPluginIdentifier().equals(((IDebugElement) element).getModelIdentifier())) { + return true; + } + } + } } return false; } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyView.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyView.java index 56c1a2becfe..6136cd69129 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyView.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyView.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Patrick Chuong (Texas Instruments) - Bug fix (326670) @@ -32,7 +32,7 @@ import org.eclipse.ui.texteditor.ITextEditorActionConstants; public class DisassemblyView extends DisassemblyPart implements IViewPart { /** - * + * */ public DisassemblyView() { super(); @@ -48,7 +48,7 @@ public class DisassemblyView extends DisassemblyPart implements IViewPart { */ @Override public IViewSite getViewSite() { - return (IViewSite)getSite(); + return (IViewSite) getSite(); } /* @@ -65,14 +65,14 @@ public class DisassemblyView extends DisassemblyPart implements IViewPart { @Override public void init(IViewSite site, IMemento memento) throws PartInitException { setSite(site); - if (memento != null) { - Boolean trackExpression = memento.getBoolean(DisassemblyPreferenceConstants.TRACK_EXPRESSION); - if (trackExpression != null) - fTrackExpression = trackExpression; - Boolean syncContext = memento.getBoolean(DisassemblyPreferenceConstants.SYNC_ACTIVE_CONTEXT); - if (syncContext != null) - fSynchWithActiveDebugContext = syncContext; - } + if (memento != null) { + Boolean trackExpression = memento.getBoolean(DisassemblyPreferenceConstants.TRACK_EXPRESSION); + if (trackExpression != null) + fTrackExpression = trackExpression; + Boolean syncContext = memento.getBoolean(DisassemblyPreferenceConstants.SYNC_ACTIVE_CONTEXT); + if (syncContext != null) + fSynchWithActiveDebugContext = syncContext; + } } /* @@ -93,18 +93,18 @@ public class DisassemblyView extends DisassemblyPart implements IViewPart { protected void fillLocalPullDown(IMenuManager manager) { manager.add(fGlobalActions.get(ActionFactory.FIND.getId())); - manager.add(new Separator("group.goto")); // ICommonMenuConstants.GROUP_GOTO //$NON-NLS-1$ + manager.add(new Separator("group.goto")); // ICommonMenuConstants.GROUP_GOTO //$NON-NLS-1$ manager.add(fActionGotoPC); manager.add(fActionGotoAddress); - manager.add(new Separator("group.show")); // ICommonMenuConstants.GROUP_SHOW //$NON-NLS-1$ - manager.add(fSyncAction); + manager.add(new Separator("group.show")); // ICommonMenuConstants.GROUP_SHOW //$NON-NLS-1$ + manager.add(fSyncAction); manager.add(fTrackExpressionAction); - manager.add(new Separator(ITextEditorActionConstants.GROUP_SETTINGS)); - manager.add(fActionToggleSource); - manager.add(fActionToggleSymbols); - manager.add(fActionOpenPreferences); - // Other plug-ins can contribute their actions here - manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); + manager.add(new Separator(ITextEditorActionConstants.GROUP_SETTINGS)); + manager.add(fActionToggleSource); + manager.add(fActionToggleSymbols); + manager.add(fActionOpenPreferences); + // Other plug-ins can contribute their actions here + manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } @Override diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyViewerConfiguration.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyViewerConfiguration.java index 6d67cd94002..dbbf0ac7ffa 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyViewerConfiguration.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyViewerConfiguration.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -55,8 +55,8 @@ public class DisassemblyViewerConfiguration extends TextSourceViewerConfiguratio */ @Override public IRegion getDamageRegion(ITypedRegion partition, DocumentEvent e, boolean documentPartitioningChanged) { - int start= e.fOffset; - int end= e.getOffset() + (e.getText() == null ? 0 : e.getText().length()); + int start = e.fOffset; + int end = e.getOffset() + (e.getText() == null ? 0 : e.getText().length()); return new Region(start, end - start); } @@ -71,7 +71,7 @@ public class DisassemblyViewerConfiguration extends TextSourceViewerConfiguratio } /** - * + * */ public DisassemblyViewerConfiguration(DisassemblyPart part) { super(EditorsUI.getPreferenceStore()); @@ -89,6 +89,7 @@ public class DisassemblyViewerConfiguration extends TextSourceViewerConfiguratio reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); return reconciler; } + /* * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getUndoManager(org.eclipse.jface.text.source.ISourceViewer) */ @@ -97,7 +98,7 @@ public class DisassemblyViewerConfiguration extends TextSourceViewerConfiguratio // no undo/redo return null; } - + /* * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getTextHover(org.eclipse.jface.text.source.ISourceViewer, java.lang.String) */ @@ -111,21 +112,21 @@ public class DisassemblyViewerConfiguration extends TextSourceViewerConfiguratio */ @Override public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) { - IHyperlinkDetector[] inheritedDetectors= super.getHyperlinkDetectors(sourceViewer); - + IHyperlinkDetector[] inheritedDetectors = super.getHyperlinkDetectors(sourceViewer); + if (fPart == null || inheritedDetectors == null) return inheritedDetectors; - - int inheritedDetectorsLength= inheritedDetectors.length; - IHyperlinkDetector[] detectors= new IHyperlinkDetector[inheritedDetectorsLength + 1]; - detectors[0]= new DisassemblyHyperlinkDetector(fPart); - for (int i= 0; i < inheritedDetectorsLength; i++) { - detectors[i+1]= inheritedDetectors[i]; + + int inheritedDetectorsLength = inheritedDetectors.length; + IHyperlinkDetector[] detectors = new IHyperlinkDetector[inheritedDetectorsLength + 1]; + detectors[0] = new DisassemblyHyperlinkDetector(fPart); + for (int i = 0; i < inheritedDetectorsLength; i++) { + detectors[i + 1] = inheritedDetectors[i]; } - + return detectors; } - + /* * @see org.eclipse.ui.editors.text.TextSourceViewerConfiguration#getReconciler(org.eclipse.jface.text.source.ISourceViewer) */ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/EditionFinderJob.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/EditionFinderJob.java index b40825d01d8..8874640a7d3 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/EditionFinderJob.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/EditionFinderJob.java @@ -40,7 +40,7 @@ class EditionFinderJob extends Job { /** * Create a new edition finder for a file resource and address. - * + * * @param sourceInfo the file info containing the file resource for which to find an edition * @param address address inside the module * @param disassemblyPart the disassembly part where this job originated from @@ -49,13 +49,13 @@ class EditionFinderJob extends Job { super(DisassemblyMessages.EditionFinderJob_name); Assert.isNotNull(sourceInfo); Assert.isLegal(sourceInfo.fFile instanceof IFile); - fSourceInfo= sourceInfo; - fFile = (IFile)sourceInfo.fFile; + fSourceInfo = sourceInfo; + fFile = (IFile) sourceInfo.fFile; fAddress = address; - fDisassemblyPart= disassemblyPart; + fDisassemblyPart = disassemblyPart; setRule(fFile); setSystem(true); - sourceInfo.fEditionJob= this; + sourceInfo.fEditionJob = this; } /* @@ -79,7 +79,7 @@ class EditionFinderJob extends Job { } monitor.worked(1); if (token instanceof Long && !monitor.isCanceled()) { - moduleTime = ((Long)token).longValue(); + moduleTime = ((Long) token).longValue(); long buildTime = moduleTime * 1000; if (fFile.getLocalTimeStamp() > buildTime) { monitor.subTask(DisassemblyMessages.EditionFinderJob_task_search_history); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/FunctionOffsetRulerColumn.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/FunctionOffsetRulerColumn.java index 9fac702c37e..1e314e637a3 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/FunctionOffsetRulerColumn.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/FunctionOffsetRulerColumn.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -29,7 +29,7 @@ public class FunctionOffsetRulerColumn extends DisassemblyRulerColumn { public static final String ID = "org.eclipse.cdt.dsf.ui.disassemblyColumn.functionOffset"; //$NON-NLS-1$ /** Maximum width of column (in characters) */ - private static final int MAXWIDTH= 20; + private static final int MAXWIDTH = 20; /** * Default constructor. @@ -44,13 +44,13 @@ public class FunctionOffsetRulerColumn extends DisassemblyRulerColumn { */ @Override protected String createDisplayString(int line) { - DisassemblyDocument doc = (DisassemblyDocument)getParentRuler().getTextViewer().getDocument(); + DisassemblyDocument doc = (DisassemblyDocument) getParentRuler().getTextViewer().getDocument(); int offset; try { offset = doc.getLineOffset(line); AddressRangePosition pos = doc.getDisassemblyPosition(offset); if (pos instanceof DisassemblyPosition && pos.length > 0 && pos.offset == offset && pos.fValid) { - DisassemblyPosition disassPos = (DisassemblyPosition)pos; + DisassemblyPosition disassPos = (DisassemblyPosition) pos; int length = disassPos.fFunction.length; if (length > MAXWIDTH) { return "..." + new String(disassPos.fFunction, length - MAXWIDTH + 3, MAXWIDTH - 3); //$NON-NLS-1$ @@ -67,13 +67,13 @@ public class FunctionOffsetRulerColumn extends DisassemblyRulerColumn { @Override protected int computeNumberOfCharacters() { - DisassemblyDocument doc = (DisassemblyDocument)getParentRuler().getTextViewer().getDocument(); + DisassemblyDocument doc = (DisassemblyDocument) getParentRuler().getTextViewer().getDocument(); return Math.min(MAXWIDTH, doc.getMaxFunctionLength()); } @Override public void propertyChange(PropertyChangeEvent event) { - String property = event.getProperty(); + String property = event.getProperty(); boolean needRedraw = false; if (DisassemblyPreferenceConstants.FUNCTION_OFFSETS_COLOR.equals(property)) { setForeground(getColor(property)); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/IDisassemblyHelpContextIds.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/IDisassemblyHelpContextIds.java index bffe1ec3058..92be62b550d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/IDisassemblyHelpContextIds.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/IDisassemblyHelpContextIds.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/OpcodeRulerColumn.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/OpcodeRulerColumn.java index d95cca8ebf0..a62c300e2d2 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/OpcodeRulerColumn.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/OpcodeRulerColumn.java @@ -30,7 +30,7 @@ public class OpcodeRulerColumn extends DisassemblyRulerColumn { public static final String ID = "org.eclipse.cdt.dsf.ui.disassemblyColumn.opcode"; //$NON-NLS-1$ /** Maximum width of column (in characters) */ - private static final int MAXWIDTH= 20; + private static final int MAXWIDTH = 20; private int fRadix; private String fRadixPrefix; @@ -45,7 +45,7 @@ public class OpcodeRulerColumn extends DisassemblyRulerColumn { } public void setRadix(int radix) { - fRadix= radix; + fRadix = radix; setShowRadixPrefix(); } @@ -66,26 +66,26 @@ public class OpcodeRulerColumn extends DisassemblyRulerColumn { protected String createDisplayString(int line) { int nChars = computeNumberOfCharacters(); if (nChars > 0) { - DisassemblyDocument doc = (DisassemblyDocument)getParentRuler().getTextViewer().getDocument(); + DisassemblyDocument doc = (DisassemblyDocument) getParentRuler().getTextViewer().getDocument(); try { int offset = doc.getLineOffset(line); AddressRangePosition pos = doc.getDisassemblyPosition(offset); if (pos instanceof DisassemblyPosition && pos.length > 0 && pos.offset == offset && pos.fValid) { - DisassemblyPosition disassPos = (DisassemblyPosition)pos; + DisassemblyPosition disassPos = (DisassemblyPosition) pos; if (disassPos.fOpcodes != null) { // Format the output. String str = disassPos.fOpcodes.toString(fRadix); int prefixLength = 0; - + if (fRadixPrefix != null) prefixLength = fRadixPrefix.length(); - + StringBuilder buf = new StringBuilder(nChars); - + if (prefixLength != 0) buf.append(fRadixPrefix); - - for (int i=str.length()+prefixLength; i < nChars; ++i) + + for (int i = str.length() + prefixLength; i < nChars; ++i) buf.append('0'); buf.append(str); if (buf.length() > nChars) @@ -104,13 +104,13 @@ public class OpcodeRulerColumn extends DisassemblyRulerColumn { @Override protected int computeNumberOfCharacters() { - DisassemblyDocument doc = (DisassemblyDocument)getParentRuler().getTextViewer().getDocument(); + DisassemblyDocument doc = (DisassemblyDocument) getParentRuler().getTextViewer().getDocument(); return Math.min(MAXWIDTH, doc.getMaxOpcodeLength(fRadix)); } @Override public void propertyChange(PropertyChangeEvent event) { - String property = event.getProperty(); + String property = event.getProperty(); IPreferenceStore store = getPreferenceStore(); boolean needRedraw = false; if (DisassemblyPreferenceConstants.CODE_BYTES_COLOR.equals(property)) { diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/SourceColorerJob.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/SourceColorerJob.java index 5e99d800703..e523f2412cc 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/SourceColorerJob.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/SourceColorerJob.java @@ -36,9 +36,9 @@ class SourceColorerJob extends UIJob implements Runnable { public SourceColorerJob(Display jobDisplay, IStorage storage, DisassemblyPart disassemblyPart) { super(DisassemblyMessages.SourceColorerJob_name); - fDisassemblyPart= disassemblyPart; - fViewer= disassemblyPart.getTextViewer(); - fDocument= (DisassemblyDocument) fViewer.getDocument(); + fDisassemblyPart = disassemblyPart; + fViewer = disassemblyPart.getTextViewer(); + fDocument = (DisassemblyDocument) fViewer.getDocument(); fStorage = storage; setDisplay(fDisassemblyPart.getSite().getShell().getDisplay()); setSystem(true); @@ -56,7 +56,7 @@ class SourceColorerJob extends UIJob implements Runnable { if (fi != null) { fi.initPresentationCreator(fViewer); if (fi.fError != null) { - String message= DisassemblyMessages.Disassembly_log_error_readFile + fi.fFileKey; + String message = DisassemblyMessages.Disassembly_log_error_readFile + fi.fFileKey; fDisassemblyPart.logWarning(message, fi.fError); } } @@ -71,8 +71,9 @@ class SourceColorerJob extends UIJob implements Runnable { */ @Override public void run() { - IWorkbenchSiteProgressService progressService = fDisassemblyPart.getSite().getAdapter(IWorkbenchSiteProgressService.class); - if(progressService != null) { + IWorkbenchSiteProgressService progressService = fDisassemblyPart.getSite() + .getAdapter(IWorkbenchSiteProgressService.class); + if (progressService != null) { progressService.schedule(this, 0, true); } else { schedule(); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/SourcePosition.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/SourcePosition.java index ba5eb30f818..289ba9d4508 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/SourcePosition.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/SourcePosition.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -27,20 +27,22 @@ public class SourcePosition extends AddressRangePosition { public int fLine; public int fLast = -1; - public SourcePosition(int offset, int length, BigInteger addressOffset, SourceFileInfo fileInfo, int line, int last) { + public SourcePosition(int offset, int length, BigInteger addressOffset, SourceFileInfo fileInfo, int line, + int last) { this(offset, length, addressOffset, fileInfo, line, last, true); } - public SourcePosition(int offset, int length, BigInteger addressOffset, SourceFileInfo fileInfo, int line, int last, boolean valid) { + public SourcePosition(int offset, int length, BigInteger addressOffset, SourceFileInfo fileInfo, int line, int last, + boolean valid) { super(offset, length, addressOffset, BigInteger.ZERO, valid); fFileInfo = fileInfo; fLine = line; fLast = last; } - + @Override public String toString() { - return super.toString() + "->["+fFileInfo.fFileKey + ':' + fLine + ']'; //$NON-NLS-1$ + return super.toString() + "->[" + fFileInfo.fFileKey + ':' + fLine + ']'; //$NON-NLS-1$ } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyAction.java index 4f3b8afa23b..5c92c047226 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyAction.java @@ -28,18 +28,18 @@ public abstract class AbstractDisassemblyAction extends Action implements IUpdat /** * Create a disassembly action. - * + * * @param disassemblyPart */ public AbstractDisassemblyAction(IDisassemblyPart disassemblyPart) { Assert.isLegal(disassemblyPart != null); - fDisassemblyPart= disassemblyPart; + fDisassemblyPart = disassemblyPart; fDisassemblyPart.addPropertyListener(this); } /** * Create a disassembly action. - * + * * @param disassemblyPart * @param style * one of <code>AS_PUSH_BUTTON</code>, @@ -50,18 +50,17 @@ public abstract class AbstractDisassemblyAction extends Action implements IUpdat public AbstractDisassemblyAction(IDisassemblyPart disassemblyPart, int style) { super(null, style); Assert.isLegal(disassemblyPart != null); - fDisassemblyPart= disassemblyPart; + fDisassemblyPart = disassemblyPart; fDisassemblyPart.addPropertyListener(this); } - /** * @return the disassembly part */ public final IDisassemblyPart getDisassemblyPart() { return fDisassemblyPart; } - + /* * @see org.eclipse.jface.action.Action#run() */ @@ -70,10 +69,10 @@ public abstract class AbstractDisassemblyAction extends Action implements IUpdat @Override public void update() { - boolean enabled= fDisassemblyPart == null || fDisassemblyPart.isConnected(); + boolean enabled = fDisassemblyPart == null || fDisassemblyPart.isConnected(); setEnabled(enabled); } - + /* * @see org.eclipse.ui.IPropertyListener#propertyChanged(java.lang.Object, int) */ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyBreakpointRulerAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyBreakpointRulerAction.java index fb961ef9428..63764b6526e 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyBreakpointRulerAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyBreakpointRulerAction.java @@ -34,7 +34,7 @@ public abstract class AbstractDisassemblyBreakpointRulerAction extends AbstractD /** * Create breakpoint ruler action. - * + * * @param disassemblyPart * @param rulerInfo */ @@ -45,7 +45,7 @@ public abstract class AbstractDisassemblyBreakpointRulerAction extends AbstractD /** * Returns the breakpoint at the last line of mouse activity in the ruler * or <code>null</code> if none. - * + * * @return breakpoint associated with activity in the ruler or <code>null</code> */ protected IBreakpoint getBreakpoint() { @@ -63,7 +63,8 @@ public abstract class AbstractDisassemblyBreakpointRulerAction extends AbstractD Position position = annotationModel.getPosition(markerAnnotation); int line = document.getLineOfOffset(position.getOffset()); if (line == getRulerInfo().getLineOfLastMouseButtonActivity()) { - IBreakpoint breakpoint = DebugPlugin.getDefault().getBreakpointManager().getBreakpoint(marker); + IBreakpoint breakpoint = DebugPlugin.getDefault().getBreakpointManager() + .getBreakpoint(marker); if (breakpoint != null) { return breakpoint; } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyRulerAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyRulerAction.java index f7d1ece3f7b..0de7b3881de 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyRulerAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyRulerAction.java @@ -26,18 +26,18 @@ public abstract class AbstractDisassemblyRulerAction extends AbstractDisassembly private final IVerticalRulerInfo fRulerInfo; protected AbstractDisassemblyRulerAction(IDisassemblyPart disassemblyPart, IVerticalRulerInfo rulerInfo) { - fDisassemblyPart= disassemblyPart; - fRulerInfo= rulerInfo; + fDisassemblyPart = disassemblyPart; + fRulerInfo = rulerInfo; } - + public final IVerticalRulerInfo getRulerInfo() { return fRulerInfo; } - + public final IDocument getDocument() { return getDisassemblyPart().getTextViewer().getDocument(); } - + public final IAnnotationModel getAnnotationModel() { return getDisassemblyPart().getTextViewer().getAnnotationModel(); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyRulerActionDelegate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyRulerActionDelegate.java index 48f2ece4c62..555cf32b4b6 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyRulerActionDelegate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AbstractDisassemblyRulerActionDelegate.java @@ -39,10 +39,11 @@ import org.eclipse.ui.texteditor.IUpdate; * adapter (inner) action on menu and mouse action on the vertical ruler.<p> * Extending classes must implement the factory method * <code>createAction(IDisassemblyPart, IVerticalRulerInfo)</code>. - * + * * @see org.eclipse.ui.texteditor.AbstractRulerActionDelegate */ -public abstract class AbstractDisassemblyRulerActionDelegate extends ActionDelegate implements IEditorActionDelegate, IViewActionDelegate, MouseListener, IMenuListener { +public abstract class AbstractDisassemblyRulerActionDelegate extends ActionDelegate + implements IEditorActionDelegate, IViewActionDelegate, MouseListener, IMenuListener { /** The disassembly part. */ private IDisassemblyPart fDisassemblyPart; @@ -68,24 +69,24 @@ public abstract class AbstractDisassemblyRulerActionDelegate extends ActionDeleg setTargetPart(callerAction, targetEditor); } - /* - * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart) - */ - @Override + /* + * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart) + */ + @Override public void init(IViewPart view) { - setTargetPart(fCallerAction, view); - } + setTargetPart(fCallerAction, view); + } @Override public void init(IAction action) { - fCallerAction= action; + fCallerAction = action; } private void setTargetPart(IAction callerAction, IWorkbenchPart targetPart) { if (fDisassemblyPart != null) { - IVerticalRulerInfo rulerInfo= fDisassemblyPart.getAdapter(IVerticalRulerInfo.class); + IVerticalRulerInfo rulerInfo = fDisassemblyPart.getAdapter(IVerticalRulerInfo.class); if (rulerInfo != null) { - Control control= rulerInfo.getControl(); + Control control = rulerInfo.getControl(); if (control != null && !control.isDisposed()) control.removeMouseListener(this); } @@ -93,19 +94,19 @@ public abstract class AbstractDisassemblyRulerActionDelegate extends ActionDeleg fDisassemblyPart.removeRulerContextMenuListener(this); } - fDisassemblyPart= targetPart == null ? null : targetPart.getAdapter(IDisassemblyPart.class); - fCallerAction= callerAction; - fAction= null; + fDisassemblyPart = targetPart == null ? null : targetPart.getAdapter(IDisassemblyPart.class); + fCallerAction = callerAction; + fAction = null; if (fDisassemblyPart != null) { - fDisassemblyPart.addRulerContextMenuListener(this); + fDisassemblyPart.addRulerContextMenuListener(this); - IVerticalRulerInfo rulerInfo= fDisassemblyPart.getAdapter(IVerticalRulerInfo.class); + IVerticalRulerInfo rulerInfo = fDisassemblyPart.getAdapter(IVerticalRulerInfo.class); if (rulerInfo != null) { - fAction= createAction(fDisassemblyPart, rulerInfo); + fAction = createAction(fDisassemblyPart, rulerInfo); update(); - Control control= rulerInfo.getControl(); + Control control = rulerInfo.getControl(); if (control != null && !control.isDisposed()) control.addMouseListener(this); } @@ -117,7 +118,7 @@ public abstract class AbstractDisassemblyRulerActionDelegate extends ActionDeleg if (fAction != null) fAction.run(); } - + @Override public void runWithEvent(IAction action, Event event) { if (fAction != null) diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/ActionGotoAddress.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/ActionGotoAddress.java index a4355d04870..109e89a7328 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/ActionGotoAddress.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/ActionGotoAddress.java @@ -30,10 +30,11 @@ public final class ActionGotoAddress extends AbstractDisassemblyAction { super(disassemblyPart); setText(DisassemblyMessages.Disassembly_action_GotoAddress_label); } + @Override public void run() { ITextViewer viewer = getDisassemblyPart().getTextViewer(); - IDocument document= viewer.getDocument(); + IDocument document = viewer.getDocument(); IRegion wordRegion = CWordFinder.findWord(document, viewer.getSelectedRange().x); String defaultValue = null; if (wordRegion != null) { @@ -51,7 +52,7 @@ public final class ActionGotoAddress extends AbstractDisassemblyAction { } String dlgTitle = DisassemblyMessages.Disassembly_GotoAddressDialog_title; String dlgLabel = DisassemblyMessages.Disassembly_GotoAddressDialog_label; - final Shell shell= getDisassemblyPart().getSite().getShell(); + final Shell shell = getDisassemblyPart().getSite().getShell(); InputDialog dlg = new InputDialog(shell, dlgTitle, dlgLabel, defaultValue, null); if (dlg.open() == IDialogConstants.OK_ID) { String value = dlg.getValue(); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/ActionGotoProgramCounter.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/ActionGotoProgramCounter.java index f68f962e63f..096653e0c92 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/ActionGotoProgramCounter.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/ActionGotoProgramCounter.java @@ -22,6 +22,7 @@ public final class ActionGotoProgramCounter extends AbstractDisassemblyAction { setText(DisassemblyMessages.Disassembly_action_GotoPC_label); setToolTipText(DisassemblyMessages.Disassembly_action_GotoPC_tooltip); } + @Override public void run() { getDisassemblyPart().gotoProgramCounter(); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/ActionOpenPreferences.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/ActionOpenPreferences.java index 6c98ba02274..018c7af3825 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/ActionOpenPreferences.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/ActionOpenPreferences.java @@ -21,10 +21,12 @@ import org.eclipse.ui.dialogs.PreferencesUtil; public final class ActionOpenPreferences extends Action { private final static String PREF_PAGE_ID = "org.eclipse.cdt.dsf.debug.ui.disassembly.preferencePage"; //$NON-NLS-1$ private final Shell fShell; + public ActionOpenPreferences(Shell shell) { - fShell= shell; + fShell = shell; setText(DisassemblyMessages.Disassembly_action_OpenPreferences_label); } + @Override public void run() { PreferencesUtil.createPreferenceDialogOn(fShell, PREF_PAGE_ID, new String[] { PREF_PAGE_ID }, null).open(); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AddBreakpointRulerAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AddBreakpointRulerAction.java index 3b6c35879db..989b352005b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AddBreakpointRulerAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AddBreakpointRulerAction.java @@ -41,101 +41,98 @@ import org.eclipse.ui.IWorkbenchPart; * Ruler action to add breakpoint with a dialog properties. */ public class AddBreakpointRulerAction extends AbstractDisassemblyBreakpointRulerAction { - - + protected AddBreakpointRulerAction(IDisassemblyPart disassemblyPart, IVerticalRulerInfo rulerInfo) { super(disassemblyPart, rulerInfo); - setText(DisassemblyMessages.Disassembly_action_AddBreakpoint_label + "\t" + //$NON-NLS-1$ - CDebugUIUtils.formatKeyBindingString(SWT.MOD1, DisassemblyMessages.Disassembly_action_ToggleBreakpoint_accelerator)); + setText(DisassemblyMessages.Disassembly_action_AddBreakpoint_label + "\t" + //$NON-NLS-1$ + CDebugUIUtils.formatKeyBindingString(SWT.MOD1, + DisassemblyMessages.Disassembly_action_ToggleBreakpoint_accelerator)); } - + /* * @see org.eclipse.cdt.dsf.debug.internal.ui.disassembly.actions.AbstractDisassemblyAction#run() */ @Override public void run() { - IWorkbenchPart part = getDisassemblyPart(); - ISelection selection = getSelection(); - IToggleBreakpointsTargetCExtension toggleTarget = getToggleTarget(selection); - if (toggleTarget != null) { - try { - if (toggleTarget.canCreateLineBreakpointsInteractive(part, selection)) { - toggleTarget.createLineBreakpointsInteractive(part, selection); - } - } catch (CoreException e) { - reportException(e); - } - } + IWorkbenchPart part = getDisassemblyPart(); + ISelection selection = getSelection(); + IToggleBreakpointsTargetCExtension toggleTarget = getToggleTarget(selection); + if (toggleTarget != null) { + try { + if (toggleTarget.canCreateLineBreakpointsInteractive(part, selection)) { + toggleTarget.createLineBreakpointsInteractive(part, selection); + } + } catch (CoreException e) { + reportException(e); + } + } } @Override public void update() { - IDisassemblyPart part = getDisassemblyPart(); - if (part != null && part.isConnected()) { - ISelection selection = getSelection(); - IToggleBreakpointsTargetCExtension toggleTarget = getToggleTarget(selection); - if (toggleTarget != null) { - setEnabled( toggleTarget.canCreateLineBreakpointsInteractive(part, selection) ); - return; - } - } - setEnabled(false); + IDisassemblyPart part = getDisassemblyPart(); + if (part != null && part.isConnected()) { + ISelection selection = getSelection(); + IToggleBreakpointsTargetCExtension toggleTarget = getToggleTarget(selection); + if (toggleTarget != null) { + setEnabled(toggleTarget.canCreateLineBreakpointsInteractive(part, selection)); + return; + } + } + setEnabled(false); } - + private IToggleBreakpointsTargetCExtension getToggleTarget(ISelection selection) { - IToggleBreakpointsTargetManager toggleMgr = DebugUITools.getToggleBreakpointsTargetManager(); - IToggleBreakpointsTarget toggleTarget = toggleMgr.getToggleBreakpointsTarget(getDisassemblyPart(), selection); - if (toggleTarget instanceof IToggleBreakpointsTargetCExtension) { - return (IToggleBreakpointsTargetCExtension)toggleTarget; - } - return null; + IToggleBreakpointsTargetManager toggleMgr = DebugUITools.getToggleBreakpointsTargetManager(); + IToggleBreakpointsTarget toggleTarget = toggleMgr.getToggleBreakpointsTarget(getDisassemblyPart(), selection); + if (toggleTarget instanceof IToggleBreakpointsTargetCExtension) { + return (IToggleBreakpointsTargetCExtension) toggleTarget; + } + return null; } - /** - * Report an error to the user. - * - * @param e underlying exception - */ - private void reportException(Exception e) { - IStatus status= new Status(IStatus.ERROR, CDebugUIPlugin.PLUGIN_ID, "Error creating breakpoint: ", e); //$NON-NLS-1$ - ErrorDialog.openError( - getDisassemblyPart().getSite().getShell(), - DisassemblyMessages.Disassembly_action_AddBreakpoint_errorTitle, - DisassemblyMessages.Disassembly_action_AddBreakpoint_errorMessage, - status); - CDebugUIPlugin.log(status); - } + /** + * Report an error to the user. + * + * @param e underlying exception + */ + private void reportException(Exception e) { + IStatus status = new Status(IStatus.ERROR, CDebugUIPlugin.PLUGIN_ID, "Error creating breakpoint: ", e); //$NON-NLS-1$ + ErrorDialog.openError(getDisassemblyPart().getSite().getShell(), + DisassemblyMessages.Disassembly_action_AddBreakpoint_errorTitle, + DisassemblyMessages.Disassembly_action_AddBreakpoint_errorMessage, status); + CDebugUIPlugin.log(status); + } /** - * Determines the text selection for the breakpoint action. If clicking on the ruler inside - * the highlighted text, return the text selection for the highlighted text. Otherwise, - * return a text selection representing the start of the line. - * - * @return An ISelection as described. - * @throws BadLocationException If underlying operations throw. - */ - private ISelection getSelection() { - IDocument document = getDocument(); - if (document != null) { - int line = getRulerInfo().getLineOfLastMouseButtonActivity(); - - try { - IRegion region = getDocument().getLineInformation(line); - ITextSelection textSelection = new TextSelection(document, region.getOffset(), 0); - ISelectionProvider provider = getDisassemblyPart().getSite().getSelectionProvider(); - if (provider != null){ - ISelection selection = provider.getSelection(); - if (selection instanceof ITextSelection - && ((ITextSelection) selection).getStartLine() <= line - && ((ITextSelection) selection).getEndLine() >= line) { - textSelection = (ITextSelection) selection; - } - } - return textSelection; - } catch (BadLocationException e) { - } - } - return StructuredSelection.EMPTY; - } + * Determines the text selection for the breakpoint action. If clicking on the ruler inside + * the highlighted text, return the text selection for the highlighted text. Otherwise, + * return a text selection representing the start of the line. + * + * @return An ISelection as described. + * @throws BadLocationException If underlying operations throw. + */ + private ISelection getSelection() { + IDocument document = getDocument(); + if (document != null) { + int line = getRulerInfo().getLineOfLastMouseButtonActivity(); + + try { + IRegion region = getDocument().getLineInformation(line); + ITextSelection textSelection = new TextSelection(document, region.getOffset(), 0); + ISelectionProvider provider = getDisassemblyPart().getSite().getSelectionProvider(); + if (provider != null) { + ISelection selection = provider.getSelection(); + if (selection instanceof ITextSelection && ((ITextSelection) selection).getStartLine() <= line + && ((ITextSelection) selection).getEndLine() >= line) { + textSelection = (ITextSelection) selection; + } + } + return textSelection; + } catch (BadLocationException e) { + } + } + return StructuredSelection.EMPTY; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AddressBarContributionItem.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AddressBarContributionItem.java index ec3d9c2a739..62659c39ac3 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AddressBarContributionItem.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AddressBarContributionItem.java @@ -57,7 +57,7 @@ public class AddressBarContributionItem extends ContributionItem { /** * Use this constructor to create an AddressBarContributionItem. - * + * * @param action * a contribution action. */ @@ -68,7 +68,7 @@ public class AddressBarContributionItem extends ContributionItem { /** * After constructing this object, call this method to create an address * box. - * + * * @param parent * a ToolBar object. Can be obtain with the getControl() method * in the ToolBarManager class. @@ -81,8 +81,7 @@ public class AddressBarContributionItem extends ContributionItem { * the tooltip of the warning label if it ever becomes visible. * May be null. */ - public void createAddressBox(ToolBar parent, int width, String initialText, - String warningText) { + public void createAddressBox(ToolBar parent, int width, String initialText, String warningText) { this.width = width; this.initialText = initialText; this.lastText = initialText; @@ -108,8 +107,8 @@ public class AddressBarContributionItem extends ContributionItem { Control box = internalCreateAddressBox(parent); item.setControl(box); item.setWidth(width); - - enableAddressBox(action.isEnabled()); + + enableAddressBox(action.isEnabled()); } /** @@ -122,7 +121,7 @@ public class AddressBarContributionItem extends ContributionItem { /** * Get the address bar text - * + * * @return The text in the address bar. */ public String getText() { @@ -135,7 +134,7 @@ public class AddressBarContributionItem extends ContributionItem { /** * Set the visibility of the warning icon. Should be set to true when there * is a problem jumping to the specified address; false otherwise - * + * * @param visible * True for visible, false for hidden. */ @@ -147,7 +146,7 @@ public class AddressBarContributionItem extends ContributionItem { /** * Return whether the warning icon is visible or not. - * + * * @return True if visible, otherwise false. */ public boolean isWarningIconVisible() { @@ -158,7 +157,7 @@ public class AddressBarContributionItem extends ContributionItem { /** * Enable the address combo box. - * + * * @param enable * true to enable, else false. */ @@ -171,7 +170,7 @@ public class AddressBarContributionItem extends ContributionItem { /** * Creates the combo box and add it to the toolbar. - * + * * @param parent * the parent, toolbar. * @return the combo box address control. @@ -186,9 +185,8 @@ public class AddressBarContributionItem extends ContributionItem { warningLabel = new Label(top, SWT.NONE); - warningImage = AbstractUIPlugin - .imageDescriptorFromPlugin( - DsfUIPlugin.PLUGIN_ID, "icons/address_warning.gif").createImage(); //$NON-NLS-1$ + warningImage = AbstractUIPlugin.imageDescriptorFromPlugin(DsfUIPlugin.PLUGIN_ID, "icons/address_warning.gif") //$NON-NLS-1$ + .createImage(); warningLabel.setImage(warningImage); warningLabel.setToolTipText(warningText); setWarningIconVisible(false); @@ -209,27 +207,21 @@ public class AddressBarContributionItem extends ContributionItem { @Override public void keyReleased(KeyEvent e) { - if (e.stateMask == SWT.CTRL - && (((char) e.keyCode) == 'c' || ((char) e.keyCode) == 'C')) { + if (e.stateMask == SWT.CTRL && (((char) e.keyCode) == 'c' || ((char) e.keyCode) == 'C')) { String selection = null; Point selectionPoint = addressBox.getSelection(); if (selectionPoint.x == selectionPoint.y) return; - selection = addressBox.getText().substring( - selectionPoint.x, selectionPoint.y); + selection = addressBox.getText().substring(selectionPoint.x, selectionPoint.y); - if ((selection != null) - && (!(selection.trim().length() == 0))) { + if ((selection != null) && (!(selection.trim().length() == 0))) { Clipboard clipboard = null; try { - clipboard = new Clipboard(addressBox - .getDisplay()); - clipboard.setContents( - new Object[] { selection }, - new Transfer[] { TextTransfer - .getInstance() }); + clipboard = new Clipboard(addressBox.getDisplay()); + clipboard.setContents(new Object[] { selection }, + new Transfer[] { TextTransfer.getInstance() }); } finally { if (clipboard != null) clipboard.dispose(); @@ -243,12 +235,12 @@ public class AddressBarContributionItem extends ContributionItem { @Override public void focusGained(FocusEvent e) { // [nmehregani] bugzilla 297387: 'Home' shouldn't jump to PC address when focus is on location combo box - if (action instanceof JumpToAddressAction) - ((JumpToAddressAction)action).deactivateDisassemblyContext(); + if (action instanceof JumpToAddressAction) + ((JumpToAddressAction) action).deactivateDisassemblyContext(); // end 297387 - + lastText = addressBox.getText(); - + // Erase the guide text when the focus is gained. if (lastText.trim().equals(initialText)) addressBox.setText(""); //$NON-NLS-1$ @@ -260,10 +252,10 @@ public class AddressBarContributionItem extends ContributionItem { @Override public void focusLost(FocusEvent e) { // [nmehregani] bugzilla 297387: 'Home' shouldn't jump to PC address when focus is on location combo box - if (action instanceof JumpToAddressAction) - ((JumpToAddressAction)action).activateDisassemblyContext(); + if (action instanceof JumpToAddressAction) + ((JumpToAddressAction) action).activateDisassemblyContext(); // end 297387 - + // Re-insert the last text when the focus is lost and the text // field is empty. if (addressBox.getText().trim().length() == 0) @@ -298,8 +290,7 @@ public class AddressBarContributionItem extends ContributionItem { } } - if ((!bExist) && (addressBox.getText() != null) - && (!(addressBox.getText().trim().length() == 0))) + if ((!bExist) && (addressBox.getText() != null) && (!(addressBox.getText().trim().length() == 0))) addressBox.add(addressBox.getText()); } } @@ -319,8 +310,7 @@ public class AddressBarContributionItem extends ContributionItem { } }); - addressBox.setLayoutData(new GridData(GridData.FILL, - GridData.BEGINNING, true, false)); + addressBox.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false)); return top; } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/BreakpointPropertiesRulerAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/BreakpointPropertiesRulerAction.java index 3add572606b..b56893ec7a7 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/BreakpointPropertiesRulerAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/BreakpointPropertiesRulerAction.java @@ -34,48 +34,64 @@ import org.eclipse.ui.IWorkbenchPart; * Ruler action to display breakpoint properties. */ public class BreakpointPropertiesRulerAction extends AbstractDisassemblyBreakpointRulerAction { - - + private ICBreakpoint fBreakpoint; protected BreakpointPropertiesRulerAction(IDisassemblyPart disassemblyPart, IVerticalRulerInfo rulerInfo) { super(disassemblyPart, rulerInfo); - setText(DisassemblyMessages.Disassembly_action_BreakpointProperties_label + "\t" + //$NON-NLS-1$ - CDebugUIUtils.formatKeyBindingString(SWT.MOD1, DisassemblyMessages.Disassembly_action_ToggleBreakpoint_accelerator)); + setText(DisassemblyMessages.Disassembly_action_BreakpointProperties_label + "\t" + //$NON-NLS-1$ + CDebugUIUtils.formatKeyBindingString(SWT.MOD1, + DisassemblyMessages.Disassembly_action_ToggleBreakpoint_accelerator)); } - + /* * @see org.eclipse.cdt.dsf.debug.internal.ui.disassembly.actions.AbstractDisassemblyAction#run() */ @Override public void run() { - if ( fBreakpoint != null ) { - final ISelection debugContext = getDebugContext(); - - CBreakpointPropertyDialogAction propertiesAction = new CBreakpointPropertyDialogAction( - getDisassemblyPart().getSite(), - new ISelectionProvider() { - @Override - public ISelection getSelection() { - return new StructuredSelection( fBreakpoint ); - } - @Override public void addSelectionChangedListener( ISelectionChangedListener listener ) {} - @Override public void removeSelectionChangedListener( ISelectionChangedListener listener ) {} - @Override public void setSelection( ISelection selection ) {} - }, - new IDebugContextProvider() { - @Override - public ISelection getActiveContext() { - return debugContext; - } - @Override public void addDebugContextListener(IDebugContextListener listener) {} - @Override public void removeDebugContextListener(IDebugContextListener listener) {} - @Override public IWorkbenchPart getPart() { return null; } - - } - ); - propertiesAction.run(); - propertiesAction.dispose(); + if (fBreakpoint != null) { + final ISelection debugContext = getDebugContext(); + + CBreakpointPropertyDialogAction propertiesAction = new CBreakpointPropertyDialogAction( + getDisassemblyPart().getSite(), new ISelectionProvider() { + @Override + public ISelection getSelection() { + return new StructuredSelection(fBreakpoint); + } + + @Override + public void addSelectionChangedListener(ISelectionChangedListener listener) { + } + + @Override + public void removeSelectionChangedListener(ISelectionChangedListener listener) { + } + + @Override + public void setSelection(ISelection selection) { + } + }, new IDebugContextProvider() { + @Override + public ISelection getActiveContext() { + return debugContext; + } + + @Override + public void addDebugContextListener(IDebugContextListener listener) { + } + + @Override + public void removeDebugContextListener(IDebugContextListener listener) { + } + + @Override + public IWorkbenchPart getPart() { + return null; + } + + }); + propertiesAction.run(); + propertiesAction.dispose(); } } @@ -84,18 +100,19 @@ public class BreakpointPropertiesRulerAction extends AbstractDisassemblyBreakpoi */ @Override public void update() { - IBreakpoint breakpoint= getBreakpoint(); - - if (breakpoint instanceof ICBreakpoint) { - fBreakpoint = (ICBreakpoint)breakpoint; - } else { - fBreakpoint = null; - } - setEnabled( fBreakpoint != null ); + IBreakpoint breakpoint = getBreakpoint(); + + if (breakpoint instanceof ICBreakpoint) { + fBreakpoint = (ICBreakpoint) breakpoint; + } else { + fBreakpoint = null; + } + setEnabled(fBreakpoint != null); } - + private ISelection getDebugContext() { - return DebugUITools.getDebugContextManager().getContextService(getDisassemblyPart().getSite().getWorkbenchWindow()).getActiveContext(); + return DebugUITools.getDebugContextManager() + .getContextService(getDisassemblyPart().getSite().getWorkbenchWindow()).getActiveContext(); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/JumpToAddressAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/JumpToAddressAction.java index 376a7adedad..c878e5e0a9e 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/JumpToAddressAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/JumpToAddressAction.java @@ -25,41 +25,41 @@ import org.eclipse.jface.action.Action; public class JumpToAddressAction extends Action { DisassemblyPart fDisassemblyPart = null; - + public JumpToAddressAction(DisassemblyPart disassemblyPart) { fDisassemblyPart = disassemblyPart; } - + @Override - public void run() { + public void run() { AddressBarContributionItem addressBar = fDisassemblyPart.getAddressBar(); - if (addressBar!=null && addressBar.isEnabled() && fDisassemblyPart.isSuspended()) { - String locationTxt = addressBar.getText(); - - if (locationTxt==null || locationTxt.trim().length()==0) - return; - - locationTxt = locationTxt.trim(); - - if (locationTxt.equals(DisassemblyMessages.Disassembly_GotoLocation_initial_text)) { - fDisassemblyPart.gotoActiveFrameByUser(); - return; - } + if (addressBar != null && addressBar.isEnabled() && fDisassemblyPart.isSuspended()) { + String locationTxt = addressBar.getText(); + + if (locationTxt == null || locationTxt.trim().length() == 0) + return; + + locationTxt = locationTxt.trim(); - BigInteger address = fDisassemblyPart.eval(locationTxt, false); + if (locationTxt.equals(DisassemblyMessages.Disassembly_GotoLocation_initial_text)) { + fDisassemblyPart.gotoActiveFrameByUser(); + return; + } + + BigInteger address = fDisassemblyPart.eval(locationTxt, false); if (address.compareTo(BigInteger.ZERO) < 0) { addressBar.setWarningIconVisible(true); - } else { + } else { fDisassemblyPart.gotoLocationByUser(address, locationTxt); addressBar.setWarningIconVisible(false); } - } + } } - + protected void activateDisassemblyContext() { - fDisassemblyPart.activateDisassemblyContext(); + fDisassemblyPart.activateDisassemblyContext(); } - + protected void deactivateDisassemblyContext() { fDisassemblyPart.deactivateDisassemblyContext(); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/RulerToggleBreakpointActionDelegate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/RulerToggleBreakpointActionDelegate.java index 6de5b847e9b..6874ffbe364 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/RulerToggleBreakpointActionDelegate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/RulerToggleBreakpointActionDelegate.java @@ -22,7 +22,7 @@ import org.eclipse.jface.text.source.IVerticalRulerInfo; * Ruler toggle breakpoint action delegate for disassembly parts. * * @since 2.1 - * + * * @see org.eclipse.debug.ui.actions.RulerToggleBreakpointActionDelegate */ public class RulerToggleBreakpointActionDelegate extends AbstractDisassemblyRulerActionDelegate { @@ -37,7 +37,8 @@ public class RulerToggleBreakpointActionDelegate extends AbstractDisassemblyRule if (fDelegate != null) { fDelegate.dispose(); } - return fDelegate = new ToggleBreakpointAction(disassemblyPart, disassemblyPart.getTextViewer().getDocument(), rulerInfo); + return fDelegate = new ToggleBreakpointAction(disassemblyPart, disassemblyPart.getTextViewer().getDocument(), + rulerInfo); } /* diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/RulerToggleBreakpointHandler.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/RulerToggleBreakpointHandler.java index b6dffe9b653..b57218784e2 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/RulerToggleBreakpointHandler.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/RulerToggleBreakpointHandler.java @@ -27,7 +27,7 @@ import org.eclipse.ui.handlers.HandlerUtil; /** * Default handler for the toggle breakpoint command in the disassembly ruler. * Invoked on double click in the ruler. - * + * * @since 2.1 */ public class RulerToggleBreakpointHandler extends AbstractHandler { @@ -38,20 +38,20 @@ public class RulerToggleBreakpointHandler extends AbstractHandler { if (part instanceof IDisassemblyPart) { IDisassemblyPart disassemblyPart = (IDisassemblyPart) part; IDocument document = disassemblyPart.getTextViewer().getDocument(); - final IVerticalRulerInfo rulerInfo= part.getAdapter(IVerticalRulerInfo.class); + final IVerticalRulerInfo rulerInfo = part.getAdapter(IVerticalRulerInfo.class); if (rulerInfo != null) { - final ToggleBreakpointAction toggleBpAction= new ToggleBreakpointAction(part, document, rulerInfo); + final ToggleBreakpointAction toggleBpAction = new ToggleBreakpointAction(part, document, rulerInfo); try { toggleBpAction.update(); if (toggleBpAction.isEnabled()) { - if (event.getTrigger() instanceof Event) { - // Pass through the event that triggered the action. - // This will give toggle action access to key modifiers - // (shift, ctrl, etc.) - toggleBpAction.runWithEvent((Event)event.getTrigger()); - } else { - toggleBpAction.run(); - } + if (event.getTrigger() instanceof Event) { + // Pass through the event that triggered the action. + // This will give toggle action access to key modifiers + // (shift, ctrl, etc.) + toggleBpAction.runWithEvent((Event) event.getTrigger()); + } else { + toggleBpAction.run(); + } } } finally { toggleBpAction.dispose(); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/TextOperationAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/TextOperationAction.java index ed34714299e..7ec162af4e0 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/TextOperationAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/TextOperationAction.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -22,41 +22,42 @@ import org.eclipse.ui.texteditor.IUpdate; * TextOperationAction */ public class TextOperationAction extends Action implements IUpdate { - - private int fOperationCode= -1; - private ITextOperationTarget fOperationTarget; - - public TextOperationAction(ITextViewer viewer, int operationCode) { - fOperationCode= operationCode; - fOperationTarget= viewer.getTextOperationTarget(); - update(); - } - - /** - * Updates the enabled state of the action. - * Fires a property change if the enabled state changes. - * - * @see Action#firePropertyChange(String, Object, Object) - */ - @Override - public void update() { - - boolean wasEnabled= isEnabled(); - boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode)); - setEnabled(isEnabled); - - if (wasEnabled != isEnabled) { - firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, isEnabled ? Boolean.TRUE : Boolean.FALSE); - } + + private int fOperationCode = -1; + private ITextOperationTarget fOperationTarget; + + public TextOperationAction(ITextViewer viewer, int operationCode) { + fOperationCode = operationCode; + fOperationTarget = viewer.getTextOperationTarget(); + update(); + } + + /** + * Updates the enabled state of the action. + * Fires a property change if the enabled state changes. + * + * @see Action#firePropertyChange(String, Object, Object) + */ + @Override + public void update() { + + boolean wasEnabled = isEnabled(); + boolean isEnabled = (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode)); + setEnabled(isEnabled); + + if (wasEnabled != isEnabled) { + firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, + isEnabled ? Boolean.TRUE : Boolean.FALSE); } - - /** - * @see Action#run() - */ - @Override - public void run() { - if (fOperationCode != -1 && fOperationTarget != null) { - fOperationTarget.doOperation(fOperationCode); - } + } + + /** + * @see Action#run() + */ + @Override + public void run() { + if (fOperationCode != -1 && fOperationTarget != null) { + fOperationTarget.doOperation(fOperationCode); } } +} diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/Addr2Line.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/Addr2Line.java index 3a47d09b619..92148529438 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/Addr2Line.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/Addr2Line.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -15,14 +15,13 @@ package org.eclipse.cdt.dsf.debug.internal.ui.disassembly.model; import java.math.BigInteger; - public class Addr2Line { - public BigInteger addr; - public Addr2Line next; - public int first; - public int last; - - public static int hash(BigInteger addr, int size) { - return (int)((addr.shiftRight(2).longValue()) % size); - } + public BigInteger addr; + public Addr2Line next; + public int first; + public int last; + + public static int hash(BigInteger addr, int size) { + return (int) ((addr.shiftRight(2).longValue()) % size); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/BreakpointsAnnotationModel.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/BreakpointsAnnotationModel.java index f39a55a3595..d4e56201573 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/BreakpointsAnnotationModel.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/BreakpointsAnnotationModel.java @@ -49,20 +49,21 @@ import org.eclipse.ui.texteditor.SimpleMarkerAnnotation; * Annotation model for breakpoints in the disassembly. * Works only with {@link DisassemblyDocument}. */ -public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel implements IBreakpointListener, IDocumentListener { - +public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel + implements IBreakpointListener, IDocumentListener { + private Runnable fCatchup; private IAdaptable fDebugContext; - + public BreakpointsAnnotationModel(IAdaptable debugContext) { fDebugContext = debugContext; } - + @Override public void connect(IDocument document) { super.connect(document); if (document instanceof DisassemblyDocument) { - final IBreakpointManager bpMgr= DebugPlugin.getDefault().getBreakpointManager(); + final IBreakpointManager bpMgr = DebugPlugin.getDefault().getBreakpointManager(); addBreakpoints(bpMgr.getBreakpoints()); bpMgr.addBreakpointListener(this); document.addDocumentListener(this); @@ -72,17 +73,17 @@ public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel imple @Override public void disconnect(IDocument document) { if (document instanceof DisassemblyDocument) { - final IBreakpointManager bpMgr= DebugPlugin.getDefault().getBreakpointManager(); + final IBreakpointManager bpMgr = DebugPlugin.getDefault().getBreakpointManager(); bpMgr.removeBreakpointListener(this); document.removeDocumentListener(this); - fCatchup= null; + fCatchup = null; } super.disconnect(document); } private void catchupWithBreakpoints() { removeAllAnnotations(false); - final IBreakpointManager bpMgr= DebugPlugin.getDefault().getBreakpointManager(); + final IBreakpointManager bpMgr = DebugPlugin.getDefault().getBreakpointManager(); addBreakpoints(bpMgr.getBreakpoints()); } @@ -106,10 +107,10 @@ public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel imple */ @Override public void breakpointChanged(IBreakpoint breakpoint, IMarkerDelta delta) { - Annotation a= findAnnotation(breakpoint.getMarker()); + Annotation a = findAnnotation(breakpoint.getMarker()); if (a != null) { if (a instanceof SimpleMarkerAnnotation) { - ((SimpleMarkerAnnotation)a).update(); + ((SimpleMarkerAnnotation) a).update(); } synchronized (getLockObject()) { getAnnotationModelEvent().annotationChanged(a); @@ -125,15 +126,15 @@ public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel imple */ @Override public void breakpointRemoved(IBreakpoint breakpoint, IMarkerDelta delta) { - Annotation a= findAnnotation(breakpoint.getMarker()); + Annotation a = findAnnotation(breakpoint.getMarker()); if (a != null) { removeAnnotation(a, true); } } private Annotation findAnnotation(IMarker marker) { - for (Iterator<Annotation> it= getAnnotationIterator(false); it.hasNext();) { - SimpleMarkerAnnotation a= (SimpleMarkerAnnotation) it.next(); + for (Iterator<Annotation> it = getAnnotationIterator(false); it.hasNext();) { + SimpleMarkerAnnotation a = (SimpleMarkerAnnotation) it.next(); if (a.getMarker().equals(marker)) { return a; } @@ -145,7 +146,7 @@ public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel imple if (fDocument == null) { return; } - final IMarker marker= breakpoint.getMarker(); + final IMarker marker = breakpoint.getMarker(); if (marker == null) { return; } @@ -160,10 +161,10 @@ public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel imple // ignore wrong positions } } - + private Position createPositionFromBreakpoint(IBreakpoint breakpoint) throws CoreException { IBreakpointLocationProvider locationProvider = breakpoint.getAdapter(IBreakpointLocationProvider.class); - + /* if there is a location provider, than use the provider to retrieve the location */ if (locationProvider != null) { @@ -172,20 +173,20 @@ public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel imple if (sourceFile != null) { int lineNumber = locationProvider.getLineNumber(breakpoint, fDebugContext) - 1; return createPositionFromSourceLine(sourceFile, lineNumber); - + } else { /* if there is label info, than create a label position */ IAddress labelAddress = locationProvider.getLabelAddress(breakpoint, fDebugContext); if (labelAddress != null) { return createPositionFromLabel(labelAddress.getValue()); - - /* Otherwise, create an address position */ + + /* Otherwise, create an address position */ } else { // See bug 300053 comment 5: - // Since there can only be one annotation per marker and in order to support multiple + // Since there can only be one annotation per marker and in order to support multiple // annotations per breakpoint, we need a specialized annotation type. // - // So for now, we only create an annotation for the first valid address. We can add + // So for now, we only create an annotation for the first valid address. We can add // support for multiple annotations per breakpoint when it's needed. IAddress[] addresses = locationProvider.getAddresses(breakpoint, fDebugContext); for (int i = 0; addresses != null && i < addresses.length; ++i) { @@ -196,31 +197,31 @@ public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel imple } } } - - /* otherwise, use legacy ICBreakpoint location info */ + + /* otherwise, use legacy ICBreakpoint location info */ } else { if (breakpoint instanceof ICAddressBreakpoint) { - ICAddressBreakpoint addressBreakpoint= (ICAddressBreakpoint) breakpoint; + ICAddressBreakpoint addressBreakpoint = (ICAddressBreakpoint) breakpoint; return createPositionFromAddress(decodeAddress(addressBreakpoint.getAddress())); } else if (breakpoint instanceof ILineBreakpoint) { - ILineBreakpoint lineBreakpoint= (ILineBreakpoint) breakpoint; - Position position= null; - final int lineNumber= lineBreakpoint.getLineNumber() - 1; - final IMarker marker= breakpoint.getMarker(); + ILineBreakpoint lineBreakpoint = (ILineBreakpoint) breakpoint; + Position position = null; + final int lineNumber = lineBreakpoint.getLineNumber() - 1; + final IMarker marker = breakpoint.getMarker(); if (marker.getResource().getType() == IResource.FILE) { - position= createPositionFromSourceLine((IFile) marker.getResource(), lineNumber); + position = createPositionFromSourceLine((IFile) marker.getResource(), lineNumber); if (position != null) { return position; } } - String fileName= marker.getAttribute(ICLineBreakpoint.SOURCE_HANDLE, null); - position= createPositionFromSourceLine(fileName, lineNumber); + String fileName = marker.getAttribute(ICLineBreakpoint.SOURCE_HANDLE, null); + position = createPositionFromSourceLine(fileName, lineNumber); if (position == null && breakpoint instanceof ICLineBreakpoint) { - ICLineBreakpoint cBreakpoint= (ICLineBreakpoint) breakpoint; + ICLineBreakpoint cBreakpoint = (ICLineBreakpoint) breakpoint; if (breakpoint instanceof ICFunctionBreakpoint) { - position= createPositionFromLabel(cBreakpoint.getFunction()); + position = createPositionFromLabel(cBreakpoint.getFunction()); } else { - position= createPositionFromAddress(decodeAddress(cBreakpoint.getAddress())); + position = createPositionFromAddress(decodeAddress(cBreakpoint.getAddress())); } } return position; @@ -232,7 +233,7 @@ public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel imple /** * Decode given string representation of a non-negative integer. A * hexadecimal encoded integer is expected to start with <code>0x</code>. - * + * * @param string * decimal or hexadecimal representation of an non-negative integer * @return address value as <code>BigInteger</code> or <code>null</code> in case of a <code>NumberFormatException</code> @@ -266,14 +267,15 @@ public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel imple @Override public void documentChanged(DocumentEvent event) { if (fCatchup == null && event.fText != null && !event.fText.isEmpty()) { - fCatchup= new Runnable() { + fCatchup = new Runnable() { @Override public void run() { if (fCatchup == this) { catchupWithBreakpoints(); - fCatchup= null; + fCatchup = null; } - }}; + } + }; Display.getCurrent().timerExec(50, fCatchup); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/DisassemblyDocument.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/DisassemblyDocument.java index f6d6376bdca..ce851ee11c9 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/DisassemblyDocument.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/DisassemblyDocument.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Patrick Chuong (Texas Instruments) - Bug 315443 @@ -69,7 +69,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu * manipulate the list. This list should be accessed only from the GUI thread */ private final List<SourcePosition> fInvalidSource = new ArrayList<SourcePosition>(); - + private final Map<IStorage, SourceFileInfo> fFileInfoMap = new HashMap<IStorage, SourceFileInfo>(); private int fMaxFunctionLength = 0; @@ -116,7 +116,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu assert isGuiThread(); super.dispose(); - + // cleanup source info for (Iterator<SourceFileInfo> iter = fFileInfoMap.values().iterator(); iter.hasNext();) { SourceFileInfo fi = iter.next(); @@ -136,7 +136,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu setLineTracker(new DefaultLineTracker()); completeInitialization(); } - + public AddressRangePosition[] getInvalidAddressRanges() { assert isGuiThread(); return fInvalidAddressRanges.toArray(new AddressRangePosition[fInvalidAddressRanges.size()]); @@ -150,35 +150,35 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu return fMaxFunctionLength; } - public void setMaxOpcodeLength(BigInteger longOpcode ) { + public void setMaxOpcodeLength(BigInteger longOpcode) { fMaxOpcodeLength = longOpcode; } - public int getMaxOpcodeLength(int radix ) { + public int getMaxOpcodeLength(int radix) { int retVal = 0; if (fMaxOpcodeLength != null) { String str = fMaxOpcodeLength.toString(radix); retVal = str.length(); switch (radix) { - case 8: - retVal += 1; // Padded for 0 prefix - break; - case 16: - retVal += 2; // Padded for 0x prefix - break; - default: - break; + case 8: + retVal += 1; // Padded for 0 prefix + break; + case 16: + retVal += 2; // Padded for 0x prefix + break; + default: + break; } } return retVal; } public int getAddressLength() { - return fNumberOfDigits+2; + return fNumberOfDigits + 2; } public int getMeanSizeOfInstructions() { - return (int)(fMeanSizeOfInstructions+.9); + return (int) (fMeanSizeOfInstructions + .9); } public Iterator<Position> getModelPositionIterator(BigInteger address) { @@ -199,7 +199,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu return positions.listIterator(idx); } - public Iterator<Position> getPositionIterator(String category, BigInteger address) throws BadPositionCategoryException { + public Iterator<Position> getPositionIterator(String category, BigInteger address) + throws BadPositionCategoryException { List<Position> positions = getDocumentManagedPositions().get(category); if (positions == null) { throw new BadPositionCategoryException(); @@ -220,11 +221,11 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu * Computes the index in the list of positions at which a position with the * given address would be inserted. The position is supposed to become the * first in this list of all positions with the same offset. - * + * * @param positions the list in which the index is computed * @param address the address for which the index is computed * @return the computed index - * + * */ protected int computeIndexInPositionListFirst(List<Position> positions, BigInteger address) { int size = positions.size(); @@ -236,7 +237,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu int mid = 0; while (low < high) { mid = (low + high) >>> 1; - AddressRangePosition range = (AddressRangePosition)positions.get(mid); + AddressRangePosition range = (AddressRangePosition) positions.get(mid); int compareSign = address.compareTo(range.fAddressOffset); if (compareSign < 0) { high = mid; @@ -250,14 +251,14 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu } int idx = mid; - AddressRangePosition p = (AddressRangePosition)positions.get(idx); + AddressRangePosition p = (AddressRangePosition) positions.get(idx); if (address.compareTo(p.fAddressOffset) == 0) { do { --idx; if (idx < 0) { break; } - p = (AddressRangePosition)positions.get(idx); + p = (AddressRangePosition) positions.get(idx); } while (address.compareTo(p.fAddressOffset) == 0); ++idx; } else if (address.compareTo(p.fAddressOffset.add(p.fAddressLength)) >= 0) { @@ -270,11 +271,11 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu * Computes the index in the list of positions at which a position with the * given address would be inserted. The position is supposed to become the * last but one in this list of all positions with the same address. - * + * * @param positions the list in which the index is computed * @param address the address for which the index is computed * @return the computed index - * + * */ protected int computeIndexInPositionListLast(List<Position> positions, BigInteger address) { int size = positions.size(); @@ -319,11 +320,11 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu * Computes the index in the list of positions at which a position with the * given offset would be inserted. The position is supposed to become the * last in this list of all positions with the same offset. - * + * * @param positions the list in which the index is computed * @param offset the offset for which the index is computed * @return the computed index - * + * * @see IDocument#computeIndexInCategory(String, int) * @deprecated Use {@link #computeIndexInPositionListLast(List, BigInteger)} * as it is for managing lists of AddressRangePositions @@ -376,7 +377,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu /** * Returns the position for the supplied category and index. - * + * * @param category * @param index * @return a Position matching the category and index, or <code>null</code>. @@ -441,7 +442,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu /** * Compute the address of the given document line number. - * + * * @param line * @return the address of the given document line number, -1 if no valid * address can be computed @@ -459,7 +460,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu /** * Compute the address off the given document offset. - * + * * @param offset * @return the address of the given document offset, -1 if no valid address * can be computed @@ -501,7 +502,6 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu return getPositionOfAddress(CATEGORY_DISASSEMBLY, address); } - /** * @param offset * @return @@ -558,34 +558,34 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu /** * Compute document position of the given source line. - * + * * @param file the file as an <code>IStorage</code> * @param lineNumber the 0-based line number * @return the document position or <code>null</code> */ public Position getSourcePosition(IStorage file, int lineNumber) { - SourceFileInfo info= getSourceInfo(file); + SourceFileInfo info = getSourceInfo(file); return getSourcePosition(info, lineNumber); } /** * Compute document position of the given source line. - * + * * @param fileName the file name, may be a raw debugger path or the path to an external file * @param lineNumber the 0-based line number * @return the document position or <code>null</code> */ public Position getSourcePosition(String fileName, int lineNumber) { - SourceFileInfo info= getSourceInfo(fileName); + SourceFileInfo info = getSourceInfo(fileName); if (info == null) { - info= getSourceInfo(new LocalFileStorage(new File(fileName))); + info = getSourceInfo(new LocalFileStorage(new File(fileName))); } return getSourcePosition(info, lineNumber); } - + /** * Compute document position of the given source line. - * + * * @param info * @param lineNumber the 0-based line number * @return the document position or <code>null</code> @@ -595,8 +595,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu return null; } try { - SourcePosition srcPos= null; - IRegion stmtLineRegion= info.fSource.getLineInformation(lineNumber); + SourcePosition srcPos = null; + IRegion stmtLineRegion = info.fSource.getLineInformation(lineNumber); final int lineOffset = stmtLineRegion.getOffset(); final int lineLength = stmtLineRegion.getLength() + 1; BigInteger stmtAddress = info.fLine2Addr[lineNumber]; @@ -604,12 +604,12 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu srcPos = getSourcePosition(stmtAddress); } if (srcPos == null) { - for (Iterator<Position> iterator = getPositionIterator(CATEGORY_SOURCE, 0); iterator.hasNext(); ) { - SourcePosition pos= (SourcePosition) iterator.next(); + for (Iterator<Position> iterator = getPositionIterator(CATEGORY_SOURCE, 0); iterator.hasNext();) { + SourcePosition pos = (SourcePosition) iterator.next(); if (pos.fFileInfo == info && pos.fValid && lineNumber >= pos.fLine) { - int baseOffset= info.fSource.getLineOffset(pos.fLine); + int baseOffset = info.fSource.getLineOffset(pos.fLine); if (lineOffset + lineLength - baseOffset <= pos.length) { - srcPos= pos; + srcPos = pos; break; } } @@ -634,7 +634,6 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu return null; } - /** * @param category * @param offset @@ -642,7 +641,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu * @throws BadPositionCategoryException * @throws BadLocationException */ - public Position getPosition(String category, int offset, boolean allowZeroLength) throws BadLocationException, BadPositionCategoryException { + public Position getPosition(String category, int offset, boolean allowZeroLength) + throws BadLocationException, BadPositionCategoryException { List<Position> list = getDocumentManagedPositions().get(category); int idx; idx = computeIndexInPositionList(list, offset, true); @@ -701,7 +701,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu // cannot happen } if (pos instanceof DisassemblyPosition) { - DisassemblyPosition disassPos = (DisassemblyPosition)pos; + DisassemblyPosition disassPos = (DisassemblyPosition) pos; int functionLength = disassPos.fFunction.length; if (functionLength > fMaxFunctionLength) { fMaxFunctionLength = functionLength; @@ -712,7 +712,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu } } if (fNumberOfInstructions < 100 && fMeanSizeOfInstructions < 16.0) { - fMeanSizeOfInstructions = (fMeanSizeOfInstructions * fNumberOfInstructions + pos.fAddressLength.floatValue()) / (++fNumberOfInstructions); + fMeanSizeOfInstructions = (fMeanSizeOfInstructions * fNumberOfInstructions + + pos.fAddressLength.floatValue()) / (++fNumberOfInstructions); } } } @@ -726,7 +727,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu if (list == null) { throw new BadPositionCategoryException(); } - if (DEBUG) System.out.println("Adding position to category <" + category + "> : " + pos); //$NON-NLS-1$ //$NON-NLS-2$ + if (DEBUG) + System.out.println("Adding position to category <" + category + "> : " + pos); //$NON-NLS-1$ //$NON-NLS-2$ list.add(computeIndexInPositionListLast(list, pos.fAddressOffset), pos); } @@ -807,8 +809,9 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu public void removePosition(String category, Position position) throws BadPositionCategoryException { super.removePosition(category, position); - if (DEBUG && isOneOfOurs(category)) System.out.println("Removing position from category(" + category + ") :" + position); //$NON-NLS-1$ //$NON-NLS-2$ - + if (DEBUG && isOneOfOurs(category)) + System.out.println("Removing position from category(" + category + ") :" + position); //$NON-NLS-1$ //$NON-NLS-2$ + if (!category.equals(CATEGORY_MODEL) && position instanceof AddressRangePosition) { super.removePosition(CATEGORY_MODEL, position); } @@ -818,15 +821,15 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu if (toRemove.isEmpty()) { return; } - - if (DEBUG && isOneOfOurs(category)) { + + if (DEBUG && isOneOfOurs(category)) { System.out.println("Removing positions from category(" + category + ')'); //$NON-NLS-1$ int i = 0; for (AddressRangePosition pos : toRemove) { - System.out.println("[" + i++ +"] " + pos); //$NON-NLS-1$ //$NON-NLS-2$ + System.out.println("[" + i++ + "] " + pos); //$NON-NLS-1$ //$NON-NLS-2$ } } - + List<Position> positions = getDocumentManagedPositions().get(category); if (positions != null) { positions.removeAll(toRemove); @@ -844,8 +847,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu * instead as DissemblyDocument's lists are AddressRangePositions */ @Deprecated - public void addPositionLast(String category, Position position) throws BadLocationException, - BadPositionCategoryException { + public void addPositionLast(String category, Position position) + throws BadLocationException, BadPositionCategoryException { if ((0 > position.offset) || (0 > position.length) || (position.offset + position.length > getLength())) throw new BadLocationException(); @@ -907,7 +910,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu pos.offset += delta; } } - + if (DEBUG) { String escapedText = null; if (text != null) { @@ -915,7 +918,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu escapedText = escapedText.replace(new StringBuilder("\r"), new StringBuilder("\\r")); //$NON-NLS-1$ //$NON-NLS-2$ escapedText = escapedText.replace(new StringBuilder("\t"), new StringBuilder("\\t")); //$NON-NLS-1$ //$NON-NLS-2$ } - System.out.println("Calling AbstractDocument.replace("+insertPos.offset+','+replaceLength+",\""+escapedText+"\")"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ + System.out.println("Calling AbstractDocument.replace(" + insertPos.offset + ',' + replaceLength + ",\"" //$NON-NLS-1$//$NON-NLS-2$ + + escapedText + "\")"); //$NON-NLS-1$ } super.replace(insertPos.offset, replaceLength, text); } @@ -927,24 +931,26 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu * @throws BadPositionCategoryException * @throws BadLocationException */ - public AddressRangePosition insertAddressRange(AddressRangePosition pos, AddressRangePosition insertPos, String line, boolean addToModel) - throws BadLocationException { - assert isGuiThread(); + public AddressRangePosition insertAddressRange(AddressRangePosition pos, AddressRangePosition insertPos, + String line, boolean addToModel) throws BadLocationException { + assert isGuiThread(); final BigInteger address = insertPos.fAddressOffset; BigInteger length = insertPos.fAddressLength; if (pos == null) { pos = getPositionOfAddress(address); } - assert !pos.isDeleted && !pos.fValid && (length.compareTo(BigInteger.ZERO) == 0 || pos.containsAddress(address)); + assert !pos.isDeleted && !pos.fValid + && (length.compareTo(BigInteger.ZERO) == 0 || pos.containsAddress(address)); int insertOffset; int replaceLength = 0; - if (length.compareTo(BigInteger.ONE) > 0 && !pos.containsAddress(address.add(length.subtract(BigInteger.ONE)))) { + if (length.compareTo(BigInteger.ONE) > 0 + && !pos.containsAddress(address.add(length.subtract(BigInteger.ONE)))) { // merge with successor positions Iterator<Position> it = getModelPositionIterator(pos.fAddressOffset.add(pos.fAddressLength)); assert it.hasNext(); do { AddressRangePosition overlap = (AddressRangePosition) it.next(); - BigInteger posEndAddress= pos.fAddressOffset.add(pos.fAddressLength); + BigInteger posEndAddress = pos.fAddressOffset.add(pos.fAddressLength); assert pos.offset <= overlap.offset && overlap.fAddressOffset.compareTo(posEndAddress) == 0; if (overlap instanceof LabelPosition || overlap instanceof SourcePosition) { // don't override label or source positions, instead fix @@ -959,7 +965,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu if (!overlap.fValid) { removeInvalidAddressRange(overlap); } - } while(!pos.containsAddress(address.add(length.subtract(BigInteger.ONE)))); + } while (!pos.containsAddress(address.add(length.subtract(BigInteger.ONE)))); } BigInteger newEndAddress = pos.fAddressOffset.add(pos.fAddressLength); BigInteger newStartAddress = address.add(length); @@ -987,9 +993,10 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu pos = null; } if (newEndAddress.compareTo(newStartAddress) > 0) { - pos = insertInvalidAddressRange(insertOffset+replaceLength, 0, newStartAddress, newEndAddress); + pos = insertInvalidAddressRange(insertOffset + replaceLength, 0, newStartAddress, newEndAddress); } - assert pos == null || pos.fAddressLength.compareTo(BigInteger.ZERO) > 0 && pos.containsAddress(address.add(length)); + assert pos == null + || pos.fAddressLength.compareTo(BigInteger.ZERO) > 0 && pos.containsAddress(address.add(length)); assert insertOffset + replaceLength <= getLength(); insertPos.offset = insertOffset; @@ -997,7 +1004,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu addModelPosition(insertPos); } replace(insertPos, replaceLength, line); - if (DEBUG) checkConsistency(); + if (DEBUG) + checkConsistency(); return pos; } @@ -1005,17 +1013,18 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyDocument#insertDisassemblyLine(org.eclipse.cdt.debug.internal.ui.disassembly.dsf.AddressRangePosition, java.math.BigInteger, int, java.lang.String, java.lang.String, java.lang.String, int) */ @Override - public AddressRangePosition insertDisassemblyLine(AddressRangePosition pos, BigInteger address, int length, String functionOffset, String instruction, String file, int lineNr) - throws BadLocationException { + public AddressRangePosition insertDisassemblyLine(AddressRangePosition pos, BigInteger address, int length, + String functionOffset, String instruction, String file, int lineNr) throws BadLocationException { return insertDisassemblyLine(pos, address, length, functionOffset, null, instruction, file, lineNr); } - + /* (non-Javadoc) * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyDocument#insertDisassemblyLine(org.eclipse.cdt.debug.internal.ui.disassembly.dsf.AddressRangePosition, java.math.BigInteger, int, java.lang.String, java.lang.String, java.lang.String, int) */ @Override - public AddressRangePosition insertDisassemblyLine(AddressRangePosition pos, BigInteger address, int length, String functionOffset, BigInteger opcode, String instruction, String file, int lineNr) - throws BadLocationException { + public AddressRangePosition insertDisassemblyLine(AddressRangePosition pos, BigInteger address, int length, + String functionOffset, BigInteger opcode, String instruction, String file, int lineNr) + throws BadLocationException { assert isGuiThread(); String disassLine = null; if (instruction == null || instruction.length() == 0) { @@ -1025,7 +1034,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu } AddressRangePosition disassPos; if (lineNr < 0) { - disassPos = new DisassemblyPosition(0, disassLine.length(), address, BigInteger.valueOf(length), functionOffset, opcode); + disassPos = new DisassemblyPosition(0, disassLine.length(), address, BigInteger.valueOf(length), + functionOffset, opcode); } else { disassPos = new DisassemblyWithSourcePosition(0, disassLine.length(), address, BigInteger.valueOf(length), functionOffset, opcode, file, lineNr); @@ -1033,7 +1043,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu pos = insertAddressRange(pos, disassPos, disassLine, true); addDisassemblyPosition(disassPos); return pos; - } + } + /** * @param address * @param functionOffset @@ -1046,7 +1057,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu buf.append(fRadixPrefix); } String str = address.toString(fRadix); - for (int i=str.length(); i<fNumberOfDigits; ++i) + for (int i = str.length(); i < fNumberOfDigits; ++i) buf.append('0'); buf.append(str); buf.append(':'); @@ -1071,10 +1082,10 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu for (int j = 0; j < n; j++) { char ch = instruction.charAt(j); if (ch == '\t') { - int tab = (buf.length()-prefixLen + 8) & ~0x7; + int tab = (buf.length() - prefixLen + 8) & ~0x7; do buf.append(' '); - while (buf.length()-prefixLen < tab); + while (buf.length() - prefixLen < tab); } else { buf.append(ch); } @@ -1085,7 +1096,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu public void setRadix(int radix) { fRadix = radix; - fNumberOfDigits = (int)(Math.log(1L<<32)/Math.log(radix)+0.9); + fNumberOfDigits = (int) (Math.log(1L << 32) / Math.log(radix) + 0.9); setShowRadixPrefix(fShowRadixPrefix); } @@ -1102,20 +1113,21 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu } } - public AddressRangePosition insertErrorLine(AddressRangePosition pos, BigInteger address, BigInteger length, String line) - throws BadLocationException { + public AddressRangePosition insertErrorLine(AddressRangePosition pos, BigInteger address, BigInteger length, + String line) throws BadLocationException { assert isGuiThread(); int hashCode = line.hashCode(); final long alignment = fErrorAlignment; if (alignment > 1 && !(pos instanceof ErrorPosition)) { AddressRangePosition before = getPositionOfAddress(address.subtract(BigInteger.ONE)); - if (before instanceof ErrorPosition && before.hashCode() == hashCode && before.offset + before.length == pos.offset) { + if (before instanceof ErrorPosition && before.hashCode() == hashCode + && before.offset + before.length == pos.offset) { assert before.fAddressOffset.add(before.fAddressLength).compareTo(address) == 0; assert pos.fAddressOffset.compareTo(address) == 0; // merge with previous error position - BigInteger pageOffset = before.fAddressOffset.and(BigInteger.valueOf(~(alignment-1))); + BigInteger pageOffset = before.fAddressOffset.and(BigInteger.valueOf(~(alignment - 1))); BigInteger mergeLen = pageOffset.add(BigInteger.valueOf(alignment)) - .subtract((before.fAddressOffset.add(before.fAddressLength))).min(length); + .subtract((before.fAddressOffset.add(before.fAddressLength))).min(length); if (mergeLen.compareTo(BigInteger.ZERO) > 0) { pos.fAddressLength = pos.fAddressLength.subtract(mergeLen); if (pos.fAddressLength.compareTo(BigInteger.ZERO) == 0) { @@ -1129,18 +1141,20 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu before.fAddressLength = before.fAddressLength.add(mergeLen); address = address.add(mergeLen); length = length.subtract(mergeLen); - if (DEBUG) checkConsistency(); + if (DEBUG) + checkConsistency(); if (length.compareTo(BigInteger.ZERO) == 0) { return pos; } } } AddressRangePosition after = getPositionOfAddress(address.add(length)); - if (after instanceof ErrorPosition && after.hashCode() == hashCode && pos != null && pos.offset + pos.length == after.offset) { + if (after instanceof ErrorPosition && after.hashCode() == hashCode && pos != null + && pos.offset + pos.length == after.offset) { assert after.fAddressOffset == address.add(length); assert pos.fAddressOffset.add(pos.fAddressLength).compareTo(after.fAddressOffset) == 0; // merge with next error position - BigInteger pageOffset = after.fAddressOffset.add(BigInteger.valueOf(~(alignment-1))); + BigInteger pageOffset = after.fAddressOffset.add(BigInteger.valueOf(~(alignment - 1))); BigInteger mergeLen = after.fAddressOffset.subtract(pageOffset).min(length); if (mergeLen.compareTo(BigInteger.ZERO) > 0) { after.fAddressOffset = after.fAddressOffset.subtract(mergeLen); @@ -1152,7 +1166,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu removeInvalidAddressRange(pos); pos = null; } - if (DEBUG) checkConsistency(); + if (DEBUG) + checkConsistency(); length = length.subtract(mergeLen); if (length.compareTo(BigInteger.ZERO) == 0) { return pos; @@ -1160,7 +1175,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu } } } - BigInteger pageOffset = address.and(BigInteger.valueOf(~(alignment-1))); + BigInteger pageOffset = address.and(BigInteger.valueOf(~(alignment - 1))); BigInteger posLen = pageOffset.add(BigInteger.valueOf(alignment)).subtract(address).min(length); while (length.compareTo(BigInteger.ZERO) > 0) { AddressRangePosition errorPos = new ErrorPosition(0, 0, address, posLen, hashCode); @@ -1182,8 +1197,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu * @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyDocument#insertLabel(org.eclipse.cdt.debug.internal.ui.disassembly.dsf.AddressRangePosition, java.math.BigInteger, java.lang.String, boolean) */ @Override - public AddressRangePosition insertLabel(AddressRangePosition pos, BigInteger address, String label, boolean showLabels) - throws BadLocationException { + public AddressRangePosition insertLabel(AddressRangePosition pos, BigInteger address, String label, + boolean showLabels) throws BadLocationException { assert isGuiThread(); String labelLine = showLabels ? label + ":\n" : ""; //$NON-NLS-1$ //$NON-NLS-2$ LabelPosition labelPos = getLabelPosition(address); @@ -1212,8 +1227,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu * @throws BadPositionCategoryException */ public SourcePosition insertSource(SourcePosition pos, String source, int line, boolean endOfSource) { -// System.out.println("insertSource at "+getAddressText(pos.fAddressOffset)); -// System.out.println(source); + // System.out.println("insertSource at "+getAddressText(pos.fAddressOffset)); + // System.out.println(source); String sourceLines = source; if (!source.isEmpty() && sourceLines.charAt(source.length() - 1) != '\n') { sourceLines += "\n"; //$NON-NLS-1$ @@ -1228,9 +1243,10 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu replace(pos, oldLength, sourceLines); if (!endOfSource) { if (pos.length > 0) { - SourcePosition oldPos = getSourcePosition(pos.offset+pos.length); + SourcePosition oldPos = getSourcePosition(pos.offset + pos.length); if (oldPos == null || oldPos.fAddressOffset.compareTo(pos.fAddressOffset) != 0) { - pos = new SourcePosition(pos.offset+pos.length, 0, pos.fAddressOffset, pos.fFileInfo, line, pos.fLast, false); + pos = new SourcePosition(pos.offset + pos.length, 0, pos.fAddressOffset, pos.fFileInfo, line, + pos.fLast, false); addSourcePosition(pos); addModelPosition(pos); addInvalidSourcePositions(pos); @@ -1246,15 +1262,16 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu return pos; } - /** + /** * @param pos * @param address * @param fi * @param firstLine - * @param lastLine + * @param lastLine * @return */ - public AddressRangePosition insertInvalidSource(AddressRangePosition pos, BigInteger address, SourceFileInfo fi, int firstLine, int lastLine) { + public AddressRangePosition insertInvalidSource(AddressRangePosition pos, BigInteger address, SourceFileInfo fi, + int firstLine, int lastLine) { assert isGuiThread(); SourcePosition sourcePos = getSourcePosition(address); if (sourcePos != null) { @@ -1280,11 +1297,12 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu * @param endAddress * @return */ - public AddressRangePosition insertInvalidAddressRange(int offset, int replaceLength, BigInteger startAddress, BigInteger endAddress) { + public AddressRangePosition insertInvalidAddressRange(int offset, int replaceLength, BigInteger startAddress, + BigInteger endAddress) { assert isGuiThread(); String periods = "...\n"; //$NON-NLS-1$ - AddressRangePosition newPos = new AddressRangePosition(offset, periods.length(), startAddress, endAddress - .subtract(startAddress), false); + AddressRangePosition newPos = new AddressRangePosition(offset, periods.length(), startAddress, + endAddress.subtract(startAddress), false); try { addModelPositionFirst(newPos); replace(newPos, replaceLength, periods); @@ -1299,8 +1317,9 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu public void invalidateAddressRange(BigInteger startAddress, BigInteger endAddress, boolean collapse) { deleteDisassemblyRange(startAddress, endAddress, true, collapse); } - - public void deleteDisassemblyRange(BigInteger startAddress, BigInteger endAddress, boolean invalidate, boolean collapse) { + + public void deleteDisassemblyRange(BigInteger startAddress, BigInteger endAddress, boolean invalidate, + boolean collapse) { assert isGuiThread(); DocumentRewriteSession session = startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL); try { @@ -1329,9 +1348,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu pos = null; } else if (pos instanceof DisassemblyPosition) { // optimization: join adjacent positions - if (collapse && lastPos != null - && (invalidate || lastPos.fValid == pos.fValid) - && lastPos.offset+lastPos.length == pos.offset) { + if (collapse && lastPos != null && (invalidate || lastPos.fValid == pos.fValid) + && lastPos.offset + lastPos.length == pos.offset) { assert lastPos.fAddressOffset.add(lastPos.fAddressLength).compareTo(pos.fAddressOffset) == 0; lastPos.length += pos.length; lastPos.fAddressLength = lastPos.fAddressLength.add(pos.fAddressLength); @@ -1372,7 +1390,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu } finally { stopRewriteSession(session); } - if (DEBUG) checkConsistency(); + if (DEBUG) + checkConsistency(); } public void invalidateSource() { @@ -1385,7 +1404,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu return; } while (it.hasNext()) { - SourcePosition srcPos = (SourcePosition)it.next(); + SourcePosition srcPos = (SourcePosition) it.next(); if (srcPos != null && srcPos.fValid) { srcPos.fValid = false; assert !fInvalidSource.contains(srcPos); @@ -1393,7 +1412,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu } } } - + public SourcePosition[] getInvalidSourcePositions() { assert isGuiThread(); return fInvalidSource.toArray(new SourcePosition[fInvalidSource.size()]); @@ -1401,26 +1420,29 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu public boolean addInvalidSourcePositions(SourcePosition srcPos) { assert isGuiThread(); - if (DEBUG) System.out.println("Adding invalid source position to list: " + srcPos); //$NON-NLS-1$ + if (DEBUG) + System.out.println("Adding invalid source position to list: " + srcPos); //$NON-NLS-1$ return fInvalidSource.add(srcPos); } public boolean removeInvalidSourcePosition(SourcePosition srcPos) { assert isGuiThread(); - if (DEBUG) System.out.println("Removing invalid source position from list: " + srcPos); //$NON-NLS-1$ + if (DEBUG) + System.out.println("Removing invalid source position from list: " + srcPos); //$NON-NLS-1$ return fInvalidSource.remove(srcPos); } - + public boolean hasInvalidSourcePositions() { assert isGuiThread(); - return !fInvalidSource.isEmpty(); + return !fInvalidSource.isEmpty(); } public void invalidateDisassemblyWithSource(boolean removeDisassembly) { for (Iterator<SourceFileInfo> it = fFileInfoMap.values().iterator(); it.hasNext();) { SourceFileInfo info = it.next(); if (info.fLine2Addr != null) { - deleteDisassemblyRange(info.fStartAddress, info.fEndAddress.add(BigInteger.ONE), !removeDisassembly, !removeDisassembly); + deleteDisassemblyRange(info.fStartAddress, info.fEndAddress.add(BigInteger.ONE), !removeDisassembly, + !removeDisassembly); } } } @@ -1459,12 +1481,13 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu toRemove.add(p); if (!p.fValid) { if (p instanceof SourcePosition) { - removeInvalidSourcePosition((SourcePosition)p); + removeInvalidSourcePosition((SourcePosition) p); } else { removeInvalidAddressRange(p); } } - if (addressLength.compareTo(BigInteger.ZERO) > 0 && p.fAddressOffset.compareTo(endPos.fAddressOffset) >= 0) { + if (addressLength.compareTo(BigInteger.ZERO) > 0 + && p.fAddressOffset.compareTo(endPos.fAddressOffset) >= 0) { break; } } @@ -1483,7 +1506,7 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu public SourceFileInfo getSourceInfo(BigInteger address) { AddressRangePosition pos = getDisassemblyPosition(address); if (pos instanceof DisassemblyPosition) { - DisassemblyPosition disassPos = (DisassemblyPosition)pos; + DisassemblyPosition disassPos = (DisassemblyPosition) pos; return getSourceInfo(disassPos.getFile()); } return null; @@ -1543,7 +1566,8 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu @Override public void addInvalidAddressRange(AddressRangePosition pos) { assert isGuiThread(); - if (DEBUG) System.out.println("Adding to invalid range list: " + pos); //$NON-NLS-1$ + if (DEBUG) + System.out.println("Adding to invalid range list: " + pos); //$NON-NLS-1$ fInvalidAddressRanges.add(pos); } @@ -1557,19 +1581,18 @@ public class DisassemblyDocument extends REDDocument implements IDisassemblyDocu } public void removeInvalidAddressRange(AddressRangePosition pos) { - assert isGuiThread(); - if (DEBUG) System.out.println("Removing from invalid range list: " + pos); //$NON-NLS-1$ + assert isGuiThread(); + if (DEBUG) + System.out.println("Removing from invalid range list: " + pos); //$NON-NLS-1$ fInvalidAddressRanges.remove(pos); } - + private static boolean isGuiThread() { return Display.getCurrent() != null; } - + private static boolean isOneOfOurs(String category) { - return category.equals(CATEGORY_MODEL) || - category.equals(CATEGORY_DISASSEMBLY) || - category.equals(CATEGORY_LABELS) || - category.equals(CATEGORY_SOURCE); + return category.equals(CATEGORY_MODEL) || category.equals(CATEGORY_DISASSEMBLY) + || category.equals(CATEGORY_LABELS) || category.equals(CATEGORY_SOURCE); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/DisassemblyWithSourcePosition.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/DisassemblyWithSourcePosition.java index 8c2a38c3d8b..a4ce9b845d7 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/DisassemblyWithSourcePosition.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/DisassemblyWithSourcePosition.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -31,9 +31,10 @@ public class DisassemblyWithSourcePosition extends DisassemblyPosition { * @param addressOffset * @param addressLength * @param functionOffset - * @param opcode + * @param opcode */ - public DisassemblyWithSourcePosition(int offset, int length, BigInteger addressOffset, BigInteger addressLength, String functionOffset, BigInteger opcode, String file, int lineNr) { + public DisassemblyWithSourcePosition(int offset, int length, BigInteger addressOffset, BigInteger addressLength, + String functionOffset, BigInteger opcode, String file, int lineNr) { super(offset, length, addressOffset, addressLength, functionOffset, opcode); fFile = file; fLine = lineNr; @@ -54,7 +55,7 @@ public class DisassemblyWithSourcePosition extends DisassemblyPosition { */ @Override public String toString() { - return super.toString() + "->["+fFile + ':' + fLine + ']'; //$NON-NLS-1$ + return super.toString() + "->[" + fFile + ':' + fLine + ']'; //$NON-NLS-1$ } - + } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceDocumentProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceDocumentProvider.java index d7d0f8441ed..b6a4d7c7c7f 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceDocumentProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceDocumentProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -43,7 +43,7 @@ public class SourceDocumentProvider extends StorageDocumentProvider { */ public void dispose() { Iterator<?> it = getConnectedElements(); - while(it.hasNext()) { + while (it.hasNext()) { Object element = it.next(); ElementInfo info = getElementInfo(element); // force refcount to 1 @@ -88,7 +88,7 @@ public class SourceDocumentProvider extends StorageDocumentProvider { super.disposeElementInfo(element, info); IDocument doc = info.fDocument; if (doc instanceof REDDocument) { - ((REDDocument)doc).dispose(); + ((REDDocument) doc).dispose(); } } @@ -99,16 +99,16 @@ public class SourceDocumentProvider extends StorageDocumentProvider { public long getModificationStamp(Object element) { try { if (element instanceof IStorageEditorInput) { - IStorage file= ((IStorageEditorInput)element).getStorage(); + IStorage file = ((IStorageEditorInput) element).getStorage(); if (file instanceof IFile) { - return ((IFile)file).getLocalTimeStamp(); + return ((IFile) file).getLocalTimeStamp(); } else if (file instanceof IFileState) { - return ((IFileState)file).getModificationTime(); + return ((IFileState) file).getModificationTime(); } else if (file instanceof LocalFileStorage) { - return ((LocalFileStorage)file).getFile().lastModified(); + return ((LocalFileStorage) file).getFile().lastModified(); } } else if (element instanceof IURIEditorInput) { - return EFS.getStore(((IURIEditorInput)element).getURI()).fetchInfo().getLastModified(); + return EFS.getStore(((IURIEditorInput) element).getURI()).fetchInfo().getLastModified(); } } catch (CoreException e) { // ignore diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceEditorInput.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceEditorInput.java index daa13011d24..5f9bd965f26 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceEditorInput.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceEditorInput.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceFileInfo.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceFileInfo.java index 1821df52c36..67b544ec318 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceFileInfo.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceFileInfo.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -40,7 +40,7 @@ import org.eclipse.ui.IEditorInput; */ public class SourceFileInfo { public final String fFileKey; - public final IStorage fFile; // fEdition is subject to change; this records value given to us at construction + public final IStorage fFile; // fEdition is subject to change; this records value given to us at construction public IStorage fEdition; public BigInteger[] fLine2Addr; public Addr2Line[] fAddr2Line; @@ -52,7 +52,7 @@ public class SourceFileInfo { public volatile Job fEditionJob; public ISourcePresentationCreator fPresentationCreator; public BigInteger fStartAddress = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE); - public BigInteger fEndAddress= BigInteger.ZERO; + public BigInteger fEndAddress = BigInteger.ZERO; public SourceFileInfo(String fileKey, IStorage file) { fFileKey = fileKey; @@ -84,19 +84,19 @@ public class SourceFileInfo { IEditorInput input = new SourceEditorInput(fEdition); IDocument doc = provider.getDocument(input); if (doc != null) { - IContentType contentType= null; + IContentType contentType = null; if (fEdition instanceof IFile) { - IFile file= (IFile)fEdition; - contentType= CCorePlugin.getContentType(file.getProject(), file.getName()); + IFile file = (IFile) fEdition; + contentType = CCorePlugin.getContentType(file.getProject(), file.getName()); } else { - contentType= CCorePlugin.getContentType(fEdition.getName()); + contentType = CCorePlugin.getContentType(fEdition.getName()); } - ILanguage language= null; + ILanguage language = null; if (contentType != null) { - language= LanguageManager.getInstance().getLanguage(contentType); + language = LanguageManager.getInstance().getLanguage(contentType); } if (language != null) { - fPresentationCreator= SourcePresentationCreatorFactory.create(language, fEdition, viewer); + fPresentationCreator = SourcePresentationCreatorFactory.create(language, fEdition, viewer); } int lines = doc.getNumberOfLines(); fLine2Addr = new BigInteger[lines]; @@ -126,7 +126,7 @@ public class SourceFileInfo { } fSource = null; fValid = false; -// fLinesNode = null; + // fLinesNode = null; } public String getLine(int lineNr) { @@ -137,8 +137,8 @@ public class SourceFileInfo { try { int startOffset = fSource.getLineOffset(first); int endOffset; - if (last < fSource.getNumberOfLines()-1) { - IRegion lastRegion = fSource.getLineInformation(last+1); + if (last < fSource.getNumberOfLines() - 1) { + IRegion lastRegion = fSource.getLineInformation(last + 1); endOffset = lastRegion.getOffset(); } else { // last line @@ -186,12 +186,12 @@ public class SourceFileInfo { } return -1; } - + /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { - return fEdition.toString(); + return fEdition.toString(); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceReadingJob.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceReadingJob.java index 47c9328a1ff..9a4f457d232 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceReadingJob.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/SourceReadingJob.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,7 +20,6 @@ import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.Job; - /** * Low-level job to read source files in the background. */ @@ -37,7 +36,7 @@ public class SourceReadingJob extends Job { fFileInfo.fReadingJob = this; fDone = done; if (fi.fFile instanceof ISchedulingRule) { - setRule((ISchedulingRule)fi.fFile); + setRule((ISchedulingRule) fi.fFile); } setSystem(true); // usually short lived job diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/preferences/DisassemblyPreferenceConstants.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/preferences/DisassemblyPreferenceConstants.java index c5e9b9781f8..e8e0544c03b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/preferences/DisassemblyPreferenceConstants.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/preferences/DisassemblyPreferenceConstants.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -41,9 +41,9 @@ public class DisassemblyPreferenceConstants { public static final String AVOID_READ_BEFORE_PC = "disassembly.avoidReadBeforePC"; //$NON-NLS-1$ public static final String TRACK_EXPRESSION = "disassembly.trackExpression"; //$NON-NLS-1$ public static final String SYNC_ACTIVE_CONTEXT = "disassembly.syncActiveContext"; //$NON-NLS-1$ - + /** - * + * */ private DisassemblyPreferenceConstants() { // not intended to be subclassed or instantiated diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/preferences/DisassemblyPreferencePage.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/preferences/DisassemblyPreferencePage.java index d0b3c1e202d..6d1e33c689c 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/preferences/DisassemblyPreferencePage.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/preferences/DisassemblyPreferencePage.java @@ -49,19 +49,15 @@ public class DisassemblyPreferencePage extends PreferencePage implements IWorkbe private ModifyListener fNumberFieldListener = new ModifyListener() { @Override public void modifyText(ModifyEvent e) { - numberFieldChanged((Text)e.widget); + numberFieldChanged((Text) e.widget); } }; private Combo fAddressFormatCombo; private Combo fOpcodeFormatCombo; - private final static String[] fcRadixItems = { - DisassemblyMessages.DisassemblyPreferencePage_radix_octal, - DisassemblyMessages.DisassemblyPreferencePage_radix_decimal, - DisassemblyMessages.DisassemblyPreferencePage_radix_hexadecimal, - }; - private final static int[] fcRadixValues = { - 8, 10, 16 - }; + private final static String[] fcRadixItems = { DisassemblyMessages.DisassemblyPreferencePage_radix_octal, + DisassemblyMessages.DisassemblyPreferencePage_radix_decimal, + DisassemblyMessages.DisassemblyPreferencePage_radix_hexadecimal, }; + private final static int[] fcRadixValues = { 8, 10, 16 }; /** * Create the Disassembly preference page. @@ -77,7 +73,8 @@ public class DisassemblyPreferencePage extends PreferencePage implements IWorkbe @Override public void createControl(Composite parent) { super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IDisassemblyHelpContextIds.DISASSEMBLY_PREFERENCE_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IDisassemblyHelpContextIds.DISASSEMBLY_PREFERENCE_PAGE); } /* (non-Javadoc) @@ -143,15 +140,15 @@ public class DisassemblyPreferencePage extends PreferencePage implements IWorkbe } private Combo addComboBox(Composite parent, String label, String key, String[] items) { - Label labelControl= new Label(parent, SWT.NONE); + Label labelControl = new Label(parent, SWT.NONE); labelControl.setText(label); - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent = 0; gd.horizontalSpan = 2; labelControl.setLayoutData(gd); Combo combo = new Combo(parent, SWT.READ_ONLY); - gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); combo.setLayoutData(gd); combo.setItems(items); combo.setData(key); @@ -160,16 +157,17 @@ public class DisassemblyPreferencePage extends PreferencePage implements IWorkbe return combo; } - protected Text addTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { + protected Text addTextField(Composite composite, String label, String key, int textLimit, int indentation, + boolean isNumber) { return getTextControl(addLabelledTextField(composite, label, key, textLimit, indentation, isNumber)); } -// private static Label getLabelControl(Control[] labelledTextField){ -// return (Label)labelledTextField[0]; -// } + // private static Label getLabelControl(Control[] labelledTextField){ + // return (Label)labelledTextField[0]; + // } - private static Text getTextControl(Control[] labelledTextField){ - return (Text)labelledTextField[1]; + private static Text getTextControl(Control[] labelledTextField) { + return (Text) labelledTextField[1]; } /** @@ -178,16 +176,17 @@ public class DisassemblyPreferencePage extends PreferencePage implements IWorkbe * - second element is of type <code>Text</code> * Use <code>getLabelControl</code> and <code>getTextControl</code> to get the 2 controls. */ - private Control[] addLabelledTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { - Label labelControl= new Label(composite, SWT.NONE); + private Control[] addLabelledTextField(Composite composite, String label, String key, int textLimit, + int indentation, boolean isNumber) { + Label labelControl = new Label(composite, SWT.NONE); labelControl.setText(label); - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent= indentation; + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indentation; labelControl.setLayoutData(gd); - Text textControl= new Text(composite, SWT.BORDER | SWT.SINGLE); - gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.widthHint= convertWidthInCharsToPixels(textLimit + 1); + Text textControl = new Text(composite, SWT.BORDER | SWT.SINGLE); + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.widthHint = convertWidthInCharsToPixels(textLimit + 1); textControl.setLayoutData(gd); textControl.setTextLimit(textLimit); textControl.setData(key); @@ -196,7 +195,7 @@ public class DisassemblyPreferencePage extends PreferencePage implements IWorkbe textControl.addModifyListener(fNumberFieldListener); } - return new Control[]{labelControl, textControl}; + return new Control[] { labelControl, textControl }; } /* (non-Javadoc) @@ -207,18 +206,19 @@ public class DisassemblyPreferencePage extends PreferencePage implements IWorkbe IPreferenceStore store = getPreferenceStore(); for (Iterator<Button> iter = fCheckBoxes.iterator(); iter.hasNext();) { Button btn = iter.next(); - store.setValue((String)btn.getData(), btn.getSelection()); + store.setValue((String) btn.getData(), btn.getSelection()); } for (Iterator<Text> iter = fNumberFields.iterator(); iter.hasNext();) { Text field = iter.next(); - store.setValue((String)field.getData(), Long.decode(field.getText()).longValue()); + store.setValue((String) field.getData(), Long.decode(field.getText()).longValue()); } for (Iterator<Combo> iter = fComboBoxes.iterator(); iter.hasNext();) { Combo combo = iter.next(); - store.setValue((String)combo.getData(), fcRadixValues[combo.getSelectionIndex()]); + store.setValue((String) combo.getData(), fcRadixValues[combo.getSelectionIndex()]); } return super.performOk(); } + /* (non-Javadoc) * @see org.eclipse.jface.preference.PreferencePage#performDefaults() */ @@ -227,16 +227,16 @@ public class DisassemblyPreferencePage extends PreferencePage implements IWorkbe IPreferenceStore store = getPreferenceStore(); for (Iterator<Button> iter = fCheckBoxes.iterator(); iter.hasNext();) { Button btn = iter.next(); - btn.setSelection(store.getDefaultBoolean((String)btn.getData())); + btn.setSelection(store.getDefaultBoolean((String) btn.getData())); } for (Iterator<Text> iter = fNumberFields.iterator(); iter.hasNext();) { Text field = iter.next(); - long value = store.getDefaultLong((String)field.getData()); - field.setText("0x"+Long.toHexString(value)); //$NON-NLS-1$ + long value = store.getDefaultLong((String) field.getData()); + field.setText("0x" + Long.toHexString(value)); //$NON-NLS-1$ } for (Iterator<Combo> iter = fComboBoxes.iterator(); iter.hasNext();) { Combo combo = iter.next(); - int value = store.getDefaultInt((String)combo.getData()); + int value = store.getDefaultInt((String) combo.getData()); for (int i = 0; i < fcRadixValues.length; i++) { if (fcRadixValues[i] == value) { combo.select(i); @@ -245,6 +245,7 @@ public class DisassemblyPreferencePage extends PreferencePage implements IWorkbe } super.performDefaults(); } + /** * Initialize widget values from preference store. */ @@ -252,16 +253,16 @@ public class DisassemblyPreferencePage extends PreferencePage implements IWorkbe IPreferenceStore store = getPreferenceStore(); for (Iterator<Button> iter = fCheckBoxes.iterator(); iter.hasNext();) { Button btn = iter.next(); - btn.setSelection(store.getBoolean((String)btn.getData())); + btn.setSelection(store.getBoolean((String) btn.getData())); } for (Iterator<Text> iter = fNumberFields.iterator(); iter.hasNext();) { Text field = iter.next(); - long value = store.getLong((String)field.getData()); - field.setText("0x"+Long.toHexString(value)); //$NON-NLS-1$ + long value = store.getLong((String) field.getData()); + field.setText("0x" + Long.toHexString(value)); //$NON-NLS-1$ } for (Iterator<Combo> iter = fComboBoxes.iterator(); iter.hasNext();) { Combo combo = iter.next(); - int value = store.getInt((String)combo.getData()); + int value = store.getInt((String) combo.getData()); for (int i = 0; i < fcRadixValues.length; i++) { if (fcRadixValues[i] == value) { combo.select(i); @@ -282,7 +283,7 @@ public class DisassemblyPreferencePage extends PreferencePage implements IWorkbe } else { setErrorMessage(null); } - } catch(NumberFormatException nfe) { + } catch (NumberFormatException nfe) { setErrorMessage(DisassemblyMessages.DisassemblyPreferencePage_error_not_a_number); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/CSourcePresentationCreator.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/CSourcePresentationCreator.java index 2222046cd48..5941fab3de1 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/CSourcePresentationCreator.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/CSourcePresentationCreator.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -54,7 +54,8 @@ import org.eclipse.ui.IEditorInput; /** * A presentation creator based on CDT syntax highlighting. */ -public class CSourcePresentationCreator extends PresentationReconciler implements ISourcePresentationCreator, IPropertyChangeListener { +public class CSourcePresentationCreator extends PresentationReconciler + implements ISourcePresentationCreator, IPropertyChangeListener { /** * @@ -71,13 +72,13 @@ public class CSourcePresentationCreator extends PresentationReconciler implement * @param preferenceStore * @param language */ - private CustomCSourceViewerConfiguration( - IColorManager colorManager, IPreferenceStore preferenceStore, + private CustomCSourceViewerConfiguration(IColorManager colorManager, IPreferenceStore preferenceStore, ILanguage language) { super(colorManager, preferenceStore, null, ICPartitions.C_PARTITIONING); fLanguage = language; if (language instanceof IAsmLanguage) { - fAsmConfig= new AsmSourceViewerConfiguration(colorManager, preferenceStore, null, ICPartitions.C_PARTITIONING); + fAsmConfig = new AsmSourceViewerConfiguration(colorManager, preferenceStore, null, + ICPartitions.C_PARTITIONING); } } @@ -127,7 +128,7 @@ public class CSourcePresentationCreator extends PresentationReconciler implement } return super.getCodeScanner(language); } - + /* * @see org.eclipse.cdt.internal.ui.text.CSourceViewerConfiguration#getPreprocessorScanner(org.eclipse.cdt.core.model.ILanguage) */ @@ -218,7 +219,7 @@ public class CSourcePresentationCreator extends PresentationReconciler implement public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) { return null; } - + /* * @see CSourceViewerConfiguration#getOutlinePresenter(ISourceViewer) */ @@ -226,7 +227,7 @@ public class CSourcePresentationCreator extends PresentationReconciler implement public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer) { return null; } -} + } private ITextViewer fViewer; private ISourceTagProvider fSourceTagProvider; @@ -243,10 +244,10 @@ public class CSourcePresentationCreator extends PresentationReconciler implement */ public CSourcePresentationCreator(ILanguage language, IStorage storage, ITextViewer textViewer) { if (language != null) { - fViewer= textViewer; - fPreferenceStore= CUIPlugin.getDefault().getCombinedPreferenceStore(); - final IColorManager colorManager= CDTUITools.getColorManager(); - fSourceViewerConfiguration= new CustomCSourceViewerConfiguration(colorManager, fPreferenceStore, language); + fViewer = textViewer; + fPreferenceStore = CUIPlugin.getDefault().getCombinedPreferenceStore(); + final IColorManager colorManager = CDTUITools.getColorManager(); + fSourceViewerConfiguration = new CustomCSourceViewerConfiguration(colorManager, fPreferenceStore, language); setDocumentPartitioning(fSourceViewerConfiguration.getConfiguredDocumentPartitioning(null)); initializeDamagerRepairer(storage, colorManager, fPreferenceStore); fPreferenceStore.addPropertyChangeListener(this); @@ -254,7 +255,7 @@ public class CSourcePresentationCreator extends PresentationReconciler implement } private void initializeDamagerRepairer(IStorage storage, IColorManager colorManager, IPreferenceStore store) { - String[] contentTypes= fSourceViewerConfiguration.getConfiguredContentTypes(null); + String[] contentTypes = fSourceViewerConfiguration.getConfiguredContentTypes(null); for (int i = 0; i < contentTypes.length; ++i) { String contentType = contentTypes[i]; ITokenScanner scanner; @@ -262,14 +263,15 @@ public class CSourcePresentationCreator extends PresentationReconciler implement if (scanner != null) { if (fDamagerRepairer == null) { fSourceTagProvider = createSourceTagProvider(storage); - fDamagerRepairer= new SourceTagDamagerRepairer(scanner, fSourceTagProvider, colorManager, store); + fDamagerRepairer = new SourceTagDamagerRepairer(scanner, fSourceTagProvider, colorManager, store); if (fSourceTagProvider != null) { if (fSourceTagListener == null) { - fSourceTagListener= new ISourceTagListener() { + fSourceTagListener = new ISourceTagListener() { @Override public void sourceTagsChanged(ISourceTagProvider provider) { handleSourceTagsChanged(); - }}; + } + }; } fSourceTagProvider.addSourceTagListener(fSourceTagListener); } @@ -286,22 +288,22 @@ public class CSourcePresentationCreator extends PresentationReconciler implement */ @Override public void dispose() { - fViewer= null; - fPresentation= null; + fViewer = null; + fPresentation = null; if (fPreferenceStore != null) { fPreferenceStore.removePropertyChangeListener(this); - fPreferenceStore= null; + fPreferenceStore = null; } if (fSourceViewerConfiguration != null) { fSourceViewerConfiguration.dispose(); - fSourceViewerConfiguration= null; + fSourceViewerConfiguration = null; } if (fSourceTagProvider != null) { if (fSourceTagListener != null) { fSourceTagProvider.removeSourceTagListener(fSourceTagListener); - fSourceTagListener= null; + fSourceTagListener = null; } - fSourceTagProvider= null; + fSourceTagProvider = null; } } @@ -317,10 +319,10 @@ public class CSourcePresentationCreator extends PresentationReconciler implement if (fPresentation == null) { setDocumentToDamagers(document); setDocumentToRepairers(document); - int docLength= document.getLength(); - if (docLength <= 128*1024) { - IRegion all= new Region(0, docLength); - fPresentation= createPresentation(all, document); + int docLength = document.getLength(); + if (docLength <= 128 * 1024) { + IRegion all = new Region(0, docLength); + fPresentation = createPresentation(all, document); } else { return createPresentation(region, document); } @@ -335,9 +337,9 @@ public class CSourcePresentationCreator extends PresentationReconciler implement private void invalidateTextPresentation() { if (fPresentation != null) { - fPresentation= null; + fPresentation = null; if (fViewer != null) { - Display display= fViewer.getTextWidget().getDisplay(); + Display display = fViewer.getTextWidget().getDisplay(); if (display.getThread() != Thread.currentThread()) { display.asyncExec(new Runnable() { @Override @@ -345,7 +347,8 @@ public class CSourcePresentationCreator extends PresentationReconciler implement if (fViewer != null) { fViewer.invalidateTextPresentation(); } - }}); + } + }); } else { fViewer.invalidateTextPresentation(); } @@ -354,23 +357,23 @@ public class CSourcePresentationCreator extends PresentationReconciler implement } private ISourceTagProvider createSourceTagProvider(IStorage storage) { - ITranslationUnit tUnit= null; + ITranslationUnit tUnit = null; if (storage instanceof IFile) { - tUnit= (ITranslationUnit) CoreModel.getDefault().create((IFile)storage); + tUnit = (ITranslationUnit) CoreModel.getDefault().create((IFile) storage); } else if (storage instanceof IFileState) { - ICModel cModel= CoreModel.getDefault().getCModel(); + ICModel cModel = CoreModel.getDefault().getCModel(); ICProject[] cProjects; try { cProjects = cModel.getCProjects(); if (cProjects.length > 0) { - tUnit= CoreModel.getDefault().createTranslationUnitFrom(cProjects[0], storage.getFullPath()); + tUnit = CoreModel.getDefault().createTranslationUnitFrom(cProjects[0], storage.getFullPath()); } } catch (CModelException e) { } } else { - IEditorInput input= CDTUITools.getEditorInputForLocation(storage.getFullPath(), null); + IEditorInput input = CDTUITools.getEditorInputForLocation(storage.getFullPath(), null); if (input != null) { - tUnit= input.getAdapter(ITranslationUnit.class); + tUnit = input.getAdapter(ITranslationUnit.class); } } if (tUnit != null) { diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/CSourceTag.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/CSourceTag.java index 766aed4a68a..2bb37db9cd7 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/CSourceTag.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/CSourceTag.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -63,7 +63,7 @@ public class CSourceTag implements ISourceTag { * @param sourceRange */ public CSourceRange(org.eclipse.cdt.core.model.ISourceRange sourceRange) { - fRange= sourceRange; + fRange = sourceRange; } @Override @@ -83,9 +83,9 @@ public class CSourceTag implements ISourceTag { @Override public int compareTo(ISourceRange other) { - int delta= this.getBeginOffset() - other.getBeginOffset(); + int delta = this.getBeginOffset() - other.getBeginOffset(); if (delta == 0) { - delta= this.getEndOffset() - other.getEndOffset(); + delta = this.getEndOffset() - other.getEndOffset(); } return delta; } @@ -100,7 +100,7 @@ public class CSourceTag implements ISourceTag { private org.eclipse.cdt.core.model.ISourceRange fRange; public CIdentifierRange(org.eclipse.cdt.core.model.ISourceRange sourceRange) { - fRange= sourceRange; + fRange = sourceRange; } @Override @@ -120,27 +120,27 @@ public class CSourceTag implements ISourceTag { @Override public int compareTo(ISourceRange other) { - int delta= this.getBeginOffset() - other.getBeginOffset(); + int delta = this.getBeginOffset() - other.getBeginOffset(); if (delta == 0) { - delta= this.getEndOffset() - other.getEndOffset(); + delta = this.getEndOffset() - other.getEndOffset(); } return delta; } } - + private ISourceReference fReference; private int fType; /** * Create a new source tag for the given element and type. - * + * * @param element * @param elementType */ public CSourceTag(ISourceReference element, int elementType) { - fReference= element; - fType= elementType; + fReference = element; + fType = elementType; } @Override @@ -154,7 +154,7 @@ public class CSourceTag implements ISourceTag { @Override public String getName() { - return ((ICElement)fReference).getElementName(); + return ((ICElement) fReference).getElementName(); } @Override @@ -179,7 +179,7 @@ public class CSourceTag implements ISourceTag { @Override public int getStyleCode() { switch (fType) { - case ICElement.C_METHOD : + case ICElement.C_METHOD: case ICElement.C_METHOD_DECLARATION: case ICElement.C_TEMPLATE_METHOD: case ICElement.C_TEMPLATE_METHOD_DECLARATION: @@ -189,7 +189,7 @@ public class CSourceTag implements ISourceTag { case ICElement.C_TEMPLATE_FUNCTION: case ICElement.C_TEMPLATE_FUNCTION_DECLARATION: return ISourceTag.STYLE_Function; - case ICElement.C_FIELD : + case ICElement.C_FIELD: return ISourceTag.STYLE_MemberVariable; case ICElement.C_VARIABLE: case ICElement.C_VARIABLE_DECLARATION: diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/CSourceTagProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/CSourceTagProvider.java index 3173393ef5a..ead860df36a 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/CSourceTagProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/CSourceTagProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -27,16 +27,16 @@ import org.eclipse.core.runtime.ListenerList; */ public class CSourceTagProvider implements ISourceTagProvider { - private ListenerList<ISourceTagListener> fListenerList= new ListenerList<>(ListenerList.IDENTITY); + private ListenerList<ISourceTagListener> fListenerList = new ListenerList<>(ListenerList.IDENTITY); private ITranslationUnit fUnit; - + /** * Create a new source tag provider for the given translation unit. - * + * * @param unit */ public CSourceTagProvider(ITranslationUnit unit) { - fUnit= unit; + fUnit = unit; } @Override @@ -69,7 +69,7 @@ public class CSourceTagProvider implements ISourceTagProvider { */ private ISourceTag convertToSourceTag(ICElement element) { if (element instanceof ISourceReference) { - return new CSourceTag((ISourceReference)element, element.getElementType()); + return new CSourceTag((ISourceReference) element, element.getElementType()); } return null; } @@ -81,13 +81,13 @@ public class CSourceTagProvider implements ISourceTagProvider { */ private void convertToSourceTags(ICElement[] children, Collection<ISourceTag> target) throws CModelException { for (int i = 0; i < children.length; i++) { - ICElement element= children[i]; - ISourceTag tag= convertToSourceTag(element); + ICElement element = children[i]; + ISourceTag tag = convertToSourceTag(element); if (tag != null) { target.add(tag); } if (element instanceof IParent) { - convertToSourceTags(((IParent)element).getChildren(), target); + convertToSourceTags(((IParent) element).getChildren(), target); } } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/DisassemblyIPAnnotation.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/DisassemblyIPAnnotation.java index 709f84f6a22..cf67a111784 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/DisassemblyIPAnnotation.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/DisassemblyIPAnnotation.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -28,29 +28,26 @@ import org.eclipse.swt.widgets.Canvas; */ public class DisassemblyIPAnnotation extends Annotation implements IAnnotationPresentation { - public static final String ID_TOP = IDebugUIConstants.ANNOTATION_TYPE_INSTRUCTION_POINTER_CURRENT; - public static final String ID_SECONDARY = IDebugUIConstants.ANNOTATION_TYPE_INSTRUCTION_POINTER_SECONDARY; + public static final String ID_TOP = IDebugUIConstants.ANNOTATION_TYPE_INSTRUCTION_POINTER_CURRENT; + public static final String ID_SECONDARY = IDebugUIConstants.ANNOTATION_TYPE_INSTRUCTION_POINTER_SECONDARY; private Image fImage; private int fContext = Integer.MIN_VALUE; - /** + /** * Annotation denoting the current instruction pointer. */ public DisassemblyIPAnnotation(boolean isTopFrame, int context) { - super( - isTopFrame ? ID_TOP : ID_SECONDARY, - false, - isTopFrame ? DisassemblyMessages.DisassemblyIPAnnotation_primary - : DisassemblyMessages.DisassemblyIPAnnotation_secondary - ); + super(isTopFrame ? ID_TOP : ID_SECONDARY, false, + isTopFrame ? DisassemblyMessages.DisassemblyIPAnnotation_primary + : DisassemblyMessages.DisassemblyIPAnnotation_secondary); setContext(context); } public boolean isTopFrame() { return ID_TOP.equals(getType()); } - + public void setContext(int context) { if (context == fContext) { return; @@ -78,7 +75,8 @@ public class DisassemblyIPAnnotation extends Annotation implements IAnnotationPr @Override public void paint(GC gc, Canvas canvas, Rectangle bounds) { Rectangle imageBounds = fImage.getBounds(); - gc.drawImage(fImage, bounds.x + (bounds.width - imageBounds.width) / 2 , bounds.y + (bounds.height - imageBounds.height) / 2); + gc.drawImage(fImage, bounds.x + (bounds.width - imageBounds.width) / 2, + bounds.y + (bounds.height - imageBounds.height) / 2); } - + } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourcePresentationCreator.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourcePresentationCreator.java index d30fe5db04d..4744f3ccad8 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourcePresentationCreator.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourcePresentationCreator.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceRange.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceRange.java index 0ebdca3a786..f44bca82539 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceRange.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceRange.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -16,16 +16,18 @@ package org.eclipse.cdt.dsf.debug.internal.ui.disassembly.presentation; /** * Represents a range within a source file. */ - + public interface ISourceRange extends Comparable<ISourceRange> { /** * Returns 0-based absolute number for the inclusive start of the range. */ int getBeginOffset(); + /** * Returns 0-based absolute number for the inclusive end of the range. */ int getEndOffset(); + /** * Checks whether the range contains the given offset. */ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceTag.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceTag.java index 3efa35a121f..1e48f515453 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceTag.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceTag.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -18,38 +18,38 @@ package org.eclipse.cdt.dsf.debug.internal.ui.disassembly.presentation; */ public interface ISourceTag { // style codes - final static int STYLE_None = 0; - final static int STYLE_Class = 1; - final static int STYLE_Struct = 2; - final static int STYLE_Union = 3; - final static int STYLE_Interface = 4; - final static int STYLE_Package = 5; - final static int STYLE_Function = 6; + final static int STYLE_None = 0; + final static int STYLE_Class = 1; + final static int STYLE_Struct = 2; + final static int STYLE_Union = 3; + final static int STYLE_Interface = 4; + final static int STYLE_Package = 5; + final static int STYLE_Function = 6; final static int STYLE_ProtectedFunction = 7; - final static int STYLE_Method = 8; - final static int STYLE_Exception = 9; - final static int STYLE_Variable = 10; - final static int STYLE_MemberVariable = 11; - final static int STYLE_Enumerator = 12; - final static int STYLE_Macro = 13; - final static int STYLE_Include = 14; - final static int STYLE_Undefined = 15; - final static int STYLE_Enumeration = 16; - final static int STYLE_Typedef = 17; - final static int STYLE_Type3 = 18; - final static int STYLE_Type4 = 19; - final static int STYLE_Type5 = 20; - final static int STYLE_File = 21; - final static int STYLE_Project = 22; + final static int STYLE_Method = 8; + final static int STYLE_Exception = 9; + final static int STYLE_Variable = 10; + final static int STYLE_MemberVariable = 11; + final static int STYLE_Enumerator = 12; + final static int STYLE_Macro = 13; + final static int STYLE_Include = 14; + final static int STYLE_Undefined = 15; + final static int STYLE_Enumeration = 16; + final static int STYLE_Typedef = 17; + final static int STYLE_Type3 = 18; + final static int STYLE_Type4 = 19; + final static int STYLE_Type5 = 20; + final static int STYLE_File = 21; + final static int STYLE_Project = 22; final static int STYLE_IncludeContainer = 23; - final static int STYLE_LocalVariable = 24; - final static int STYLE_Label = 25; - final static int STYLE_Record = 26; - final static int STYLE_TaggedType = 27; - final static int STYLE_Subtype = 28; - final static int STYLE_Warning = 29; - final static int STYLE_Count = 30; - + final static int STYLE_LocalVariable = 24; + final static int STYLE_Label = 25; + final static int STYLE_Record = 26; + final static int STYLE_TaggedType = 27; + final static int STYLE_Subtype = 28; + final static int STYLE_Warning = 29; + final static int STYLE_Count = 30; + /** * Returns the unqualified name of the source tag. Files return their base name. */ @@ -69,7 +69,7 @@ public interface ISourceTag { * Returns the range of the identifier of the symbol within the file. */ ISourceRange getRangeOfIdentifier(); - + /** * Computes the style code. Style codes are language dependent. You * cannot derive any information from the style-code of a symbol. It diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceTagListener.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceTagListener.java index e53f6dadff7..551d785ef03 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceTagListener.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceTagListener.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceTagProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceTagProvider.java index d318ec7b6f2..fe002a02caf 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceTagProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/ISourceTagProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -48,5 +48,5 @@ public interface ISourceTagProvider { * information cannot be obtained. */ public int[] getActiveCodePositions(); - + } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/SourcePresentationCreatorFactory.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/SourcePresentationCreatorFactory.java index d68c9a0aba9..5971ce09557 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/SourcePresentationCreatorFactory.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/SourcePresentationCreatorFactory.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/SourceTagDamagerRepairer.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/SourceTagDamagerRepairer.java index 5d730d746b6..03b7116b9d6 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/SourceTagDamagerRepairer.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/presentation/SourceTagDamagerRepairer.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -45,33 +45,27 @@ import org.eclipse.swt.graphics.RGB; public class SourceTagDamagerRepairer extends DefaultDamagerRepairer implements ISourceTagListener { private ISourceTagProvider fSourceTagProvider; - private Map<String, ITokenScanner> fScannerMap= new HashMap<String, ITokenScanner>(); + private Map<String, ITokenScanner> fScannerMap = new HashMap<String, ITokenScanner>(); private List<ISourceTag> fSourceTags = new ArrayList<ISourceTag>(); private IColorManager fColorManager; private IPreferenceStore fPreferenceStore; - private Map<String, TextAttribute> fAttributeMap= new HashMap<String, TextAttribute>(); - - private final static String[] KEYS= { - SemanticHighlightings.CLASS, - SemanticHighlightings.METHOD_DECLARATION, - SemanticHighlightings.FUNCTION_DECLARATION, - SemanticHighlightings.FIELD, - SemanticHighlightings.GLOBAL_VARIABLE, - SemanticHighlightings.TYPEDEF, - SemanticHighlightings.MACRO_DEFINITION, - SemanticHighlightings.ENUMERATOR, - SemanticHighlightings.ENUM, - }; + private Map<String, TextAttribute> fAttributeMap = new HashMap<String, TextAttribute>(); + + private final static String[] KEYS = { SemanticHighlightings.CLASS, SemanticHighlightings.METHOD_DECLARATION, + SemanticHighlightings.FUNCTION_DECLARATION, SemanticHighlightings.FIELD, + SemanticHighlightings.GLOBAL_VARIABLE, SemanticHighlightings.TYPEDEF, + SemanticHighlightings.MACRO_DEFINITION, SemanticHighlightings.ENUMERATOR, SemanticHighlightings.ENUM, }; /** * @param scanner * @param sourceTagProvider */ - public SourceTagDamagerRepairer(ITokenScanner scanner, ISourceTagProvider sourceTagProvider, IColorManager colorManager, IPreferenceStore store) { + public SourceTagDamagerRepairer(ITokenScanner scanner, ISourceTagProvider sourceTagProvider, + IColorManager colorManager, IPreferenceStore store) { super(scanner); - fSourceTagProvider= sourceTagProvider; - fColorManager= colorManager; - fPreferenceStore= store; + fSourceTagProvider = sourceTagProvider; + fColorManager = colorManager; + fPreferenceStore = store; fDefaultTextAttribute = new TextAttribute(null, null, SWT.NORMAL); if (fSourceTagProvider != null) { fSourceTagProvider.addSourceTagListener(this); @@ -80,16 +74,22 @@ public class SourceTagDamagerRepairer extends DefaultDamagerRepairer implements } private void initTextAttributes() { - boolean shEnabled= fPreferenceStore.getBoolean(PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED); - for (int i= 0; i < KEYS.length; i++) { - String enabledKey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + KEYS[i] + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED_SUFFIX; - String colorKey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + KEYS[i] + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_COLOR_SUFFIX; - boolean enabled= shEnabled && fPreferenceStore.getBoolean(enabledKey); + boolean shEnabled = fPreferenceStore.getBoolean(PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED); + for (int i = 0; i < KEYS.length; i++) { + String enabledKey = PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + KEYS[i] + + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED_SUFFIX; + String colorKey = PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + KEYS[i] + + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_COLOR_SUFFIX; + boolean enabled = shEnabled && fPreferenceStore.getBoolean(enabledKey); if (enabled) { - String boldKey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + KEYS[i] + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_BOLD_SUFFIX; - String italicKey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + KEYS[i] + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ITALIC_SUFFIX; - String strikethroughKey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + KEYS[i] + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_STRIKETHROUGH_SUFFIX; - String underlineKey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + KEYS[i] + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_UNDERLINE_SUFFIX; + String boldKey = PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + KEYS[i] + + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_BOLD_SUFFIX; + String italicKey = PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + KEYS[i] + + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ITALIC_SUFFIX; + String strikethroughKey = PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + KEYS[i] + + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_STRIKETHROUGH_SUFFIX; + String underlineKey = PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + KEYS[i] + + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_UNDERLINE_SUFFIX; addTextAttribute(KEYS[i], colorKey, boldKey, italicKey, strikethroughKey, underlineKey); } else { removeTextAttribute(KEYS[i], colorKey); @@ -99,7 +99,7 @@ public class SourceTagDamagerRepairer extends DefaultDamagerRepairer implements private void removeTextAttribute(String key, String colorKey) { if (fColorManager != null && colorKey != null) { - Color color= fColorManager.getColor(colorKey); + Color color = fColorManager.getColor(colorKey); if (color != null) { fColorManager.unbindColor(colorKey); } @@ -108,26 +108,28 @@ public class SourceTagDamagerRepairer extends DefaultDamagerRepairer implements fAttributeMap.remove(key); } - private void addTextAttribute(String key, String colorKey, String boldKey, String italicKey, String strikethroughKey, String underlineKey) { + private void addTextAttribute(String key, String colorKey, String boldKey, String italicKey, + String strikethroughKey, String underlineKey) { if (fColorManager != null && colorKey != null) { - RGB rgb= PreferenceConverter.getColor(fPreferenceStore, colorKey); - Color color= fColorManager.getColor(colorKey); + RGB rgb = PreferenceConverter.getColor(fPreferenceStore, colorKey); + Color color = fColorManager.getColor(colorKey); if (color == null || !rgb.equals(color.getRGB())) { fColorManager.unbindColor(colorKey); fColorManager.bindColor(colorKey, rgb); } } - TextAttribute textAttribute= createTextAttribute(colorKey, boldKey, italicKey, strikethroughKey, underlineKey); + TextAttribute textAttribute = createTextAttribute(colorKey, boldKey, italicKey, strikethroughKey, underlineKey); fAttributeMap.put(key, textAttribute); } - private TextAttribute createTextAttribute(String colorKey, String boldKey, String italicKey, String strikethroughKey, String underlineKey) { - Color color= null; + private TextAttribute createTextAttribute(String colorKey, String boldKey, String italicKey, + String strikethroughKey, String underlineKey) { + Color color = null; if (colorKey != null) - color= fColorManager.getColor(colorKey); + color = fColorManager.getColor(colorKey); - int style= fPreferenceStore.getBoolean(boldKey) ? SWT.BOLD : SWT.NORMAL; + int style = fPreferenceStore.getBoolean(boldKey) ? SWT.BOLD : SWT.NORMAL; if (fPreferenceStore.getBoolean(italicKey)) style |= SWT.ITALIC; @@ -157,7 +159,7 @@ public class SourceTagDamagerRepairer extends DefaultDamagerRepairer implements if (fAttributeMap.isEmpty()) { initTextAttributes(); } - String contentType= region.getType(); + String contentType = region.getType(); fScanner = fScannerMap.get(contentType); if (!contentType.equals(IDocument.DEFAULT_CONTENT_TYPE) && !contentType.equals(ICPartitions.C_PREPROCESSOR)) { super.createPresentation(presentation, region); @@ -181,7 +183,7 @@ public class SourceTagDamagerRepairer extends DefaultDamagerRepairer implements if (sourceTagCount > 0 && fDocument.getLength() > 0) { int left = 0; - int mid = (int) (sourceTagCount * ((float)lastStart / fDocument.getLength())); + int mid = (int) (sourceTagCount * ((float) lastStart / fDocument.getLength())); int right = sourceTagCount - 1; while (true) { sourceTag = fSourceTags.get(mid); @@ -218,7 +220,7 @@ public class SourceTagDamagerRepairer extends DefaultDamagerRepairer implements TextAttribute attribute = getTokenTextAttribute(token); int tokenLength = fScanner.getTokenLength(); if (tokenLength > 0 - && (lastAttribute == attribute || lastAttribute != null && lastAttribute.equals(attribute))) { + && (lastAttribute == attribute || lastAttribute != null && lastAttribute.equals(attribute))) { length += tokenLength; continue; } @@ -234,14 +236,12 @@ public class SourceTagDamagerRepairer extends DefaultDamagerRepairer implements String sourceTagStyle = getSourceTagStyle(sourceTag.getStyleCode()); if (sourceTagStyle != null) { if (sourceTagStart > lastStart) { - addRange(presentation, lastStart, Math.min(sourceTagStart - lastStart, length), lastAttribute); + addRange(presentation, lastStart, Math.min(sourceTagStart - lastStart, length), + lastAttribute); } int rangeEnd = Math.min(sourceTagEnd, regionEnd); - addRange( - presentation, - sourceTagStart, - rangeEnd - sourceTagStart, - getSourceTagTextAttribute(sourceTagStyle)); + addRange(presentation, sourceTagStart, rangeEnd - sourceTagStart, + getSourceTagTextAttribute(sourceTagStyle)); length = lastStart + length - rangeEnd; lastStart = rangeEnd; } else { @@ -293,37 +293,37 @@ public class SourceTagDamagerRepairer extends DefaultDamagerRepairer implements */ private String getSourceTagStyle(int styleCode) { switch (styleCode) { - case ISourceTag.STYLE_None : - return null; - case ISourceTag.STYLE_Class : - return SemanticHighlightings.CLASS; - case ISourceTag.STYLE_Struct : - return SemanticHighlightings.CLASS; - case ISourceTag.STYLE_Union : - return SemanticHighlightings.CLASS; - case ISourceTag.STYLE_Function : - return SemanticHighlightings.FUNCTION_DECLARATION; - case ISourceTag.STYLE_Method : - return SemanticHighlightings.METHOD_DECLARATION; - case ISourceTag.STYLE_Variable : - return SemanticHighlightings.GLOBAL_VARIABLE; - case ISourceTag.STYLE_MemberVariable : - return SemanticHighlightings.FIELD; - case ISourceTag.STYLE_Enumerator : - return SemanticHighlightings.ENUMERATOR; - case ISourceTag.STYLE_Macro : - return SemanticHighlightings.MACRO_DEFINITION; - case ISourceTag.STYLE_Include : - // include is colored by the scanner - return null; - case ISourceTag.STYLE_Enumeration : - return SemanticHighlightings.ENUM; - case ISourceTag.STYLE_Undefined : - return null; - case ISourceTag.STYLE_Typedef : - return SemanticHighlightings.TYPEDEF; - default : - return null; + case ISourceTag.STYLE_None: + return null; + case ISourceTag.STYLE_Class: + return SemanticHighlightings.CLASS; + case ISourceTag.STYLE_Struct: + return SemanticHighlightings.CLASS; + case ISourceTag.STYLE_Union: + return SemanticHighlightings.CLASS; + case ISourceTag.STYLE_Function: + return SemanticHighlightings.FUNCTION_DECLARATION; + case ISourceTag.STYLE_Method: + return SemanticHighlightings.METHOD_DECLARATION; + case ISourceTag.STYLE_Variable: + return SemanticHighlightings.GLOBAL_VARIABLE; + case ISourceTag.STYLE_MemberVariable: + return SemanticHighlightings.FIELD; + case ISourceTag.STYLE_Enumerator: + return SemanticHighlightings.ENUMERATOR; + case ISourceTag.STYLE_Macro: + return SemanticHighlightings.MACRO_DEFINITION; + case ISourceTag.STYLE_Include: + // include is colored by the scanner + return null; + case ISourceTag.STYLE_Enumeration: + return SemanticHighlightings.ENUM; + case ISourceTag.STYLE_Undefined: + return null; + case ISourceTag.STYLE_Typedef: + return SemanticHighlightings.TYPEDEF; + default: + return null; } } @@ -335,8 +335,8 @@ public class SourceTagDamagerRepairer extends DefaultDamagerRepairer implements Collections.sort(fSourceTags, new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { - ISourceRange sr1 = ((ISourceTag)o1).getRangeOfIdentifier(); - ISourceRange sr2 = ((ISourceTag)o2).getRangeOfIdentifier(); + ISourceRange sr1 = ((ISourceTag) o1).getRangeOfIdentifier(); + ISourceRange sr2 = ((ISourceTag) o2).getRangeOfIdentifier(); return (sr1.getBeginOffset() - sr2.getBeginOffset()); } }); @@ -350,13 +350,13 @@ public class SourceTagDamagerRepairer extends DefaultDamagerRepairer implements protected void addRange(TextPresentation presentation, int offset, int length, TextAttribute attr) { if (length > 0 && attr != null) { presentation.addStyleRange( - new StyleRange(offset, length, attr.getForeground(), attr.getBackground(), attr.getStyle())); + new StyleRange(offset, length, attr.getForeground(), attr.getBackground(), attr.getStyle())); } } /** * Test whether the given preference change affects us. - * + * * @param event * @return <code>true</code> if the given event affects the behavior. */ @@ -366,7 +366,7 @@ public class SourceTagDamagerRepairer extends DefaultDamagerRepairer implements /** * Adapt to changes in the preferences. - * + * * @param event */ public void handlePropertyChangeEvent(PropertyChangeEvent event) { diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblyAnnotationModel.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblyAnnotationModel.java index bd26ba1d5b1..ba2e5e7c47b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblyAnnotationModel.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblyAnnotationModel.java @@ -49,7 +49,7 @@ public class DisassemblyAnnotationModel extends AnnotationModel { protected Position createPositionFromAddress(BigInteger address) { if (address != null) { - AddressRangePosition p= getDisassemblyDocument().getDisassemblyPosition(address); + AddressRangePosition p = getDisassemblyDocument().getDisassemblyPosition(address); if (p != null && p.fValid) { return new Position(p.offset, p.length); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblyRulerColumn.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblyRulerColumn.java index f4a4fd3b4e7..bcd5cf16451 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblyRulerColumn.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblyRulerColumn.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation * Anton Leherbauer (Wind River Systems) @@ -69,7 +69,7 @@ import org.eclipse.ui.editors.text.EditorsUI; * </p> */ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn implements IPropertyChangeListener { - protected final static String DOTS = "......................................................................"; //$NON-NLS-1$ + protected final static String DOTS = "......................................................................"; //$NON-NLS-1$ protected final static String SPACES = " "; //$NON-NLS-1$ /** @@ -231,7 +231,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Expands the line selection from the remembered start line to the * given line. - * + * * @param lineNumber * the line to which to expand the selection */ @@ -242,8 +242,8 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple IRegion lineInfo = document.getLineInformation(lineNumber); int start = Math.min(fStartLine.getOffset(), lineInfo.getOffset()); - int end = Math.max(fStartLine.getOffset() + fStartLine.getLength(), lineInfo.getOffset() - + lineInfo.getLength()); + int end = Math.max(fStartLine.getOffset() + fStartLine.getLength(), + lineInfo.getOffset() + lineInfo.getLength()); if (lineNumber < fStartLineNumber) fCachedTextViewer.setSelectedRange(end, start - end); @@ -263,7 +263,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Called on drag selection. - * + * * @param event * the mouse event caught by the mouse move listener * @return <code>true</code> if scrolling happened, <code>false</code> @@ -288,7 +288,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Scrolls the viewer into the given direction. - * + * * @param direction * the scroll direction */ @@ -340,7 +340,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Returns the viewer's first visible line, even if only partially * visible. - * + * * @return the viewer's first visible line */ private int getInclusiveTopIndex() { @@ -408,7 +408,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Constructs a new vertical ruler column. - * + * */ public DisassemblyRulerColumn() { this(SWT.LEFT); @@ -439,7 +439,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Sets the foreground color of this column. - * + * * @param foreground * the foreground color */ @@ -449,7 +449,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Returns the foreground color being used to print the line numbers. - * + * * @return the configured foreground color */ protected Color getForeground() { @@ -458,7 +458,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Sets the background color of this column. - * + * * @param background * the background color */ @@ -470,7 +470,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Returns the System background color for list widgets. - * + * * @param display * the display * @return the System background color for list widgets @@ -506,7 +506,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple * if the number of digits changed compared to the previous call of this * method. If the method is called for the first time, the return value is * also <code>true</code>. - * + * * @return whether the number of digits has been changed */ protected boolean updateNumberOfDigits() { @@ -527,14 +527,14 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple * Does the real computation of the number of characters. The default * implementation computes the number of digits for the line number. * Subclasses may override this method if they need extra space on the ruler. - * + * * @return the number of characters to be displayed on the ruler. */ protected int computeNumberOfCharacters() { IDocument document = fCachedTextViewer.getDocument(); - int lines= document == null ? 0 : document.getNumberOfLines(); + int lines = document == null ? 0 : document.getNumberOfLines(); - int digits= 2; + int digits = 2; while (lines > Math.pow(10, digits) - 1) { ++digits; } @@ -544,22 +544,22 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Layouts the enclosing viewer to adapt the layout to changes of the size * of the individual components. - * + * * @param redraw * <code>true</code> if this column can be redrawn */ protected void layout(boolean redraw) { if (!redraw) { - fRelayoutRequired= true; + fRelayoutRequired = true; return; } - fRelayoutRequired= false; + fRelayoutRequired = false; if (fCachedTextViewer instanceof ITextViewerExtension) { - ITextViewerExtension extension= (ITextViewerExtension) fCachedTextViewer; - Control control= extension.getControl(); + ITextViewerExtension extension = (ITextViewerExtension) fCachedTextViewer; + Control control = extension.getControl(); if (control instanceof Composite && !control.isDisposed()) { - Composite composite= (Composite) control; + Composite composite = (Composite) control; composite.layout(true); } } @@ -573,20 +573,20 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple if (fCanvas == null) return; - GC gc= new GC(fCanvas); + GC gc = new GC(fCanvas); try { gc.setFont(fCanvas.getFont()); - fIndentation= new int[fCachedNumberOfDigits + 1]; - char[] digitStr= new char[fCachedNumberOfDigits + 1]; + fIndentation = new int[fCachedNumberOfDigits + 1]; + char[] digitStr = new char[fCachedNumberOfDigits + 1]; Arrays.fill(digitStr, '9'); - Point p= gc.stringExtent(new String(digitStr, 0, fCachedNumberOfDigits + 1)); - fIndentation[0]= p.x; + Point p = gc.stringExtent(new String(digitStr, 0, fCachedNumberOfDigits + 1)); + fIndentation[0] = p.x; - for (int i= 1; i <= fCachedNumberOfDigits; i++) { - p= gc.stringExtent(new String(digitStr, 0, i)); - fIndentation[i]= fIndentation[0] - p.x; + for (int i = 1; i <= fCachedNumberOfDigits; i++) { + p = gc.stringExtent(new String(digitStr, 0, i)); + fIndentation[i] = fIndentation[0] - p.x; } } finally { @@ -600,11 +600,11 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple @Override public Control createControl(CompositeRuler parentRuler, Composite parentControl) { - fParentRuler= parentRuler; - fCachedTextViewer= parentRuler.getTextViewer(); - fCachedTextWidget= fCachedTextViewer.getTextWidget(); + fParentRuler = parentRuler; + fCachedTextViewer = parentRuler.getTextViewer(); + fCachedTextWidget = fCachedTextViewer.getTextWidget(); - fCanvas= new Canvas(parentControl, SWT.NONE); + fCanvas = new Canvas(parentControl, SWT.NONE); fCanvas.setBackground(getBackground(fCanvas.getDisplay())); fCanvas.setForeground(fForeground); @@ -620,8 +620,8 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple @Override public void widgetDisposed(DisposeEvent e) { handleDispose(); - fCachedTextViewer= null; - fCachedTextWidget= null; + fCachedTextViewer = null; + fCachedTextWidget = null; } }); @@ -635,7 +635,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple if (fFont == null) { if (fCachedTextWidget != null && !fCachedTextWidget.isDisposed()) - fFont= fCachedTextWidget.getFont(); + fFont = fCachedTextWidget.getFont(); } } @@ -660,7 +660,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple if (fBuffer != null) { fBuffer.dispose(); - fBuffer= null; + fBuffer = null; } } @@ -674,28 +674,28 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Double buffer drawing. - * + * * @param dest * the gc to draw into */ private void doubleBufferPaint(GC dest) { - Point size= fCanvas.getSize(); + Point size = fCanvas.getSize(); if (size.x <= 0 || size.y <= 0) return; if (fBuffer != null) { - Rectangle r= fBuffer.getBounds(); + Rectangle r = fBuffer.getBounds(); if (r.width != size.x || r.height != size.y) { fBuffer.dispose(); - fBuffer= null; + fBuffer = null; } } if (fBuffer == null) - fBuffer= new Image(fCanvas.getDisplay(), size.x, size.y); + fBuffer = new Image(fCanvas.getDisplay(), size.x, size.y); - GC gc= new GC(fBuffer); + GC gc = new GC(fBuffer); gc.setFont(fCanvas.getFont()); if (fForeground != null) gc.setForeground(fForeground); @@ -718,17 +718,17 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Returns the viewport height in lines. - * + * * @return the viewport height in lines */ protected int getVisibleLinesInViewport() { - Rectangle clArea= fCachedTextWidget.getClientArea(); + Rectangle clArea = fCachedTextWidget.getClientArea(); return clArea.height / fCachedTextWidget.getLineHeight(); } /** * Draws the ruler column. - * + * * @param gc * the gc to draw into */ @@ -740,12 +740,12 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple if (fCachedTextWidget == null) return; - int firstLine= 0; + int firstLine = 0; - int topLine= fCachedTextWidget.getTopIndex(); - fScrollPos= fCachedTextWidget.getTopPixel(); - int lineheight= fCachedTextWidget.getLineHeight(); - int partialLineHidden= fScrollPos % lineheight; + int topLine = fCachedTextWidget.getTopIndex(); + fScrollPos = fCachedTextWidget.getTopPixel(); + int lineheight = fCachedTextWidget.getLineHeight(); + int partialLineHidden = fScrollPos % lineheight; if (partialLineHidden > 0 && topLine > 0) // widgetTopLine shows the // first fully visible line @@ -755,51 +755,51 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple try { - IRegion region= fCachedTextViewer.getVisibleRegion(); - IDocument doc= fCachedTextViewer.getDocument(); + IRegion region = fCachedTextViewer.getVisibleRegion(); + IDocument doc = fCachedTextViewer.getDocument(); if (doc == null) return; - firstLine= doc.getLineOfOffset(region.getOffset()); + firstLine = doc.getLineOfOffset(region.getOffset()); if (firstLine > topLine) - topLine= firstLine; + topLine = firstLine; - bottomLine= doc.getLineOfOffset(region.getOffset() + region.getLength()); + bottomLine = doc.getLineOfOffset(region.getOffset() + region.getLength()); } catch (BadLocationException x) { return; } - fSensitiveToTextChanges= bottomLine - topLine < getVisibleLinesInViewport(); + fSensitiveToTextChanges = bottomLine - topLine < getVisibleLinesInViewport(); - int baselineBias= getBaselineBias(gc); + int baselineBias = getBaselineBias(gc); - int topInset= fCachedTextViewer.getTopInset(); - int y= topInset - partialLineHidden; - Point canvasSize= fCanvas.getSize(); - Point selection= fCachedTextWidget.getSelection(); - boolean selectedLine= false; - Color defaultForeground= gc.getForeground(); - Color defaultBackground= gc.getBackground(); + int topInset = fCachedTextViewer.getTopInset(); + int y = topInset - partialLineHidden; + Point canvasSize = fCanvas.getSize(); + Point selection = fCachedTextWidget.getSelection(); + boolean selectedLine = false; + Color defaultForeground = gc.getForeground(); + Color defaultBackground = gc.getBackground(); - for (int line= topLine; y < canvasSize.y && line <= bottomLine; line++, y += lineheight) { - int widgetOffset= fCachedTextWidget.getOffsetAtLine(line); + for (int line = topLine; y < canvasSize.y && line <= bottomLine; line++, y += lineheight) { + int widgetOffset = fCachedTextWidget.getOffsetAtLine(line); if (fPaintSelectionBackground && widgetOffset >= selection.x && widgetOffset < selection.y) { if (!selectedLine) { - selectedLine= true; + selectedLine = true; gc.setForeground(fCachedTextWidget.getSelectionForeground()); gc.setBackground(fCachedTextWidget.getSelectionBackground()); } } else if (selectedLine) { - selectedLine= false; + selectedLine = false; gc.setForeground(defaultForeground); gc.setBackground(defaultBackground); } if (selectedLine) { gc.fillRectangle(0, y, canvasSize.x, lineheight); } else if (fPaintStyleBackground && widgetOffset >= 0 && widgetOffset < fCachedTextWidget.getCharCount()) { - StyleRange style= fCachedTextWidget.getStyleRangeAtOffset(widgetOffset); + StyleRange style = fCachedTextWidget.getStyleRangeAtOffset(widgetOffset); if (style != null && style.background != null) { gc.setBackground(style.background); gc.fillRectangle(0, y + baselineBias, canvasSize.x, lineheight - baselineBias); @@ -807,8 +807,8 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple } } paintLine(line, y, lineheight, gc, fCachedTextWidget.getDisplay()); - String s= createDisplayString(line); - int indentation= fAlignRight ? fIndentation[s.length()] : 0; + String s = createDisplayString(line); + int indentation = fAlignRight ? fIndentation[s.length()] : 0; gc.drawString(s, indentation, y + baselineBias, true); } } @@ -816,7 +816,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Computes the string to be printed for <code>line</code>. The default * implementation returns <code>Integer.toString(line + 1)</code>. - * + * * @param line * the line number for which the string is generated * @return the string to be printed on the ruler column for <code>line</code> @@ -828,7 +828,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Draws the ruler column. Uses <code>ITextViewerExtension5</code> for the * implementation. Will replace <code>doPinat(GC)</code>. - * + * * @param gc * the gc to draw into */ @@ -837,77 +837,77 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple if (fCachedTextViewer == null) return; - ITextViewerExtension5 extension= (ITextViewerExtension5) fCachedTextViewer; + ITextViewerExtension5 extension = (ITextViewerExtension5) fCachedTextViewer; - int widgetTopLine= fCachedTextWidget.getTopIndex(); - fScrollPos= fCachedTextWidget.getTopPixel(); - int lineheight= fCachedTextWidget.getLineHeight(); - int partialLineHidden= fScrollPos % lineheight; + int widgetTopLine = fCachedTextWidget.getTopIndex(); + fScrollPos = fCachedTextWidget.getTopPixel(); + int lineheight = fCachedTextWidget.getLineHeight(); + int partialLineHidden = fScrollPos % lineheight; if (partialLineHidden > 0 && widgetTopLine > 0) // widgetTopLine shows // the first fully // visible line --widgetTopLine; - int modelTopLine= extension.widgetLine2ModelLine(widgetTopLine); - int modelBottomLine= fCachedTextViewer.getBottomIndex(); + int modelTopLine = extension.widgetLine2ModelLine(widgetTopLine); + int modelBottomLine = fCachedTextViewer.getBottomIndex(); if (modelBottomLine >= 0) ++modelBottomLine; try { - IRegion region= extension.getModelCoverage(); - IDocument doc= fCachedTextViewer.getDocument(); + IRegion region = extension.getModelCoverage(); + IDocument doc = fCachedTextViewer.getDocument(); if (doc == null) return; - int coverageTopLine= doc.getLineOfOffset(region.getOffset()); + int coverageTopLine = doc.getLineOfOffset(region.getOffset()); if (coverageTopLine > modelTopLine || modelTopLine == -1) - modelTopLine= coverageTopLine; + modelTopLine = coverageTopLine; - int coverageBottomLine= doc.getLineOfOffset(region.getOffset() + region.getLength()); + int coverageBottomLine = doc.getLineOfOffset(region.getOffset() + region.getLength()); if (coverageBottomLine < modelBottomLine || modelBottomLine == -1) - modelBottomLine= coverageBottomLine; + modelBottomLine = coverageBottomLine; } catch (BadLocationException x) { return; } - fSensitiveToTextChanges= modelBottomLine - modelTopLine < getVisibleLinesInViewport(); + fSensitiveToTextChanges = modelBottomLine - modelTopLine < getVisibleLinesInViewport(); - int baselineBias= getBaselineBias(gc); + int baselineBias = getBaselineBias(gc); - int topInset= fCachedTextViewer.getTopInset(); - int y= topInset - partialLineHidden; - Point canvasSize= fCanvas.getSize(); - Point selection= fCachedTextWidget.getSelection(); - boolean selectedLine= false; - Color defaultForeground= gc.getForeground(); - Color defaultBackground= gc.getBackground(); + int topInset = fCachedTextViewer.getTopInset(); + int y = topInset - partialLineHidden; + Point canvasSize = fCanvas.getSize(); + Point selection = fCachedTextWidget.getSelection(); + boolean selectedLine = false; + Color defaultForeground = gc.getForeground(); + Color defaultBackground = gc.getBackground(); - for (int modelLine= modelTopLine; y < canvasSize.y && modelLine <= modelBottomLine; modelLine++) { + for (int modelLine = modelTopLine; y < canvasSize.y && modelLine <= modelBottomLine; modelLine++) { // don't draw hidden (e.g. folded) lines - int widgetLine= extension.modelLine2WidgetLine(modelLine); + int widgetLine = extension.modelLine2WidgetLine(modelLine); if (widgetLine == -1) continue; - int widgetOffset= fCachedTextWidget.getOffsetAtLine(widgetLine); + int widgetOffset = fCachedTextWidget.getOffsetAtLine(widgetLine); if (fPaintSelectionBackground && widgetOffset >= selection.x && widgetOffset < selection.y) { if (!selectedLine) { - selectedLine= true; + selectedLine = true; gc.setForeground(fCachedTextWidget.getSelectionForeground()); gc.setBackground(fCachedTextWidget.getSelectionBackground()); } } else if (selectedLine) { - selectedLine= false; + selectedLine = false; gc.setForeground(defaultForeground); gc.setBackground(defaultBackground); } if (selectedLine) { gc.fillRectangle(0, y, canvasSize.x, lineheight); } else if (fPaintStyleBackground && widgetOffset >= 0 && widgetOffset < fCachedTextWidget.getCharCount()) { - StyleRange style= fCachedTextWidget.getStyleRangeAtOffset(widgetOffset); + StyleRange style = fCachedTextWidget.getStyleRangeAtOffset(widgetOffset); if (style != null && style.background != null) { gc.setBackground(style.background); gc.fillRectangle(0, y + baselineBias, canvasSize.x, lineheight - baselineBias); @@ -917,8 +917,8 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple paintLine(modelLine, y, lineheight, gc, fCachedTextWidget.getDisplay()); - String s= createDisplayString(modelLine); - int indentation= fAlignRight ? fIndentation[s.length()] : 0; + String s = createDisplayString(modelLine); + int indentation = fAlignRight ? fIndentation[s.length()] : 0; gc.drawString(s, indentation, y + baselineBias, true); y += lineheight; } @@ -929,7 +929,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple * baseline as specified by the font for <code>gc</code>. When drawing * text, the returned bias should be added to obtain text line up on * the correct base line of the text widget. - * + * * @param gc * the <code>GC</code> to get the font metrics from * @return the baseline bias to use when drawing text that is line up with @@ -942,11 +942,11 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple * since font styles (bold, italics...) can have larger font metrics * than the simple font used for the numbers. */ - int widgetBaseline= fCachedTextWidget.getBaseline(); - FontMetrics fm= gc.getFontMetrics(); - int fontBaseline= fm.getAscent() + fm.getLeading(); + int widgetBaseline = fCachedTextWidget.getBaseline(); + FontMetrics fm = gc.getFontMetrics(); + int fontBaseline = fm.getAscent() + fm.getLeading(); Assert.isTrue(widgetBaseline >= fontBaseline); - int baselineBias= widgetBaseline - fontBaseline; + int baselineBias = widgetBaseline - fontBaseline; return baselineBias; } @@ -956,7 +956,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple * <p> * This default implementation does nothing. * </p> - * + * * @param line * the line of the document which the ruler is painted for * @param y @@ -978,12 +978,12 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple */ protected final void postRedraw() { if (fCanvas != null && !fCanvas.isDisposed()) { - Display d= fCanvas.getDisplay(); + Display d = fCanvas.getDisplay(); if (d != null) { synchronized (fRunnableLock) { if (fIsRunnablePosted) return; - fIsRunnablePosted= true; + fIsRunnablePosted = true; } d.asyncExec(fRunnable); } @@ -1002,7 +1002,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple } if (fCanvas != null && !fCanvas.isDisposed()) { - GC gc= new GC(fCanvas); + GC gc = new GC(fCanvas); doubleBufferPaint(gc); gc.dispose(); } @@ -1020,7 +1020,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple */ @Override public void setFont(Font font) { - fFont= font; + fFont = font; if (fCanvas != null && !fCanvas.isDisposed()) { fCanvas.setFont(fFont); updateNumberOfDigits(); @@ -1030,7 +1030,7 @@ public class DisassemblyRulerColumn extends AbstractContributedRulerColumn imple /** * Returns the parent (composite) ruler of this ruler column. - * + * * @return the parent ruler */ protected CompositeRuler getParentRuler() { diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblySelection.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblySelection.java index ed8b92cee64..a92cdd31bb7 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblySelection.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblySelection.java @@ -36,7 +36,7 @@ import org.eclipse.jface.text.Position; /** * Default implementation of {@link IDisassemblySelection}. - * + * * @since 2.1 * @noextend This class is not intended to be subclassed by clients. */ @@ -50,7 +50,7 @@ public class DisassemblySelection implements IDisassemblySelection { /** * Create a disassembly selection from a normal text selection and a disassembly part. - * + * * @param selection the text selection * @param part the disassembly part */ @@ -91,7 +91,7 @@ public class DisassemblySelection implements IDisassemblySelection { fStartAddress = null; } } - + try { Position labelPosition = document.getPosition(DisassemblyDocument.CATEGORY_LABELS, offset, true); if (labelPosition != null) { @@ -103,7 +103,7 @@ public class DisassemblySelection implements IDisassemblySelection { fLabel = null; } } - + /* * @see org.eclipse.jface.viewers.ISelection#isEmpty() */ @@ -203,7 +203,7 @@ public class DisassemblySelection implements IDisassemblySelection { public IAddress getStartAddress() { return fStartAddress; } - + /** * @since 2.2 */ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblyViewer.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblyViewer.java index 6fd302a24c7..c0cc9951143 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblyViewer.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/DisassemblyViewer.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -47,6 +47,7 @@ public class DisassemblyViewer extends SourceViewer { public void controlResized(ControlEvent e) { updateViewportListeners(RESIZE); } + @Override public void controlMoved(ControlEvent e) { } @@ -54,7 +55,7 @@ public class DisassemblyViewer extends SourceViewer { private boolean fUserTriggeredScrolling; private int fCachedLastTopPixel; - + /** * Create a new DisassemblyViewer. * @param parent @@ -63,7 +64,8 @@ public class DisassemblyViewer extends SourceViewer { * @param showsAnnotationOverview * @param styles */ - public DisassemblyViewer(Composite parent, IVerticalRuler ruler, IOverviewRuler overviewRuler, boolean showsAnnotationOverview, int styles) { + public DisassemblyViewer(Composite parent, IVerticalRuler ruler, IOverviewRuler overviewRuler, + boolean showsAnnotationOverview, int styles) { super(parent, ruler, overviewRuler, showsAnnotationOverview, styles); // always readonly setEditable(false); @@ -100,7 +102,8 @@ public class DisassemblyViewer extends SourceViewer { selectedText = getSelectedText(); } catch (BadLocationException e) { // should not happend - DsfUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, e.getLocalizedMessage(), e)); + DsfUIPlugin.getDefault().getLog() + .log(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, e.getLocalizedMessage(), e)); return; } Clipboard clipboard = new Clipboard(textWidget.getDisplay()); @@ -121,7 +124,7 @@ public class DisassemblyViewer extends SourceViewer { public String getSelectedText() throws BadLocationException { StringBuilder text = new StringBuilder(200); String lineSeparator = System.getProperty("line.separator"); //$NON-NLS-1$ - DisassemblyDocument doc = (DisassemblyDocument)getDocument(); + DisassemblyDocument doc = (DisassemblyDocument) getDocument(); Point selection = getSelectedRange(); int startOffset = selection.x; int length = selection.y; @@ -176,15 +179,15 @@ public class DisassemblyViewer extends SourceViewer { StringBuilder prefix = new StringBuilder(10); IVerticalRuler ruler = getVerticalRuler(); if (ruler instanceof CompositeRuler) { - for (Iterator<?> iter = ((CompositeRuler)ruler).getDecoratorIterator(); iter.hasNext();) { + for (Iterator<?> iter = ((CompositeRuler) ruler).getDecoratorIterator(); iter.hasNext();) { IVerticalRulerColumn column = (IVerticalRulerColumn) iter.next(); if (column instanceof DisassemblyRulerColumn) { - DisassemblyRulerColumn disassColumn = (DisassemblyRulerColumn)column; + DisassemblyRulerColumn disassColumn = (DisassemblyRulerColumn) column; String columnText = disassColumn.createDisplayString(line); prefix.append(columnText); int columnWidth = disassColumn.computeNumberOfCharacters(); columnWidth -= columnText.length(); - while(columnWidth-- > 0) + while (columnWidth-- > 0) prefix.append(' '); prefix.append(' '); } @@ -213,7 +216,7 @@ public class DisassemblyViewer extends SourceViewer { int bottom = top + lines; int bottomBuffer = Math.max(1, lines / 3); - + if (!onTop && focusLine >= top && focusLine <= bottom - bottomBuffer) { // do not scroll at all as it is already visible } else { @@ -242,7 +245,7 @@ public class DisassemblyViewer extends SourceViewer { private int getEstimatedVisibleLinesInViewport() { StyledText textWidget = getTextWidget(); if (textWidget != null) { - Rectangle clArea= textWidget.getClientArea(); + Rectangle clArea = textWidget.getClientArea(); if (!clArea.isEmpty()) return clArea.height / textWidget.getLineHeight(); } @@ -252,7 +255,7 @@ public class DisassemblyViewer extends SourceViewer { public int getLastTopPixel() { return fCachedLastTopPixel; } - + public boolean isUserTriggeredScrolling() { return fUserTriggeredScrolling; } @@ -269,5 +272,5 @@ public class DisassemblyViewer extends SourceViewer { } super.updateViewportListeners(origin); } - + } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IBreakpointLocationProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IBreakpointLocationProvider.java index c8529129777..287d505a4bf 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IBreakpointLocationProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IBreakpointLocationProvider.java @@ -27,13 +27,13 @@ import org.eclipse.debug.core.model.ILineBreakpoint; * If a breakpoint adapts to this interface, its position in the viewer is * determined by the information provided by the location provider. * </p> - * + * * <p> * Breakpoints implementing either {@link ICAddressBreakpoint} or {@link ILineBreakpoint} * need not provide a location provider but may do so in order to override default * location retrieval. - * </p> - * + * </p> + * * <p> * The annotation position will be determined with the following ordering: * <ol> @@ -50,7 +50,7 @@ public interface IBreakpointLocationProvider { /** * Returns the line number of the breakpoint or -1 if no line number is * available. - * + * * @param breakpoint the breakpoint * @param debugContext the debug context of the view * @return the line number or -1 @@ -60,7 +60,7 @@ public interface IBreakpointLocationProvider { /** * Returns the source file path of the breakpoint or <code>null</code> if no * source file is associated with this breakpoint. - * + * * @param breakpoint the breakpoint * @param debugContext the debug context of the view * @return the file path, can be <code>null</code> @@ -70,7 +70,7 @@ public interface IBreakpointLocationProvider { /** * Returns the label address of the breakpoint or <code>null</code> if no * label is associated with this breakpoint. - * + * * @param breakpoint the breakpoint * @param debugContext the debug context of the view * @return the label address, can be <code>null</code> @@ -79,13 +79,13 @@ public interface IBreakpointLocationProvider { /** * Returns the addresses of the breakpoint. - * + * * <p> * <i>Currently there can only be one annotation per breakpoint. Therefore * an annotation is created only for the first valid address. Support for * multiple annotations per breakpoint is up for future enhancements. </i> * </p> - * + * * @param breakpoint the breakpoint * @param debugContext the debug context of the view * @return the addresses, can be <code>null</code> diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IDisassemblyPart.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IDisassemblyPart.java index 6499d6fbd6b..70c09ab2869 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IDisassemblyPart.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IDisassemblyPart.java @@ -20,60 +20,60 @@ import org.eclipse.ui.IWorkbenchPart; /** * Interface which the disassembly view and editor implement. - * + * * @since 2.1 * @noextend This interface is not intended to be extended by clients. * @noimplement This interface is not intended to be implemented by clients. */ public interface IDisassemblyPart extends IWorkbenchPart { - + /** * Property id for the active state of the part. */ - public final int PROP_ACTIVE= 0x505; + public final int PROP_ACTIVE = 0x505; /** * Property id for the connected state of the part. */ - public final int PROP_CONNECTED= 0x506; + public final int PROP_CONNECTED = 0x506; /** * Property id for the suspended state of the underlying execution context. */ - public final int PROP_SUSPENDED= 0x507; - + public final int PROP_SUSPENDED = 0x507; + /** * Test whether this part is connected to a debug session and execution context. - * + * * @return <code>true</code> if the part is connected to a debug session and execution context */ boolean isConnected(); - + /** * Test whether this part is active. A part is active if it is visible and connected. - * + * * @return <code>true</code> if the part is active */ boolean isActive(); - + /** * Test whether the underlying execution context is currently suspended. * Implies connected state. - * + * * @return <code>true</code> if the execution context is currently suspended */ boolean isSuspended(); /** * Get access to the text viewer. - * + * * @return the text viewer */ ISourceViewer getTextViewer(); - + /** * Navigate to the given address. - * + * * @param address */ void gotoAddress(IAddress address); @@ -85,7 +85,7 @@ public interface IDisassemblyPart extends IWorkbenchPart { /** * Navigate to the address the given expression evaluates to. - * + * * @param expression a symbolic address expression */ void gotoSymbol(String expression); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IDisassemblySelection.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IDisassemblySelection.java index a33141d56ff..e9c2c8f99fd 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IDisassemblySelection.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IDisassemblySelection.java @@ -35,25 +35,25 @@ public interface IDisassemblySelection extends ITextSelection { * @return the address associated with the start of the selection, may be <code>null</code> */ IAddress getStartAddress(); - + /** * @return the {@link IFile} associated with the selection, may be <code>null</code> */ IFile getSourceFile(); - + /** * @return the source location {@link URI} of the associated source file, may be <code>null</code> */ URI getSourceLocationURI(); - + /** * @return the 0-based line number of the source file associated with the selection, -1 if not available */ int getSourceLine(); - + /** * @return the label, may be <code>null</code> - * + * * @since 2.2 */ String getLabel(); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/IFileRider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/IFileRider.java index af72483c741..2bc548bef57 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/IFileRider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/IFileRider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDDocument.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDDocument.java index 23e66736085..e4e24359a94 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDDocument.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDDocument.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -35,7 +35,7 @@ public class REDDocument extends AbstractDocument { public void dispose() { ITextStore store = getStore(); if (store instanceof REDTextStore) { - ((REDTextStore)store).dispose(); + ((REDTextStore) store).dispose(); setTextStore(new StringTextStore()); getTracker().set(""); //$NON-NLS-1$ } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDFile.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDFile.java index 1f4a36ccc0c..32378d84fe1 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDFile.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDFile.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -78,7 +78,7 @@ public final class REDFile { if (file != null) { try { setFile(file); - fLength = (int)(fFile.length() / 2); + fLength = (int) (fFile.length() / 2); } catch (IOException ioe) { throw new Error(ioe); } @@ -86,7 +86,7 @@ public final class REDFile { } public REDFile() { - this((File)null, false); + this((File) null, false); } public REDFile(String name, boolean readonly) { @@ -172,7 +172,7 @@ public final class REDFile { fLength = 0; } else { try { - fLength = (int)(fFile.length() / 2); + fLength = (int) (fFile.length() / 2); } catch (IOException e) { fLength = 0; } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDFileRider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDFileRider.java index b81ef2a403b..414684b4dee 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDFileRider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDFileRider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -30,6 +30,7 @@ public final class REDFileRider implements IFileRider { public REDFileRider(REDFile f) throws IOException { set(f, 0); } + public REDFileRider(REDFile f, int limit) throws IOException { fLimit = limit; set(f, 0); @@ -47,7 +48,7 @@ public final class REDFileRider implements IFileRider { /** * Set rider to file and position - * + * * @param f the file the rider should operate on * @param pos is normalized to be in range [0, f.length()] * @pre f != null @@ -137,14 +138,14 @@ public final class REDFileRider implements IFileRider { @Override public void readChars(char[] buf, int off, int n) throws IOException { int count = fFile.readBuffered(buf, off, n); - fResult = n-count; + fResult = n - count; fEof = fResult > 0; } @Override public void readChars(StringBuffer buf, int n) throws IOException { int count = fFile.readBuffered(buf, n); - fResult = n-count; + fResult = n - count; fEof = fResult > 0; } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDRun.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDRun.java index 92d4acafe46..274879d7adc 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDRun.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDRun.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -111,7 +111,6 @@ public class REDRun implements CharSequence { return r.fRider == fRider && r.fOffset == fOffset + fLength; } - /* * @see java.lang.Object#toString() */ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDTextStore.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDTextStore.java index b5e9ee26506..45bf337ef97 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDTextStore.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/REDTextStore.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -63,13 +63,13 @@ public final class REDTextStore implements ITextStore { REDFileRider fileRider = null; if (!monitor.isCanceled()) { try { -// System.out.println("TextStoreSwapper.run() creating swap file"); + // System.out.println("TextStoreSwapper.run() creating swap file"); fileRider = new REDFileRider(new REDFile()); int size = fText.length(); - monitor.beginTask(getName(), size+1); + monitor.beginTask(getName(), size + 1); int written = 0; while (written < size && !monitor.isCanceled()) { - int n = Math.min(size-written, CHUNK_SIZE); + int n = Math.min(size - written, CHUNK_SIZE); fileRider.writeChars(fText, written, n); monitor.worked(n); written += n; @@ -79,19 +79,19 @@ public final class REDTextStore implements ITextStore { } } if (!monitor.isCanceled()) { -// System.out.println("TextStoreSwapper.run() swapping"); + // System.out.println("TextStoreSwapper.run() swapping"); fileRider = swap(fRider, fileRider); monitor.done(); } // something went wrong, dispose the file if (fileRider != null) { -// System.out.println("TextStoreSwapper.run() disposing"); + // System.out.println("TextStoreSwapper.run() disposing"); fileRider.getFile().dispose(); } // remove references fText = null; fRider = null; -// System.out.println("TextStoreSwapper.run() done"); + // System.out.println("TextStoreSwapper.run() done"); return Status.OK_STATUS; } } @@ -103,9 +103,11 @@ public final class REDTextStore implements ITextStore { LinkedRun(IFileRider rider, String str) throws IOException { super(rider, str); } + LinkedRun(IFileRider rider, char[] buf, int off, int n) throws IOException { super(rider, buf, off, n); } + LinkedRun(IFileRider rider, int offset, int length) { super(rider, offset, length); } @@ -179,8 +181,8 @@ public final class REDTextStore implements ITextStore { synchronized (fRunSpec) { // special case: long in-memory text in full length (about to be swapped) if (length == fLength && fSwapper != null && fHead != null && fHead.fNext == null) { - ((StringRider)fHead.fRider).fBuffer.position(0); - return ((StringRider)fHead.fRider).fBuffer.toString(); + ((StringRider) fHead.fRider).fBuffer.position(0); + return ((StringRider) fHead.fRider).fBuffer.toString(); } return toString(offset, offset + length); } @@ -283,7 +285,7 @@ public final class REDTextStore implements ITextStore { assert from >= 0 && from <= fLength; assert deleteLen >= 0; assert from + deleteLen <= fLength; - + RunPair split = null; if (deleteLen > 0) { split = delete(from, from + deleteLen); @@ -291,19 +293,19 @@ public final class REDTextStore implements ITextStore { if (buf == null || insertLen == 0) { return; } -// assert off >= 0 && off < buf.length; -// assert insertLen >= 0 && off+insertLen <= buf.length; - if (split == null) { - split = splitRun(from); - } + // assert off >= 0 && off < buf.length; + // assert insertLen >= 0 && off+insertLen <= buf.length; + if (split == null) { + split = splitRun(from); + } RunPair insert = makeRuns(split.fBefore, buf, off, insertLen); -// assert runLength(insert.fBefore, insert.fAfter) == insertLen; + // assert runLength(insert.fBefore, insert.fAfter) == insertLen; insertRuns(split, insert.fBefore, insert.fAfter); fLength += insertLen; -// assert runLength(fHead, null) == fLength; + // assert runLength(fHead, null) == fLength; fCache = insert.fAfter; - fCachePos = from+insertLen-insert.fAfter.fLength; -// assert checkConsistency(); + fCachePos = from + insertLen - insert.fAfter.fLength; + // assert checkConsistency(); if (split.fBefore != null) { mergeRuns(split.fBefore, split.fAfter); } else { @@ -366,7 +368,8 @@ public final class REDTextStore implements ITextStore { */ private LinkedRun createRun(LinkedRun before, int n) { IFileRider scratchFile; - if (before != null && before.fRider.length() == before.fOffset + before.fLength && before.fRider.limit() >= before.fRider.length() + n) { + if (before != null && before.fRider.length() == before.fOffset + before.fLength + && before.fRider.limit() >= before.fRider.length() + n) { scratchFile = before.fRider; } else { scratchFile = getScratchFile(); @@ -457,6 +460,7 @@ public final class REDTextStore implements ITextStore { private final static class RunSpec { public LinkedRun fRun = null; public int fOff = -1; + public boolean isValid() { return fRun != null; } @@ -586,7 +590,8 @@ public final class REDTextStore implements ITextStore { p.fBefore = spec.fRun; int len = spec.fRun.length(); if (spec.fOff != len) { // need to split - p.fAfter = new LinkedRun(p.fBefore.fRider, p.fBefore.fOffset + spec.fOff, p.fBefore.fLength - spec.fOff); + p.fAfter = new LinkedRun(p.fBefore.fRider, p.fBefore.fOffset + spec.fOff, + p.fBefore.fLength - spec.fOff); p.fBefore.fLength = spec.fOff; p.fAfter.fNext = p.fBefore.fNext; if (p.fAfter.fNext != null) { @@ -648,13 +653,13 @@ public final class REDTextStore implements ITextStore { } run.fRider.seek(run.fOffset); if (buf instanceof char[]) { - run.fRider.writeChars((char[])buf, off, count); + run.fRider.writeChars((char[]) buf, off, count); } else { - run.fRider.writeChars((String)buf, off, count); + run.fRider.writeChars((String) buf, off, count); } if (run.fLength - count >= RECYCLE_THRESHOLD) { LinkedRun next = run.fNext; - LinkedRun newRun = new LinkedRun(run.fRider, run.fOffset+count, run.fLength-count); + LinkedRun newRun = new LinkedRun(run.fRider, run.fOffset + count, run.fLength - count); joinRuns(run, newRun); joinRuns(newRun, next); } else { @@ -667,7 +672,7 @@ public final class REDTextStore implements ITextStore { run = run.fNext; } catch (IOException e) { run = null; -// internalError(e); + // internalError(e); break; } } while (run != null && n > 0); @@ -681,18 +686,18 @@ public final class REDTextStore implements ITextStore { if (buf instanceof char[]) { try { run.fRider.seek(run.fOffset); - run.fRider.writeChars((char[])buf, off, n); + run.fRider.writeChars((char[]) buf, off, n); } catch (IOException e) { -// internalError(e); - run = new LinkedRun(new StringRider(CharBuffer.wrap((char[])buf, off, off+n)), 0, n); + // internalError(e); + run = new LinkedRun(new StringRider(CharBuffer.wrap((char[]) buf, off, off + n)), 0, n); } } else { try { run.fRider.seek(run.fOffset); - run.fRider.writeChars((String)buf, off, n); + run.fRider.writeChars((String) buf, off, n); } catch (IOException e) { -// internalError(e); - run = new LinkedRun(new StringRider(CharBuffer.wrap((String)buf, off, off+n)), 0, n); + // internalError(e); + run = new LinkedRun(new StringRider(CharBuffer.wrap((String) buf, off, off + n)), 0, n); } } if (result.fBefore == null) { @@ -706,7 +711,7 @@ public final class REDTextStore implements ITextStore { } return result; } - + private void joinRuns(LinkedRun start, LinkedRun next) { assert start != next; start.fNext = next; @@ -714,6 +719,7 @@ public final class REDTextStore implements ITextStore { next.fPrev = start; } } + private void insertRuns(RunPair pos, LinkedRun start, LinkedRun end) { assert pos.fBefore == null || pos.fBefore != pos.fAfter; start.fPrev = pos.fBefore; @@ -727,7 +733,7 @@ public final class REDTextStore implements ITextStore { pos.fAfter.fPrev = end; } } - + /** * Swap given old (readonly) rider with the new (writable) one. * @param oldRider @@ -735,7 +741,7 @@ public final class REDTextStore implements ITextStore { * @return <code>null</code> if the new rider was consumed */ private REDFileRider swap(IFileRider oldRider, REDFileRider newRider) { - synchronized(fRunSpec) { + synchronized (fRunSpec) { // search linked run list starting from head and replace // all instances of oldRider with newRider // in the general case, spare list should be searched, too @@ -754,7 +760,7 @@ public final class REDTextStore implements ITextStore { } if (newRider != null) { // unlikely, but possible: need to increase array - REDFileRider[] scratchFiles = new REDFileRider[fScratchFiles.length+1]; + REDFileRider[] scratchFiles = new REDFileRider[fScratchFiles.length + 1]; System.arraycopy(fScratchFiles, 0, scratchFiles, 0, fScratchFiles.length); scratchFiles[fScratchFiles.length] = newRider; fScratchFiles = scratchFiles; @@ -775,23 +781,23 @@ public final class REDTextStore implements ITextStore { int nSpare = 0; int spareLength = 0; LinkedRun run = fHead; - while(run != null) { + while (run != null) { ++nRuns; run = run.fNext; } run = fSpare; - while(run != null) { + while (run != null) { ++nSpare; spareLength += run.fLength; run = run.fNext; } - double runMean = nRuns > 0 ? (double)fLength / nRuns : Double.NaN; + double runMean = nRuns > 0 ? (double) fLength / nRuns : Double.NaN; double spareMean = nSpare > 0 ? spareLength / nSpare : Double.NaN; - out.println("Length: "+fLength); //$NON-NLS-1$ - out.println("Number of runs: "+nRuns); //$NON-NLS-1$ + out.println("Length: " + fLength); //$NON-NLS-1$ + out.println("Number of runs: " + nRuns); //$NON-NLS-1$ out.println("Mean length of runs: " + runMean); //$NON-NLS-1$ - out.println("Length of spare runs: "+spareLength); //$NON-NLS-1$ - out.println("Number of spare runs: "+nSpare); //$NON-NLS-1$ + out.println("Length of spare runs: " + spareLength); //$NON-NLS-1$ + out.println("Number of spare runs: " + nSpare); //$NON-NLS-1$ out.println("Mean length of spare runs: " + spareMean); //$NON-NLS-1$ out.println("Length of dead runs: " + fDeadLength); //$NON-NLS-1$ } @@ -817,7 +823,7 @@ public final class REDTextStore implements ITextStore { structure += "null"; //$NON-NLS-1$ return structure; } - + /** * For debugging purposes only. */ @@ -862,7 +868,7 @@ public final class REDTextStore implements ITextStore { } return true; } - + int runLength(LinkedRun first, LinkedRun last) { LinkedRun run = first; int length = 0; diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/StringRider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/StringRider.java index ba5c4df0912..3d360f28b2a 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/StringRider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/StringRider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -61,7 +61,7 @@ public class StringRider implements IFileRider { @Override public void writeChars(String buf, int off, int n) throws IOException { - fBuffer.put(buf, off, off+n); + fBuffer.put(buf, off, off + n); } @Override @@ -90,7 +90,7 @@ public class StringRider implements IFileRider { if (fBuffer.hasArray()) { buf.append(fBuffer.array(), fBuffer.arrayOffset() + pos, n); } else { - fBuffer.limit(pos+n); + fBuffer.limit(pos + n); String str = fBuffer.toString(); assert str.length() == n; buf.append(str); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/StringTextStore.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/StringTextStore.java index 0c19fb4aa89..18c9b2f2473 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/StringTextStore.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/text/StringTextStore.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -47,7 +47,7 @@ public class StringTextStore implements ITextStore { if (length == fText.length()) { return fText; } - return new String(fText.substring(offset, offset+length)); + return new String(fText.substring(offset, offset + length)); } /* (non-Javadoc) diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/util/HSL.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/util/HSL.java index 61ae28c3214..66cc3d38d11 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/util/HSL.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/util/HSL.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -32,14 +32,14 @@ public class HSL { double red = rgb.red / 255.0; double green = rgb.green / 255.0; double blue = rgb.blue / 255.0; - double cmax= Math.max(Math.max(red, green), blue); - double cmin= Math.min(Math.min(red, green), blue); - luminance = (cmax+cmin)/2; + double cmax = Math.max(Math.max(red, green), blue); + double cmin = Math.min(Math.min(red, green), blue); + luminance = (cmax + cmin) / 2; if (cmax == cmin) { hue = 0; saturation = 0; } else { - double delta = cmax-cmin; + double delta = cmax - cmin; if (luminance < 0.5) { saturation = delta / (cmax + cmin); } else { @@ -62,9 +62,9 @@ public class HSL { } public RGB toRGB() { - int red,green,blue; + int red, green, blue; if (saturation == 0) { - red = (int)Math.round(255*luminance); + red = (int) Math.round(255 * luminance); green = red; blue = red; } else { @@ -75,9 +75,9 @@ public class HSL { m2 = luminance + saturation - luminance * saturation; } m1 = 2 * luminance - m2; - red = hueToColorValue(hue + 1./3., m1, m2); + red = hueToColorValue(hue + 1. / 3., m1, m2); green = hueToColorValue(hue, m1, m2); - blue = hueToColorValue(hue - 1./3., m1, m2); + blue = hueToColorValue(hue - 1. / 3., m1, m2); } return new RGB(red, green, blue); } @@ -89,16 +89,16 @@ public class HSL { } else if (hue > 1) { hue -= 1; } - if (6*hue < 1) { - v = m1 + (m2-m1) * hue * 6; - } else if (2*hue < 1) { + if (6 * hue < 1) { + v = m1 + (m2 - m1) * hue * 6; + } else if (2 * hue < 1) { v = m2; - } else if (3*hue < 2) { - v = m1 + (m2-m1) * (2./3. - hue) * 6; + } else if (3 * hue < 2) { + v = m1 + (m2 - m1) * (2. / 3. - hue) * 6; } else { v = m1; } - return (int)Math.round(255 * v); + return (int) Math.round(255 * v); } /** @@ -108,7 +108,7 @@ public class HSL { * @return a string representation of the <code>HSL</code> */ @Override - public String toString () { + public String toString() { return "HSL {" + hue + ", " + saturation + ", " + luminance + "}"; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/util/StorageEditorInput.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/util/StorageEditorInput.java index ff198b4fe08..ada4e152065 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/util/StorageEditorInput.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/util/StorageEditorInput.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,7 +19,6 @@ import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.IPersistableElement; import org.eclipse.ui.IStorageEditorInput; - /** * Abstract implementation of <code>IStorageEditorInput</code>. */ @@ -96,7 +95,7 @@ abstract public class StorageEditorInput implements IStorageEditorInput { } try { return object instanceof IStorageEditorInput - && getStorage().equals(((IStorageEditorInput)object).getStorage()); + && getStorage().equals(((IStorageEditorInput) object).getStorage()); } catch (CoreException e) { } return false; diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/DecoratingIntegerFieldEditor.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/DecoratingIntegerFieldEditor.java index 5290a442ac4..92285661eb4 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/DecoratingIntegerFieldEditor.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/DecoratingIntegerFieldEditor.java @@ -25,7 +25,7 @@ import org.eclipse.swt.widgets.Text; /** * An {@link IntegerFieldEditor} with field decoration. - * + * * @since 1.1 */ public class DecoratingIntegerFieldEditor extends IntegerFieldEditor { @@ -35,25 +35,25 @@ public class DecoratingIntegerFieldEditor extends IntegerFieldEditor { protected DecoratingIntegerFieldEditor() { } - /** - * Creates an integer field editor. - * - * @param name the name of the preference this field editor works on - * @param labelText the label text of the field editor - * @param parent the parent of the field editor's control - */ + /** + * Creates an integer field editor. + * + * @param name the name of the preference this field editor works on + * @param labelText the label text of the field editor + * @param parent the parent of the field editor's control + */ public DecoratingIntegerFieldEditor(String name, String labelText, Composite parent) { super(name, labelText, parent); } - /** - * Creates an integer field editor. - * - * @param name the name of the preference this field editor works on - * @param labelText the label text of the field editor - * @param parent the parent of the field editor's control - * @param textLimit the maximum number of characters in the text. - */ + /** + * Creates an integer field editor. + * + * @param name the name of the preference this field editor works on + * @param labelText the label text of the field editor + * @param parent the parent of the field editor's control + * @param textLimit the maximum number of characters in the text. + */ public DecoratingIntegerFieldEditor(String name, String labelText, Composite parent, int textLimit) { super(name, labelText, parent, textLimit); } @@ -63,21 +63,22 @@ public class DecoratingIntegerFieldEditor extends IntegerFieldEditor { Text control = super.getTextControl(parent); if (fDecoration == null) { fDecoration = new ControlDecoration(control, SWT.LEFT | SWT.TOP); - FieldDecoration errorDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_ERROR); + FieldDecoration errorDecoration = FieldDecorationRegistry.getDefault() + .getFieldDecoration(FieldDecorationRegistry.DEC_ERROR); fDecoration.setImage(errorDecoration.getImage()); fDecoration.setDescriptionText(getErrorMessage()); // validate on focus gain - control.addFocusListener(new FocusAdapter() { - @Override + control.addFocusListener(new FocusAdapter() { + @Override public void focusGained(FocusEvent e) { - refreshValidState(); - } - }); + refreshValidState(); + } + }); } return control; } - + @Override protected void showErrorMessage(String msg) { super.showErrorMessage(msg); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/DecoratingStringFieldEditor.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/DecoratingStringFieldEditor.java index 057e4c4ed43..b34af4ac9b6 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/DecoratingStringFieldEditor.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/DecoratingStringFieldEditor.java @@ -34,45 +34,45 @@ public class DecoratingStringFieldEditor extends StringFieldEditor { protected DecoratingStringFieldEditor() { } - /** - * Creates a string field editor of unlimited width. - * Use the method <code>setTextLimit</code> to limit the text. - * - * @param name the name of the preference this field editor works on - * @param labelText the label text of the field editor - * @param parent the parent of the field editor's control - */ + /** + * Creates a string field editor of unlimited width. + * Use the method <code>setTextLimit</code> to limit the text. + * + * @param name the name of the preference this field editor works on + * @param labelText the label text of the field editor + * @param parent the parent of the field editor's control + */ public DecoratingStringFieldEditor(String name, String labelText, Composite parent) { super(name, labelText, parent); } - /** - * Creates a string field editor. - * Use the method <code>setTextLimit</code> to limit the text. - * - * @param name the name of the preference this field editor works on - * @param labelText the label text of the field editor - * @param width the width of the text input field in characters, - * or <code>UNLIMITED</code> for no limit - * @param parent the parent of the field editor's control - */ + /** + * Creates a string field editor. + * Use the method <code>setTextLimit</code> to limit the text. + * + * @param name the name of the preference this field editor works on + * @param labelText the label text of the field editor + * @param width the width of the text input field in characters, + * or <code>UNLIMITED</code> for no limit + * @param parent the parent of the field editor's control + */ public DecoratingStringFieldEditor(String name, String labelText, int width, Composite parent) { super(name, labelText, width, parent); } - /** - * Creates a string field editor. - * Use the method <code>setTextLimit</code> to limit the text. - * - * @param name the name of the preference this field editor works on - * @param labelText the label text of the field editor - * @param width the width of the text input field in characters, - * or <code>UNLIMITED</code> for no limit - * @param strategy either <code>VALIDATE_ON_KEY_STROKE</code> to perform - * on the fly checking (the default), or <code>VALIDATE_ON_FOCUS_LOST</code> to - * perform validation only after the text has been typed in - * @param parent the parent of the field editor's control - */ + /** + * Creates a string field editor. + * Use the method <code>setTextLimit</code> to limit the text. + * + * @param name the name of the preference this field editor works on + * @param labelText the label text of the field editor + * @param width the width of the text input field in characters, + * or <code>UNLIMITED</code> for no limit + * @param strategy either <code>VALIDATE_ON_KEY_STROKE</code> to perform + * on the fly checking (the default), or <code>VALIDATE_ON_FOCUS_LOST</code> to + * perform validation only after the text has been typed in + * @param parent the parent of the field editor's control + */ public DecoratingStringFieldEditor(String name, String labelText, int width, int strategy, Composite parent) { super(name, labelText, width, strategy, parent); } @@ -82,21 +82,22 @@ public class DecoratingStringFieldEditor extends StringFieldEditor { Text control = super.getTextControl(parent); if (fDecoration == null) { fDecoration = new ControlDecoration(control, SWT.LEFT | SWT.TOP); - FieldDecoration errorDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_ERROR); + FieldDecoration errorDecoration = FieldDecorationRegistry.getDefault() + .getFieldDecoration(FieldDecorationRegistry.DEC_ERROR); fDecoration.setImage(errorDecoration.getImage()); fDecoration.setDescriptionText(getErrorMessage()); // validate on focus gain - control.addFocusListener(new FocusAdapter() { - @Override + control.addFocusListener(new FocusAdapter() { + @Override public void focusGained(FocusEvent e) { - refreshValidState(); - } - }); + refreshValidState(); + } + }); } return control; } - + @Override protected void showErrorMessage(String msg) { super.showErrorMessage(msg); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/DsfDebugPreferencePage.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/DsfDebugPreferencePage.java index 55f900ccc08..acfc6d5753b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/DsfDebugPreferencePage.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/DsfDebugPreferencePage.java @@ -39,9 +39,9 @@ public class DsfDebugPreferencePage extends FieldEditorPreferencePage implements */ public DsfDebugPreferencePage() { super(FLAT); - IPreferenceStore store= DsfUIPlugin.getDefault().getPreferenceStore(); + IPreferenceStore store = DsfUIPlugin.getDefault().getPreferenceStore(); setPreferenceStore(store); - setDescription(MessagesForPreferences.DsfDebugPreferencePage_description); + setDescription(MessagesForPreferences.DsfDebugPreferencePage_description); } /* @@ -59,23 +59,21 @@ public class DsfDebugPreferencePage extends FieldEditorPreferencePage implements @Override protected void createFieldEditors() { - final Composite parent= getFieldEditorParent(); - final GridLayout layout= new GridLayout(); - layout.marginWidth= 0; + final Composite parent = getFieldEditorParent(); + final GridLayout layout = new GridLayout(); + layout.marginWidth = 0; parent.setLayout(layout); - - Group performanceGroup= new Group(parent, SWT.NONE); + + Group performanceGroup = new Group(parent, SWT.NONE); performanceGroup.setText(MessagesForPreferences.DsfDebugPreferencePage_performanceGroup_label); - GridLayout groupLayout= new GridLayout(3, false); + GridLayout groupLayout = new GridLayout(3, false); performanceGroup.setLayout(groupLayout); performanceGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // stack frame limit - IntegerFieldEditor limitEditor= new IntegerWithBooleanFieldEditor( - IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT_ENABLE, - IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT, - MessagesForPreferences.DsfDebugPreferencePage_limitStackFrames_label, - performanceGroup); + IntegerFieldEditor limitEditor = new IntegerWithBooleanFieldEditor( + IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT_ENABLE, IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT, + MessagesForPreferences.DsfDebugPreferencePage_limitStackFrames_label, performanceGroup); limitEditor.setValidRange(1, Integer.MAX_VALUE); limitEditor.setValidateStrategy(StringFieldEditor.VALIDATE_ON_FOCUS_LOST); @@ -83,27 +81,25 @@ public class DsfDebugPreferencePage extends FieldEditorPreferencePage implements addField(limitEditor); // sync stepping speed - BooleanFieldEditor syncSteppingEditor= new BooleanFieldEditor( + BooleanFieldEditor syncSteppingEditor = new BooleanFieldEditor( IDsfDebugUIConstants.PREF_WAIT_FOR_VIEW_UPDATE_AFTER_STEP_ENABLE, - MessagesForPreferences.DsfDebugPreferencePage_waitForViewUpdate_label, - performanceGroup); + MessagesForPreferences.DsfDebugPreferencePage_waitForViewUpdate_label, performanceGroup); syncSteppingEditor.fillIntoGrid(performanceGroup, 3); addField(syncSteppingEditor); // minimum step interval - IntegerFieldEditor minIntervalEditor= new DecoratingIntegerFieldEditor( + IntegerFieldEditor minIntervalEditor = new DecoratingIntegerFieldEditor( IDsfDebugUIConstants.PREF_MIN_STEP_INTERVAL, - MessagesForPreferences.DsfDebugPreferencePage_minStepInterval_label, - performanceGroup); + MessagesForPreferences.DsfDebugPreferencePage_minStepInterval_label, performanceGroup); minIntervalEditor.setValidRange(0, 10000); minIntervalEditor.fillIntoGrid(performanceGroup, 3); addField(minIntervalEditor); - + // need to set layout again performanceGroup.setLayout(groupLayout); -} + } @Override protected void adjustGridLayout() { diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/IntegerWithBooleanFieldEditor.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/IntegerWithBooleanFieldEditor.java index d067578c1da..821b798458a 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/IntegerWithBooleanFieldEditor.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/IntegerWithBooleanFieldEditor.java @@ -32,12 +32,13 @@ public class IntegerWithBooleanFieldEditor extends DecoratingIntegerFieldEditor public IntegerWithBooleanFieldEditor(String enableKey, String nameKey, String labelText, Composite parent) { super(nameKey, labelText, parent); - fEnableKey= enableKey; + fEnableKey = enableKey; } - public IntegerWithBooleanFieldEditor(String enableKey, String nameKey, String labelText, Composite parent, int textLimit) { + public IntegerWithBooleanFieldEditor(String enableKey, String nameKey, String labelText, Composite parent, + int textLimit) { super(nameKey, labelText, parent, textLimit); - fEnableKey= enableKey; + fEnableKey = enableKey; } @Override @@ -48,11 +49,11 @@ public class IntegerWithBooleanFieldEditor extends DecoratingIntegerFieldEditor private Button getCheckboxControl(Composite parent) { if (fCheckbox == null) { - Composite inner= new Composite(parent, SWT.NULL); - final GridLayout layout= new GridLayout(2, false); + Composite inner = new Composite(parent, SWT.NULL); + final GridLayout layout = new GridLayout(2, false); layout.marginWidth = 0; inner.setLayout(layout); - fCheckbox= new Button(inner, SWT.CHECK); + fCheckbox = new Button(inner, SWT.CHECK); fCheckbox.setFont(parent.getFont()); fCheckbox.setText(getLabelText()); // create and hide label from base class @@ -62,9 +63,9 @@ public class IntegerWithBooleanFieldEditor extends DecoratingIntegerFieldEditor fCheckbox.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - boolean isSelected = fCheckbox.getSelection(); - valueChanged(fWasSelected, isSelected); - fWasSelected = isSelected; + boolean isSelected = fCheckbox.getSelection(); + valueChanged(fWasSelected, isSelected); + fWasSelected = isSelected; } }); } else { @@ -75,7 +76,7 @@ public class IntegerWithBooleanFieldEditor extends DecoratingIntegerFieldEditor @Override public Label getLabelControl(Composite parent) { - final Label label= getLabelControl(); + final Label label = getLabelControl(); if (label == null) { return super.getLabelControl(parent); } else { @@ -85,11 +86,11 @@ public class IntegerWithBooleanFieldEditor extends DecoratingIntegerFieldEditor } protected void valueChanged(boolean oldValue, boolean newValue) { - if (oldValue != newValue) { - valueChanged(); + if (oldValue != newValue) { + valueChanged(); fireStateChanged(VALUE, oldValue, newValue); - getTextControl().setEnabled(newValue); - getLabelControl().setEnabled(newValue); + getTextControl().setEnabled(newValue); + getLabelControl().setEnabled(newValue); } } @@ -105,40 +106,40 @@ public class IntegerWithBooleanFieldEditor extends DecoratingIntegerFieldEditor @Override protected void doLoad() { super.doLoad(); - if (fCheckbox != null) { - boolean value = getPreferenceStore().getBoolean(fEnableKey); - fCheckbox.setSelection(value); - fWasSelected = value; - getTextControl().setEnabled(value); - getLabelControl().setEnabled(value); - } + if (fCheckbox != null) { + boolean value = getPreferenceStore().getBoolean(fEnableKey); + fCheckbox.setSelection(value); + fWasSelected = value; + getTextControl().setEnabled(value); + getLabelControl().setEnabled(value); + } } @Override protected void doLoadDefault() { super.doLoadDefault(); - if (fCheckbox != null) { - boolean value = getPreferenceStore().getDefaultBoolean(fEnableKey); - fCheckbox.setSelection(value); - fWasSelected = value; - getTextControl().setEnabled(value); - getLabelControl().setEnabled(value); - } + if (fCheckbox != null) { + boolean value = getPreferenceStore().getDefaultBoolean(fEnableKey); + fCheckbox.setSelection(value); + fWasSelected = value; + getTextControl().setEnabled(value); + getLabelControl().setEnabled(value); + } } - @Override + @Override protected void doStore() { - super.doStore(); - getPreferenceStore().setValue(fEnableKey, fCheckbox.getSelection()); - } + super.doStore(); + getPreferenceStore().setValue(fEnableKey, fCheckbox.getSelection()); + } - /** - * Returns this field editor's current boolean value. - * - * @return the value - */ - public boolean getBooleanValue() { - return fCheckbox.getSelection(); - } + /** + * Returns this field editor's current boolean value. + * + * @return the value + */ + public boolean getBooleanValue() { + return fCheckbox.getSelection(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/StringWithBooleanFieldEditor.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/StringWithBooleanFieldEditor.java index edc9af69763..1a203893883 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/StringWithBooleanFieldEditor.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/preferences/StringWithBooleanFieldEditor.java @@ -32,19 +32,21 @@ public class StringWithBooleanFieldEditor extends DecoratingStringFieldEditor { public StringWithBooleanFieldEditor(String enableKey, String nameKey, String labelText, Composite parent) { super(nameKey, labelText, parent); - fEnableKey= enableKey; + fEnableKey = enableKey; } - public StringWithBooleanFieldEditor(String enableKey, String nameKey, String labelText, int width, Composite parent) { + public StringWithBooleanFieldEditor(String enableKey, String nameKey, String labelText, int width, + Composite parent) { super(nameKey, labelText, width, parent); - fEnableKey= enableKey; + fEnableKey = enableKey; } - public StringWithBooleanFieldEditor(String enableKey, String nameKey, String labelText, int width, int strategy, Composite parent) { + public StringWithBooleanFieldEditor(String enableKey, String nameKey, String labelText, int width, int strategy, + Composite parent) { super(nameKey, labelText, width, strategy, parent); - fEnableKey= enableKey; + fEnableKey = enableKey; } - + @Override protected void doFillIntoGrid(Composite parent, int numColumns) { getCheckboxControl(parent); @@ -53,11 +55,11 @@ public class StringWithBooleanFieldEditor extends DecoratingStringFieldEditor { public Button getCheckboxControl(Composite parent) { if (fCheckbox == null) { - Composite inner= new Composite(parent, SWT.NULL); - final GridLayout layout= new GridLayout(2, false); + Composite inner = new Composite(parent, SWT.NULL); + final GridLayout layout = new GridLayout(2, false); layout.marginWidth = 0; inner.setLayout(layout); - fCheckbox= new Button(inner, SWT.CHECK); + fCheckbox = new Button(inner, SWT.CHECK); fCheckbox.setFont(parent.getFont()); fCheckbox.setText(getLabelText()); // create and hide label from base class @@ -67,9 +69,9 @@ public class StringWithBooleanFieldEditor extends DecoratingStringFieldEditor { fCheckbox.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - boolean isSelected = fCheckbox.getSelection(); - valueChanged(fWasSelected, isSelected); - fWasSelected = isSelected; + boolean isSelected = fCheckbox.getSelection(); + valueChanged(fWasSelected, isSelected); + fWasSelected = isSelected; } }); } else { @@ -80,7 +82,7 @@ public class StringWithBooleanFieldEditor extends DecoratingStringFieldEditor { @Override public Label getLabelControl(Composite parent) { - final Label label= getLabelControl(); + final Label label = getLabelControl(); if (label == null) { return super.getLabelControl(parent); } else { @@ -90,11 +92,11 @@ public class StringWithBooleanFieldEditor extends DecoratingStringFieldEditor { } protected void valueChanged(boolean oldValue, boolean newValue) { - if (oldValue != newValue) { - valueChanged(); + if (oldValue != newValue) { + valueChanged(); fireStateChanged(VALUE, oldValue, newValue); - getTextControl().setEnabled(newValue); - getLabelControl().setEnabled(newValue); + getTextControl().setEnabled(newValue); + getLabelControl().setEnabled(newValue); } } @@ -110,40 +112,40 @@ public class StringWithBooleanFieldEditor extends DecoratingStringFieldEditor { @Override protected void doLoad() { super.doLoad(); - if (fCheckbox != null) { - boolean value = getPreferenceStore().getBoolean(fEnableKey); - fCheckbox.setSelection(value); - fWasSelected = value; - getTextControl().setEnabled(value); - getLabelControl().setEnabled(value); - } + if (fCheckbox != null) { + boolean value = getPreferenceStore().getBoolean(fEnableKey); + fCheckbox.setSelection(value); + fWasSelected = value; + getTextControl().setEnabled(value); + getLabelControl().setEnabled(value); + } } @Override protected void doLoadDefault() { super.doLoadDefault(); - if (fCheckbox != null) { - boolean value = getPreferenceStore().getDefaultBoolean(fEnableKey); - fCheckbox.setSelection(value); - fWasSelected = value; - getTextControl().setEnabled(value); - getLabelControl().setEnabled(value); - } + if (fCheckbox != null) { + boolean value = getPreferenceStore().getDefaultBoolean(fEnableKey); + fCheckbox.setSelection(value); + fWasSelected = value; + getTextControl().setEnabled(value); + getLabelControl().setEnabled(value); + } } - @Override + @Override protected void doStore() { - super.doStore(); - getPreferenceStore().setValue(fEnableKey, fCheckbox.getSelection()); - } - - /** - * Returns this field editor's current boolean value. - * - * @return the value - */ - public boolean getBooleanValue() { - return fCheckbox.getSelection(); - } + super.doStore(); + getPreferenceStore().setValue(fEnableKey, fCheckbox.getSelection()); + } + + /** + * Returns this field editor's current boolean value. + * + * @return the value + */ + public boolean getBooleanValue() { + return fCheckbox.getSelection(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/sourcelookup/DsfSourceSelectionResolver.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/sourcelookup/DsfSourceSelectionResolver.java index 13d91160e6a..8aee0d5cc99 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/sourcelookup/DsfSourceSelectionResolver.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/sourcelookup/DsfSourceSelectionResolver.java @@ -30,7 +30,7 @@ import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.editors.text.TextEditor; import org.eclipse.ui.texteditor.ITextEditor; -public class DsfSourceSelectionResolver implements Runnable { +public class DsfSourceSelectionResolver implements Runnable { private ITextEditor fEditorPage = null; private ITextSelection fSelection = null; private LineLocation fLineLocation = new LineLocation(); @@ -40,19 +40,19 @@ public class DsfSourceSelectionResolver implements Runnable { public class LineLocation { private String fileName = null; private int lineNumber = 0; - + public String getFileName() { return fileName; } - + public void setFileName(String fileName) { this.fileName = fileName; } - + public int getLineNumber() { return lineNumber; } - + public void setLineNumber(int lineNumber) { this.lineNumber = lineNumber; } @@ -63,7 +63,7 @@ public class DsfSourceSelectionResolver implements Runnable { } public DsfSourceSelectionResolver() { - + } public DsfSourceSelectionResolver(ITextEditor editor, ITextSelection selection) { @@ -108,7 +108,7 @@ public class DsfSourceSelectionResolver implements Runnable { if (fEditorPage != null) { return fEditorPage; } - + final IWorkbench wb = DsfUIPlugin.getDefault().getWorkbench(); // Run in UI thread to access UI resources ResolveEditorRunnable reditorRunnable = new ResolveEditorRunnable() { @@ -135,13 +135,13 @@ public class DsfSourceSelectionResolver implements Runnable { Display.getDefault().syncExec(reditorRunnable); return reditorRunnable.getEditor(); - } - + } + private LineLocation resolveSelectedLine() { String errorMessage = ""; //$NON-NLS-1$ IEditorInput input = fEditorPage.getEditorInput(); if (input == null) { - errorMessage = "Invalid Editor input on selection"; //$NON-NLS-1$ + errorMessage = "Invalid Editor input on selection"; //$NON-NLS-1$ } else { IDocument document = fEditorPage.getDocumentProvider().getDocument(input); if (document == null) { @@ -178,21 +178,21 @@ public class DsfSourceSelectionResolver implements Runnable { DsfUIPlugin.logErrorMessage(errorMessage); return null; } - + public ITextSelection resolveSelection() { if (fSelection != null) { //Value received at construction time return fSelection; } - + ISelection selection = fEditorPage.getEditorSite().getSelectionProvider().getSelection(); if (selection instanceof ITextSelection) { return (ITextSelection) selection; } - + return null; } - + private IFunctionDeclaration[] resolveSelectedFunction(ITextSelection textSelection) { if (textSelection != null) { SelectionToDeclarationJob job; @@ -207,11 +207,11 @@ public class DsfSourceSelectionResolver implements Runnable { DsfUIPlugin.log(e); return null; } - - //fetch the result + + //fetch the result return job.getSelectedFunctions(); } - + return null; } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/DsfCastToTypeSupport.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/DsfCastToTypeSupport.java index e4617e4f3c9..cd902c16d78 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/DsfCastToTypeSupport.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/DsfCastToTypeSupport.java @@ -10,7 +10,7 @@ * * Contributors: * Nokia - Initial API and implementation - * Marc Khouzam (Ericsson) - Turn off casting for expression-group or + * Marc Khouzam (Ericsson) - Turn off casting for expression-group or * pattern expressions (bug 394408) *******************************************************************************/ @@ -50,60 +50,59 @@ import org.eclipse.debug.core.DebugException; * This provides {@link ICastToType} and {@link ICastToArray} support on * expression nodes. */ -public class DsfCastToTypeSupport { +public class DsfCastToTypeSupport { private final DsfServicesTracker serviceTracker; private final AbstractDMVMProvider dmvmProvider; private final SyncVariableDataAccess fSyncVariableDataAccess; - - /** expression memento to casting context (TODO: persist these; bug 228301)*/ - private Map<String, CastInfo> fCastedExpressionStorage = new HashMap<String, CastInfo>(); - public class CastImplementation extends PlatformObject implements ICastToArray { + /** expression memento to casting context (TODO: persist these; bug 228301)*/ + private Map<String, CastInfo> fCastedExpressionStorage = new HashMap<String, CastInfo>(); + + public class CastImplementation extends PlatformObject implements ICastToArray { private final IExpressionDMContext exprDMC; private String memento; public CastImplementation(IExpressionDMContext exprDMC) { this.exprDMC = exprDMC; this.memento = createCastedExpressionMemento(exprDMC); - } - - public class TestExpressions2Query extends Query<Boolean> { - - public TestExpressions2Query() { - super(); - } - - @Override - protected void execute(final DataRequestMonitor<Boolean> rm) { - /* - * We're in another dispatch, so we must guard against executor - * shutdown again. - */ - final DsfSession session = DsfSession.getSession( - dmvmProvider.getSession().getId()); - if (session == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Debug session already shut down.", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - DsfServicesTracker tracker = new DsfServicesTracker( - DsfUIPlugin.getBundleContext(), dmvmProvider.getSession().getId()); - IExpressions2 expressions2 = tracker.getService(IExpressions2.class); - rm.setData(expressions2 != null); - rm.done(); - tracker.dispose(); - } - } + } + + public class TestExpressions2Query extends Query<Boolean> { + + public TestExpressions2Query() { + super(); + } + + @Override + protected void execute(final DataRequestMonitor<Boolean> rm) { + /* + * We're in another dispatch, so we must guard against executor + * shutdown again. + */ + final DsfSession session = DsfSession.getSession(dmvmProvider.getSession().getId()); + if (session == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Debug session already shut down.", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + dmvmProvider.getSession().getId()); + IExpressions2 expressions2 = tracker.getService(IExpressions2.class); + rm.setData(expressions2 != null); + rm.done(); + tracker.dispose(); + } + } private boolean isValid() { - if (exprDMC instanceof IIndexedPartitionDMContext || - exprDMC instanceof IExpressionGroupDMContext) { + if (exprDMC instanceof IIndexedPartitionDMContext || exprDMC instanceof IExpressionGroupDMContext) { return false; } - - TestExpressions2Query query = new TestExpressions2Query(); - dmvmProvider.getSession().getExecutor().execute(query); + + TestExpressions2Query query = new TestExpressions2Query(); + dmvmProvider.getSession().getExecutor().execute(query); try { /* @@ -118,39 +117,40 @@ public class DsfCastToTypeSupport { return false; } } - + private void throwIfNotValid() throws DebugException { - if (!isValid()) - throw new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, - MessagesForVariablesVM.VariableVMNode_CannotCastVariable, null)); + if (!isValid()) + throw new DebugException( + new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, + MessagesForVariablesVM.VariableVMNode_CannotCastVariable, null)); } - - /* + + /* * (non-Javadoc) * @see org.eclipse.cdt.debug.core.model.ICastToType#canCast() */ - @Override - public boolean canCast() { - return isValid(); + @Override + public boolean canCast() { + return isValid(); } /* * (non-Javadoc) * @see org.eclipse.cdt.debug.core.model.ICastToType#getCurrentType() */ - @Override - public String getCurrentType() { - // get expected casted type first, if possible (if there's an error in the type, - // the expression might not evaluate successfully) - CastInfo castDMC = fCastedExpressionStorage.get(memento); - if (castDMC != null && castDMC.getTypeString() != null) - return castDMC.getTypeString(); - - // else, get the actual type - IExpressionDMData data = fSyncVariableDataAccess.readVariable(exprDMC); - if (data != null) - return data.getTypeName(); - + @Override + public String getCurrentType() { + // get expected casted type first, if possible (if there's an error in the type, + // the expression might not evaluate successfully) + CastInfo castDMC = fCastedExpressionStorage.get(memento); + if (castDMC != null && castDMC.getTypeString() != null) + return castDMC.getTypeString(); + + // else, get the actual type + IExpressionDMData data = fSyncVariableDataAccess.readVariable(exprDMC); + if (data != null) + return data.getTypeName(); + return ""; //$NON-NLS-1$ } @@ -158,34 +158,33 @@ public class DsfCastToTypeSupport { * (non-Javadoc) * @see org.eclipse.cdt.debug.core.model.ICastToType#cast(java.lang.String) */ - @Override - public void cast(String type) throws DebugException { - throwIfNotValid(); - - CastInfo currentContext = fCastedExpressionStorage.get(memento); - - updateCastInformation(type, - currentContext != null ? currentContext.getArrayStartIndex() : 0, - currentContext != null ? currentContext.getArrayCount() : 0); - + @Override + public void cast(String type) throws DebugException { + throwIfNotValid(); + + CastInfo currentContext = fCastedExpressionStorage.get(memento); + + updateCastInformation(type, currentContext != null ? currentContext.getArrayStartIndex() : 0, + currentContext != null ? currentContext.getArrayCount() : 0); + } - /* - * (non-Javadoc) - * @see org.eclipse.cdt.debug.core.model.ICastToType#restoreOriginal() - */ - @Override + /* + * (non-Javadoc) + * @see org.eclipse.cdt.debug.core.model.ICastToType#restoreOriginal() + */ + @Override public void restoreOriginal() throws DebugException { throwIfNotValid(); - fCastedExpressionStorage.remove(memento); - fireExpressionChangedEvent(exprDMC); + fCastedExpressionStorage.remove(memento); + fireExpressionChangedEvent(exprDMC); } /* * (non-Javadoc) * @see org.eclipse.cdt.debug.core.model.ICastToType#isCasted() */ - @Override + @Override public boolean isCasted() { if (isValid()) return fCastedExpressionStorage.containsKey(memento); @@ -197,7 +196,7 @@ public class DsfCastToTypeSupport { * (non-Javadoc) * @see org.eclipse.cdt.debug.core.model.ICastToArray#canCastToArray() */ - @Override + @Override public boolean canCastToArray() { return isValid(); } @@ -206,74 +205,71 @@ public class DsfCastToTypeSupport { * (non-Javadoc) * @see org.eclipse.cdt.debug.core.model.ICastToArray#castToArray(int, int) */ - @Override - public void castToArray(int startIndex, int length) - throws DebugException { + @Override + public void castToArray(int startIndex, int length) throws DebugException { throwIfNotValid(); - + CastInfo currentContext = fCastedExpressionStorage.get(memento); - - updateCastInformation(currentContext != null ? currentContext.getTypeString() : null, - startIndex, - length); + + updateCastInformation(currentContext != null ? currentContext.getTypeString() : null, startIndex, length); } - private void updateCastInformation( - String type, int arrayStartIndex, - int arrayCount) { + private void updateCastInformation(String type, int arrayStartIndex, int arrayCount) { final CastInfo info = new CastInfo(type, arrayStartIndex, arrayCount); fCastedExpressionStorage.put(memento, info); - fireExpressionChangedEvent(exprDMC); + fireExpressionChangedEvent(exprDMC); } - private class ExpressionChangedEvent extends AbstractDMEvent<IExpressionDMContext> implements IExpressionChangedDMEvent { + private class ExpressionChangedEvent extends AbstractDMEvent<IExpressionDMContext> + implements IExpressionChangedDMEvent { public ExpressionChangedEvent(IExpressionDMContext context) { super(context); } } - + private void fireExpressionChangedEvent(IExpressionDMContext exprDMC) { ExpressionChangedEvent event = new ExpressionChangedEvent(exprDMC); dmvmProvider.handleEvent(event); } - } - - public DsfCastToTypeSupport(DsfSession session, AbstractDMVMProvider dmvmProvider, SyncVariableDataAccess fSyncVariableDataAccess) { + } + + public DsfCastToTypeSupport(DsfSession session, AbstractDMVMProvider dmvmProvider, + SyncVariableDataAccess fSyncVariableDataAccess) { this.dmvmProvider = dmvmProvider; this.fSyncVariableDataAccess = fSyncVariableDataAccess; this.serviceTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); } - + /* (non-Javadoc) * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.variable.ICastSupportTarget#createCastedExpressionMemento(org.eclipse.cdt.dsf.debug.service.IExpressions.IExpressionDMContext, java.lang.String) */ public String createCastedExpressionMemento(IExpressionDMContext exprDMC) { // go to the original variable first if (exprDMC instanceof ICastedExpressionDMContext) { - IExpressionDMContext origExpr = DMContexts.getAncestorOfType(exprDMC.getParents()[0], IExpressionDMContext.class); + IExpressionDMContext origExpr = DMContexts.getAncestorOfType(exprDMC.getParents()[0], + IExpressionDMContext.class); if (origExpr == null) { assert false; } else { exprDMC = origExpr; } } - + // TODO: the memento doesn't really strictly define the expression's context; // we should fetch module name, function name, etc. to be more useful (but do that asynchronously) String expression = exprDMC.getExpression(); - String memento = exprDMC.getSessionId() + "." + expression; //$NON-NLS-1$ + String memento = exprDMC.getSessionId() + "." + expression; //$NON-NLS-1$ return memento; } /* (non-Javadoc) * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.variable.ICastSupportTarget#replaceWihCastedExpression(org.eclipse.cdt.dsf.debug.service.IExpressions.IExpressionDMContext) */ - public IExpressionDMContext replaceWithCastedExpression( - IExpressionDMContext exprDMC) { + public IExpressionDMContext replaceWithCastedExpression(IExpressionDMContext exprDMC) { IExpressions2 expression2Service = serviceTracker.getService(IExpressions2.class); if (expression2Service == null) return exprDMC; - + if (!fCastedExpressionStorage.isEmpty()) { String memento = createCastedExpressionMemento(exprDMC); CastInfo castInfo = fCastedExpressionStorage.get(memento); @@ -286,7 +282,7 @@ public class DsfCastToTypeSupport { /** * Get the ICastToArray (and ICastToType) implementation for the expression. - * This does not necessarily return a unique object for each call. + * This does not necessarily return a unique object for each call. * @param exprDMC * @return {@link ICastToArray} */ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/VMViewerUpdateTracing.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/VMViewerUpdateTracing.java index 360366a7227..e8f4c28b03e 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/VMViewerUpdateTracing.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/VMViewerUpdateTracing.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Freescale Semiconductor. - initial API and implementation *******************************************************************************/ @@ -31,13 +31,15 @@ public final class VMViewerUpdateTracing { * The value of the trace option "debug/vmUpdates/regex", which is a regular * expression used to filter VMViewerUpdate traces. */ - public final static String DEBUG_VMUPDATE_REGEX = Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/vm/updates/regex"); //$NON-NLS-1$ + public final static String DEBUG_VMUPDATE_REGEX = Platform + .getDebugOption("org.eclipse.cdt.dsf.ui/debug/vm/updates/regex"); //$NON-NLS-1$ /** * Has the "debug/vmUpdates/properties" tracing option been turned on? Requires * "debug/vmUpdates" to also be turned on. */ - public static final boolean DEBUG_VMUPDATES = DsfUIPlugin.DEBUG && Boolean.parseBoolean(Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/vm/updates")); //$NON-NLS-1$ + public static final boolean DEBUG_VMUPDATES = DsfUIPlugin.DEBUG + && Boolean.parseBoolean(Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/vm/updates")); //$NON-NLS-1$ /** * Looks at the optional filter (regular expression) set in the tracing @@ -46,22 +48,20 @@ public final class VMViewerUpdateTracing { * classes. Note that for optimization reasons, we expect the caller to * first check that DEBUG_VMUPDATES is true before invoking us; we do not * check it here (other than to assert it). - * + * * @return true if this class's activity should be traced */ - public static boolean matchesFilterRegex(Class<?> clazz) { - assert DEBUG_VMUPDATES; - if (DEBUG_VMUPDATE_REGEX == null || DEBUG_VMUPDATE_REGEX.length() == 0) { - return true; - } - try { - Pattern regex = Pattern.compile(DEBUG_VMUPDATE_REGEX); - Matcher matcher = regex.matcher(clazz.toString()); - return matcher.find(); - } - catch (PatternSyntaxException exc) { - return false; - } - } + public static boolean matchesFilterRegex(Class<?> clazz) { + assert DEBUG_VMUPDATES; + if (DEBUG_VMUPDATE_REGEX == null || DEBUG_VMUPDATE_REGEX.length() == 0) { + return true; + } + try { + Pattern regex = Pattern.compile(DEBUG_VMUPDATE_REGEX); + Matcher matcher = regex.matcher(clazz.toString()); + return matcher.find(); + } catch (PatternSyntaxException exc) { + return false; + } + } } - diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/DsfViewMemoryHandler.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/DsfViewMemoryHandler.java index 5f945baf666..30f5a81eb8c 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/DsfViewMemoryHandler.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/DsfViewMemoryHandler.java @@ -84,59 +84,60 @@ public class DsfViewMemoryHandler extends AbstractHandler { setBaseEnabled(viewableMemoryITems.length > 0); setMemoryViewables(viewableMemoryITems); } - + /* * (non-Javadoc) * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent) */ @Override public Object execute(ExecutionEvent event) throws ExecutionException { - if (getMemoryViewables() == null || getMemoryViewables().length == 0) { - return null; - } - - showInMemoryView(getMemoryViewables()); - - return null; + if (getMemoryViewables() == null || getMemoryViewables().length == 0) { + return null; + } + + showInMemoryView(getMemoryViewables()); + + return null; } private VariableExpressionVMC[] getMemoryViewables(Object evaluationContext) { - List<VariableExpressionVMC> viewableMemoryItems = new ArrayList<VariableExpressionVMC>(); - if (evaluationContext instanceof IEvaluationContext) { - Object s = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_MENU_SELECTION_NAME); - if (s instanceof IStructuredSelection) { - Iterator<?> iter = ((IStructuredSelection)s).iterator(); - while(iter.hasNext()) { - Object obj = iter.next(); - if (obj instanceof VariableExpressionVMC) { - Object element = DebugPlugin.getAdapter(obj, IViewInMemory.class); - if (element != null) { - if (((IViewInMemory)element).canViewInMemory()) { - viewableMemoryItems.add((VariableExpressionVMC)obj); - } - } - } - } - } - } - return viewableMemoryItems.toArray(new VariableExpressionVMC[viewableMemoryItems.size()]); + List<VariableExpressionVMC> viewableMemoryItems = new ArrayList<VariableExpressionVMC>(); + if (evaluationContext instanceof IEvaluationContext) { + Object s = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_MENU_SELECTION_NAME); + if (s instanceof IStructuredSelection) { + Iterator<?> iter = ((IStructuredSelection) s).iterator(); + while (iter.hasNext()) { + Object obj = iter.next(); + if (obj instanceof VariableExpressionVMC) { + Object element = DebugPlugin.getAdapter(obj, IViewInMemory.class); + if (element != null) { + if (((IViewInMemory) element).canViewInMemory()) { + viewableMemoryItems.add((VariableExpressionVMC) obj); + } + } + } + } + } + } + return viewableMemoryItems.toArray(new VariableExpressionVMC[viewableMemoryItems.size()]); } private void addDefaultRenderings(IMemoryBlock memoryBlock, IMemoryRenderingSite memRendSite) { // This method was mostly lifted from the platform's AddMemoryBlockAction - IMemoryRenderingType primaryType = DebugUITools.getMemoryRenderingManager().getPrimaryRenderingType(memoryBlock); - IMemoryRenderingType renderingTypes[] = DebugUITools.getMemoryRenderingManager().getDefaultRenderingTypes(memoryBlock); + IMemoryRenderingType primaryType = DebugUITools.getMemoryRenderingManager() + .getPrimaryRenderingType(memoryBlock); + IMemoryRenderingType renderingTypes[] = DebugUITools.getMemoryRenderingManager() + .getDefaultRenderingTypes(memoryBlock); try { if (primaryType != null) { - createRenderingInContainer(memoryBlock, memRendSite, - primaryType, IDebugUIConstants.ID_RENDERING_VIEW_PANE_1); + createRenderingInContainer(memoryBlock, memRendSite, primaryType, + IDebugUIConstants.ID_RENDERING_VIEW_PANE_1); } else if (renderingTypes.length > 0) { primaryType = renderingTypes[0]; - createRenderingInContainer(memoryBlock, memRendSite, - renderingTypes[0], + createRenderingInContainer(memoryBlock, memRendSite, renderingTypes[0], IDebugUIConstants.ID_RENDERING_VIEW_PANE_1); } } catch (CoreException e) { @@ -151,8 +152,7 @@ public class DsfViewMemoryHandler extends AbstractHandler { create = false; } if (create) - createRenderingInContainer(memoryBlock, memRendSite, - renderingTypes[i], + createRenderingInContainer(memoryBlock, memRendSite, renderingTypes[i], IDebugUIConstants.ID_RENDERING_VIEW_PANE_2); } catch (CoreException e) { DsfUIPlugin.logErrorMessage(e.getMessage()); @@ -160,9 +160,8 @@ public class DsfViewMemoryHandler extends AbstractHandler { } } - private void createRenderingInContainer(IMemoryBlock memoryBlock, - IMemoryRenderingSite memRendSite, IMemoryRenderingType primaryType, - String paneId) throws CoreException { + private void createRenderingInContainer(IMemoryBlock memoryBlock, IMemoryRenderingSite memRendSite, + IMemoryRenderingType primaryType, String paneId) throws CoreException { // This method was mostly lifted from the platform's AddMemoryBlockAction @@ -178,21 +177,20 @@ public class DsfViewMemoryHandler extends AbstractHandler { addDefaultRenderings(memBlock, memRendSite); } - private IStatus showExpressionInMemoryView(VariableExpressionVMC context, IExpressionDMData exprData, + private IStatus showExpressionInMemoryView(VariableExpressionVMC context, IExpressionDMData exprData, IMemoryRenderingSite memRendSite) { - BasicType type = exprData.getBasicType(); - String exprString; - if (type == BasicType.array || type == BasicType.pointer) { - exprString = context.getExpression(); - } - else { - exprString = "&(" + context.getExpression() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - } - try { + BasicType type = exprData.getBasicType(); + String exprString; + if (type == BasicType.array || type == BasicType.pointer) { + exprString = context.getExpression(); + } else { + exprString = "&(" + context.getExpression() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } + try { IDMContext dmc = context.getDMContext(); IMemoryBlockRetrieval retrieval = (IMemoryBlockRetrieval) context.getAdapter(IMemoryBlockRetrieval.class); if (retrieval == null && context instanceof IDebugElement) - retrieval = ((IDebugElement)context).getDebugTarget(); + retrieval = ((IDebugElement) context).getDebugTarget(); if (retrieval == null || !(retrieval instanceof IMemoryBlockRetrievalExtension)) return Status.OK_STATUS; IMemoryBlockRetrievalExtension dsfRetrieval = (IMemoryBlockRetrievalExtension) retrieval; @@ -210,7 +208,8 @@ public class DsfViewMemoryHandler extends AbstractHandler { IViewPart memoryView = page.showView(IDebugUIConstants.ID_MEMORY_VIEW, null, IWorkbenchPage.VIEW_ACTIVATE); final IMemoryRenderingSite memRendSite = (IMemoryRenderingSite) memoryView; for (final VariableExpressionVMC context : contexts) { - final IExpressionDMContext dmc = DMContexts.getAncestorOfType(context.getDMContext(), IExpressionDMContext.class); + final IExpressionDMContext dmc = DMContexts.getAncestorOfType(context.getDMContext(), + IExpressionDMContext.class); if (dmc == null) { continue; } @@ -225,7 +224,8 @@ public class DsfViewMemoryHandler extends AbstractHandler { executor.execute(new DsfRunnable() { @Override public void run() { - DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + session.getId()); IExpressions service = tracker.getService(IExpressions.class); tracker.dispose(); if (service != null) { diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/MessagesForVMActions.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/MessagesForVMActions.java index 332660331d1..0c8b567f048 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/MessagesForVMActions.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/MessagesForVMActions.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems, Inc. - initial API and implementation *******************************************************************************/ @@ -17,19 +17,20 @@ package org.eclipse.cdt.dsf.debug.internal.ui.viewmodel.actions; import org.eclipse.osgi.util.NLS; public class MessagesForVMActions extends NLS { - - private static final String BUNDLE_NAME = "org.eclipse.cdt.dsf.debug.internal.ui.viewmodel.actions.messages"; //$NON-NLS-1$ - public static String RetargetDebugContextAction_ErrorDialog_title; - public static String RetargetDebugContextAction_ErrorDialog_message; - - public static String UpdatePoliciesContribution_EmptyPoliciesList_label; - public static String UpdateScopesContribution_EmptyScopesList_label; + private static final String BUNDLE_NAME = "org.eclipse.cdt.dsf.debug.internal.ui.viewmodel.actions.messages"; //$NON-NLS-1$ + + public static String RetargetDebugContextAction_ErrorDialog_title; + public static String RetargetDebugContextAction_ErrorDialog_message; + + public static String UpdatePoliciesContribution_EmptyPoliciesList_label; + public static String UpdateScopesContribution_EmptyScopesList_label; - static { - // initialize resource bundle - NLS.initializeMessages(BUNDLE_NAME, MessagesForVMActions.class); - } + static { + // initialize resource bundle + NLS.initializeMessages(BUNDLE_NAME, MessagesForVMActions.class); + } - private MessagesForVMActions() {} + private MessagesForVMActions() { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RefreshActionDelegate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RefreshActionDelegate.java index d1f6843c60c..d763320b68f 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RefreshActionDelegate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RefreshActionDelegate.java @@ -7,10 +7,10 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation - * Texas Instruments - Bug 340478 + * Texas Instruments - Bug 340478 *******************************************************************************/ package org.eclipse.cdt.dsf.debug.internal.ui.viewmodel.actions; @@ -24,36 +24,36 @@ import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IViewPart; /** - * + * */ public class RefreshActionDelegate extends AbstractVMProviderActionDelegate { - @Override + @Override public void run(IAction action) { - IVMProvider provider = VMHandlerUtils.getVMProviderForPart(getView()); - if (provider instanceof ICachingVMProvider) { - ((ICachingVMProvider)provider).refresh(); - } - } - - @Override - public void init(IViewPart view) { - super.init(view); - IVMProvider vp = VMHandlerUtils.getVMProviderForPart(getView()); - getAction().setEnabled(vp instanceof ICachingVMProvider); - } - - @Override - public void debugContextChanged(DebugContextEvent event) { - super.debugContextChanged(event); - IVMProvider vp = VMHandlerUtils.getVMProviderForPart(getView()); - getAction().setEnabled(vp instanceof ICachingVMProvider); - } + IVMProvider provider = VMHandlerUtils.getVMProviderForPart(getView()); + if (provider instanceof ICachingVMProvider) { + ((ICachingVMProvider) provider).refresh(); + } + } + + @Override + public void init(IViewPart view) { + super.init(view); + IVMProvider vp = VMHandlerUtils.getVMProviderForPart(getView()); + getAction().setEnabled(vp instanceof ICachingVMProvider); + } + + @Override + public void debugContextChanged(DebugContextEvent event) { + super.debugContextChanged(event); + IVMProvider vp = VMHandlerUtils.getVMProviderForPart(getView()); + getAction().setEnabled(vp instanceof ICachingVMProvider); + } - @Override - public void selectionChanged(IAction action, ISelection selection) { - super.selectionChanged(action, selection); - IVMProvider vp = VMHandlerUtils.getVMProviderForPart(getView()); - getAction().setEnabled(vp instanceof ICachingVMProvider); - } + @Override + public void selectionChanged(IAction action, ISelection selection) { + super.selectionChanged(action, selection); + IVMProvider vp = VMHandlerUtils.getVMProviderForPart(getView()); + getAction().setEnabled(vp instanceof ICachingVMProvider); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RefreshAllRetargetAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RefreshAllRetargetAction.java index 0ec7109b675..b6d74484c00 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RefreshAllRetargetAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RefreshAllRetargetAction.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -18,23 +18,23 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.viewers.ISelection; /** - * + * */ public class RefreshAllRetargetAction extends RetargetDebugContextAction { - @Override - protected boolean canPerformAction(Object target, ISelection selection) { - return true; - } + @Override + protected boolean canPerformAction(Object target, ISelection selection) { + return true; + } - @Override - protected Class<?> getAdapterClass() { - return IRefreshAllTarget.class; - } + @Override + protected Class<?> getAdapterClass() { + return IRefreshAllTarget.class; + } - @Override - protected void performAction(Object target, ISelection debugContext) throws CoreException { - ((IRefreshAllTarget)target).refresh(debugContext); - } + @Override + protected void performAction(Object target, ISelection debugContext) throws CoreException { + ((IRefreshAllTarget) target).refresh(debugContext); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RefreshHandler.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RefreshHandler.java index f9fd2d8f4e7..a9d37a53cf2 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RefreshHandler.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RefreshHandler.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,16 +20,16 @@ import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; -public class RefreshHandler extends AbstractHandler { +public class RefreshHandler extends AbstractHandler { - @Override + @Override public Object execute(ExecutionEvent event) throws ExecutionException { - IVMProvider vmProvider = VMHandlerUtils.getActiveVMProvider(event); - - if (vmProvider instanceof ICachingVMProvider) { - ((ICachingVMProvider)vmProvider).refresh(); - } - - return null; - } + IVMProvider vmProvider = VMHandlerUtils.getActiveVMProvider(event); + + if (vmProvider instanceof ICachingVMProvider) { + ((ICachingVMProvider) vmProvider).refresh(); + } + + return null; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RetargetDebugContextAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RetargetDebugContextAction.java index c472227b201..080113fa5b3 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RetargetDebugContextAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/RetargetDebugContextAction.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems, Inc. - initial implementation *******************************************************************************/ @@ -34,128 +34,130 @@ import org.eclipse.ui.IWorkbenchWindowActionDelegate; /** * Base class for actions which delegate functionality to an adapter retrieved * from the current debug context. - * + * * @since 1.1 */ -abstract public class RetargetDebugContextAction implements IWorkbenchWindowActionDelegate, IDebugContextListener, IActionDelegate2 { - - private IWorkbenchWindow fWindow = null; - private IAction fAction = null; - private ISelection fDebugContext; - private Object fTargetAdapter = null; - - /* (non-Javadoc) - * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow) - */ - @Override - public void init(IWorkbenchWindow window) { - fWindow = window; - IDebugContextService debugContextService = DebugUITools.getDebugContextManager().getContextService(fWindow); - debugContextService.addPostDebugContextListener(this); - fDebugContext = debugContextService.getActiveContext(); - update(); - } +abstract public class RetargetDebugContextAction + implements IWorkbenchWindowActionDelegate, IDebugContextListener, IActionDelegate2 { + + private IWorkbenchWindow fWindow = null; + private IAction fAction = null; + private ISelection fDebugContext; + private Object fTargetAdapter = null; + /* (non-Javadoc) + * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow) + */ + @Override + public void init(IWorkbenchWindow window) { + fWindow = window; + IDebugContextService debugContextService = DebugUITools.getDebugContextManager().getContextService(fWindow); + debugContextService.addPostDebugContextListener(this); + fDebugContext = debugContextService.getActiveContext(); + update(); + } - @Override + @Override public void selectionChanged(IAction action, ISelection selection) { - if (fAction != action) { - fAction = action; - } - // Update on debug context changed events - } - - @Override + if (fAction != action) { + fAction = action; + } + // Update on debug context changed events + } + + @Override public void runWithEvent(IAction action, Event event) { - run(action); - } - - @Override + run(action); + } + + @Override public void run(IAction action) { - if (fTargetAdapter != null) { - try { - performAction(fTargetAdapter, fDebugContext); - } catch (CoreException e) { - ErrorDialog.openError(fWindow.getShell(), MessagesForVMActions.RetargetDebugContextAction_ErrorDialog_title, MessagesForVMActions.RetargetDebugContextAction_ErrorDialog_message, e.getStatus()); - } - } - } - - /** - * Returns whether the specific operation is supported. - * - * @param target the target adapter - * @param selection the selection to verify the operation on - * @param part the part the operation has been requested on - * @return whether the operation can be performed - */ - protected abstract boolean canPerformAction(Object target, ISelection debugContext); - - /** - * Performs the specific breakpoint toggling. - * - * @param selection selection in the active part - * @param part active part - * @throws CoreException if an exception occurrs - */ - protected abstract void performAction(Object target, ISelection debugContext) throws CoreException; - - /** - * Returns the type of adapter (target) this action works on. - * - * @return the type of adapter this action works on - */ - protected abstract Class<?> getAdapterClass(); - - @Override + if (fTargetAdapter != null) { + try { + performAction(fTargetAdapter, fDebugContext); + } catch (CoreException e) { + ErrorDialog.openError(fWindow.getShell(), + MessagesForVMActions.RetargetDebugContextAction_ErrorDialog_title, + MessagesForVMActions.RetargetDebugContextAction_ErrorDialog_message, e.getStatus()); + } + } + } + + /** + * Returns whether the specific operation is supported. + * + * @param target the target adapter + * @param selection the selection to verify the operation on + * @param part the part the operation has been requested on + * @return whether the operation can be performed + */ + protected abstract boolean canPerformAction(Object target, ISelection debugContext); + + /** + * Performs the specific breakpoint toggling. + * + * @param selection selection in the active part + * @param part active part + * @throws CoreException if an exception occurrs + */ + protected abstract void performAction(Object target, ISelection debugContext) throws CoreException; + + /** + * Returns the type of adapter (target) this action works on. + * + * @return the type of adapter this action works on + */ + protected abstract Class<?> getAdapterClass(); + + @Override public void init(IAction action) { - fAction = action; - } - - /* (non-Javadoc) - * @see org.eclipse.ui.texteditor.IUpdate#update() - */ - public void update() { - if (fAction == null) { - return; - } - fTargetAdapter = null; - if (fDebugContext instanceof IStructuredSelection) { - IStructuredSelection ss = (IStructuredSelection) fDebugContext; - if (!ss.isEmpty()) { - Object object = ss.getFirstElement(); - if (object instanceof IAdaptable) { - fTargetAdapter = getAdapter((IAdaptable) object); - if (fTargetAdapter != null) { - fAction.setEnabled(canPerformAction(fTargetAdapter, fDebugContext)); - return; - } - } - } - } - fAction.setEnabled(false); - } - - @Override + fAction = action; + } + + /* (non-Javadoc) + * @see org.eclipse.ui.texteditor.IUpdate#update() + */ + public void update() { + if (fAction == null) { + return; + } + fTargetAdapter = null; + if (fDebugContext instanceof IStructuredSelection) { + IStructuredSelection ss = (IStructuredSelection) fDebugContext; + if (!ss.isEmpty()) { + Object object = ss.getFirstElement(); + if (object instanceof IAdaptable) { + fTargetAdapter = getAdapter((IAdaptable) object); + if (fTargetAdapter != null) { + fAction.setEnabled(canPerformAction(fTargetAdapter, fDebugContext)); + return; + } + } + } + } + fAction.setEnabled(false); + } + + @Override public void dispose() { - DebugUITools.getDebugContextManager().getContextService(fWindow).removePostDebugContextListener(this); - fTargetAdapter = null; - } - - @Override + DebugUITools.getDebugContextManager().getContextService(fWindow).removePostDebugContextListener(this); + fTargetAdapter = null; + } + + @Override public void debugContextChanged(DebugContextEvent event) { - fDebugContext = event.getContext(); - update(); - } - - protected Object getAdapter(IAdaptable adaptable) { - Object adapter = adaptable.getAdapter(getAdapterClass()); - if (adapter == null) { - IAdapterManager adapterManager = Platform.getAdapterManager(); - if (adapterManager.hasAdapter(adaptable, getAdapterClass().getName())) { - adapter = adapterManager.loadAdapter(adaptable, getAdapterClass().getName()); - } - } - return adapter; - } + fDebugContext = event.getContext(); + update(); + } + + protected Object getAdapter(IAdaptable adaptable) { + Object adapter = adaptable.getAdapter(getAdapterClass()); + if (adapter == null) { + IAdapterManager adapterManager = Platform.getAdapterManager(); + if (adapterManager.hasAdapter(adaptable, getAdapterClass().getName())) { + adapter = adapterManager.loadAdapter(adaptable, getAdapterClass().getName()); + } + } + return adapter; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/UpdatePoliciesContribution.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/UpdatePoliciesContribution.java index 46ba8019fbc..6aef69cc9c7 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/UpdatePoliciesContribution.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/UpdatePoliciesContribution.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -32,83 +32,83 @@ import org.eclipse.ui.menus.IWorkbenchContribution; import org.eclipse.ui.services.IServiceLocator; /** - * Dynamic menu contribution that shows available update policies + * Dynamic menu contribution that shows available update policies * in the current view. - * + * * @since 1.1 */ public class UpdatePoliciesContribution extends CompoundContributionItem implements IWorkbenchContribution { - - private class SelectUpdatePolicyAction extends Action { - private final ICachingVMProvider fProvider; - private final IVMUpdatePolicy fPolicy; - SelectUpdatePolicyAction(ICachingVMProvider provider, IVMUpdatePolicy policy) { - super(policy.getName(), AS_RADIO_BUTTON); - fProvider = provider; - fPolicy = policy; - } - - @Override - public void run() { - if (isChecked()) { - fProvider.setActiveUpdatePolicy(fPolicy); - } - } - } - - private IServiceLocator fServiceLocator; - - private static IContributionItem[] NO_UPDATE_POLICIES_CONTRIBUTION_ITEMS = new IContributionItem[] { - new ContributionItem() { - @Override - public void fill(Menu menu, int index) { - MenuItem item = new MenuItem(menu, SWT.NONE); - item.setEnabled(false); - item.setText(MessagesForVMActions.UpdatePoliciesContribution_EmptyPoliciesList_label); + + private class SelectUpdatePolicyAction extends Action { + private final ICachingVMProvider fProvider; + private final IVMUpdatePolicy fPolicy; + + SelectUpdatePolicyAction(ICachingVMProvider provider, IVMUpdatePolicy policy) { + super(policy.getName(), AS_RADIO_BUTTON); + fProvider = provider; + fPolicy = policy; + } + + @Override + public void run() { + if (isChecked()) { + fProvider.setActiveUpdatePolicy(fPolicy); } - - @Override - public boolean isEnabled() { - return false; + } + } + + private IServiceLocator fServiceLocator; + + private static IContributionItem[] NO_UPDATE_POLICIES_CONTRIBUTION_ITEMS = new IContributionItem[] { + new ContributionItem() { + @Override + public void fill(Menu menu, int index) { + MenuItem item = new MenuItem(menu, SWT.NONE); + item.setEnabled(false); + item.setText(MessagesForVMActions.UpdatePoliciesContribution_EmptyPoliciesList_label); + } + + @Override + public boolean isEnabled() { + return false; + } + } }; + + @Override + protected IContributionItem[] getContributionItems() { + IVMProvider provider = VMHandlerUtils.getActiveVMProvider(fServiceLocator); + + // If no part or selection, disable all. + if (provider == null || !(provider instanceof ICachingVMProvider)) { + return NO_UPDATE_POLICIES_CONTRIBUTION_ITEMS; + } + ICachingVMProvider cachingProvider = (ICachingVMProvider) provider; + + IVMUpdatePolicy[] policies = cachingProvider.getAvailableUpdatePolicies(); + IVMUpdatePolicy activePolicy = cachingProvider.getActiveUpdatePolicy(); + + List<Action> actions = new ArrayList<Action>(policies.length); + for (IVMUpdatePolicy policy : policies) { + Action action = new SelectUpdatePolicyAction(cachingProvider, policy); + if (policy.getID().equals(activePolicy.getID())) { + action.setChecked(true); } - } - }; - - @Override - protected IContributionItem[] getContributionItems() { - IVMProvider provider = VMHandlerUtils.getActiveVMProvider(fServiceLocator); - - // If no part or selection, disable all. - if (provider == null || !(provider instanceof ICachingVMProvider)) { - return NO_UPDATE_POLICIES_CONTRIBUTION_ITEMS; - } - ICachingVMProvider cachingProvider = (ICachingVMProvider)provider; - - IVMUpdatePolicy[] policies = cachingProvider.getAvailableUpdatePolicies(); - IVMUpdatePolicy activePolicy = cachingProvider.getActiveUpdatePolicy(); - - List<Action> actions = new ArrayList<Action>(policies.length); - for (IVMUpdatePolicy policy : policies) { - Action action = new SelectUpdatePolicyAction(cachingProvider, policy); - if (policy.getID().equals(activePolicy.getID())) { - action.setChecked(true); - } - actions.add(action); - } - - if ( actions.isEmpty() ) { - return NO_UPDATE_POLICIES_CONTRIBUTION_ITEMS; - } - - IContributionItem[] items = new IContributionItem[actions.size()]; - for (int i = 0; i < actions.size(); i++) { - items[i] = new ActionContributionItem(actions.get(i)); - } - return items; - } - - @Override + actions.add(action); + } + + if (actions.isEmpty()) { + return NO_UPDATE_POLICIES_CONTRIBUTION_ITEMS; + } + + IContributionItem[] items = new IContributionItem[actions.size()]; + for (int i = 0; i < actions.size(); i++) { + items[i] = new ActionContributionItem(actions.get(i)); + } + return items; + } + + @Override public void initialize(IServiceLocator serviceLocator) { - fServiceLocator = serviceLocator; - } + fServiceLocator = serviceLocator; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/UpdatePoliciesPropertyTester.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/UpdatePoliciesPropertyTester.java index 6349e50a28c..1ec52a98330 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/UpdatePoliciesPropertyTester.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/actions/UpdatePoliciesPropertyTester.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -23,60 +23,60 @@ import org.eclipse.debug.ui.IDebugView; import org.eclipse.ui.IWorkbenchPart; /** - * Property tester for update policy information available through the given - * object. The object being tested should be either an {@link IVMContext}, + * Property tester for update policy information available through the given + * object. The object being tested should be either an {@link IVMContext}, * through which an instance of {@link ICachingVMProvider} could be obtained. * Or it could be an {@link IWorkbenchPart}, which is tested to see if it - * is a debug view through which a caching VM provider can be obtained. + * is a debug view through which a caching VM provider can be obtained. * The Caching View Model provider is used to test the given property. * <p> * Three properties are supported: * <ul> - * <li> "areUpdatePoliciesSupported" - Checks whether update policies are + * <li> "areUpdatePoliciesSupported" - Checks whether update policies are * available at all given the receiver.</li> - * <li> "isUpdatePolicyAvailable" - Checks whether the update policy in the + * <li> "isUpdatePolicyAvailable" - Checks whether the update policy in the * expected value is available for the given receiver.</li> - * <li> "isUpdatePolicyActive" - Checks whether the policy given in the expected + * <li> "isUpdatePolicyActive" - Checks whether the policy given in the expected * value is the currently active policy for the given receiver.</li> * </ul> * </p> */ public class UpdatePoliciesPropertyTester extends PropertyTester { - private static final String SUPPORTED = "areUpdatePoliciesSupported"; //$NON-NLS-1$ - private static final String AVAILABLE = "isUpdatePolicyAvailable"; //$NON-NLS-1$ - private static final String ACTIVE = "isUpdatePolicyActive"; //$NON-NLS-1$ + private static final String SUPPORTED = "areUpdatePoliciesSupported"; //$NON-NLS-1$ + private static final String AVAILABLE = "isUpdatePolicyAvailable"; //$NON-NLS-1$ + private static final String ACTIVE = "isUpdatePolicyActive"; //$NON-NLS-1$ - @Override + @Override public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { - if (receiver instanceof IVMContext) { - IVMProvider provider = ((IVMContext)receiver).getVMNode().getVMProvider(); - if (provider instanceof ICachingVMProvider) { - return testProvider((ICachingVMProvider)provider, property, expectedValue); - } - } else if (receiver instanceof IDebugView) { - IVMProvider provider = VMHandlerUtils.getVMProviderForPart((IDebugView)receiver); - if (provider instanceof ICachingVMProvider) { - return testProvider((ICachingVMProvider)provider, property, expectedValue); - } - } - return false; - } + if (receiver instanceof IVMContext) { + IVMProvider provider = ((IVMContext) receiver).getVMNode().getVMProvider(); + if (provider instanceof ICachingVMProvider) { + return testProvider((ICachingVMProvider) provider, property, expectedValue); + } + } else if (receiver instanceof IDebugView) { + IVMProvider provider = VMHandlerUtils.getVMProviderForPart((IDebugView) receiver); + if (provider instanceof ICachingVMProvider) { + return testProvider((ICachingVMProvider) provider, property, expectedValue); + } + } + return false; + } + + private boolean testProvider(ICachingVMProvider provider, String property, Object expectedValue) { + if (SUPPORTED.equals(property)) { + return true; + } else if (AVAILABLE.equals(property)) { + for (IVMUpdatePolicy policy : provider.getAvailableUpdatePolicies()) { + if (policy.getID().equals(expectedValue)) { + return true; + } + return false; + } + } else if (ACTIVE.equals(property)) { + return expectedValue != null && expectedValue.equals(provider.getActiveUpdatePolicy().getID()); + } + return false; + } - private boolean testProvider(ICachingVMProvider provider, String property, Object expectedValue) { - if (SUPPORTED.equals(property)) { - return true; - } else if (AVAILABLE.equals(property)) { - for (IVMUpdatePolicy policy : provider.getAvailableUpdatePolicies()) { - if (policy.getID().equals(expectedValue)) { - return true; - } - return false; - } - } else if (ACTIVE.equals(property)) { - return expectedValue != null && expectedValue.equals(provider.getActiveUpdatePolicy().getID()); - } - return false; - } - } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/DetailPaneMaxLengthAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/DetailPaneMaxLengthAction.java index 2b2b1af34f8..d0887300707 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/DetailPaneMaxLengthAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/DetailPaneMaxLengthAction.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation * Wind River Systems, Inc. - extended implementation @@ -22,22 +22,22 @@ import org.eclipse.ui.PlatformUI; /** * Opens a dialog so that the user can enter the maximum length in characters that * the detail pane should display. - * + * * @see DetailPaneMaxLengthDialog * @since 3.0 */ public class DetailPaneMaxLengthAction extends Action { - + private Shell fDialogShell; - - public DetailPaneMaxLengthAction(Shell dialogShell){ + + public DetailPaneMaxLengthAction(Shell dialogShell) { super(MessagesForDetailPane.PaneMaxLengthAction_MaxLength); fDialogShell = dialogShell; - + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IDsfDebugHelpContextIds.DETAIL_PANE_MAX_LENGTH_ACTION); - + } - + @Override public void run() { DetailPaneMaxLengthDialog dialog = new DetailPaneMaxLengthDialog(fDialogShell); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/DetailPaneMaxLengthDialog.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/DetailPaneMaxLengthDialog.java index dc28b9b7130..37312cc133d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/DetailPaneMaxLengthDialog.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/DetailPaneMaxLengthDialog.java @@ -7,9 +7,9 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: - * IBM Corporation - initial API and implementation + * IBM Corporation - initial API and implementation * Wind River Systems, Inc. - extended implementation *******************************************************************************/ package org.eclipse.cdt.dsf.debug.internal.ui.viewmodel.detailsupport; @@ -34,43 +34,44 @@ import org.eclipse.ui.PlatformUI; /** * Provides a dialog for changing the maximum length allowed in the detail pane - * + * * @since 3.0 */ public class DetailPaneMaxLengthDialog extends TrayDialog { private static final String SETTINGS_ID = DsfUIPlugin.PLUGIN_ID + ".MAX_DETAILS_LENGTH_DIALOG"; //$NON-NLS-1$ - + private Text fTextWidget; private Text fErrorTextWidget; private String fErrorMessage; private String fValue; private IInputValidator fValidator; - + /** * Constructs a new dialog on the given shell. - * + * * @param parent shell */ public DetailPaneMaxLengthDialog(Shell parent) { super(parent); setShellStyle(getShellStyle() | SWT.RESIZE); - fValue = Integer.toString(DsfUIPlugin.getDefault().getPreferenceStore().getInt(IDebugUIConstants.PREF_MAX_DETAIL_LENGTH)); + fValue = Integer.toString( + DsfUIPlugin.getDefault().getPreferenceStore().getInt(IDebugUIConstants.PREF_MAX_DETAIL_LENGTH)); fValidator = new IInputValidator() { - @Override - public String isValid(String newText) { - try { - int num = Integer.parseInt(newText); - if (num < 0) { - return MessagesForDetailPane.PaneMaxLengthDialog_IntegerCannotBeNegative; - } - } catch (NumberFormatException e) { - return MessagesForDetailPane.PaneMaxLengthDialog_EnterAnInteger; - } - return null; + @Override + public String isValid(String newText) { + try { + int num = Integer.parseInt(newText); + if (num < 0) { + return MessagesForDetailPane.PaneMaxLengthDialog_IntegerCannotBeNegative; } - - }; + } catch (NumberFormatException e) { + return MessagesForDetailPane.PaneMaxLengthDialog_EnterAnInteger; + } + return null; + } + + }; } /* (non-Javadoc) @@ -82,10 +83,10 @@ public class DetailPaneMaxLengthDialog extends TrayDialog { IDialogSettings section = settings.getSection(SETTINGS_ID); if (section == null) { section = settings.addNewSection(SETTINGS_ID); - } + } return section; } - + /* (non-Javadoc) * @see org.eclipse.jface.dialogs.Dialog#createContents(org.eclipse.swt.widgets.Composite) */ @@ -93,7 +94,8 @@ public class DetailPaneMaxLengthDialog extends TrayDialog { protected Control createContents(Composite parent) { getShell().setText(MessagesForDetailPane.PaneMaxLengthDialog_ConfigureDetails); Control contents = super.createContents(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getDialogArea(), IDsfDebugHelpContextIds.DETAIL_PANE_MAX_LENGTH_ACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getDialogArea(), + IDsfDebugHelpContextIds.DETAIL_PANE_MAX_LENGTH_ACTION); return contents; } @@ -102,30 +104,30 @@ public class DetailPaneMaxLengthDialog extends TrayDialog { */ @Override protected Control createDialogArea(Composite parent) { - Composite composite = (Composite) super.createDialogArea(parent); - Label label = new Label(composite, SWT.WRAP); - label.setText(MessagesForDetailPane.PaneMaxLengthDialog_MaxCharactersToDisplay); - GridData data = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_CENTER); - data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH); - label.setLayoutData(data); - label.setFont(parent.getFont()); - fTextWidget = new Text(composite, SWT.SINGLE | SWT.BORDER); - fTextWidget.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL)); - fTextWidget.setText(fValue); - fTextWidget.addModifyListener(new ModifyListener() { - @Override + Composite composite = (Composite) super.createDialogArea(parent); + Label label = new Label(composite, SWT.WRAP); + label.setText(MessagesForDetailPane.PaneMaxLengthDialog_MaxCharactersToDisplay); + GridData data = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL + | GridData.VERTICAL_ALIGN_CENTER); + data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH); + label.setLayoutData(data); + label.setFont(parent.getFont()); + fTextWidget = new Text(composite, SWT.SINGLE | SWT.BORDER); + fTextWidget.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL)); + fTextWidget.setText(fValue); + fTextWidget.addModifyListener(new ModifyListener() { + @Override public void modifyText(ModifyEvent e) { - validateInput(); - fValue = fTextWidget.getText(); - } - }); - fErrorTextWidget = new Text(composite, SWT.READ_ONLY); - fErrorTextWidget.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL - | GridData.HORIZONTAL_ALIGN_FILL)); - fErrorTextWidget.setBackground(fErrorTextWidget.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); - setErrorMessage(fErrorMessage); - applyDialogFont(composite); - return composite; + validateInput(); + fValue = fTextWidget.getText(); + } + }); + fErrorTextWidget = new Text(composite, SWT.READ_ONLY); + fErrorTextWidget.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL)); + fErrorTextWidget.setBackground(fErrorTextWidget.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); + setErrorMessage(fErrorMessage); + applyDialogFont(composite); + return composite; } /* (non-Javadoc) @@ -135,52 +137,52 @@ public class DetailPaneMaxLengthDialog extends TrayDialog { protected void okPressed() { String text = getValue(); try { - DsfUIPlugin.getDefault().getPreferenceStore().setValue(IDebugUIConstants.PREF_MAX_DETAIL_LENGTH, Integer.parseInt(text)); - } - catch (NumberFormatException e) { + DsfUIPlugin.getDefault().getPreferenceStore().setValue(IDebugUIConstants.PREF_MAX_DETAIL_LENGTH, + Integer.parseInt(text)); + } catch (NumberFormatException e) { DsfUIPlugin.log(e); } super.okPressed(); } - + + /** + * Returns the string typed into this input dialog. + * + * @return the input string + * @since 3.3 + */ + public String getValue() { + return fValue; + } + + /** + * Validates the current input + * @since 3.3 + */ + private void validateInput() { + String errorMessage = null; + if (fValidator != null) { + errorMessage = fValidator.isValid(fTextWidget.getText()); + } + setErrorMessage(errorMessage); + } + /** - * Returns the string typed into this input dialog. - * - * @return the input string - * @since 3.3 - */ - public String getValue() { - return fValue; - } - - /** - * Validates the current input - * @since 3.3 - */ - private void validateInput() { - String errorMessage = null; - if (fValidator != null) { - errorMessage = fValidator.isValid(fTextWidget.getText()); - } - setErrorMessage(errorMessage); - } - - /** - * Sets the current error message or none if null - * @param errorMessage - * @since 3.3 - */ - public void setErrorMessage(String errorMessage) { - fErrorMessage = errorMessage; - if (fErrorTextWidget != null && !fErrorTextWidget.isDisposed()) { - fErrorTextWidget.setText(errorMessage == null ? "" : errorMessage); //$NON-NLS-1$ - fErrorTextWidget.getParent().update(); - // Access the ok button by id, in case clients have overridden button creation. - // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=113643 - Control button = getButton(IDialogConstants.OK_ID); - if (button != null) { - button.setEnabled(errorMessage == null); - } - } - } + * Sets the current error message or none if null + * @param errorMessage + * @since 3.3 + */ + public void setErrorMessage(String errorMessage) { + fErrorMessage = errorMessage; + if (fErrorTextWidget != null && !fErrorTextWidget.isDisposed()) { + fErrorTextWidget.setText(errorMessage == null ? "" : errorMessage); //$NON-NLS-1$ + fErrorTextWidget.getParent().update(); + // Access the ok button by id, in case clients have overridden button creation. + // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=113643 + Control button = getButton(IDialogConstants.OK_ID); + if (button != null) { + button.setEnabled(errorMessage == null); + } + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/DetailPaneWordWrapAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/DetailPaneWordWrapAction.java index 249e08ddcbf..717cc7ab33b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/DetailPaneWordWrapAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/DetailPaneWordWrapAction.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation * Wind River Systems, Inc. - extended implementation @@ -29,30 +29,31 @@ import org.eclipse.ui.PlatformUI; public class DetailPaneWordWrapAction extends Action { ITextViewer fTextViewer; - + public DetailPaneWordWrapAction(ITextViewer textViewer) { - super(MessagesForDetailPane.PaneWordWrapAction_WrapText,IAction.AS_CHECK_BOX); - + super(MessagesForDetailPane.PaneWordWrapAction_WrapText, IAction.AS_CHECK_BOX); + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IDsfDebugHelpContextIds.DETAIL_PANE_WORD_WRAP_ACTION); - + fTextViewer = textViewer; setEnabled(true); - - boolean prefSetting = DsfUIPlugin.getDefault().getPreferenceStore().getBoolean(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP); + + boolean prefSetting = DsfUIPlugin.getDefault().getPreferenceStore() + .getBoolean(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP); fTextViewer.getTextWidget().setWordWrap(prefSetting); setChecked(prefSetting); - } - + /* (non-Javadoc) * @see org.eclipse.jface.action.IAction#run() */ @Override public void run() { fTextViewer.getTextWidget().setWordWrap(isChecked()); - DsfUIPlugin.getDefault().getPreferenceStore().setValue(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP,isChecked()); + DsfUIPlugin.getDefault().getPreferenceStore().setValue(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP, + isChecked()); DsfUIPlugin.getDefault().savePluginPreferences(); } - + } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/MessagesForDetailPane.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/MessagesForDetailPane.java index 8f7868592e6..5540996ef85 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/MessagesForDetailPane.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/MessagesForDetailPane.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation * Wind River Systems, Inc. - extended implementation @@ -18,23 +18,23 @@ package org.eclipse.cdt.dsf.debug.internal.ui.viewmodel.detailsupport; import org.eclipse.osgi.util.NLS; public class MessagesForDetailPane extends NLS { - public static String NumberFormatDetailPane_Name; - public static String NumberFormatDetailPane_Description; + public static String NumberFormatDetailPane_Name; + public static String NumberFormatDetailPane_Description; public static String DetailPane_Copy; public static String DetailPane_LabelPattern; public static String DetailPane_Select_All; - public static String PaneWordWrapAction_WrapText; - public static String PaneMaxLengthAction_MaxLength; - public static String PaneMaxLengthDialog_ConfigureDetails; + public static String PaneWordWrapAction_WrapText; + public static String PaneMaxLengthAction_MaxLength; + public static String PaneMaxLengthDialog_ConfigureDetails; public static String PaneMaxLengthDialog_MaxCharactersToDisplay; public static String PaneMaxLengthDialog_IntegerCannotBeNegative; public static String PaneMaxLengthDialog_EnterAnInteger; - - static { - // initialize resource bundle - NLS.initializeMessages(MessagesForDetailPane.class.getName(), MessagesForDetailPane.class); - } - private MessagesForDetailPane() { - } + static { + // initialize resource bundle + NLS.initializeMessages(MessagesForDetailPane.class.getName(), MessagesForDetailPane.class); + } + + private MessagesForDetailPane() { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/TextViewerAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/TextViewerAction.java index 8132694cbc7..98ec5207d2f 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/TextViewerAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/detailsupport/TextViewerAction.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation * Wind River Systems, Inc. - extended implementation @@ -28,63 +28,63 @@ import org.eclipse.ui.texteditor.IUpdate; */ public class TextViewerAction extends Action implements IUpdate { - private int fOperationCode= -1; - private ITextOperationTarget fOperationTarget; + private int fOperationCode = -1; + private ITextOperationTarget fOperationTarget; - /** - * Constructs a new action in the given text viewer with - * the specified operation code. - * - * @param viewer - * @param operationCode - */ - public TextViewerAction(ITextViewer viewer, int operationCode) { - fOperationCode= operationCode; - fOperationTarget= viewer.getTextOperationTarget(); - update(); - } + /** + * Constructs a new action in the given text viewer with + * the specified operation code. + * + * @param viewer + * @param operationCode + */ + public TextViewerAction(ITextViewer viewer, int operationCode) { + fOperationCode = operationCode; + fOperationTarget = viewer.getTextOperationTarget(); + update(); + } - /* (non-Javadoc) - * @see org.eclipse.ui.texteditor.IUpdate#update() - * - * Updates the enabled state of the action. - * Fires a property change if the enabled state changes. - * - * @see org.eclipse.jface.action.Action#firePropertyChange(String, Object, Object) - */ - @Override + /* (non-Javadoc) + * @see org.eclipse.ui.texteditor.IUpdate#update() + * + * Updates the enabled state of the action. + * Fires a property change if the enabled state changes. + * + * @see org.eclipse.jface.action.Action#firePropertyChange(String, Object, Object) + */ + @Override public void update() { - boolean wasEnabled= isEnabled(); - boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode)); - setEnabled(isEnabled); + boolean wasEnabled = isEnabled(); + boolean isEnabled = (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode)); + setEnabled(isEnabled); - if (wasEnabled != isEnabled) { - firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, isEnabled ? Boolean.TRUE : Boolean.FALSE); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.action.IAction#run() - */ - @Override - public void run() { - if (fOperationCode != -1 && fOperationTarget != null) { - fOperationTarget.doOperation(fOperationCode); - } - } - - /** - * Configures this action with a label, tool tip, and description. - * - * @param text action label - * @param toolTipText action tool tip - * @param description action description - */ - public void configureAction(String text, String toolTipText, String description) { - setText(text); - setToolTipText(toolTipText); - setDescription(description); - } -} + if (wasEnabled != isEnabled) { + firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, + isEnabled ? Boolean.TRUE : Boolean.FALSE); + } + } + /* (non-Javadoc) + * @see org.eclipse.jface.action.IAction#run() + */ + @Override + public void run() { + if (fOperationCode != -1 && fOperationTarget != null) { + fOperationTarget.doOperation(fOperationCode); + } + } + + /** + * Configures this action with a label, tool tip, and description. + * + * @param text action label + * @param toolTipText action tool tip + * @param description action description + */ + public void configureAction(String text, String toolTipText, String description) { + setText(text); + setToolTipText(toolTipText); + setDescription(description); + } +} diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/numberformat/detail/MessagesForNumberFormatDetailPane.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/numberformat/detail/MessagesForNumberFormatDetailPane.java index 3432677cbf7..e72e1d9a7a5 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/numberformat/detail/MessagesForNumberFormatDetailPane.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/numberformat/detail/MessagesForNumberFormatDetailPane.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems, Inc. - initial API and implementation *******************************************************************************/ @@ -20,18 +20,19 @@ import org.eclipse.osgi.util.NLS; * @noinstantiate This class is not intended to be instantiated by clients. */ public class MessagesForNumberFormatDetailPane extends NLS { - public static String NumberFormatDetailPane_format_separator__label; - public static String NumberFormatDetailPane_Name_label; - public static String NumberFormatDetailPane_Spaces_label; - public static String NumberFormatDetailPane_CarriageReturn_label; - public static String NumberFormatDetailPane_DotDotDot_label; - public static String NumberFormatDetailPane__End_parentheses; + public static String NumberFormatDetailPane_format_separator__label; + public static String NumberFormatDetailPane_Name_label; + public static String NumberFormatDetailPane_Spaces_label; + public static String NumberFormatDetailPane_CarriageReturn_label; + public static String NumberFormatDetailPane_DotDotDot_label; + public static String NumberFormatDetailPane__End_parentheses; - static { - // initialize resource bundle - NLS.initializeMessages(MessagesForNumberFormatDetailPane.class.getName(), MessagesForNumberFormatDetailPane.class); - } + static { + // initialize resource bundle + NLS.initializeMessages(MessagesForNumberFormatDetailPane.class.getName(), + MessagesForNumberFormatDetailPane.class); + } - private MessagesForNumberFormatDetailPane() { - } + private MessagesForNumberFormatDetailPane() { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/numberformat/detail/NumberFormatDetailPane.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/numberformat/detail/NumberFormatDetailPane.java index fdc081f6496..7cb4cec91c2 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/numberformat/detail/NumberFormatDetailPane.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/numberformat/detail/NumberFormatDetailPane.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation * Wind River Systems, Inc. - extended implementation @@ -101,732 +101,753 @@ import org.eclipse.ui.texteditor.IUpdate; public class NumberFormatDetailPane implements IDetailPane2, IAdaptable, IPropertyChangeListener { - /** - * The <code>IWorkbenchPartSite</code> that the details area (and the - * variables view) belongs to. - */ - private IWorkbenchPartSite fWorkbenchPartSite; - - /** - * Map of actions. Keys are strings, values - * are <code>IAction</code>. - */ - private Map<String, IAction> fActionMap = new HashMap<String, IAction>(); - - /** - * Collection to track actions that should be updated when selection occurs. - */ - private List<String> fSelectionActions = new ArrayList<String>(); - - /* (non-Javadoc) - * @see org.eclipse.debug.ui.IDetailPane#init(org.eclipse.ui.IWorkbenchPartSite) - */ - @Override + /** + * The <code>IWorkbenchPartSite</code> that the details area (and the + * variables view) belongs to. + */ + private IWorkbenchPartSite fWorkbenchPartSite; + + /** + * Map of actions. Keys are strings, values + * are <code>IAction</code>. + */ + private Map<String, IAction> fActionMap = new HashMap<String, IAction>(); + + /** + * Collection to track actions that should be updated when selection occurs. + */ + private List<String> fSelectionActions = new ArrayList<String>(); + + /* (non-Javadoc) + * @see org.eclipse.debug.ui.IDetailPane#init(org.eclipse.ui.IWorkbenchPartSite) + */ + @Override public void init(IWorkbenchPartSite workbench) { - fWorkbenchPartSite = workbench; - - } - - /** - * Adds an action to the Map storing actions. Removes it if action is null. - * - * @param actionID The ID of the action, used as the key in the Map - * @param action The action associated with the ID - */ - protected void setAction(String actionID, IAction action) { - if (action == null) { - fActionMap.remove(actionID); - } else { - fActionMap.put(actionID, action); - } - } - - /** - * Adds the given action to the global action handler for the ViewSite. - * A call to <code>updateActionBars()</code> must be called after changes - * to propagate changes through the workbench. - * - * @param actionID The ID of the action - * @param action The action to be set globally - */ - protected void setGlobalAction(String actionID, IAction action){ - getViewSite().getActionBars().setGlobalActionHandler(actionID, action); - } - - /** - * Adds the given action to the list of actions that will be updated when - * <code>updateSelectionDependentActions()</code> is called. If the string - * is null it will not be added to the list. - * - * @param actionID The ID of the action which should be updated - */ - protected void setSelectionDependantAction(String actionID){ - if (actionID != null) fSelectionActions.add(actionID); - } - - /** - * Gets the action out of the map, casts it to an <code>IAction</code> - * - * @param actionID The ID of the action to find - * @return The action associated with the ID or null if none is found. - */ - protected IAction getAction(String actionID) { - return fActionMap.get(actionID); - } - - /** - * Calls the update method of the action with the given action ID. - * The action must exist in the action map and must be an instance of - * </code>IUpdate</code> - * - * @param actionId The ID of the action to update - */ - protected void updateAction(String actionId) { - IAction action= getAction(actionId); - if (action instanceof IUpdate) { - ((IUpdate) action).update(); - } - } - - /** - * Iterates through the list of selection dependent actions and - * updates them. Use <code>setSelectionDependentAction(String actionID)</code> - * to add an action to the list. The action must have been added to the known - * actions map by calling <code>setAction(String actionID, IAction action)</code> - * before it can be updated by this method. - */ - protected void updateSelectionDependentActions() { - Iterator<String> iterator= fSelectionActions.iterator(); - while (iterator.hasNext()) { - updateAction(iterator.next()); - } - } - - /** - * Gets the view site for this view. May be null if this detail pane - * is not part of a view. - * - * @return The site for this view or <code>null</code> - */ - protected IViewSite getViewSite(){ - if (fWorkbenchPartSite == null){ - return null; - } else { - return (IViewSite) fWorkbenchPartSite.getPart().getSite(); - } - } - - /** - * Gets the workbench part site for this view. May be null if this detail pane - * is not part of a view. - * - * @return The workbench part site or <code>null</code> - */ - protected IWorkbenchPartSite getWorkbenchPartSite() { - return fWorkbenchPartSite; - } - - /** - * Returns whether this detail pane is being displayed in a view with a workbench part site. - * - * @return whether this detail pane is being displayed in a view with a workbench part site. - */ - protected boolean isInView(){ - return fWorkbenchPartSite != null; - } - - /** - * These are the IDs for the actions in the context menu - */ - protected static final String DETAIL_COPY_ACTION = ActionFactory.COPY.getId() + ".TextDetailPane"; //$NON-NLS-1$ - protected static final String DETAIL_SELECT_ALL_ACTION = IDebugView.SELECT_ALL_ACTION + ".TextDetailPane"; //$NON-NLS-1$ - protected static final String DETAIL_WORD_WRAP_ACTION = DsfUIPlugin.PLUGIN_ID + ".detail_pane_word_wrap"; //$NON-NLS-1$ - protected static final String DETAIL_MAX_LENGTH_ACTION = "MaxLength"; //$NON-NLS-1$ - - /** - * The ID, name and description of this pane are stored in constants so that the class - * does not have to be instantiated to access them. - */ - public static final String ID = "NumberFormatPane"; //$NON-NLS-1$ - - /** - * Useful shortened names for the internationalized strings. - */ - public static String FORMAT_SEPARATOR = MessagesForNumberFormatDetailPane.NumberFormatDetailPane_format_separator__label; - public static String NAME = MessagesForNumberFormatDetailPane.NumberFormatDetailPane_Name_label; - public static String SPACES = MessagesForNumberFormatDetailPane.NumberFormatDetailPane_Spaces_label; - public static String CRLF = MessagesForNumberFormatDetailPane.NumberFormatDetailPane_CarriageReturn_label; - public static String DOTS = MessagesForNumberFormatDetailPane.NumberFormatDetailPane_DotDotDot_label; - public static String PARENTHESES = MessagesForNumberFormatDetailPane.NumberFormatDetailPane__End_parentheses; - - /** - * Job to compute the details for a selection - */ - class DetailJob extends Job implements IValueDetailListener { - private IPresentationContext fPresentationContext; - private Object fViewerInput; - private ITreeSelection fElements; - private boolean fFirst = true; - private IProgressMonitor fMonitor; - - public DetailJob(IPresentationContext context, Object viewerInput, ITreeSelection elements, - IDebugModelPresentation model) - { - super("compute variable details"); //$NON-NLS-1$ - setSystem(true); - fPresentationContext = context; - fViewerInput = viewerInput; - fElements = elements; - } - - public IProgressMonitor getDetailMonitor() { - return fMonitor; - } - - /* (non-Javadoc) - * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) - */ - @Override - protected IStatus run(final IProgressMonitor monitor) { - if ( fMonitor != null && ! fMonitor.isCanceled() ) { - fMonitor.setCanceled(true); - } - fMonitor = monitor; - TreePath[] paths = fElements.getPaths(); - for (int i = 0; i < paths.length; i++) { - if (monitor.isCanceled()) { - break; - } - final TreePath path = paths[i]; - Object element = paths[i].getLastSegment(); - - final IElementPropertiesProvider propertiesProvider = - (IElementPropertiesProvider)DebugPlugin.getAdapter(element, IElementPropertiesProvider.class); - - Display display; - if (fWorkbenchPartSite != null) { - display = fWorkbenchPartSite.getShell().getDisplay(); - } else { - display = PlatformUI.getWorkbench().getDisplay(); - } + fWorkbenchPartSite = workbench; + + } + + /** + * Adds an action to the Map storing actions. Removes it if action is null. + * + * @param actionID The ID of the action, used as the key in the Map + * @param action The action associated with the ID + */ + protected void setAction(String actionID, IAction action) { + if (action == null) { + fActionMap.remove(actionID); + } else { + fActionMap.put(actionID, action); + } + } + + /** + * Adds the given action to the global action handler for the ViewSite. + * A call to <code>updateActionBars()</code> must be called after changes + * to propagate changes through the workbench. + * + * @param actionID The ID of the action + * @param action The action to be set globally + */ + protected void setGlobalAction(String actionID, IAction action) { + getViewSite().getActionBars().setGlobalActionHandler(actionID, action); + } + + /** + * Adds the given action to the list of actions that will be updated when + * <code>updateSelectionDependentActions()</code> is called. If the string + * is null it will not be added to the list. + * + * @param actionID The ID of the action which should be updated + */ + protected void setSelectionDependantAction(String actionID) { + if (actionID != null) + fSelectionActions.add(actionID); + } + + /** + * Gets the action out of the map, casts it to an <code>IAction</code> + * + * @param actionID The ID of the action to find + * @return The action associated with the ID or null if none is found. + */ + protected IAction getAction(String actionID) { + return fActionMap.get(actionID); + } + + /** + * Calls the update method of the action with the given action ID. + * The action must exist in the action map and must be an instance of + * </code>IUpdate</code> + * + * @param actionId The ID of the action to update + */ + protected void updateAction(String actionId) { + IAction action = getAction(actionId); + if (action instanceof IUpdate) { + ((IUpdate) action).update(); + } + } + + /** + * Iterates through the list of selection dependent actions and + * updates them. Use <code>setSelectionDependentAction(String actionID)</code> + * to add an action to the list. The action must have been added to the known + * actions map by calling <code>setAction(String actionID, IAction action)</code> + * before it can be updated by this method. + */ + protected void updateSelectionDependentActions() { + Iterator<String> iterator = fSelectionActions.iterator(); + while (iterator.hasNext()) { + updateAction(iterator.next()); + } + } + + /** + * Gets the view site for this view. May be null if this detail pane + * is not part of a view. + * + * @return The site for this view or <code>null</code> + */ + protected IViewSite getViewSite() { + if (fWorkbenchPartSite == null) { + return null; + } else { + return (IViewSite) fWorkbenchPartSite.getPart().getSite(); + } + } + + /** + * Gets the workbench part site for this view. May be null if this detail pane + * is not part of a view. + * + * @return The workbench part site or <code>null</code> + */ + protected IWorkbenchPartSite getWorkbenchPartSite() { + return fWorkbenchPartSite; + } + + /** + * Returns whether this detail pane is being displayed in a view with a workbench part site. + * + * @return whether this detail pane is being displayed in a view with a workbench part site. + */ + protected boolean isInView() { + return fWorkbenchPartSite != null; + } + + /** + * These are the IDs for the actions in the context menu + */ + protected static final String DETAIL_COPY_ACTION = ActionFactory.COPY.getId() + ".TextDetailPane"; //$NON-NLS-1$ + protected static final String DETAIL_SELECT_ALL_ACTION = IDebugView.SELECT_ALL_ACTION + ".TextDetailPane"; //$NON-NLS-1$ + protected static final String DETAIL_WORD_WRAP_ACTION = DsfUIPlugin.PLUGIN_ID + ".detail_pane_word_wrap"; //$NON-NLS-1$ + protected static final String DETAIL_MAX_LENGTH_ACTION = "MaxLength"; //$NON-NLS-1$ + + /** + * The ID, name and description of this pane are stored in constants so that the class + * does not have to be instantiated to access them. + */ + public static final String ID = "NumberFormatPane"; //$NON-NLS-1$ + + /** + * Useful shortened names for the internationalized strings. + */ + public static String FORMAT_SEPARATOR = MessagesForNumberFormatDetailPane.NumberFormatDetailPane_format_separator__label; + public static String NAME = MessagesForNumberFormatDetailPane.NumberFormatDetailPane_Name_label; + public static String SPACES = MessagesForNumberFormatDetailPane.NumberFormatDetailPane_Spaces_label; + public static String CRLF = MessagesForNumberFormatDetailPane.NumberFormatDetailPane_CarriageReturn_label; + public static String DOTS = MessagesForNumberFormatDetailPane.NumberFormatDetailPane_DotDotDot_label; + public static String PARENTHESES = MessagesForNumberFormatDetailPane.NumberFormatDetailPane__End_parentheses; + + /** + * Job to compute the details for a selection + */ + class DetailJob extends Job implements IValueDetailListener { + private IPresentationContext fPresentationContext; + private Object fViewerInput; + private ITreeSelection fElements; + private boolean fFirst = true; + private IProgressMonitor fMonitor; + + public DetailJob(IPresentationContext context, Object viewerInput, ITreeSelection elements, + IDebugModelPresentation model) { + super("compute variable details"); //$NON-NLS-1$ + setSystem(true); + fPresentationContext = context; + fViewerInput = viewerInput; + fElements = elements; + } + + public IProgressMonitor getDetailMonitor() { + return fMonitor; + } + + /* (non-Javadoc) + * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) + */ + @Override + protected IStatus run(final IProgressMonitor monitor) { + if (fMonitor != null && !fMonitor.isCanceled()) { + fMonitor.setCanceled(true); + } + fMonitor = monitor; + TreePath[] paths = fElements.getPaths(); + for (int i = 0; i < paths.length; i++) { + if (monitor.isCanceled()) { + break; + } + final TreePath path = paths[i]; + Object element = paths[i].getLastSegment(); + + final IElementPropertiesProvider propertiesProvider = (IElementPropertiesProvider) DebugPlugin + .getAdapter(element, IElementPropertiesProvider.class); + + Display display; + if (fWorkbenchPartSite != null) { + display = fWorkbenchPartSite.getShell().getDisplay(); + } else { + display = PlatformUI.getWorkbench().getDisplay(); + } final Executor executor = SimpleDisplayExecutor.getSimpleDisplayExecutor(display); - Set<String> properties = new HashSet<String>(1); - properties.add(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS); - propertiesProvider.update(new IPropertiesUpdate[] { new VMPropertiesUpdate( - properties, path, fViewerInput, fPresentationContext, - new DataRequestMonitor<Map<String,Object>>(executor, null) { - @Override - protected void handleCompleted() { - - // Bugzilla 310191: Detail pane does not clear up when DSF-GDB session is terminated - if (fMonitor.isCanceled()) - return; - - Set<String> properties = new HashSet<String>(1); - properties.add(IElementPropertiesProvider.PROP_NAME); - final String[] formats = (String[])getData().get( - IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS); - if (formats != null) { - for (String format : formats) { - properties.add(FormattedValueVMUtil.getPropertyForFormatId(format, null)); - } - } - - propertiesProvider.update(new IPropertiesUpdate[] { new VMPropertiesUpdate( - properties, path, fViewerInput, fPresentationContext, - new DataRequestMonitor<Map<String,Object>>(executor, null) { - @Override - protected void handleSuccess() { - StringBuilder finalResult = new StringBuilder(); - finalResult.append(NAME).append(getData().get(IElementPropertiesProvider.PROP_NAME)).append(CRLF); - - if (formats != null) { - for (int i = 0; i < formats.length; i++) { - String formatId = formats[i]; - finalResult.append(SPACES); - finalResult.append( FormattedValueVMUtil.getFormatLabel(formatId) ); - finalResult.append(FORMAT_SEPARATOR); - finalResult.append( getData().get(FormattedValueVMUtil.getPropertyForFormatId(formatId, null)) ); - if ( i < formats.length + 1 ) { - finalResult.append(CRLF); - } - } - } - detailComputed(null, finalResult.toString()); - } - - @Override - protected void handleErrorOrWarning() { - String rootMessage = new String(getStatus().getMessage()).trim(); - // Provide a detail Error message to the user - StringBuilder finalResult = new StringBuilder(rootMessage); - IStatus[] statuses = getStatus().getChildren(); - if (statuses != null) { - for (int i=0; i < statuses.length; i++) { - String childMessage = statuses[i].getMessage().trim(); - // Avoid root message duplication - if (!childMessage.equals(rootMessage)) { - finalResult.append(CRLF).append(CRLF).append(i + 1).append(PARENTHESES).append(childMessage); - } - } - } - - detailComputed(null, finalResult.toString()); - }; - }) - }); - } - }) - }); - continue; - } - - return Status.OK_STATUS; - } - - /* (non-Javadoc) - * @see org.eclipse.core.runtime.jobs.Job#canceling() - */ - @Override - protected void canceling() { - super.canceling(); - synchronized (this) { - notifyAll(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.debug.ui.IValueDetailListener#detailComputed(org.eclipse.debug.core.model.IValue, java.lang.String) - */ - @Override + Set<String> properties = new HashSet<String>(1); + properties.add(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS); + propertiesProvider + .update(new IPropertiesUpdate[] { new VMPropertiesUpdate(properties, path, fViewerInput, + fPresentationContext, new DataRequestMonitor<Map<String, Object>>(executor, null) { + @Override + protected void handleCompleted() { + + // Bugzilla 310191: Detail pane does not clear up when DSF-GDB session is terminated + if (fMonitor.isCanceled()) + return; + + Set<String> properties = new HashSet<String>(1); + properties.add(IElementPropertiesProvider.PROP_NAME); + final String[] formats = (String[]) getData() + .get(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS); + if (formats != null) { + for (String format : formats) { + properties + .add(FormattedValueVMUtil.getPropertyForFormatId(format, null)); + } + } + + propertiesProvider + .update(new IPropertiesUpdate[] { new VMPropertiesUpdate(properties, + path, fViewerInput, fPresentationContext, + new DataRequestMonitor<Map<String, Object>>(executor, null) { + @Override + protected void handleSuccess() { + StringBuilder finalResult = new StringBuilder(); + finalResult.append(NAME) + .append(getData().get( + IElementPropertiesProvider.PROP_NAME)) + .append(CRLF); + + if (formats != null) { + for (int i = 0; i < formats.length; i++) { + String formatId = formats[i]; + finalResult.append(SPACES); + finalResult.append(FormattedValueVMUtil + .getFormatLabel(formatId)); + finalResult.append(FORMAT_SEPARATOR); + finalResult.append( + getData().get(FormattedValueVMUtil + .getPropertyForFormatId( + formatId, null))); + if (i < formats.length + 1) { + finalResult.append(CRLF); + } + } + } + detailComputed(null, finalResult.toString()); + } + + @Override + protected void handleErrorOrWarning() { + String rootMessage = new String( + getStatus().getMessage()).trim(); + // Provide a detail Error message to the user + StringBuilder finalResult = new StringBuilder( + rootMessage); + IStatus[] statuses = getStatus().getChildren(); + if (statuses != null) { + for (int i = 0; i < statuses.length; i++) { + String childMessage = statuses[i].getMessage() + .trim(); + // Avoid root message duplication + if (!childMessage.equals(rootMessage)) { + finalResult.append(CRLF).append(CRLF) + .append(i + 1).append(PARENTHESES) + .append(childMessage); + } + } + } + + detailComputed(null, finalResult.toString()); + }; + }) }); + } + }) }); + continue; + } + + return Status.OK_STATUS; + } + + /* (non-Javadoc) + * @see org.eclipse.core.runtime.jobs.Job#canceling() + */ + @Override + protected void canceling() { + super.canceling(); + synchronized (this) { + notifyAll(); + } + } + + /* (non-Javadoc) + * @see org.eclipse.debug.ui.IValueDetailListener#detailComputed(org.eclipse.debug.core.model.IValue, java.lang.String) + */ + @Override public void detailComputed(IValue value, final String result) { - synchronized (this) { + synchronized (this) { + } + if (!fMonitor.isCanceled()) { + WorkbenchJob append = new WorkbenchJob("append details") { //$NON-NLS-1$ + @Override + public IStatus runInUIThread(IProgressMonitor monitor) { + if (!fMonitor.isCanceled()) { + String insert = result; + int length = 0; + if (!fFirst) { + length = getDetailDocument().getLength(); + } + if (length > 0) { + insert = CRLF + result; + } + try { + int max = DsfUIPlugin.getDefault().getPreferenceStore() + .getInt(IDebugUIConstants.PREF_MAX_DETAIL_LENGTH); + if (max > 0 && insert.length() > max) { + insert = insert.substring(0, max) + DOTS; + } + if (fFirst) { + getDetailDocument().set(insert); + fFirst = false; + } else { + getDetailDocument().replace(length, 0, insert); + } + } catch (BadLocationException e) { + DsfUIPlugin.log(e); + } + } + return Status.OK_STATUS; + } + }; + append.setSystem(true); + append.schedule(); + } + synchronized (this) { + notifyAll(); } - if (!fMonitor.isCanceled()) { - WorkbenchJob append = new WorkbenchJob("append details") { //$NON-NLS-1$ - @Override - public IStatus runInUIThread(IProgressMonitor monitor) { - if (!fMonitor.isCanceled()) { - String insert = result; - int length = 0; - if (!fFirst) { - length = getDetailDocument().getLength(); - } - if (length > 0) { - insert = CRLF + result; - } - try { - int max = DsfUIPlugin.getDefault().getPreferenceStore().getInt(IDebugUIConstants.PREF_MAX_DETAIL_LENGTH); - if (max > 0 && insert.length() > max) { - insert = insert.substring(0, max) + DOTS; - } - if (fFirst) { - getDetailDocument().set(insert); - fFirst = false; - } else { - getDetailDocument().replace(length, 0,insert); - } - } catch (BadLocationException e) { - DsfUIPlugin.log(e); - } - } - return Status.OK_STATUS; - } - }; - append.setSystem(true); - append.schedule(); - } - synchronized (this) { - notifyAll(); - } - } - } - - /** - * The model presentation used to produce the string details for a - * selected variable. - */ - private String fDebugModelIdentifier; - - /** - * The text viewer in which the computed string detail - * of selected variables will be displayed. - */ - private TextViewer fTextViewer; - - /** - * The last selection displayed in the text viewer. - */ - private IStructuredSelection fLastDisplayed = null; - - /** - * Variables used to create the detailed information for a selection - */ - private IDocument fDetailDocument; - private DetailJob fDetailJob = null; - - /* (non-Javadoc) - * @see org.eclipse.debug.ui.IDetailPane#createControl(org.eclipse.swt.widgets.Composite) - */ - @Override + } + } + + /** + * The model presentation used to produce the string details for a + * selected variable. + */ + private String fDebugModelIdentifier; + + /** + * The text viewer in which the computed string detail + * of selected variables will be displayed. + */ + private TextViewer fTextViewer; + + /** + * The last selection displayed in the text viewer. + */ + private IStructuredSelection fLastDisplayed = null; + + /** + * Variables used to create the detailed information for a selection + */ + private IDocument fDetailDocument; + private DetailJob fDetailJob = null; + + /* (non-Javadoc) + * @see org.eclipse.debug.ui.IDetailPane#createControl(org.eclipse.swt.widgets.Composite) + */ + @Override public Control createControl(Composite parent) { - - createTextViewer(parent); - - if (isInView()){ - createViewSpecificComponents(); - createActions(); - DsfUIPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); - JFaceResources.getFontRegistry().addListener(this); - } - - return fTextViewer.getControl(); - } - - /** - * Creates the text viewer in the given parent composite - * - * @param parent Parent composite to create the text viewer in - */ - private void createTextViewer(Composite parent) { - - // Create & configure a TextViewer - fTextViewer = new TextViewer(parent, SWT.V_SCROLL | SWT.H_SCROLL); - fTextViewer.setDocument(getDetailDocument()); - fTextViewer.getTextWidget().setFont(JFaceResources.getFont(IDebugUIConstants.PREF_DETAIL_PANE_FONT)); - fTextViewer.getTextWidget().setWordWrap(DsfUIPlugin.getDefault().getPreferenceStore().getBoolean(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP)); - fTextViewer.setEditable(false); - PlatformUI.getWorkbench().getHelpSystem().setHelp(fTextViewer.getTextWidget(), IDsfDebugHelpContextIds.DETAIL_PANE); - Control control = fTextViewer.getControl(); - GridData gd = new GridData(GridData.FILL_BOTH); - control.setLayoutData(gd); - } - - /** - * Creates listeners and other components that should only be added to the - * text viewer when this detail pane is inside a view. - */ - private void createViewSpecificComponents(){ - - // Add a document listener so actions get updated when the document changes - getDetailDocument().addDocumentListener(new IDocumentListener() { - @Override - public void documentAboutToBeChanged(DocumentEvent event) {} - @Override + + createTextViewer(parent); + + if (isInView()) { + createViewSpecificComponents(); + createActions(); + DsfUIPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); + JFaceResources.getFontRegistry().addListener(this); + } + + return fTextViewer.getControl(); + } + + /** + * Creates the text viewer in the given parent composite + * + * @param parent Parent composite to create the text viewer in + */ + private void createTextViewer(Composite parent) { + + // Create & configure a TextViewer + fTextViewer = new TextViewer(parent, SWT.V_SCROLL | SWT.H_SCROLL); + fTextViewer.setDocument(getDetailDocument()); + fTextViewer.getTextWidget().setFont(JFaceResources.getFont(IDebugUIConstants.PREF_DETAIL_PANE_FONT)); + fTextViewer.getTextWidget().setWordWrap(DsfUIPlugin.getDefault().getPreferenceStore() + .getBoolean(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP)); + fTextViewer.setEditable(false); + PlatformUI.getWorkbench().getHelpSystem().setHelp(fTextViewer.getTextWidget(), + IDsfDebugHelpContextIds.DETAIL_PANE); + Control control = fTextViewer.getControl(); + GridData gd = new GridData(GridData.FILL_BOTH); + control.setLayoutData(gd); + } + + /** + * Creates listeners and other components that should only be added to the + * text viewer when this detail pane is inside a view. + */ + private void createViewSpecificComponents() { + + // Add a document listener so actions get updated when the document changes + getDetailDocument().addDocumentListener(new IDocumentListener() { + @Override + public void documentAboutToBeChanged(DocumentEvent event) { + } + + @Override public void documentChanged(DocumentEvent event) { - updateSelectionDependentActions(); - } - }); - - // Add the selection listener so selection dependent actions get updated. - fTextViewer.getSelectionProvider().addSelectionChangedListener(new ISelectionChangedListener() { - @Override + updateSelectionDependentActions(); + } + }); + + // Add the selection listener so selection dependent actions get updated. + fTextViewer.getSelectionProvider().addSelectionChangedListener(new ISelectionChangedListener() { + @Override public void selectionChanged(SelectionChangedEvent event) { - updateSelectionDependentActions(); - } - }); - - // Add a focus listener to update actions when details area gains focus - fTextViewer.getControl().addFocusListener(new FocusAdapter() { - @Override - public void focusGained(FocusEvent e) { - - setGlobalAction(IDebugView.SELECT_ALL_ACTION, getAction(DETAIL_SELECT_ALL_ACTION)); - setGlobalAction(IDebugView.COPY_ACTION, getAction(DETAIL_COPY_ACTION)); - - getViewSite().getActionBars().updateActionBars(); - } - - @Override - public void focusLost(FocusEvent e) { - - setGlobalAction(IDebugView.SELECT_ALL_ACTION, null); - setGlobalAction(IDebugView.COPY_ACTION, null); - - getViewSite().getActionBars().updateActionBars(); - } - }); - - // Add a context menu to the detail area - createDetailContextMenu(fTextViewer.getTextWidget()); - } - - /** - * Creates the actions to add to the context menu - */ - private void createActions() { - - TextViewerAction textAction= new TextViewerAction(fTextViewer, ITextOperationTarget.SELECT_ALL); - textAction.configureAction(MessagesForDetailPane.DetailPane_Select_All, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ - textAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_SELECT_ALL); - PlatformUI.getWorkbench().getHelpSystem().setHelp(textAction, IDsfDebugHelpContextIds.DETAIL_PANE_SELECT_ALL_ACTION); - setAction(DETAIL_SELECT_ALL_ACTION, textAction); - - textAction= new TextViewerAction(fTextViewer, ITextOperationTarget.COPY); - textAction.configureAction(MessagesForDetailPane.DetailPane_Copy, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ - textAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_COPY); - PlatformUI.getWorkbench().getHelpSystem().setHelp(textAction, IDsfDebugHelpContextIds.DETAIL_PANE_COPY_ACTION); - setAction(DETAIL_COPY_ACTION, textAction); - - setSelectionDependantAction(DETAIL_COPY_ACTION); - - updateSelectionDependentActions(); - - IAction action = new DetailPaneWordWrapAction(fTextViewer); - setAction(DETAIL_WORD_WRAP_ACTION, action); - - action = new DetailPaneMaxLengthAction(fTextViewer.getControl().getShell()); - setAction(DETAIL_MAX_LENGTH_ACTION,action); - } - - /** - * Create the context menu particular to the detail pane. Note that anyone - * wishing to contribute an action to this menu must use - * <code>IDebugUIConstants.VARIABLE_VIEW_DETAIL_ID</code> as the - * <code>targetID</code> in the extension XML. - */ - protected void createDetailContextMenu(Control menuControl) { - MenuManager menuMgr= new MenuManager(); - menuMgr.setRemoveAllWhenShown(true); - menuMgr.addMenuListener(new IMenuListener() { - @Override + updateSelectionDependentActions(); + } + }); + + // Add a focus listener to update actions when details area gains focus + fTextViewer.getControl().addFocusListener(new FocusAdapter() { + @Override + public void focusGained(FocusEvent e) { + + setGlobalAction(IDebugView.SELECT_ALL_ACTION, getAction(DETAIL_SELECT_ALL_ACTION)); + setGlobalAction(IDebugView.COPY_ACTION, getAction(DETAIL_COPY_ACTION)); + + getViewSite().getActionBars().updateActionBars(); + } + + @Override + public void focusLost(FocusEvent e) { + + setGlobalAction(IDebugView.SELECT_ALL_ACTION, null); + setGlobalAction(IDebugView.COPY_ACTION, null); + + getViewSite().getActionBars().updateActionBars(); + } + }); + + // Add a context menu to the detail area + createDetailContextMenu(fTextViewer.getTextWidget()); + } + + /** + * Creates the actions to add to the context menu + */ + private void createActions() { + + TextViewerAction textAction = new TextViewerAction(fTextViewer, ITextOperationTarget.SELECT_ALL); + textAction.configureAction(MessagesForDetailPane.DetailPane_Select_All, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ + textAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_SELECT_ALL); + PlatformUI.getWorkbench().getHelpSystem().setHelp(textAction, + IDsfDebugHelpContextIds.DETAIL_PANE_SELECT_ALL_ACTION); + setAction(DETAIL_SELECT_ALL_ACTION, textAction); + + textAction = new TextViewerAction(fTextViewer, ITextOperationTarget.COPY); + textAction.configureAction(MessagesForDetailPane.DetailPane_Copy, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ + textAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_COPY); + PlatformUI.getWorkbench().getHelpSystem().setHelp(textAction, IDsfDebugHelpContextIds.DETAIL_PANE_COPY_ACTION); + setAction(DETAIL_COPY_ACTION, textAction); + + setSelectionDependantAction(DETAIL_COPY_ACTION); + + updateSelectionDependentActions(); + + IAction action = new DetailPaneWordWrapAction(fTextViewer); + setAction(DETAIL_WORD_WRAP_ACTION, action); + + action = new DetailPaneMaxLengthAction(fTextViewer.getControl().getShell()); + setAction(DETAIL_MAX_LENGTH_ACTION, action); + } + + /** + * Create the context menu particular to the detail pane. Note that anyone + * wishing to contribute an action to this menu must use + * <code>IDebugUIConstants.VARIABLE_VIEW_DETAIL_ID</code> as the + * <code>targetID</code> in the extension XML. + */ + protected void createDetailContextMenu(Control menuControl) { + MenuManager menuMgr = new MenuManager(); + menuMgr.setRemoveAllWhenShown(true); + menuMgr.addMenuListener(new IMenuListener() { + @Override public void menuAboutToShow(IMenuManager mgr) { - fillDetailContextMenu(mgr); - } - }); - Menu menu= menuMgr.createContextMenu(menuControl); - menuControl.setMenu(menu); - - getViewSite().registerContextMenu(IDebugUIConstants.VARIABLE_VIEW_DETAIL_ID, menuMgr, fTextViewer.getSelectionProvider()); - } - - /** - * Adds items to the detail pane's context menu including any extension defined - * actions. - * - * @param menu The menu to add the item to. - */ - protected void fillDetailContextMenu(IMenuManager menu) { - - menu.add(new Separator(IDebugUIConstants.VARIABLE_GROUP)); - menu.add(new Separator()); - menu.add(getAction(DETAIL_COPY_ACTION)); - menu.add(getAction(DETAIL_SELECT_ALL_ACTION)); - menu.add(new Separator()); - menu.add(getAction(DETAIL_WORD_WRAP_ACTION)); - menu.add(getAction(DETAIL_MAX_LENGTH_ACTION)); - menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); - } - - /* (non-Javadoc) - * @see org.eclipse.debug.ui.IDetailPane#display(org.eclipse.jface.viewers.IStructuredSelection) - */ - @Override + fillDetailContextMenu(mgr); + } + }); + Menu menu = menuMgr.createContextMenu(menuControl); + menuControl.setMenu(menu); + + getViewSite().registerContextMenu(IDebugUIConstants.VARIABLE_VIEW_DETAIL_ID, menuMgr, + fTextViewer.getSelectionProvider()); + } + + /** + * Adds items to the detail pane's context menu including any extension defined + * actions. + * + * @param menu The menu to add the item to. + */ + protected void fillDetailContextMenu(IMenuManager menu) { + + menu.add(new Separator(IDebugUIConstants.VARIABLE_GROUP)); + menu.add(new Separator()); + menu.add(getAction(DETAIL_COPY_ACTION)); + menu.add(getAction(DETAIL_SELECT_ALL_ACTION)); + menu.add(new Separator()); + menu.add(getAction(DETAIL_WORD_WRAP_ACTION)); + menu.add(getAction(DETAIL_MAX_LENGTH_ACTION)); + menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); + } + + /* (non-Javadoc) + * @see org.eclipse.debug.ui.IDetailPane#display(org.eclipse.jface.viewers.IStructuredSelection) + */ + @Override public void display(IStructuredSelection selection) { - - if (selection == null){ - clearTextViewer(); - return; - } - - fLastDisplayed = selection; - - if ( selection.isEmpty() || !(selection instanceof ITreeSelection) ) { - clearTextViewer(); - return; - } - - Object firstElement = selection.getFirstElement(); - if (firstElement instanceof IAdaptable) { - IDebugModelProvider debugModelProvider = - ((IAdaptable)firstElement).getAdapter(IDebugModelProvider.class); - if (debugModelProvider != null) { - String[] ids = debugModelProvider.getModelIdentifiers(); - if (ids != null && ids.length > 0) { - setDebugModel(ids[0]); - } - } - } - - synchronized (this) { - if (fDetailJob != null) { - fDetailJob.cancel(); - } - if (fWorkbenchPartSite != null) { - IWorkbenchPart part = fWorkbenchPartSite.getPart(); - if (part instanceof IDebugView) { - Viewer viewer = ((IDebugView)part).getViewer(); - Object input = viewer.getInput(); - if (input != null && viewer instanceof TreeModelViewer) { - TreeModelViewer treeModelViewer = (TreeModelViewer)viewer; - fDetailJob = new DetailJob(treeModelViewer.getPresentationContext(), input, - (ITreeSelection)selection, null); - fDetailJob.schedule(); - } - } - } else if (firstElement instanceof IDMVMContext) { - IVMNode vmNode = ((IDMVMContext) firstElement).getVMNode(); - if (vmNode != null) { - Object input = firstElement; - IVMProvider vmProvider = vmNode.getVMProvider(); - final IPresentationContext context= vmProvider.getPresentationContext(); - if (IDsfDebugUIConstants.ID_EXPRESSION_HOVER.equals(context.getId())) { - // magic access to viewer input - see ExpressionVMProvider - input = context.getProperty("__viewerInput"); //$NON-NLS-1$ - } - fDetailJob = new DetailJob(context, input, (ITreeSelection)selection, null); - fDetailJob.schedule(); - } - } - } - } - - /* (non-Javadoc) - * @see org.eclipse.debug.ui.IDetailPane#setFocus() - */ - @Override - public boolean setFocus(){ - if (fTextViewer != null){ - fTextViewer.getTextWidget().setFocus(); - return true; - } - return false; - } - - /* - * - */ - @Override - public void dispose(){ - fActionMap.clear(); - fSelectionActions.clear(); - - if (fDetailJob != null) fDetailJob.cancel(); - fDebugModelIdentifier = null; // Setting this to null makes sure the text viewer is reconfigured with the model presentation after disposal - if (fTextViewer != null && fTextViewer.getControl() != null) { - fTextViewer.getControl().dispose(); - fTextViewer = null; - } - - if (isInView()){ - DsfUIPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); - JFaceResources.getFontRegistry().removeListener(this); - } - } - - /* (non-Javadoc) - * @see org.eclipse.debug.ui.IDetailPane#getDescription() - */ - @Override + + if (selection == null) { + clearTextViewer(); + return; + } + + fLastDisplayed = selection; + + if (selection.isEmpty() || !(selection instanceof ITreeSelection)) { + clearTextViewer(); + return; + } + + Object firstElement = selection.getFirstElement(); + if (firstElement instanceof IAdaptable) { + IDebugModelProvider debugModelProvider = ((IAdaptable) firstElement).getAdapter(IDebugModelProvider.class); + if (debugModelProvider != null) { + String[] ids = debugModelProvider.getModelIdentifiers(); + if (ids != null && ids.length > 0) { + setDebugModel(ids[0]); + } + } + } + + synchronized (this) { + if (fDetailJob != null) { + fDetailJob.cancel(); + } + if (fWorkbenchPartSite != null) { + IWorkbenchPart part = fWorkbenchPartSite.getPart(); + if (part instanceof IDebugView) { + Viewer viewer = ((IDebugView) part).getViewer(); + Object input = viewer.getInput(); + if (input != null && viewer instanceof TreeModelViewer) { + TreeModelViewer treeModelViewer = (TreeModelViewer) viewer; + fDetailJob = new DetailJob(treeModelViewer.getPresentationContext(), input, + (ITreeSelection) selection, null); + fDetailJob.schedule(); + } + } + } else if (firstElement instanceof IDMVMContext) { + IVMNode vmNode = ((IDMVMContext) firstElement).getVMNode(); + if (vmNode != null) { + Object input = firstElement; + IVMProvider vmProvider = vmNode.getVMProvider(); + final IPresentationContext context = vmProvider.getPresentationContext(); + if (IDsfDebugUIConstants.ID_EXPRESSION_HOVER.equals(context.getId())) { + // magic access to viewer input - see ExpressionVMProvider + input = context.getProperty("__viewerInput"); //$NON-NLS-1$ + } + fDetailJob = new DetailJob(context, input, (ITreeSelection) selection, null); + fDetailJob.schedule(); + } + } + } + } + + /* (non-Javadoc) + * @see org.eclipse.debug.ui.IDetailPane#setFocus() + */ + @Override + public boolean setFocus() { + if (fTextViewer != null) { + fTextViewer.getTextWidget().setFocus(); + return true; + } + return false; + } + + /* + * + */ + @Override + public void dispose() { + fActionMap.clear(); + fSelectionActions.clear(); + + if (fDetailJob != null) + fDetailJob.cancel(); + fDebugModelIdentifier = null; // Setting this to null makes sure the text viewer is reconfigured with the model presentation after disposal + if (fTextViewer != null && fTextViewer.getControl() != null) { + fTextViewer.getControl().dispose(); + fTextViewer = null; + } + + if (isInView()) { + DsfUIPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); + JFaceResources.getFontRegistry().removeListener(this); + } + } + + /* (non-Javadoc) + * @see org.eclipse.debug.ui.IDetailPane#getDescription() + */ + @Override public String getDescription() { - return MessagesForDetailPane.NumberFormatDetailPane_Description; - } + return MessagesForDetailPane.NumberFormatDetailPane_Description; + } - /* (non-Javadoc) - * @see org.eclipse.debug.ui.IDetailPane#getID() - */ - @Override + /* (non-Javadoc) + * @see org.eclipse.debug.ui.IDetailPane#getID() + */ + @Override public String getID() { - return ID; - } + return ID; + } - /* (non-Javadoc) - * @see org.eclipse.debug.ui.IDetailPane#getName() - */ - @Override + /* (non-Javadoc) + * @see org.eclipse.debug.ui.IDetailPane#getName() + */ + @Override public String getName() { - return MessagesForDetailPane.NumberFormatDetailPane_Name; - } - - /* (non-Javadoc) - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) - */ - @Override + return MessagesForDetailPane.NumberFormatDetailPane_Name; + } + + /* (non-Javadoc) + * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) + */ + @Override @SuppressWarnings("unchecked") public <T> T getAdapter(Class<T> required) { - if (IFindReplaceTarget.class.equals(required)) { - return (T)fTextViewer.getFindReplaceTarget(); - } - if (ITextViewer.class.equals(required)) { - return (T)fTextViewer; - } - return null; - } - - /** - * Lazily instantiate and return a Document for the detail pane text viewer. - */ - protected IDocument getDetailDocument() { - if (fDetailDocument == null) { - fDetailDocument = new Document(); - } - return fDetailDocument; - } - - /** - * Clears the text viewer, removes all text. - */ - protected void clearTextViewer(){ - if (fDetailJob != null) { - fDetailJob.cancel(); - - // Bugzilla 310191: Detail pane does not clear up when DSF-GDB session is terminated - IProgressMonitor progressMonitor = fDetailJob.getDetailMonitor(); - if (progressMonitor!=null) - progressMonitor.setCanceled(true); - } - fLastDisplayed = null; - fDetailDocument.set(""); //$NON-NLS-1$ - fTextViewer.setEditable(false); - } - - /** - * Configures the details viewer for the debug model - * currently being displayed - */ - protected void configureDetailsViewer() { - fTextViewer.setEditable(false); - } - - /** - * Returns the identifier of the debug model being displayed - * in this view, or <code>null</code> if none. - * - * @return debug model identifier - */ - protected String getDebugModel() { - return fDebugModelIdentifier; - } - - /** - * Sets the identifier of the debug model being displayed - * in this view, or <code>null</code> if none. - * - * @param id debug model identifier of the type of debug - * elements being displayed in this view - */ - protected void setDebugModel(String id) { - if (!id.equals(fDebugModelIdentifier)) { - fDebugModelIdentifier = id; - configureDetailsViewer(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) - */ - @Override + if (IFindReplaceTarget.class.equals(required)) { + return (T) fTextViewer.getFindReplaceTarget(); + } + if (ITextViewer.class.equals(required)) { + return (T) fTextViewer; + } + return null; + } + + /** + * Lazily instantiate and return a Document for the detail pane text viewer. + */ + protected IDocument getDetailDocument() { + if (fDetailDocument == null) { + fDetailDocument = new Document(); + } + return fDetailDocument; + } + + /** + * Clears the text viewer, removes all text. + */ + protected void clearTextViewer() { + if (fDetailJob != null) { + fDetailJob.cancel(); + + // Bugzilla 310191: Detail pane does not clear up when DSF-GDB session is terminated + IProgressMonitor progressMonitor = fDetailJob.getDetailMonitor(); + if (progressMonitor != null) + progressMonitor.setCanceled(true); + } + fLastDisplayed = null; + fDetailDocument.set(""); //$NON-NLS-1$ + fTextViewer.setEditable(false); + } + + /** + * Configures the details viewer for the debug model + * currently being displayed + */ + protected void configureDetailsViewer() { + fTextViewer.setEditable(false); + } + + /** + * Returns the identifier of the debug model being displayed + * in this view, or <code>null</code> if none. + * + * @return debug model identifier + */ + protected String getDebugModel() { + return fDebugModelIdentifier; + } + + /** + * Sets the identifier of the debug model being displayed + * in this view, or <code>null</code> if none. + * + * @param id debug model identifier of the type of debug + * elements being displayed in this view + */ + protected void setDebugModel(String id) { + if (!id.equals(fDebugModelIdentifier)) { + fDebugModelIdentifier = id; + configureDetailsViewer(); + } + } + + /* (non-Javadoc) + * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) + */ + @Override public void propertyChange(PropertyChangeEvent event) { - String propertyName= event.getProperty(); - if (propertyName.equals(IDebugUIConstants.PREF_DETAIL_PANE_FONT)) { - fTextViewer.getTextWidget().setFont(JFaceResources.getFont(IDebugUIConstants.PREF_DETAIL_PANE_FONT)); - } else if (propertyName.equals(IDebugUIConstants.PREF_MAX_DETAIL_LENGTH)) { - display(fLastDisplayed); - } else if (propertyName.equals(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP)) { - fTextViewer.getTextWidget().setWordWrap(DsfUIPlugin.getDefault().getPreferenceStore().getBoolean(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP)); - getAction(DETAIL_WORD_WRAP_ACTION).setChecked(DsfUIPlugin.getDefault().getPreferenceStore().getBoolean(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP)); - } - } + String propertyName = event.getProperty(); + if (propertyName.equals(IDebugUIConstants.PREF_DETAIL_PANE_FONT)) { + fTextViewer.getTextWidget().setFont(JFaceResources.getFont(IDebugUIConstants.PREF_DETAIL_PANE_FONT)); + } else if (propertyName.equals(IDebugUIConstants.PREF_MAX_DETAIL_LENGTH)) { + display(fLastDisplayed); + } else if (propertyName.equals(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP)) { + fTextViewer.getTextWidget().setWordWrap(DsfUIPlugin.getDefault().getPreferenceStore() + .getBoolean(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP)); + getAction(DETAIL_WORD_WRAP_ACTION).setChecked(DsfUIPlugin.getDefault().getPreferenceStore() + .getBoolean(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP)); + } + } /* * @see org.eclipse.debug.ui.IDetailPane2#getSelectionProvider() diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/numberformat/detail/NumberFormatDetailPaneFactory.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/numberformat/detail/NumberFormatDetailPaneFactory.java index 36f50f06f9b..98160946ba0 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/numberformat/detail/NumberFormatDetailPaneFactory.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/viewmodel/numberformat/detail/NumberFormatDetailPaneFactory.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems, Inc. - initial implementation *******************************************************************************/ @@ -27,53 +27,53 @@ import org.eclipse.jface.viewers.IStructuredSelection; public class NumberFormatDetailPaneFactory implements IDetailPaneFactory { - /* (non-Javadoc) - * @see org.eclipse.debug.internal.ui.views.variables.IDetailsFactory#createDetailsArea(java.lang.String) - */ - @Override - public IDetailPane createDetailPane(String id) { - return new NumberFormatDetailPane(); - } + /* (non-Javadoc) + * @see org.eclipse.debug.internal.ui.views.variables.IDetailsFactory#createDetailsArea(java.lang.String) + */ + @Override + public IDetailPane createDetailPane(String id) { + return new NumberFormatDetailPane(); + } + + /* (non-Javadoc) + * @see org.eclipse.debug.internal.ui.views.variables.IDetailsFactory#getDetailsTypes(org.eclipse.jface.viewers.IStructuredSelection) + */ + @SuppressWarnings("rawtypes") + @Override + public Set getDetailPaneTypes(IStructuredSelection selection) { + Set<String> possibleIDs = new HashSet<String>(1); + possibleIDs.add(NumberFormatDetailPane.ID); + return possibleIDs; + } - /* (non-Javadoc) - * @see org.eclipse.debug.internal.ui.views.variables.IDetailsFactory#getDetailsTypes(org.eclipse.jface.viewers.IStructuredSelection) - */ - @SuppressWarnings("rawtypes") - @Override - public Set getDetailPaneTypes(IStructuredSelection selection) { - Set<String> possibleIDs = new HashSet<String>(1); - possibleIDs.add(NumberFormatDetailPane.ID); - return possibleIDs; - } - - /* (non-Javadoc) - * @see org.eclipse.debug.ui.IDetailPaneFactory#getDefaultDetailPane(java.util.Set, org.eclipse.jface.viewers.IStructuredSelection) - */ - @Override - public String getDefaultDetailPane(IStructuredSelection selection) { - return null; // Allow competing detail pane factories to override this one - } + /* (non-Javadoc) + * @see org.eclipse.debug.ui.IDetailPaneFactory#getDefaultDetailPane(java.util.Set, org.eclipse.jface.viewers.IStructuredSelection) + */ + @Override + public String getDefaultDetailPane(IStructuredSelection selection) { + return null; // Allow competing detail pane factories to override this one + } - /* (non-Javadoc) - * @see org.eclipse.debug.internal.ui.views.variables.IDetailsFactory#getName(java.lang.String) - */ - @Override - public String getDetailPaneName(String id) { - if (id.equals(NumberFormatDetailPane.ID)){ - return MessagesForDetailPane.NumberFormatDetailPane_Name; - } - return null; - } + /* (non-Javadoc) + * @see org.eclipse.debug.internal.ui.views.variables.IDetailsFactory#getName(java.lang.String) + */ + @Override + public String getDetailPaneName(String id) { + if (id.equals(NumberFormatDetailPane.ID)) { + return MessagesForDetailPane.NumberFormatDetailPane_Name; + } + return null; + } - /* (non-Javadoc) - * @see org.eclipse.debug.internal.ui.views.variables.IDetailsFactory#getDescription(java.lang.String) - */ - @Override - public String getDetailPaneDescription(String id) { - if (id.equals(NumberFormatDetailPane.ID)){ - return MessagesForDetailPane.NumberFormatDetailPane_Description; - } - return null; - } + /* (non-Javadoc) + * @see org.eclipse.debug.internal.ui.views.variables.IDetailsFactory#getDescription(java.lang.String) + */ + @Override + public String getDetailPaneDescription(String id) { + if (id.equals(NumberFormatDetailPane.ID)) { + return MessagesForDetailPane.NumberFormatDetailPane_Description; + } + return null; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/AbstractDsfDebugTextHover.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/AbstractDsfDebugTextHover.java index ea1166f5a3f..20c91140d3f 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/AbstractDsfDebugTextHover.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/AbstractDsfDebugTextHover.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Nokia Corporation - initial API and implementation * Wind River Systems - Added support for advanced expression hover @@ -44,87 +44,90 @@ import org.eclipse.ui.editors.text.EditorsUI; /** * An implementation of AbstractDebugTextHover using DSF services - * + * * @since 2.1 */ abstract public class AbstractDsfDebugTextHover extends AbstractDebugTextHover implements ITextHoverExtension2 { - /** - * Returns the debug model ID that this debug text hover is to be used for. - */ - abstract protected String getModelId(); - - /** - * Returns the type of format that should be used for the hover. - */ - protected String getHoverFormat() { - return IFormattedValues.NATURAL_FORMAT; - } - + /** + * Returns the debug model ID that this debug text hover is to be used for. + */ + abstract protected String getModelId(); + + /** + * Returns the type of format that should be used for the hover. + */ + protected String getHoverFormat() { + return IFormattedValues.NATURAL_FORMAT; + } + private class GetExpressionValueQuery extends Query<FormattedValueDMData> { - private final IFrameDMContext frame; - private final String expression; + private final IFrameDMContext frame; + private final String expression; private DsfServicesTracker dsfServicesTracker; - public GetExpressionValueQuery(IFrameDMContext frame, String expression, DsfServicesTracker dsfServicesTracker) { - this.frame = frame; + public GetExpressionValueQuery(IFrameDMContext frame, String expression, + DsfServicesTracker dsfServicesTracker) { + this.frame = frame; this.expression = expression; this.dsfServicesTracker = dsfServicesTracker; - } + } - @Override - protected void execute(final DataRequestMonitor<FormattedValueDMData> rm) { - DsfSession session = DsfSession.getSession(frame.getSessionId()); + @Override + protected void execute(final DataRequestMonitor<FormattedValueDMData> rm) { + DsfSession session = DsfSession.getSession(frame.getSessionId()); IExpressions expressions = dsfServicesTracker.getService(IExpressions.class); if (expressions == null) { - rm.setStatus(DsfUIPlugin.newErrorStatus(IDsfStatusConstants.REQUEST_FAILED, "No expression service", null)); //$NON-NLS-1$ - rm.done(); - return; + rm.setStatus( + DsfUIPlugin.newErrorStatus(IDsfStatusConstants.REQUEST_FAILED, "No expression service", null)); //$NON-NLS-1$ + rm.done(); + return; } - IExpressionDMContext expressionDMC = expressions.createExpression(frame, expression); - FormattedValueDMContext formattedValueContext = expressions.getFormattedValueContext(expressionDMC, getHoverFormat()); - expressions.getFormattedExpressionValue(formattedValueContext, - new DataRequestMonitor<FormattedValueDMData>(session.getExecutor(), rm) { - @Override - protected void handleSuccess() { - rm.setData(getData()); - rm.done(); - } - - @Override - protected void handleFailure() { - rm.done(); - } - }); - } - } + IExpressionDMContext expressionDMC = expressions.createExpression(frame, expression); + FormattedValueDMContext formattedValueContext = expressions.getFormattedValueContext(expressionDMC, + getHoverFormat()); + expressions.getFormattedExpressionValue(formattedValueContext, + new DataRequestMonitor<FormattedValueDMData>(session.getExecutor(), rm) { + @Override + protected void handleSuccess() { + rm.setData(getData()); + rm.done(); + } + + @Override + protected void handleFailure() { + rm.done(); + } + }); + } + } protected IFrameDMContext getFrame() { - IAdaptable adaptable = getSelectionAdaptable(); - if (adaptable != null) { - return adaptable.getAdapter(IFrameDMContext.class); + IAdaptable adaptable = getSelectionAdaptable(); + if (adaptable != null) { + return adaptable.getAdapter(IFrameDMContext.class); } return null; } @Override protected boolean canEvaluate() { - if (getFrame() == null) { - return false; - } - + if (getFrame() == null) { + return false; + } + IAdaptable adaptable = getSelectionAdaptable(); if (adaptable != null) { - IDebugModelProvider modelProvider = adaptable.getAdapter(IDebugModelProvider.class); - if (modelProvider != null) { - String[] models = modelProvider.getModelIdentifiers(); - String myModel = getModelId(); - for (int i = 0; i < models.length; i++) { - if (models[i].equals(myModel)) { - return true; - } - } - } + IDebugModelProvider modelProvider = adaptable.getAdapter(IDebugModelProvider.class); + if (modelProvider != null) { + String[] models = modelProvider.getModelIdentifiers(); + String myModel = getModelId(); + for (int i = 0; i < models.length; i++) { + if (models[i].equals(myModel)) { + return true; + } + } + } } return false; } @@ -142,58 +145,59 @@ abstract public class AbstractDsfDebugTextHover extends AbstractDebugTextHover i GetExpressionValueQuery query = new GetExpressionValueQuery(frame, expression, dsfServicesTracker); DsfSession session = DsfSession.getSession(sessionId); if (session != null) { - session.getExecutor().execute(query); - try { - FormattedValueDMData data = query.get(); - if (data != null) - return data.getFormattedValue(); - } catch (Exception e) { - } + session.getExecutor().execute(query); + try { + FormattedValueDMData data = query.get(); + if (data != null) + return data.getFormattedValue(); + } catch (Exception e) { + } } } finally { dsfServicesTracker.dispose(); } - return null; + return null; + } + + /** + * Returns whether the "advanced" expression information control should be used. + * The default implementation returns <code>false</code>. + */ + protected boolean useExpressionExplorer() { + return false; + } + + /** + * Create an information control creator for the "advanced" hover. + * <p> + * Clients can call this method to create an information control creator + * with custom options. + * </p> + * @param showDetailPane whether the detail pane should be visible + * @param defaultExpansionLevel automatically expand the expression to this level + * @return the information control creator + */ + protected final IInformationControlCreator createExpressionInformationControlCreator(boolean showDetailPane, + int defaultExpansionLevel) { + return new ExpressionInformationControlCreator(showDetailPane, defaultExpansionLevel); + } + + /** + * Create an information control creator for the "advanced" hover. + * Called by {@link #getHoverControlCreator()} when {@link #useExpressionExplorer()} + * returns <code>true</code>. + * <p> + * The default implementation returns an information control creator with + * details pane enabled and default expansion level = 1. + * Clients may override this method to return an instance with different options. + * </p> + * @return the information control creator + * @see {@link #createExpressionInformationControlCreator(boolean, int)} + */ + protected IInformationControlCreator createExpressionInformationControlCreator() { + return createExpressionInformationControlCreator(true, 1); } - /** - * Returns whether the "advanced" expression information control should be used. - * The default implementation returns <code>false</code>. - */ - protected boolean useExpressionExplorer() { - return false; - } - - /** - * Create an information control creator for the "advanced" hover. - * <p> - * Clients can call this method to create an information control creator - * with custom options. - * </p> - * @param showDetailPane whether the detail pane should be visible - * @param defaultExpansionLevel automatically expand the expression to this level - * @return the information control creator - */ - protected final IInformationControlCreator createExpressionInformationControlCreator(boolean showDetailPane, int defaultExpansionLevel) { - return new ExpressionInformationControlCreator(showDetailPane, defaultExpansionLevel); - } - - /** - * Create an information control creator for the "advanced" hover. - * Called by {@link #getHoverControlCreator()} when {@link #useExpressionExplorer()} - * returns <code>true</code>. - * <p> - * The default implementation returns an information control creator with - * details pane enabled and default expansion level = 1. - * Clients may override this method to return an instance with different options. - * </p> - * @return the information control creator - * @see {@link #createExpressionInformationControlCreator(boolean, int)} - */ - protected IInformationControlCreator createExpressionInformationControlCreator() { - return createExpressionInformationControlCreator(true, 1); - } - @Override public IInformationControlCreator getHoverControlCreator() { if (useExpressionExplorer()) { @@ -213,15 +217,15 @@ abstract public class AbstractDsfDebugTextHover extends AbstractDebugTextHover i */ @Override public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) { - final String simpleInfo = getHoverInfo(textViewer, hoverRegion); + final String simpleInfo = getHoverInfo(textViewer, hoverRegion); if (!useExpressionExplorer() || simpleInfo == null) { - return simpleInfo; - } + return simpleInfo; + } // improved version using ExpressionInformationControlCreator - // see also getHoverControlCreator() - final String text; - text= getExpressionText(textViewer, hoverRegion); - if (text != null && !text.isEmpty()) { + // see also getHoverControlCreator() + final String text; + text = getExpressionText(textViewer, hoverRegion); + if (text != null && !text.isEmpty()) { final IFrameDMContext frameDmc = getFrame(); if (frameDmc != null) { final DsfSession dsfSession = DsfSession.getSession(frameDmc.getSessionId()); @@ -229,7 +233,8 @@ abstract public class AbstractDsfDebugTextHover extends AbstractDebugTextHover i Callable<IExpressionDMContext> callable = new Callable<IExpressionDMContext>() { @Override public IExpressionDMContext call() throws Exception { - DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), frameDmc.getSessionId()); + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + frameDmc.getSessionId()); try { IExpressions expressions = tracker.getService(IExpressions.class); if (expressions != null) { @@ -248,8 +253,8 @@ abstract public class AbstractDsfDebugTextHover extends AbstractDebugTextHover i } } } - } - return null; + } + return null; } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/DsfDebugTextHover.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/DsfDebugTextHover.java index 1c4e5ed06e3..8ab60ac47bf 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/DsfDebugTextHover.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/DsfDebugTextHover.java @@ -7,39 +7,40 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Ericsson - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.dsf.debug.ui; - /** * A default hover provided by DSF. Any hover provided by another * debugger integration using DSF will automatically override this one * based on the <code>BestMatchHover</code> class. - * + * * @since 2.1 */ public class DsfDebugTextHover extends AbstractDsfDebugTextHover { - /* - * This Hover should work for any model using DSF, so we don't - * use the getModelId() method. - */ + /* + * This Hover should work for any model using DSF, so we don't + * use the getModelId() method. + */ @Override - protected String getModelId() { return null; } - + protected String getModelId() { + return null; + } + /* * Override to not use the getModelId() method, since this hover should * be valid for any modelId using DSF. */ @Override protected boolean canEvaluate() { - if (getFrame() != null) { - return true; - } - return false; + if (getFrame() != null) { + return true; + } + return false; } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/DsfDebugUITools.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/DsfDebugUITools.java index b467ce10fa6..b4c430c94ea 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/DsfDebugUITools.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/DsfDebugUITools.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -27,9 +27,8 @@ import org.eclipse.ui.activities.IWorkbenchActivitySupport; * @since 1.1 */ public class DsfDebugUITools { - - public static IPreferenceStore getPreferenceStore() - { + + public static IPreferenceStore getPreferenceStore() { return DsfUIPlugin.getDefault().getPreferenceStore(); } @@ -37,8 +36,7 @@ public class DsfDebugUITools { * @since 2.1 */ @SuppressWarnings("unchecked") - public static void enableActivity(final String activityID, final boolean enableit) - { + public static void enableActivity(final String activityID, final boolean enableit) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { @@ -47,9 +45,9 @@ public class DsfDebugUITools { Set<String> enabledActivityIds = new HashSet<String>(activityManager.getEnabledActivityIds()); boolean changed = false; if (enableit) - changed = enabledActivityIds.add(activityID); + changed = enabledActivityIds.add(activityID); else - changed = enabledActivityIds.remove(activityID); + changed = enabledActivityIds.remove(activityID); if (changed) workbenchActivitySupport.setEnabledActivityIds(enabledActivityIds); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/IDsfDebugUIConstants.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/IDsfDebugUIConstants.java index 53095792a2b..75839a5a080 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/IDsfDebugUIConstants.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/IDsfDebugUIConstants.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems, Inc. - initial implementation *******************************************************************************/ @@ -19,7 +19,7 @@ import org.eclipse.debug.ui.IDebugUIConstants; /** * @noimplement This interface is not intended to be implemented by clients. - * + * * @since 1.0 */ public interface IDsfDebugUIConstants { @@ -27,75 +27,76 @@ public interface IDsfDebugUIConstants { /** * Debug UI plug-in identifier (value <code>"org.eclipse.cdt.dsf.ui"</code>). */ - public static final String PLUGIN_ID = DsfUIPlugin.PLUGIN_ID; - + public static final String PLUGIN_ID = DsfUIPlugin.PLUGIN_ID; + /** Loaded shared library symbols image identifier. */ public static final String IMG_OBJS_SHARED_LIBRARY_SYMBOLS_LOADED = "icons/library_syms_obj.gif"; //$NON-NLS-1$ - + /** Unloaded Shared library symbols image identifier. */ public static final String IMG_OBJS_SHARED_LIBRARY_SYMBOLS_UNLOADED = "icons/library_obj.gif"; //$NON-NLS-1$ - + /** * Integer preference to control the maximum amount of stack frames to * retrieve from the backend. Default value is <code>10</code>. * @see {@link #PREF_STACK_FRAME_LIMIT_ENABLE} - * + * * @since 1.1 */ public static final String PREF_STACK_FRAME_LIMIT = "stackFrameLimit"; //$NON-NLS-1$ - + /** * Boolean preference whether to apply the stack frame limit preference. Default is <code>true</code>. * @see {@link #PREF_STACK_FRAME_LIMIT} - * + * * @since 1.1 */ public static final String PREF_STACK_FRAME_LIMIT_ENABLE = "stackFrameLimitEnable"; //$NON-NLS-1$ /** * Boolean preference whether to keep stepping speed in sync with UI updates. Default is <code>false</code>. - * + * * @since 1.1 */ public static final String PREF_WAIT_FOR_VIEW_UPDATE_AFTER_STEP_ENABLE = "delaySteppingForViewUpdatesEnable"; //$NON-NLS-1$ /** * Integer preference to enforce a minimum time interval between steps. Default is <code>100</code>. - * + * * @since 1.1 */ - public static final String PREF_MIN_STEP_INTERVAL= "minStepInterval"; //$NON-NLS-1$ - - /** + public static final String PREF_MIN_STEP_INTERVAL = "minStepInterval"; //$NON-NLS-1$ + + /** * @since 1.1 */ - public static final String PREFERENCE_PAGE= PLUGIN_ID + ".preference_page_context"; //$NON-NLS-1$ - - /** - * Stale data foreground color preference key. - * - * @since 2.0 - */ - public static final String PREF_COLOR_STALE_DATA_FOREGROUND= PLUGIN_ID + ".staledata.foreground"; //$NON-NLS-1$ + public static final String PREFERENCE_PAGE = PLUGIN_ID + ".preference_page_context"; //$NON-NLS-1$ - /** - * Stale data foreground color preference key. - * - * @since 2.0 - */ - public static final String PREF_COLOR_STALE_DATA_BACKGROUND= PLUGIN_ID + ".staledata.background"; //$NON-NLS-1$ + /** + * Stale data foreground color preference key. + * + * @since 2.0 + */ + public static final String PREF_COLOR_STALE_DATA_FOREGROUND = PLUGIN_ID + ".staledata.foreground"; //$NON-NLS-1$ + + /** + * Stale data foreground color preference key. + * + * @since 2.0 + */ + public static final String PREF_COLOR_STALE_DATA_BACKGROUND = PLUGIN_ID + ".staledata.background"; //$NON-NLS-1$ - /** - * Presentation context id for the expression hover. - * - * @since 2.1 - */ - public static final String ID_EXPRESSION_HOVER= PLUGIN_ID + ".expression_hover"; //$NON-NLS-1$ - - /** + /** + * Presentation context id for the expression hover. + * + * @since 2.1 + */ + public static final String ID_EXPRESSION_HOVER = PLUGIN_ID + ".expression_hover"; //$NON-NLS-1$ + + /** * Property id to know if we should show full paths in the debug view. * The value of this id must match what is being used as a full key in ShowFullPathsAction.run() - * + * * @since 2.1 */ - public static final String DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY = IDebugUIConstants.ID_DEBUG_VIEW + "." + ICDebugInternalConstants.SHOW_FULL_PATHS_PREF_KEY; //$NON-NLS-1$ + public static final String DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY = IDebugUIConstants.ID_DEBUG_VIEW + "." //$NON-NLS-1$ + + ICDebugInternalConstants.SHOW_FULL_PATHS_PREF_KEY; } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/AbstractDisassemblyBreakpointsTarget.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/AbstractDisassemblyBreakpointsTarget.java index 56a6dd6e8d8..24b770cd773 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/AbstractDisassemblyBreakpointsTarget.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/AbstractDisassemblyBreakpointsTarget.java @@ -57,28 +57,26 @@ import org.eclipse.ui.texteditor.SimpleMarkerAnnotation; * Base class for toggle breakpoint targets for the disassembly part. * @since 2.2 */ -public abstract class AbstractDisassemblyBreakpointsTarget - implements IToggleBreakpointsTargetExtension2, IToggleBreakpointsTargetCExtension -{ +public abstract class AbstractDisassemblyBreakpointsTarget + implements IToggleBreakpointsTargetExtension2, IToggleBreakpointsTargetCExtension { /* (non-Javadoc) * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleLineBreakpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) */ @Override - public void toggleLineBreakpoints( IWorkbenchPart part, ISelection selection ) throws CoreException { + public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException { assert part instanceof IDisassemblyPart && selection instanceof ITextSelection; - if ( !(selection instanceof IDisassemblySelection) ) { - selection = new DisassemblySelection( (ITextSelection)selection, (IDisassemblyPart)part ); + if (!(selection instanceof IDisassemblySelection)) { + selection = new DisassemblySelection((ITextSelection) selection, (IDisassemblyPart) part); } - IDisassemblySelection disassemblySelection = (IDisassemblySelection)selection; + IDisassemblySelection disassemblySelection = (IDisassemblySelection) selection; int line = disassemblySelection.getStartLine(); - IBreakpoint[] bp = getBreakpointsAtLine( (IDisassemblyPart)part, line ); - if ( bp == null || bp.length == 0 ) { + IBreakpoint[] bp = getBreakpointsAtLine((IDisassemblyPart) part, line); + if (bp == null || bp.length == 0) { insertBreakpoint(part, disassemblySelection, false); - } - else { - for( int i = 0; i < bp.length; i++ ) { + } else { + for (int i = 0; i < bp.length; i++) { bp[i].delete(); } } @@ -88,7 +86,7 @@ public abstract class AbstractDisassemblyBreakpointsTarget * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleLineBreakpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) */ @Override - public boolean canToggleLineBreakpoints( IWorkbenchPart part, ISelection selection ) { + public boolean canToggleLineBreakpoints(IWorkbenchPart part, ISelection selection) { return part instanceof IDisassemblyPart && selection instanceof ITextSelection; } @@ -96,14 +94,14 @@ public abstract class AbstractDisassemblyBreakpointsTarget * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) */ @Override - public void toggleMethodBreakpoints( IWorkbenchPart part, ISelection selection ) throws CoreException { + public void toggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException { } /* (non-Javadoc) * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) */ @Override - public boolean canToggleMethodBreakpoints( IWorkbenchPart part, ISelection selection ) { + public boolean canToggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) { return false; } @@ -111,14 +109,14 @@ public abstract class AbstractDisassemblyBreakpointsTarget * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleWatchpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) */ @Override - public void toggleWatchpoints( IWorkbenchPart part, ISelection selection ) throws CoreException { + public void toggleWatchpoints(IWorkbenchPart part, ISelection selection) throws CoreException { } /* (non-Javadoc) * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleWatchpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) */ @Override - public boolean canToggleWatchpoints( IWorkbenchPart part, ISelection selection ) { + public boolean canToggleWatchpoints(IWorkbenchPart part, ISelection selection) { return false; } @@ -126,266 +124,266 @@ public abstract class AbstractDisassemblyBreakpointsTarget * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTargetExtension#toggleBreakpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) */ @Override - public void toggleBreakpoints( IWorkbenchPart part, ISelection selection ) throws CoreException { - toggleLineBreakpoints( part, selection ); + public void toggleBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException { + toggleLineBreakpoints(part, selection); } /* (non-Javadoc) * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTargetExtension#canToggleBreakpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) */ @Override - public boolean canToggleBreakpoints( IWorkbenchPart part, ISelection selection ) { - return canToggleLineBreakpoints( part, selection ); + public boolean canToggleBreakpoints(IWorkbenchPart part, ISelection selection) { + return canToggleLineBreakpoints(part, selection); } /** - * @since 2.3 - */ + * @since 2.3 + */ @Override public boolean canToggleBreakpointsWithEvent(IWorkbenchPart part, ISelection selection, Event event) { - return canToggleBreakpoints(part, selection); + return canToggleBreakpoints(part, selection); } - - /** - * @since 2.3 - */ + + /** + * @since 2.3 + */ @Override - public void toggleBreakpointsWithEvent(IWorkbenchPart part, ISelection selection, Event event) throws CoreException { - assert part instanceof IDisassemblyPart && selection instanceof ITextSelection; - - boolean mod1 = event != null && (event.stateMask & SWT.MOD1) > 0; - boolean mod2 = event != null && (event.stateMask & SWT.MOD2) > 0; - if ( !(selection instanceof IDisassemblySelection) ) { - selection = new DisassemblySelection( (ITextSelection)selection, (IDisassemblyPart)part ); - } - IDisassemblySelection disassemblySelection = (IDisassemblySelection)selection; - int line = disassemblySelection.getStartLine(); - IBreakpoint[] bp = getBreakpointsAtLine( (IDisassemblyPart)part, line ); - if ( bp == null || bp.length == 0 ) { - insertBreakpoint(part, disassemblySelection, mod1); - } - else { - if(mod2) { - toggleBreakpointEnabled(bp[0]); - return; - } else if (mod1 && bp[0] instanceof ICBreakpoint) { - CDebugUIUtils.editBreakpointProperties(part, (ICBreakpoint)bp[0]); - return; - } - - for( int i = 0; i < bp.length; i++ ) { - bp[i].delete(); - } - } + public void toggleBreakpointsWithEvent(IWorkbenchPart part, ISelection selection, Event event) + throws CoreException { + assert part instanceof IDisassemblyPart && selection instanceof ITextSelection; + + boolean mod1 = event != null && (event.stateMask & SWT.MOD1) > 0; + boolean mod2 = event != null && (event.stateMask & SWT.MOD2) > 0; + if (!(selection instanceof IDisassemblySelection)) { + selection = new DisassemblySelection((ITextSelection) selection, (IDisassemblyPart) part); + } + IDisassemblySelection disassemblySelection = (IDisassemblySelection) selection; + int line = disassemblySelection.getStartLine(); + IBreakpoint[] bp = getBreakpointsAtLine((IDisassemblyPart) part, line); + if (bp == null || bp.length == 0) { + insertBreakpoint(part, disassemblySelection, mod1); + } else { + if (mod2) { + toggleBreakpointEnabled(bp[0]); + return; + } else if (mod1 && bp[0] instanceof ICBreakpoint) { + CDebugUIUtils.editBreakpointProperties(part, (ICBreakpoint) bp[0]); + return; + } + + for (int i = 0; i < bp.length; i++) { + bp[i].delete(); + } + } } - /** - * @since 2.3 - */ - @Override - public boolean canCreateLineBreakpointsInteractive(IWorkbenchPart part, ISelection selection) { - return canToggleLineBreakpoints(part, selection) && !hasBreakpoint(part, selection); - } - - /** - * @since 2.3 - */ - @Override - public void createLineBreakpointsInteractive(IWorkbenchPart part, ISelection selection) throws CoreException { - assert part instanceof IDisassemblyPart && selection instanceof ITextSelection; - - if ( !(selection instanceof IDisassemblySelection) ) { - selection = new DisassemblySelection( (ITextSelection)selection, (IDisassemblyPart)part ); - } - IDisassemblySelection disassemblySelection = (IDisassemblySelection)selection; - insertBreakpoint(part, disassemblySelection, true); - } - - /** - * @since 2.3 - */ - @Override - public boolean canCreateFunctionBreakpointInteractive(IWorkbenchPart part, ISelection selection) { - return false; - } - - /** - * @since 2.3 - */ - @Override - public void createFunctionBreakpointInteractive(IWorkbenchPart part, ISelection selection) throws CoreException { - } - - /** - * @since 2.3 - */ - @Override - public boolean canCreateWatchpointsInteractive(IWorkbenchPart part, ISelection selection) { - return false; - } - - /** - * @since 2.3 - */ - @Override - public void createWatchpointsInteractive(IWorkbenchPart part, ISelection selection) throws CoreException { - } - - /** - * @since 2.3 - */ - @Override - public boolean canCreateEventBreakpointsInteractive(IWorkbenchPart part, ISelection selection) { - return false; - } - - /** - * @since 2.3 - */ - @Override - public void createEventBreakpointsInteractive(IWorkbenchPart part, ISelection selection) throws CoreException { - } + /** + * @since 2.3 + */ + @Override + public boolean canCreateLineBreakpointsInteractive(IWorkbenchPart part, ISelection selection) { + return canToggleLineBreakpoints(part, selection) && !hasBreakpoint(part, selection); + } + + /** + * @since 2.3 + */ + @Override + public void createLineBreakpointsInteractive(IWorkbenchPart part, ISelection selection) throws CoreException { + assert part instanceof IDisassemblyPart && selection instanceof ITextSelection; + + if (!(selection instanceof IDisassemblySelection)) { + selection = new DisassemblySelection((ITextSelection) selection, (IDisassemblyPart) part); + } + IDisassemblySelection disassemblySelection = (IDisassemblySelection) selection; + insertBreakpoint(part, disassemblySelection, true); + } + + /** + * @since 2.3 + */ + @Override + public boolean canCreateFunctionBreakpointInteractive(IWorkbenchPart part, ISelection selection) { + return false; + } + + /** + * @since 2.3 + */ + @Override + public void createFunctionBreakpointInteractive(IWorkbenchPart part, ISelection selection) throws CoreException { + } + + /** + * @since 2.3 + */ + @Override + public boolean canCreateWatchpointsInteractive(IWorkbenchPart part, ISelection selection) { + return false; + } + + /** + * @since 2.3 + */ + @Override + public void createWatchpointsInteractive(IWorkbenchPart part, ISelection selection) throws CoreException { + } + + /** + * @since 2.3 + */ + @Override + public boolean canCreateEventBreakpointsInteractive(IWorkbenchPart part, ISelection selection) { + return false; + } + + /** + * @since 2.3 + */ + @Override + public void createEventBreakpointsInteractive(IWorkbenchPart part, ISelection selection) throws CoreException { + } private void toggleBreakpointEnabled(IBreakpoint bp) { - try { - bp.setEnabled(!bp.isEnabled()); - } catch (CoreException e) { - CDebugUIPlugin.log(e.getStatus()); - } + try { + bp.setEnabled(!bp.isEnabled()); + } catch (CoreException e) { + CDebugUIPlugin.log(e.getStatus()); + } } - - protected abstract void createLineBreakpoint( String sourceHandle, IResource resource, int lineNumber ) throws CoreException; + + protected abstract void createLineBreakpoint(String sourceHandle, IResource resource, int lineNumber) + throws CoreException; /** - * @since 2.3 - */ - protected void createLineBreakpointInteractive(IWorkbenchPart part, String sourceHandle, IResource resource, int lineNumber ) throws CoreException { - createLineBreakpoint(sourceHandle, resource, lineNumber); + * @since 2.3 + */ + protected void createLineBreakpointInteractive(IWorkbenchPart part, String sourceHandle, IResource resource, + int lineNumber) throws CoreException { + createLineBreakpoint(sourceHandle, resource, lineNumber); } - protected abstract void createAddressBreakpoint( IResource resource, IAddress address ) throws CoreException; + protected abstract void createAddressBreakpoint(IResource resource, IAddress address) throws CoreException; /** - * @since 2.3 - */ - protected void createAddressBreakpointInteractive(IWorkbenchPart part, IResource resource, IAddress address ) throws CoreException { - createAddressBreakpoint(resource, address); + * @since 2.3 + */ + protected void createAddressBreakpointInteractive(IWorkbenchPart part, IResource resource, IAddress address) + throws CoreException { + createAddressBreakpoint(resource, address); } - private boolean hasBreakpoint(IWorkbenchPart part, ISelection selection) { + private boolean hasBreakpoint(IWorkbenchPart part, ISelection selection) { assert part instanceof IDisassemblyPart && selection instanceof ITextSelection; - if ( !(selection instanceof IDisassemblySelection) ) { - selection = new DisassemblySelection( (ITextSelection)selection, (IDisassemblyPart)part ); + if (!(selection instanceof IDisassemblySelection)) { + selection = new DisassemblySelection((ITextSelection) selection, (IDisassemblyPart) part); } - IDisassemblySelection disassemblySelection = (IDisassemblySelection)selection; + IDisassemblySelection disassemblySelection = (IDisassemblySelection) selection; int line = disassemblySelection.getStartLine(); - IBreakpoint[] bp = getBreakpointsAtLine( (IDisassemblyPart)part, line ); + IBreakpoint[] bp = getBreakpointsAtLine((IDisassemblyPart) part, line); return bp != null && bp.length > 0; - } - - private IBreakpoint[] getBreakpointsAtLine( IDisassemblyPart part, int line ) { + } + + private IBreakpoint[] getBreakpointsAtLine(IDisassemblyPart part, int line) { List<IBreakpoint> breakpoints = new ArrayList<IBreakpoint>(); IAnnotationModel annotationModel = part.getTextViewer().getAnnotationModel(); IDocument document = part.getTextViewer().getDocument(); - if ( annotationModel != null ) { + if (annotationModel != null) { Iterator<?> iterator = annotationModel.getAnnotationIterator(); - while( iterator.hasNext() ) { + while (iterator.hasNext()) { Object object = iterator.next(); - if ( object instanceof SimpleMarkerAnnotation ) { - SimpleMarkerAnnotation markerAnnotation = (SimpleMarkerAnnotation)object; + if (object instanceof SimpleMarkerAnnotation) { + SimpleMarkerAnnotation markerAnnotation = (SimpleMarkerAnnotation) object; IMarker marker = markerAnnotation.getMarker(); try { - if ( marker.isSubtypeOf( IBreakpoint.BREAKPOINT_MARKER ) ) { - Position position = annotationModel.getPosition( markerAnnotation ); - int bpLine = document.getLineOfOffset( position.getOffset() ); - if ( line == bpLine ) { - IBreakpoint breakpoint = DebugPlugin.getDefault().getBreakpointManager().getBreakpoint( marker ); - if ( breakpoint != null ) { - breakpoints.add( breakpoint ); + if (marker.isSubtypeOf(IBreakpoint.BREAKPOINT_MARKER)) { + Position position = annotationModel.getPosition(markerAnnotation); + int bpLine = document.getLineOfOffset(position.getOffset()); + if (line == bpLine) { + IBreakpoint breakpoint = DebugPlugin.getDefault().getBreakpointManager() + .getBreakpoint(marker); + if (breakpoint != null) { + breakpoints.add(breakpoint); } } } - } - catch( CoreException e ) { - } - catch( BadLocationException e ) { + } catch (CoreException e) { + } catch (BadLocationException e) { } } } } IBreakpoint[] breakpointsArray = new IBreakpoint[breakpoints.size()]; - return breakpoints.toArray( breakpointsArray ); + return breakpoints.toArray(breakpointsArray); } - private void insertBreakpoint(IWorkbenchPart part, IDisassemblySelection selection, boolean interactive) throws CoreException { + private void insertBreakpoint(IWorkbenchPart part, IDisassemblySelection selection, boolean interactive) + throws CoreException { IAddress address = selection.getStartAddress(); - if ( address == null ) { + if (address == null) { return; } URI fileUri = selection.getSourceLocationURI(); - if ( fileUri != null ) { + if (fileUri != null) { String filePath = null; IResource resource = selection.getSourceFile(); - if ( resource != null ) { + if (resource != null) { final IPath location = resource.getLocation(); - if ( location == null ) { + if (location == null) { return; } filePath = location.toOSString(); - } - else { + } else { resource = ResourcesPlugin.getWorkspace().getRoot(); - filePath = URIUtil.toPath( fileUri ).toOSString(); + filePath = URIUtil.toPath(fileUri).toOSString(); } int srcLine = selection.getSourceLine(); if (interactive) { - createLineBreakpointInteractive(part, filePath, resource, srcLine + 1 ); + createLineBreakpointInteractive(part, filePath, resource, srcLine + 1); } else { - createLineBreakpoint( filePath, resource, srcLine + 1 ); - } - } - else { + createLineBreakpoint(filePath, resource, srcLine + 1); + } + } else { IResource resource = ResourcesPlugin.getWorkspace().getRoot(); - if (interactive) { - createAddressBreakpointInteractive(part, resource, address ); - } else { - createAddressBreakpoint( resource, address ); - } + if (interactive) { + createAddressBreakpointInteractive(part, resource, address); + } else { + createAddressBreakpoint(resource, address); + } + } + } + + /** + * Opens the properties dialog for the given breakpoint. This method can be + * used on an existing breakpoint or on a blank breakpoint which doesn't + * have an associated marker yet. + * + * @param bp + * The breakpoint to edit. This breakpoint may not have an + * associated marker yet. + * @param part + * Workbench part where the action was invoked. + * @param resource + * Workbench resource to create the breakpoint on. + * @param attributes + * Breakpoint attributes to show in properties dialog. If the + * breakpoint already exists, this attribute map can be used to + * override the attributes currently in the breakpoint. Can be + * <code>null</code>. + * @since 2.3 + */ + protected void openBreakpointPropertiesDialog(ICBreakpoint bp, IWorkbenchPart part, IResource resource, + Map<String, Object> attributes) { + ISelection debugContext = DebugUITools.getDebugContextManager() + .getContextService(part.getSite().getWorkbenchWindow()).getActiveContext(part.getSite().getId()); + CBreakpointContext bpContext = new CBreakpointContext(bp, debugContext, resource, attributes); + + PreferenceDialog dialog = PreferencesUtil.createPropertyDialogOn(part.getSite().getShell(), bpContext, null, + null, null); + if (dialog != null) { + dialog.open(); } - } - - /** - * Opens the properties dialog for the given breakpoint. This method can be - * used on an existing breakpoint or on a blank breakpoint which doesn't - * have an associated marker yet. - * - * @param bp - * The breakpoint to edit. This breakpoint may not have an - * associated marker yet. - * @param part - * Workbench part where the action was invoked. - * @param resource - * Workbench resource to create the breakpoint on. - * @param attributes - * Breakpoint attributes to show in properties dialog. If the - * breakpoint already exists, this attribute map can be used to - * override the attributes currently in the breakpoint. Can be - * <code>null</code>. - * @since 2.3 - */ - protected void openBreakpointPropertiesDialog(ICBreakpoint bp, IWorkbenchPart part, IResource resource, - Map<String, Object> attributes) - { - ISelection debugContext = DebugUITools.getDebugContextManager() - .getContextService(part.getSite().getWorkbenchWindow()).getActiveContext(part.getSite().getId()); - CBreakpointContext bpContext = new CBreakpointContext(bp, debugContext, resource, attributes); - - PreferenceDialog dialog = PreferencesUtil.createPropertyDialogOn(part.getSite().getShell(), bpContext, null, - null, null); - if (dialog != null) { - dialog.open(); - } - } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfCommandRunnable.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfCommandRunnable.java index d98e47728c1..1f8b6689585 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfCommandRunnable.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfCommandRunnable.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Marc Khouzam (Ericsson) - Added support for multiple selection (bug 330974) @@ -36,55 +36,62 @@ import org.eclipse.debug.core.commands.IDebugCommandRequest; */ @Immutable public abstract class DsfCommandRunnable extends DsfRunnable { - private final IExecutionDMContext[] fContexts; - private final DsfServicesTracker fTracker; - private final IDebugCommandRequest fRequest; - - // For backwards compatibility, keep this method that returns the first selection. This method - // is meaningful when we only support a single selection. - public IExecutionDMContext getContext() { return (fContexts != null && fContexts.length > 0) ? fContexts[0] : null; } - /** - * Return all selected contexts. - * @since 2.3 - */ - public IExecutionDMContext[] getContexts() { return fContexts; } - public IRunControl getRunControl() { - return fTracker.getService(IRunControl.class); - } - - /** + private final IExecutionDMContext[] fContexts; + private final DsfServicesTracker fTracker; + private final IDebugCommandRequest fRequest; + + // For backwards compatibility, keep this method that returns the first selection. This method + // is meaningful when we only support a single selection. + public IExecutionDMContext getContext() { + return (fContexts != null && fContexts.length > 0) ? fContexts[0] : null; + } + + /** + * Return all selected contexts. + * @since 2.3 + */ + public IExecutionDMContext[] getContexts() { + return fContexts; + } + + public IRunControl getRunControl() { + return fTracker.getService(IRunControl.class); + } + + /** + * @since 1.1 + */ + public SteppingController getSteppingController() { + if (fContexts != null && fContexts.length > 0) { + return fContexts[0].getAdapter(SteppingController.class); + } + return null; + } + + /** * @since 1.1 */ - public SteppingController getSteppingController() { - if (fContexts != null && fContexts.length > 0) { - return fContexts[0].getAdapter(SteppingController.class); - } - return null; - } - - /** - * @since 1.1 - */ - public IProcesses getProcessService() { - return fTracker.getService(IProcesses.class); - } - - public DsfCommandRunnable(DsfServicesTracker servicesTracker, Object element, IDebugCommandRequest request) { - this(servicesTracker, new Object[] { element }, request); - } - - /** @since 2.3 */ - public DsfCommandRunnable(DsfServicesTracker servicesTracker, Object[] elements, IDebugCommandRequest request) { - fTracker = servicesTracker; - fRequest = request; + public IProcesses getProcessService() { + return fTracker.getService(IProcesses.class); + } + + public DsfCommandRunnable(DsfServicesTracker servicesTracker, Object element, IDebugCommandRequest request) { + this(servicesTracker, new Object[] { element }, request); + } + + /** @since 2.3 */ + public DsfCommandRunnable(DsfServicesTracker servicesTracker, Object[] elements, IDebugCommandRequest request) { + fTracker = servicesTracker; + fRequest = request; // Extract all selected execution contexts, using a set to avoid duplicates. Duplicates will - // happen if multiple stack frames of the same thread are selected. + // happen if multiple stack frames of the same thread are selected. Set<IExecutionDMContext> execDmcSet = new HashSet<IExecutionDMContext>(request.getElements().length); for (Object element : request.getElements()) { if (element instanceof IDMVMContext) { - IDMVMContext vmc = (IDMVMContext)element; - IExecutionDMContext execDmc = DMContexts.getAncestorOfType(vmc.getDMContext(), IExecutionDMContext.class); + IDMVMContext vmc = (IDMVMContext) element; + IExecutionDMContext execDmc = DMContexts.getAncestorOfType(vmc.getDMContext(), + IExecutionDMContext.class); if (execDmc != null) { // We have a thread or a process execDmcSet.add(execDmc); @@ -97,31 +104,31 @@ public abstract class DsfCommandRunnable extends DsfRunnable { } else { fContexts = execDmcSet.toArray(new IExecutionDMContext[execDmcSet.size()]); } - } - - @Override + } + + @Override public final void run() { - if (fRequest.isCanceled()) { - fRequest.done(); - return; - } - if (getContexts() == null || getContexts().length == 0) { - fRequest.setStatus(makeError("Selected objects do not support run control.", null)); //$NON-NLS-1$ - } else if (getRunControl() == null || getSteppingController() == null) { - fRequest.setStatus(makeError("Run Control not available", null)); //$NON-NLS-1$ - } else { - doExecute(); - } - fRequest.done(); - } - - /** - * Method to perform the actual work. - */ - protected abstract void doExecute(); - - protected IStatus makeError(String message, Throwable e) { - return new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, -1, message, e); - } + if (fRequest.isCanceled()) { + fRequest.done(); + return; + } + if (getContexts() == null || getContexts().length == 0) { + fRequest.setStatus(makeError("Selected objects do not support run control.", null)); //$NON-NLS-1$ + } else if (getRunControl() == null || getSteppingController() == null) { + fRequest.setStatus(makeError("Run Control not available", null)); //$NON-NLS-1$ + } else { + doExecute(); + } + fRequest.done(); + } + + /** + * Method to perform the actual work. + */ + protected abstract void doExecute(); + + protected IStatus makeError(String message, Throwable e) { + return new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, -1, message, e); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfResumeCommand.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfResumeCommand.java index 220f7aad588..8ee7b25e796 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfResumeCommand.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfResumeCommand.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Marc Khouzam (Ericsson) - Added support for multi-selection (Bug 330974) @@ -29,112 +29,112 @@ import org.eclipse.debug.core.commands.IEnabledStateRequest; import org.eclipse.debug.core.commands.IResumeHandler; /** - * + * * @since 1.0 */ @Immutable public class DsfResumeCommand implements IResumeHandler { - + private final DsfExecutor fExecutor; - private final DsfServicesTracker fTracker; - - public DsfResumeCommand(DsfSession session) { - fExecutor = session.getExecutor(); - fTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); - } + private final DsfServicesTracker fTracker; - public void dispose() { - fTracker.dispose(); - } + public DsfResumeCommand(DsfSession session) { + fExecutor = session.getExecutor(); + fTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); + } - @Override + public void dispose() { + fTracker.dispose(); + } + + @Override public void canExecute(final IEnabledStateRequest request) { - if (request.getElements().length == 1) { + if (request.getElements().length == 1) { canExecuteSingle(request); - return; - } + return; + } + + // Handle multi-selection + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements(), request) { + @Override + public void doExecute() { + final IMultiRunControl multiRun = fTracker.getService(IMultiRunControl.class); + if (multiRun == null) { + // No multi run control service: multi selection not allowed + request.setEnabled(false); + request.done(); + return; + } - // Handle multi-selection - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements(), request) { - @Override public void doExecute() { - final IMultiRunControl multiRun = fTracker.getService(IMultiRunControl.class); - if (multiRun == null) { - // No multi run control service: multi selection not allowed - request.setEnabled(false); - request.done(); - return; - } - - // Check if some of the selections can be resumed - multiRun.canResumeSome( - getContexts(), - new ImmediateDataRequestMonitor<Boolean>() { - @Override - protected void handleCompleted() { - request.setEnabled(isSuccess() && getData()); - request.done(); - } - }); - } - }); - } - - private void canExecuteSingle(final IEnabledStateRequest request) { - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { - @Override public void doExecute() { - getRunControl().canResume( - getContext(), - new ImmediateDataRequestMonitor<Boolean>() { - @Override - protected void handleCompleted() { - request.setEnabled(isSuccess() && getData()); - request.done(); - } - }); - } - }); - } - - @Override + // Check if some of the selections can be resumed + multiRun.canResumeSome(getContexts(), new ImmediateDataRequestMonitor<Boolean>() { + @Override + protected void handleCompleted() { + request.setEnabled(isSuccess() && getData()); + request.done(); + } + }); + } + }); + } + + private void canExecuteSingle(final IEnabledStateRequest request) { + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { + @Override + public void doExecute() { + getRunControl().canResume(getContext(), new ImmediateDataRequestMonitor<Boolean>() { + @Override + protected void handleCompleted() { + request.setEnabled(isSuccess() && getData()); + request.done(); + } + }); + } + }); + } + + @Override public boolean execute(final IDebugCommandRequest request) { - if (request.getElements().length == 1) { - executeSingle(request); - return false; - } - - // Handle multi-selection - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements(), request) { - @Override public void doExecute() { - final IMultiRunControl multiRun = fTracker.getService(IMultiRunControl.class); - if (multiRun == null) { - // No multi run control service: multi selection not allowed - request.done(); - return; - } + if (request.getElements().length == 1) { + executeSingle(request); + return false; + } + + // Handle multi-selection + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements(), request) { + @Override + public void doExecute() { + final IMultiRunControl multiRun = fTracker.getService(IMultiRunControl.class); + if (multiRun == null) { + // No multi run control service: multi selection not allowed + request.done(); + return; + } + + multiRun.resume(getContexts(), new ImmediateRequestMonitor() { + @Override + protected void handleError() { + super.handleError(); + CDebugUtils.error(getStatus(), DsfResumeCommand.this); + } + }); + } + }); + return false; + } - multiRun.resume(getContexts(), new ImmediateRequestMonitor() { - @Override - protected void handleError() { - super.handleError(); - CDebugUtils.error(getStatus(), DsfResumeCommand.this); - } - }); - } - }); - return false; - } - private void executeSingle(IDebugCommandRequest request) { - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { - @Override public void doExecute() { - getRunControl().resume(getContext(), new ImmediateRequestMonitor() { - @Override - protected void handleError() { - super.handleError(); - CDebugUtils.error(getStatus(), DsfResumeCommand.this); - } - }); - } - }); - } + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { + @Override + public void doExecute() { + getRunControl().resume(getContext(), new ImmediateRequestMonitor() { + @Override + protected void handleError() { + super.handleError(); + CDebugUtils.error(getStatus(), DsfResumeCommand.this); + } + }); + } + }); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepIntoCommand.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepIntoCommand.java index 1307d906d5a..c809670ac4b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepIntoCommand.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepIntoCommand.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -27,78 +27,78 @@ import org.eclipse.debug.core.commands.IEnabledStateRequest; import org.eclipse.debug.core.commands.IStepIntoHandler; /** - * + * * @since 1.0 */ @Immutable public class DsfStepIntoCommand implements IStepIntoHandler { - private final DsfExecutor fExecutor; - private final DsfServicesTracker fTracker; + private final DsfExecutor fExecutor; + private final DsfServicesTracker fTracker; private final DsfSteppingModeTarget fSteppingMode; - - public DsfStepIntoCommand(DsfSession session, DsfSteppingModeTarget steppingMode) { - fExecutor = session.getExecutor(); - fTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); - fSteppingMode = steppingMode; - } - public void dispose() { - fTracker.dispose(); - } - - @Override + public DsfStepIntoCommand(DsfSession session, DsfSteppingModeTarget steppingMode) { + fExecutor = session.getExecutor(); + fTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); + fSteppingMode = steppingMode; + } + + public void dispose() { + fTracker.dispose(); + } + + @Override public void canExecute(final IEnabledStateRequest request) { - if (request.getElements().length != 1) { - request.setEnabled(false); - request.done(); - return; - } - - final StepType stepType= getStepType(); - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { - @Override public void doExecute() { - SteppingController steppingControl = getSteppingController(); - if (steppingControl == null) { - request.setEnabled(false); - request.done(); - return; - } - steppingControl.canEnqueueStep( - getContext(), stepType, - new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), null) { - @Override - protected void handleCompleted() { - request.setEnabled(isSuccess() && getData()); - request.done(); - } - }); - } - }); - } - - @Override + if (request.getElements().length != 1) { + request.setEnabled(false); + request.done(); + return; + } + + final StepType stepType = getStepType(); + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { + @Override + public void doExecute() { + SteppingController steppingControl = getSteppingController(); + if (steppingControl == null) { + request.setEnabled(false); + request.done(); + return; + } + steppingControl.canEnqueueStep(getContext(), stepType, + new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), null) { + @Override + protected void handleCompleted() { + request.setEnabled(isSuccess() && getData()); + request.done(); + } + }); + } + }); + } + + @Override public boolean execute(final IDebugCommandRequest request) { - if (request.getElements().length != 1) { - request.done(); - return false; - } - - final StepType stepType= getStepType(); - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { - @Override public void doExecute() { - getSteppingController().enqueueStep(getContext(), stepType); - } - }); - return true; - } + if (request.getElements().length != 1) { + request.done(); + return false; + } + final StepType stepType = getStepType(); + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { + @Override + public void doExecute() { + getSteppingController().enqueueStep(getContext(), stepType); + } + }); + return true; + } - /** + /** * @return the currently active step type */ protected final StepType getStepType() { - boolean instructionSteppingEnabled= fSteppingMode != null && fSteppingMode.isInstructionSteppingEnabled(); + boolean instructionSteppingEnabled = fSteppingMode != null && fSteppingMode.isInstructionSteppingEnabled(); return instructionSteppingEnabled ? StepType.INSTRUCTION_STEP_INTO : StepType.STEP_INTO; } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepIntoSelectionCommand.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepIntoSelectionCommand.java index 4eaa7255438..38693c6db1a 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepIntoSelectionCommand.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepIntoSelectionCommand.java @@ -46,15 +46,16 @@ import org.eclipse.swt.widgets.Display; /** * @since 2.4 */ -public class DsfStepIntoSelectionCommand extends AbstractDebugCommand implements IStepIntoSelectionHandler, IDsfStepIntoSelection { +public class DsfStepIntoSelectionCommand extends AbstractDebugCommand + implements IStepIntoSelectionHandler, IDsfStepIntoSelection { private final DsfSession fSession; private final DsfServicesTracker fTracker; - + public DsfStepIntoSelectionCommand(DsfSession session) { fSession = session; fTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); } - + public void dispose() { fTracker.dispose(); } @@ -66,7 +67,8 @@ public class DsfStepIntoSelectionCommand extends AbstractDebugCommand implements return; } - final IExecutionDMContext dmc = DMContexts.getAncestorOfType(((IDMVMContext) targets[0]).getDMContext(), IExecutionDMContext.class); + final IExecutionDMContext dmc = DMContexts.getAncestorOfType(((IDMVMContext) targets[0]).getDMContext(), + IExecutionDMContext.class); if (dmc == null) { return; } @@ -83,13 +85,15 @@ public class DsfStepIntoSelectionCommand extends AbstractDebugCommand implements } @Override - protected boolean isExecutable(Object[] targets, IProgressMonitor monitor, IEnabledStateRequest request) throws CoreException { + protected boolean isExecutable(Object[] targets, IProgressMonitor monitor, IEnabledStateRequest request) + throws CoreException { // No multiple selections allowed for Step into selection if (targets.length != 1) { return false; } - final IExecutionDMContext dmc = DMContexts.getAncestorOfType(((IDMVMContext) targets[0]).getDMContext(), IExecutionDMContext.class); + final IExecutionDMContext dmc = DMContexts.getAncestorOfType(((IDMVMContext) targets[0]).getDMContext(), + IExecutionDMContext.class); return isExecutable(dmc); } @@ -105,7 +109,7 @@ public class DsfStepIntoSelectionCommand extends AbstractDebugCommand implements protected boolean isRemainEnabled(IDebugCommandRequest request) { return true; } - + @Override public boolean isExecutable(final IExecutionDMContext dmc) { if (dmc == null) { @@ -140,7 +144,8 @@ public class DsfStepIntoSelectionCommand extends AbstractDebugCommand implements } @Override - public void runToSelection(final String fileName, final int lineLocation, final IFunctionDeclaration selectedFunction, final IExecutionDMContext dmc) { + public void runToSelection(final String fileName, final int lineLocation, + final IFunctionDeclaration selectedFunction, final IExecutionDMContext dmc) { if (fSession != null && fSession.isActive()) { Throwable exception = null; try { @@ -149,12 +154,15 @@ public class DsfStepIntoSelectionCommand extends AbstractDebugCommand implements protected void execute(final DataRequestMonitor<Object> rm) { IRunControl3 runControl = fTracker.getService(IRunControl3.class); if (runControl == null) { - rm.done(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "IRunControl3 service not available", null)); //$NON-NLS-1$ + rm.done(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, + "IRunControl3 service not available", null)); //$NON-NLS-1$ return; } - boolean skipBreakpoints = DebugUITools.getPreferenceStore().getBoolean(IDebugUIConstants.PREF_SKIP_BREAKPOINTS_DURING_RUN_TO_LINE); - runControl.stepIntoSelection(dmc, fileName, lineLocation, skipBreakpoints, selectedFunction, rm); + boolean skipBreakpoints = DebugUITools.getPreferenceStore() + .getBoolean(IDebugUIConstants.PREF_SKIP_BREAKPOINTS_DURING_RUN_TO_LINE); + runControl.stepIntoSelection(dmc, fileName, lineLocation, skipBreakpoints, selectedFunction, + rm); } }; @@ -169,10 +177,12 @@ public class DsfStepIntoSelectionCommand extends AbstractDebugCommand implements } if (exception != null) { - DsfUIPlugin.log(new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Failed executing Step into Selection", exception)));//$NON-NLS-1$ + DsfUIPlugin.log(new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + DebugException.REQUEST_FAILED, "Failed executing Step into Selection", exception)));//$NON-NLS-1$ } } else { - DsfUIPlugin.log(new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Debug session is not active", null))); //$NON-NLS-1$ + DsfUIPlugin.log(new DebugException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + DebugException.REQUEST_FAILED, "Debug session is not active", null))); //$NON-NLS-1$ } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepIntoSelectionHyperlinkDetector.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepIntoSelectionHyperlinkDetector.java index 5f8be4ad323..32952fd63e7 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepIntoSelectionHyperlinkDetector.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepIntoSelectionHyperlinkDetector.java @@ -47,7 +47,7 @@ import org.eclipse.ui.texteditor.ITextEditor; /** * @since 2.4 - * + * */ public class DsfStepIntoSelectionHyperlinkDetector extends AbstractHyperlinkDetector { private class DsfStepIntoSelectionHyperlink implements IHyperlink { @@ -58,11 +58,12 @@ public class DsfStepIntoSelectionHyperlinkDetector extends AbstractHyperlinkDete /** * Constructor - * + * * @param stepIntoSelectionCommand * @param region */ - public DsfStepIntoSelectionHyperlink(DsfSourceSelectionResolver selectionResolver, IDsfStepIntoSelection stepIntoSelectionCommand) { + public DsfStepIntoSelectionHyperlink(DsfSourceSelectionResolver selectionResolver, + IDsfStepIntoSelection stepIntoSelectionCommand) { fSelection = selectionResolver.resolveSelection(); fStepIntoSelectionCommand = stepIntoSelectionCommand; fSelectionResolver = selectionResolver; @@ -89,7 +90,8 @@ public class DsfStepIntoSelectionHyperlinkDetector extends AbstractHyperlinkDete final IExecutionDMContext dmc = resolveDebugContext(); if (fSelectionResolver.isSuccessful() && dmc != null) { LineLocation location = fSelectionResolver.getLineLocation(); - fStepIntoSelectionCommand.runToSelection(location.getFileName(), location.getLineNumber(), fSelectionResolver.getFunction(), dmc); + fStepIntoSelectionCommand.runToSelection(location.getFileName(), location.getLineNumber(), + fSelectionResolver.getFunction(), dmc); } else { String message = null; if (dmc == null) { @@ -103,7 +105,8 @@ public class DsfStepIntoSelectionHyperlinkDetector extends AbstractHyperlinkDete } @Override - public IHyperlink[] detectHyperlinks(ITextViewer textViewer, final IRegion region, boolean canShowMultipleHyperlinks) { + public IHyperlink[] detectHyperlinks(ITextViewer textViewer, final IRegion region, + boolean canShowMultipleHyperlinks) { // Only valid in the context of a selection within the CEditor ITextEditor editor = getAdapter(ITextEditor.class); if (editor == null || region == null || !(editor instanceof CEditor)) @@ -126,9 +129,10 @@ public class DsfStepIntoSelectionHyperlinkDetector extends AbstractHyperlinkDete } IDsfStepIntoSelection stepIntoSelectionCommand = null; - IStepIntoSelectionHandler stepIntoSelectionHandler = (IStepIntoSelectionHandler) session.getModelAdapter(IStepIntoSelectionHandler.class); + IStepIntoSelectionHandler stepIntoSelectionHandler = (IStepIntoSelectionHandler) session + .getModelAdapter(IStepIntoSelectionHandler.class); if (stepIntoSelectionHandler instanceof IDsfStepIntoSelection) { - stepIntoSelectionCommand = (IDsfStepIntoSelection)stepIntoSelectionHandler; + stepIntoSelectionCommand = (IDsfStepIntoSelection) stepIntoSelectionHandler; } else { return null; } @@ -152,13 +156,15 @@ public class DsfStepIntoSelectionHyperlinkDetector extends AbstractHyperlinkDete ITextSelection selection = null; if (editor != null) { IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); - final IWorkingCopy workingCopy = CUIPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editor.getEditorInput()); + final IWorkingCopy workingCopy = CUIPlugin.getDefault().getWorkingCopyManager() + .getWorkingCopy(editor.getEditorInput()); if (document != null && workingCopy != null) { // Check partition type. String partitionType; try { - partitionType = TextUtilities.getContentType(document, ICPartitions.C_PARTITIONING, region.getOffset(), false); + partitionType = TextUtilities.getContentType(document, ICPartitions.C_PARTITIONING, + region.getOffset(), false); if (IDocument.DEFAULT_CONTENT_TYPE.equals(partitionType)) { // Regular code i.e. Not a Preprocessor directive. IRegion wregion = getIdentifier(document, region.getOffset(), workingCopy.getLanguage()); @@ -180,7 +186,8 @@ public class DsfStepIntoSelectionHyperlinkDetector extends AbstractHyperlinkDete /** * Returns the identifier at the given offset, or {@code null} if the there is no identifier at the offset. */ - private static IRegion getIdentifier(IDocument document, int offset, ILanguage language) throws BadLocationException { + private static IRegion getIdentifier(IDocument document, int offset, ILanguage language) + throws BadLocationException { IRegion wordRegion = CWordFinder.findWord(document, offset); if (wordRegion != null && wordRegion.getLength() > 0) { String word = document.get(wordRegion.getOffset(), wordRegion.getLength()); @@ -203,7 +210,8 @@ public class DsfStepIntoSelectionHyperlinkDetector extends AbstractHyperlinkDete return true; } for (String keyword : keywords.getPreprocessorKeywords()) { - if (keyword.charAt(0) == '#' && keyword.length() == word.length() + 1 && keyword.regionMatches(1, word, 0, word.length())) { + if (keyword.charAt(0) == '#' && keyword.length() == word.length() + 1 + && keyword.regionMatches(1, word, 0, word.length())) { return true; } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepOverCommand.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepOverCommand.java index 5b7bbd571a6..a101e78dfa2 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepOverCommand.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepOverCommand.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -27,77 +27,79 @@ import org.eclipse.debug.core.commands.IEnabledStateRequest; import org.eclipse.debug.core.commands.IStepOverHandler; /** - * + * * @since 1.0 */ @Immutable public class DsfStepOverCommand implements IStepOverHandler { - private final DsfExecutor fExecutor; - private final DsfServicesTracker fTracker; + private final DsfExecutor fExecutor; + private final DsfServicesTracker fTracker; private final DsfSteppingModeTarget fSteppingMode; - - public DsfStepOverCommand(DsfSession session, DsfSteppingModeTarget steppingMode) { - fExecutor = session.getExecutor(); - fTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); - fSteppingMode = steppingMode; - } - public void dispose() { - fTracker.dispose(); - } - - @Override - public void canExecute(final IEnabledStateRequest request) { - if (request.getElements().length != 1) { - request.setEnabled(false); - request.done(); - return; - } - - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { - final StepType stepType= getStepType(); - @Override public void doExecute() { - SteppingController steppingControl = getSteppingController(); - if (steppingControl == null) { - request.setEnabled(false); - request.done(); - return; - } - steppingControl.canEnqueueStep( - getContext(), stepType, - new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), null) { - @Override - protected void handleCompleted() { - request.setEnabled(isSuccess() && getData()); - request.done(); - } - }); - } - }); - } - - @Override + public DsfStepOverCommand(DsfSession session, DsfSteppingModeTarget steppingMode) { + fExecutor = session.getExecutor(); + fTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); + fSteppingMode = steppingMode; + } + + public void dispose() { + fTracker.dispose(); + } + + @Override + public void canExecute(final IEnabledStateRequest request) { + if (request.getElements().length != 1) { + request.setEnabled(false); + request.done(); + return; + } + + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { + final StepType stepType = getStepType(); + + @Override + public void doExecute() { + SteppingController steppingControl = getSteppingController(); + if (steppingControl == null) { + request.setEnabled(false); + request.done(); + return; + } + steppingControl.canEnqueueStep(getContext(), stepType, + new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), null) { + @Override + protected void handleCompleted() { + request.setEnabled(isSuccess() && getData()); + request.done(); + } + }); + } + }); + } + + @Override public boolean execute(final IDebugCommandRequest request) { - if (request.getElements().length != 1) { - request.done(); - return false; - } - - final StepType stepType= getStepType(); - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { - @Override public void doExecute() { - getSteppingController().enqueueStep(getContext(), stepType); - } - }); - return true; - } + if (request.getElements().length != 1) { + request.done(); + return false; + } + + final StepType stepType = getStepType(); + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { + @Override + public void doExecute() { + getSteppingController().enqueueStep(getContext(), stepType); + } + }); + return true; + } - /** + /** * @return the currently active step type */ protected final StepType getStepType() { - boolean instructionSteppingEnabled= fSteppingMode != null && fSteppingMode.isInstructionSteppingEnabled(); + boolean instructionSteppingEnabled = fSteppingMode != null && fSteppingMode.isInstructionSteppingEnabled(); return instructionSteppingEnabled ? StepType.INSTRUCTION_STEP_OVER : StepType.STEP_OVER; } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepReturnCommand.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepReturnCommand.java index 2be1f7fd810..5c4c9cc723c 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepReturnCommand.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfStepReturnCommand.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -27,65 +27,66 @@ import org.eclipse.debug.core.commands.IEnabledStateRequest; import org.eclipse.debug.core.commands.IStepReturnHandler; /** - * + * * @since 1.0 */ @Immutable public class DsfStepReturnCommand implements IStepReturnHandler { - private final DsfExecutor fExecutor; - private final DsfServicesTracker fTracker; - - public DsfStepReturnCommand(DsfSession session) { - fExecutor = session.getExecutor(); - fTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); - } + private final DsfExecutor fExecutor; + private final DsfServicesTracker fTracker; + + public DsfStepReturnCommand(DsfSession session) { + fExecutor = session.getExecutor(); + fTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); + } + + public void dispose() { + fTracker.dispose(); + } - public void dispose() { - fTracker.dispose(); - } - - @Override + @Override public void canExecute(final IEnabledStateRequest request) { - if (request.getElements().length != 1) { - request.setEnabled(false); - request.done(); - return; - } - - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { - @Override public void doExecute() { - SteppingController steppingControl = getSteppingController(); - if (steppingControl == null) { - request.setEnabled(false); - request.done(); - return; - } - steppingControl.canEnqueueStep( - getContext(), StepType.STEP_RETURN, - new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), null) { - @Override - protected void handleCompleted() { - request.setEnabled(isSuccess() && getData()); - request.done(); - } - }); - } - }); - } - - @Override + if (request.getElements().length != 1) { + request.setEnabled(false); + request.done(); + return; + } + + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { + @Override + public void doExecute() { + SteppingController steppingControl = getSteppingController(); + if (steppingControl == null) { + request.setEnabled(false); + request.done(); + return; + } + steppingControl.canEnqueueStep(getContext(), StepType.STEP_RETURN, + new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), null) { + @Override + protected void handleCompleted() { + request.setEnabled(isSuccess() && getData()); + request.done(); + } + }); + } + }); + } + + @Override public boolean execute(final IDebugCommandRequest request) { - if (request.getElements().length != 1) { - request.done(); - return false; - } - - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { - @Override public void doExecute() { - getSteppingController().enqueueStep(getContext(), StepType.STEP_RETURN); - } - }); - return true; - } + if (request.getElements().length != 1) { + request.done(); + return false; + } + + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { + @Override + public void doExecute() { + getSteppingController().enqueueStep(getContext(), StepType.STEP_RETURN); + } + }); + return true; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfSteppingModeTarget.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfSteppingModeTarget.java index 641c2a459c8..f1855108ee0 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfSteppingModeTarget.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfSteppingModeTarget.java @@ -23,17 +23,17 @@ import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; /** - * + * * @since 1.0 */ public class DsfSteppingModeTarget implements ISteppingModeTarget, ITargetProperties { - private static final String ID_DISASSEMBLY_VIEW= "org.eclipse.cdt.dsf.debug.ui.disassembly.view"; //$NON-NLS-1$ + private static final String ID_DISASSEMBLY_VIEW = "org.eclipse.cdt.dsf.debug.ui.disassembly.view"; //$NON-NLS-1$ private final Preferences fPreferences; public DsfSteppingModeTarget() { - fPreferences= new Preferences(); + fPreferences = new Preferences(); fPreferences.setDefault(PREF_INSTRUCTION_STEPPING_MODE, false); } @@ -45,7 +45,7 @@ public class DsfSteppingModeTarget implements ISteppingModeTarget, ITargetProper fPreferences.setValue(PREF_INSTRUCTION_STEPPING_MODE, enabled); if (enabled) { try { - final IWorkbenchWindow activeWorkbenchWindow= PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + final IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (activeWorkbenchWindow != null && activeWorkbenchWindow.getActivePage() != null) { activeWorkbenchWindow.getActivePage().showView(ID_DISASSEMBLY_VIEW); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfSuspendCommand.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfSuspendCommand.java index c947618fd93..9fd113a92cb 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfSuspendCommand.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/DsfSuspendCommand.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Marc Khouzam (Ericsson) - Added support for multi-selection (Bug 330974) @@ -29,111 +29,111 @@ import org.eclipse.debug.core.commands.IEnabledStateRequest; import org.eclipse.debug.core.commands.ISuspendHandler; /** - * + * * @since 1.0 */ @Immutable public class DsfSuspendCommand implements ISuspendHandler { - private final DsfExecutor fExecutor; - private final DsfServicesTracker fTracker; - - public DsfSuspendCommand(DsfSession session) { - fExecutor = session.getExecutor(); - fTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); - } + private final DsfExecutor fExecutor; + private final DsfServicesTracker fTracker; - public void dispose() { - fTracker.dispose(); - } + public DsfSuspendCommand(DsfSession session) { + fExecutor = session.getExecutor(); + fTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); + } - @Override + public void dispose() { + fTracker.dispose(); + } + + @Override public void canExecute(final IEnabledStateRequest request) { - if (request.getElements().length == 1) { + if (request.getElements().length == 1) { canExecuteSingle(request); - return; - } - - // Handle multi-selection - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements(), request) { - @Override public void doExecute() { - final IMultiRunControl multiRun = fTracker.getService(IMultiRunControl.class); - if (multiRun == null) { - // No multi run control service: multi selection not allowed - request.setEnabled(false); - request.done(); - return; - } - - // Check if some of the selections can be suspended - multiRun.canSuspendSome( - getContexts(), - new ImmediateDataRequestMonitor<Boolean>() { - @Override - protected void handleCompleted() { - request.setEnabled(isSuccess() && getData()); - request.done(); - } - }); - } - }); - } - - private void canExecuteSingle(final IEnabledStateRequest request) { - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { - @Override public void doExecute() { - getRunControl().canSuspend( - getContext(), - new ImmediateDataRequestMonitor<Boolean>() { - @Override - protected void handleCompleted() { - request.setEnabled(isSuccess() && getData()); - request.done(); - } - }); - } - }); - } + return; + } + + // Handle multi-selection + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements(), request) { + @Override + public void doExecute() { + final IMultiRunControl multiRun = fTracker.getService(IMultiRunControl.class); + if (multiRun == null) { + // No multi run control service: multi selection not allowed + request.setEnabled(false); + request.done(); + return; + } - @Override + // Check if some of the selections can be suspended + multiRun.canSuspendSome(getContexts(), new ImmediateDataRequestMonitor<Boolean>() { + @Override + protected void handleCompleted() { + request.setEnabled(isSuccess() && getData()); + request.done(); + } + }); + } + }); + } + + private void canExecuteSingle(final IEnabledStateRequest request) { + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { + @Override + public void doExecute() { + getRunControl().canSuspend(getContext(), new ImmediateDataRequestMonitor<Boolean>() { + @Override + protected void handleCompleted() { + request.setEnabled(isSuccess() && getData()); + request.done(); + } + }); + } + }); + } + + @Override public boolean execute(final IDebugCommandRequest request) { - if (request.getElements().length == 1) { - executeSingle(request); - return false; - } - - // Handle multi-selection - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements(), request) { - @Override public void doExecute() { - final IMultiRunControl multiRun = fTracker.getService(IMultiRunControl.class); - if (multiRun == null) { - // No multi run control service: multi selection not allowed - request.done(); - return; - } + if (request.getElements().length == 1) { + executeSingle(request); + return false; + } + + // Handle multi-selection + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements(), request) { + @Override + public void doExecute() { + final IMultiRunControl multiRun = fTracker.getService(IMultiRunControl.class); + if (multiRun == null) { + // No multi run control service: multi selection not allowed + request.done(); + return; + } + + multiRun.suspend(getContexts(), new ImmediateRequestMonitor() { + @Override + protected void handleError() { + super.handleError(); + CDebugUtils.error(getStatus(), DsfSuspendCommand.this); + } + }); + } + }); + return false; + } - multiRun.suspend(getContexts(), new ImmediateRequestMonitor() { - @Override - protected void handleError() { - super.handleError(); - CDebugUtils.error(getStatus(), DsfSuspendCommand.this); - } - }); - } - }); - return false; - } - private void executeSingle(IDebugCommandRequest request) { - fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { - @Override public void doExecute() { - getRunControl().suspend(getContext(), new ImmediateRequestMonitor() { - @Override - protected void handleError() { - super.handleError(); - CDebugUtils.error(getStatus(), DsfSuspendCommand.this); - } - }); - } - }); - } + fExecutor.submit(new DsfCommandRunnable(fTracker, request.getElements()[0], request) { + @Override + public void doExecute() { + getRunControl().suspend(getContext(), new ImmediateRequestMonitor() { + @Override + protected void handleError() { + super.handleError(); + CDebugUtils.error(getStatus(), DsfSuspendCommand.this); + } + }); + } + }); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/IDsfStepIntoSelection.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/IDsfStepIntoSelection.java index 19bebf14c35..20105b8dd5e 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/IDsfStepIntoSelection.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/actions/IDsfStepIntoSelection.java @@ -20,7 +20,7 @@ import org.eclipse.cdt.dsf.debug.service.IRunControl.IExecutionDMContext; * @since 2.4 */ public interface IDsfStepIntoSelection { - + /** * Checks if within a state to perform step into selection * @param dmc @@ -35,5 +35,6 @@ public interface IDsfStepIntoSelection { * @param selectedFunction * @param context */ - public void runToSelection(final String fileName, final int lineLocation, final IFunctionDeclaration selectedFunction, final IExecutionDMContext context); + public void runToSelection(final String fileName, final int lineLocation, + final IFunctionDeclaration selectedFunction, final IExecutionDMContext context); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/contexts/DsfSuspendTrigger.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/contexts/DsfSuspendTrigger.java index b25cfa3526f..d26bfa0554d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/contexts/DsfSuspendTrigger.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/contexts/DsfSuspendTrigger.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -44,325 +44,327 @@ import org.eclipse.debug.ui.contexts.ISuspendTriggerListener; /** * DSF implementation of the ISuspendTrigger interface. The suspend trigger - * is used by the IDE to trigger activation of the debug perspective when + * is used by the IDE to trigger activation of the debug perspective when * the debugger suspends. - * + * * @see ISuspendTrigger - * + * * @since 1.0 */ @ConfinedToDsfExecutor("fSession.getExecutor()") public class DsfSuspendTrigger implements ISuspendTrigger { - private final DsfSession fSession; - private final ILaunch fLaunch; - private volatile boolean fDisposed = false; - private boolean fEventListenerRegisterd = false; - private final DsfServicesTracker fServicesTracker; + private final DsfSession fSession; + private final ILaunch fLaunch; + private volatile boolean fDisposed = false; + private boolean fEventListenerRegisterd = false; + private final DsfServicesTracker fServicesTracker; + + @ThreadSafe + private final ListenerList<ISuspendTriggerListener> fListeners = new ListenerList<>(); + + @ThreadSafe + public DsfSuspendTrigger(DsfSession session, ILaunch launch) { + fSession = session; + fLaunch = launch; + fServicesTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fSession.getId()); + try { + fSession.getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + if (!fDisposed) { + fSession.addServiceEventListener(DsfSuspendTrigger.this, null); + fEventListenerRegisterd = true; + } + } + }); + } catch (RejectedExecutionException e) { + } + } + + @ThreadSafe + @Override + public void addSuspendTriggerListener(final ISuspendTriggerListener listener) { + fListeners.add(listener); + + // Check if an execution context in the model is already suspended. + // If so notify the listener. + getIsLaunchSuspended(new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), null) { + @Override + protected void handleSuccess() { + if (!fDisposed && getData().booleanValue()) { + listener.suspended(fLaunch, null); + } + } + + @Override + protected void handleErrorOrWarning() { + // Ignore expected race condition and not supported error. + // Log other errors. + if (getStatus().getCode() > IDsfStatusConstants.NOT_SUPPORTED) { + super.handleErrorOrWarning(); + } + } + }); + } + + @ThreadSafe + @Override + public void removeSuspendTriggerListener(ISuspendTriggerListener listener) { + fListeners.remove(listener); + } + + @ThreadSafe + public void dispose() { + try { + fSession.getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + if (fEventListenerRegisterd) { + fSession.removeServiceEventListener(DsfSuspendTrigger.this); + } + } + }); + } catch (RejectedExecutionException e) { + // Session already gone. + } + + fServicesTracker.dispose(); + fDisposed = true; + } + + @DsfServiceEventHandler + public void eventDispatched(IRunControl.ISuspendedDMEvent e) { + fireSuspended(null); + } + + /** + * @noreference This method is not intended to be referenced by clients. + */ + @DsfServiceEventHandler + public void eventDispatched(DataModelInitializedEvent e) { + getIsLaunchSuspended(new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), null) { + @Override + protected void handleSuccess() { + if (!fDisposed && getData().booleanValue()) { + fireSuspended(null); + } + } + + @Override + protected void handleErrorOrWarning() { + // Ignore expected race condition and not supported error. + // Log other errors. + if (getStatus().getCode() > IDsfStatusConstants.NOT_SUPPORTED) { + super.handleErrorOrWarning(); + } + } + }); + } + + /** + * Returns the services tracker used by the suspend trigger. + * @since 2.1 + */ + protected DsfServicesTracker getServicesTracker() { + return fServicesTracker; + } + + /** + * Returns the launch for this suspend trigger. + * @since 2.1 + */ + @ThreadSafe + protected ILaunch getLaunch() { + return fLaunch; + } + + /** + * Returns the DSF session for this suspend trigger. + * @since 2.1 + */ + @ThreadSafe + protected DsfSession getSession() { + return fSession; + } - @ThreadSafe - private final ListenerList<ISuspendTriggerListener> fListeners = new ListenerList<>(); + /** + * Notifies the listeners that a suspend event was received. + * + * @param context + * + * @since 2.1 + */ + @ThreadSafe + protected void fireSuspended(final Object context) { + if (!fListeners.isEmpty()) { + new Job("DSF Suspend Trigger Notify") { //$NON-NLS-1$ + { + setSystem(true); + } - @ThreadSafe - public DsfSuspendTrigger(DsfSession session, ILaunch launch) { - fSession = session; - fLaunch = launch; - fServicesTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fSession.getId()); - try { - fSession.getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - if (!fDisposed) { - fSession.addServiceEventListener(DsfSuspendTrigger.this, null); - fEventListenerRegisterd = true; - } - } - }); - } catch(RejectedExecutionException e) {} - } - - @ThreadSafe - @Override - public void addSuspendTriggerListener(final ISuspendTriggerListener listener) { - fListeners.add(listener); + @Override + protected IStatus run(IProgressMonitor monitor) { + final MultiStatus status = new MultiStatus(DsfUIPlugin.PLUGIN_ID, 0, + "DSF Suspend Trigger Notify Job Status", null); //$NON-NLS-1$ + for (final ISuspendTriggerListener listener : fListeners) { + SafeRunner.run(new ISafeRunnable() { + @Override + public void run() throws Exception { + listener.suspended(fLaunch, context); + } - // Check if an execution context in the model is already suspended. - // If so notify the listener. - getIsLaunchSuspended(new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), null) { - @Override - protected void handleSuccess() { - if (!fDisposed && getData().booleanValue()) { - listener.suspended(fLaunch, null); - } - } - @Override - protected void handleErrorOrWarning() { - // Ignore expected race condition and not supported error. - // Log other errors. - if (getStatus().getCode() > IDsfStatusConstants.NOT_SUPPORTED) { - super.handleErrorOrWarning(); - } - } - }); - } + @Override + public void handleException(Throwable exception) { + status.add(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + "Exception while calling suspend trigger listeners", exception)); //$NON-NLS-1$ + } - @ThreadSafe - @Override - public void removeSuspendTriggerListener(ISuspendTriggerListener listener) { - fListeners.remove(listener); - } - - @ThreadSafe - public void dispose() { - try { - fSession.getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - if (fEventListenerRegisterd) { - fSession.removeServiceEventListener(DsfSuspendTrigger.this); - } - } - }); - } catch (RejectedExecutionException e) { - // Session already gone. - } - - fServicesTracker.dispose(); - fDisposed = true; - } + }); + } + return status; + } + }.schedule(); + } + } - @DsfServiceEventHandler - public void eventDispatched(IRunControl.ISuspendedDMEvent e) { - fireSuspended(null); - } + /** + * Retrieves the top-level containers for this launch. This method should + * be overriden by specific debugger integrations. + * @param rm + * + * @since 2.1 + */ + @ThreadSafe + protected void getLaunchTopContainers(DataRequestMonitor<IContainerDMContext[]> rm) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, + "Not implemented.", null)); //$NON-NLS-1$ + rm.done(); + } - /** - * @noreference This method is not intended to be referenced by clients. - */ - @DsfServiceEventHandler - public void eventDispatched(DataModelInitializedEvent e) { - getIsLaunchSuspended(new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), null) { - @Override - protected void handleSuccess() { - if (!fDisposed && getData().booleanValue()) { - fireSuspended(null); - } - } - - @Override - protected void handleErrorOrWarning() { - // Ignore expected race condition and not supported error. - // Log other errors. - if (getStatus().getCode() > IDsfStatusConstants.NOT_SUPPORTED) { - super.handleErrorOrWarning(); - } - } - }); - } - - /** - * Returns the services tracker used by the suspend trigger. - * @since 2.1 - */ - protected DsfServicesTracker getServicesTracker() { - return fServicesTracker; - } + /** + * Checks if the given launch is currently suspended. + * + * @param rm Request monitor. + * + * @since 2.1 + */ + @ThreadSafe + private void getIsLaunchSuspended(final DataRequestMonitor<Boolean> rm) { + getLaunchTopContainers(new DataRequestMonitor<IContainerDMContext[]>(fSession.getExecutor(), rm) { + @Override + protected void handleSuccess() { + final CountingRequestMonitor crm = new CountingRequestMonitor(fSession.getExecutor(), rm) { + @Override + protected void handleSuccess() { + if (rm.getData() == null) { + rm.setData(Boolean.FALSE); + } + rm.done(); + }; + }; + int count = 0; + for (final IContainerDMContext containerCtx : getData()) { + getIsContainerSuspended(containerCtx, + new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), crm) { + @Override + protected void handleSuccess() { + if (getData().booleanValue()) { + rm.setData(Boolean.TRUE); + } + crm.done(); + }; + }); + count++; + } + crm.setDoneCount(count); + } + }); + } - /** - * Returns the launch for this suspend trigger. - * @since 2.1 - */ - @ThreadSafe - protected ILaunch getLaunch() { - return fLaunch; - } + /** + * Recursively checks if the given container or any of its execution + * contexts are suspended. + * + * @param container Container to check. + * @param rm Request monitor. + * + * @since 2.1 + */ + @ConfinedToDsfExecutor("fSession.getExecutor()") + private void getIsContainerSuspended(final IContainerDMContext container, final DataRequestMonitor<Boolean> rm) { + // Check if run control service is still available. + IRunControl rc = fServicesTracker.getService(IRunControl.class); + if (rc == null) { + rm.setData(Boolean.FALSE); + rm.done(); + return; + } - /** - * Returns the DSF session for this suspend trigger. - * @since 2.1 - */ - @ThreadSafe - protected DsfSession getSession() { - return fSession; - } - - /** - * Notifies the listeners that a suspend event was received. - * - * @param context - * - * @since 2.1 - */ - @ThreadSafe - protected void fireSuspended(final Object context) { - if (!fListeners.isEmpty()) { - new Job("DSF Suspend Trigger Notify") { //$NON-NLS-1$ - { - setSystem(true); - } - - @Override - protected IStatus run(IProgressMonitor monitor) { - final MultiStatus status = new MultiStatus(DsfUIPlugin.PLUGIN_ID, 0, "DSF Suspend Trigger Notify Job Status", null); //$NON-NLS-1$ - for (final ISuspendTriggerListener listener : fListeners) { - SafeRunner.run(new ISafeRunnable() { - @Override - public void run() throws Exception { - listener.suspended(fLaunch, context); - } - - @Override - public void handleException(Throwable exception) { - status.add(new Status( - IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, "Exception while calling suspend trigger listeners", exception)); //$NON-NLS-1$ - } - - }); - } - return status; - } - }.schedule(); - } - } + // Check if container is suspended. If so, stop searching. + if (rc.isSuspended(container)) { + rm.setData(Boolean.TRUE); + rm.done(); + return; + } - /** - * Retrieves the top-level containers for this launch. This method should - * be overriden by specific debugger integrations. - * @param rm - * - * @since 2.1 - */ - @ThreadSafe - protected void getLaunchTopContainers(DataRequestMonitor<IContainerDMContext[]> rm) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "Not implemented.", null)); //$NON-NLS-1$ - rm.done(); - } + // Retrieve the execution contexts and check if any of them are suspended. + rc.getExecutionContexts(container, new DataRequestMonitor<IExecutionDMContext[]>(fSession.getExecutor(), rm) { + @Override + protected void handleSuccess() { + // Check if run control service is still available. + IRunControl rc = fServicesTracker.getService(IRunControl.class); + if (rc == null) { + rm.setData(Boolean.FALSE); + rm.done(); + return; + } - /** - * Checks if the given launch is currently suspended. - * - * @param rm Request monitor. - * - * @since 2.1 - */ - @ThreadSafe - private void getIsLaunchSuspended(final DataRequestMonitor<Boolean> rm) { - getLaunchTopContainers(new DataRequestMonitor<IContainerDMContext[]>(fSession.getExecutor(), rm) { - @Override - protected void handleSuccess() { - final CountingRequestMonitor crm = new CountingRequestMonitor(fSession.getExecutor(), rm) { - @Override - protected void handleSuccess() { - if (rm.getData() == null) { - rm.setData(Boolean.FALSE); - } - rm.done(); - }; - }; - int count = 0; - for (final IContainerDMContext containerCtx : getData()) { - getIsContainerSuspended(containerCtx, new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), crm) { - @Override - protected void handleSuccess() { - if (getData().booleanValue()) { - rm.setData(Boolean.TRUE); - } - crm.done(); - }; - }); - count++; - } - crm.setDoneCount(count); - } - }); - } - - /** - * Recursively checks if the given container or any of its execution - * contexts are suspended. - * - * @param container Container to check. - * @param rm Request monitor. - * - * @since 2.1 - */ - @ConfinedToDsfExecutor("fSession.getExecutor()") - private void getIsContainerSuspended(final IContainerDMContext container, final DataRequestMonitor<Boolean> rm) { - // Check if run control service is still available. - IRunControl rc = fServicesTracker.getService(IRunControl.class); - if (rc == null) { - rm.setData(Boolean.FALSE); - rm.done(); - return; - } + // If any of the execution contexts are suspended, stop searching + boolean hasContainers = false; + for (IExecutionDMContext execCtx : getData()) { + if (rc.isSuspended(execCtx)) { + rm.setData(Boolean.TRUE); + rm.done(); + return; + } + hasContainers = hasContainers || execCtx instanceof IContainerDMContext; + } - // Check if container is suspended. If so, stop searching. - if (rc.isSuspended(container)) { - rm.setData(Boolean.TRUE); - rm.done(); - return; - } - - // Retrieve the execution contexts and check if any of them are suspended. - rc.getExecutionContexts( - container, - new DataRequestMonitor<IExecutionDMContext[]>(fSession.getExecutor(), rm) { - @Override - protected void handleSuccess() { - // Check if run control service is still available. - IRunControl rc = fServicesTracker.getService(IRunControl.class); - if (rc == null) { - rm.setData(Boolean.FALSE); - rm.done(); - return; - } - - // If any of the execution contexts are suspended, stop searching - boolean hasContainers = false; - for (IExecutionDMContext execCtx : getData()) { - if (rc.isSuspended(execCtx)) { - rm.setData(Boolean.TRUE); - rm.done(); - return; - } - hasContainers = hasContainers || execCtx instanceof IContainerDMContext; - } - - // If any of the returned contexts were containers, check them recursively. - if (hasContainers) { - final CountingRequestMonitor crm = new CountingRequestMonitor(fSession.getExecutor(), rm) { - @Override - protected void handleSuccess() { - if (rm.getData() == null) { - rm.setData(Boolean.FALSE); - } - rm.done(); - }; - }; - int count = 0; - for (IExecutionDMContext execCtx : getData()) { - if (execCtx instanceof IContainerDMContext) { - getIsContainerSuspended( - (IContainerDMContext)execCtx, - new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), crm) { - @Override - protected void handleSuccess() { - if (getData().booleanValue()) { - rm.setData(Boolean.TRUE); - } - crm.done(); - }; - }); - count++; - } - } - crm.setDoneCount(count); - } else { - rm.setData(Boolean.FALSE); - rm.done(); - } - } - }); - } + // If any of the returned contexts were containers, check them recursively. + if (hasContainers) { + final CountingRequestMonitor crm = new CountingRequestMonitor(fSession.getExecutor(), rm) { + @Override + protected void handleSuccess() { + if (rm.getData() == null) { + rm.setData(Boolean.FALSE); + } + rm.done(); + }; + }; + int count = 0; + for (IExecutionDMContext execCtx : getData()) { + if (execCtx instanceof IContainerDMContext) { + getIsContainerSuspended((IContainerDMContext) execCtx, + new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), crm) { + @Override + protected void handleSuccess() { + if (getData().booleanValue()) { + rm.setData(Boolean.TRUE); + } + crm.done(); + }; + }); + count++; + } + } + crm.setDoneCount(count); + } else { + rm.setData(Boolean.FALSE); + rm.done(); + } + } + }); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/memory/RefreshAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/memory/RefreshAction.java index 29dc69466ac..edc0ff75905 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/memory/RefreshAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/memory/RefreshAction.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - Ted Williams - initial API and implementation *******************************************************************************/ @@ -28,15 +28,15 @@ import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; /** - * + * * @since 2.0 Moved to different package, exists since 1.0. */ public class RefreshAction implements IViewActionDelegate { private IMemoryBlock fMemoryBlock = null; - + private IMemoryRenderingSite fsite; - + @Override public void init(IViewPart view) { fsite = (IMemoryRenderingSite) view; @@ -44,20 +44,16 @@ public class RefreshAction implements IViewActionDelegate { @Override public void run(IAction action) { - - if(fMemoryBlock instanceof IMemoryBlockUpdatePolicyProvider) - { + + if (fMemoryBlock instanceof IMemoryBlockUpdatePolicyProvider) { ((IMemoryBlockUpdatePolicyProvider) fMemoryBlock).clearCache(); IMemoryRenderingContainer containers[] = fsite.getMemoryRenderingContainers(); - for(int i = 0; i < containers.length; i++) - { + for (int i = 0; i < containers.length; i++) { IMemoryRendering renderings[] = containers[i].getRenderings(); - for(int j = 0; j < renderings.length; j++) - { - if (renderings[j].getControl() instanceof IDebugEventSetListener) - { + for (int j = 0; j < renderings.length; j++) { + if (renderings[j].getControl() instanceof IDebugEventSetListener) { ((IDebugEventSetListener) renderings[j].getControl()).handleDebugEvents( - new DebugEvent[] { new DebugEvent(fMemoryBlock, DebugEvent.CHANGE) } ); + new DebugEvent[] { new DebugEvent(fMemoryBlock, DebugEvent.CHANGE) }); } } } @@ -67,20 +63,17 @@ public class RefreshAction implements IViewActionDelegate { @Override public void selectionChanged(IAction action, ISelection selection) { fMemoryBlock = null; - action.setEnabled(false); - if(selection instanceof IStructuredSelection) - { - if(((IStructuredSelection) selection).getFirstElement() instanceof IMemoryBlock) - { - fMemoryBlock = (IMemoryBlock) ((IStructuredSelection) selection).getFirstElement(); - action.setEnabled(true); - } - else if(((IStructuredSelection) selection).getFirstElement() instanceof IMemoryRendering) - { - fMemoryBlock = ((IMemoryRendering) ((IStructuredSelection) selection).getFirstElement()).getMemoryBlock(); - action.setEnabled(true); - } - } + action.setEnabled(false); + if (selection instanceof IStructuredSelection) { + if (((IStructuredSelection) selection).getFirstElement() instanceof IMemoryBlock) { + fMemoryBlock = (IMemoryBlock) ((IStructuredSelection) selection).getFirstElement(); + action.setEnabled(true); + } else if (((IStructuredSelection) selection).getFirstElement() instanceof IMemoryRendering) { + fMemoryBlock = ((IMemoryRendering) ((IStructuredSelection) selection).getFirstElement()) + .getMemoryBlock(); + action.setEnabled(true); + } + } } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/memory/SelectUpdatePolicyAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/memory/SelectUpdatePolicyAction.java index 928dd24460e..61d87629153 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/memory/SelectUpdatePolicyAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/memory/SelectUpdatePolicyAction.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - Ted Williams - initial API and implementation *******************************************************************************/ @@ -36,18 +36,19 @@ import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; /** - * + * * @since 2.0 Moved to different package, exists since 1.0. */ -public class SelectUpdatePolicyAction implements IMenuCreator, IViewActionDelegate, IDebugContextListener, IActionDelegate2 { +public class SelectUpdatePolicyAction + implements IMenuCreator, IViewActionDelegate, IDebugContextListener, IActionDelegate2 { private IAction fAction = null; - private IMemoryBlock fMemoryBlock = null; - - @Override + private IMemoryBlock fMemoryBlock = null; + + @Override public void dispose() { // do nothing - + } @Override @@ -56,111 +57,107 @@ public class SelectUpdatePolicyAction implements IMenuCreator, IViewActionDelega } class SelectPolicy extends Action { - + String fID; String fDescription; - public SelectPolicy(String id, String description) { - fID = id; - fDescription = description; - } - - @Override + public SelectPolicy(String id, String description) { + fID = id; + fDescription = description; + } + + @Override public String getText() { return fDescription; } @Override public void run() { - ((IMemoryBlockUpdatePolicyProvider) fMemoryBlock).setUpdatePolicy(fID); - } - - } + ((IMemoryBlockUpdatePolicyProvider) fMemoryBlock).setUpdatePolicy(fID); + } + } - @Override + @Override public Menu getMenu(Control parent) { - // Never called - return null; - } - - protected IAction getAction() { return fAction; } - - @Override + // Never called + return null; + } + + protected IAction getAction() { + return fAction; + } + + @Override public void init(IViewPart view) { - } + } - @Override + @Override public void init(IAction action) { - fAction = action; - action.setMenuCreator(this); - } - - @Override + fAction = action; + action.setMenuCreator(this); + } + + @Override public void run(IAction action) { - // Do nothing, this is a pull-down menu - } + // Do nothing, this is a pull-down menu + } - @Override + @Override public void selectionChanged(IAction action, ISelection selection) { - fMemoryBlock = null; - action.setEnabled(false); - if(selection instanceof IStructuredSelection) - { - if(((IStructuredSelection) selection).getFirstElement() instanceof IMemoryBlock) - { - fMemoryBlock = (IMemoryBlock) ((IStructuredSelection) selection).getFirstElement(); - action.setMenuCreator(this); - action.setEnabled(true); - } - else if(((IStructuredSelection) selection).getFirstElement() instanceof IMemoryRendering) - { - fMemoryBlock = ((IMemoryRendering) ((IStructuredSelection) selection).getFirstElement()).getMemoryBlock(); - action.setMenuCreator(this); - action.setEnabled(true); - } - } - } - - @Override + fMemoryBlock = null; + action.setEnabled(false); + if (selection instanceof IStructuredSelection) { + if (((IStructuredSelection) selection).getFirstElement() instanceof IMemoryBlock) { + fMemoryBlock = (IMemoryBlock) ((IStructuredSelection) selection).getFirstElement(); + action.setMenuCreator(this); + action.setEnabled(true); + } else if (((IStructuredSelection) selection).getFirstElement() instanceof IMemoryRendering) { + fMemoryBlock = ((IMemoryRendering) ((IStructuredSelection) selection).getFirstElement()) + .getMemoryBlock(); + action.setMenuCreator(this); + action.setEnabled(true); + } + } + } + + @Override public void debugContextChanged(DebugContextEvent event) { - } - - @Override + } + + @Override public Menu getMenu(Menu parent) { - Menu menu = new Menu(parent); - menu.addMenuListener(new MenuAdapter() { - @Override + Menu menu = new Menu(parent); + menu.addMenuListener(new MenuAdapter() { + @Override public void menuShown(MenuEvent e) { - Menu m = (Menu)e.widget; - MenuItem[] items = m.getItems(); - for (int i=0; i < items.length; i++) { - items[i].dispose(); - } - fillMenu(m); - } - }); - return menu; - } - - private void fillMenu(Menu menu) { - if(fMemoryBlock instanceof IMemoryBlockUpdatePolicyProvider) - { - IMemoryBlockUpdatePolicyProvider blockPolicy = (IMemoryBlockUpdatePolicyProvider) fMemoryBlock; - - String currentPolicy = blockPolicy.getUpdatePolicy(); - - String policies[] = blockPolicy.getUpdatePolicies(); - for(int i = 0; i < policies.length; i++) - { - SelectPolicy action = new SelectPolicy(policies[i], blockPolicy.getUpdatePolicyDescription(policies[i])); - ActionContributionItem item = new ActionContributionItem(action); - action.setChecked(policies[i].equals(currentPolicy)); - - item.fill(menu, -1); - } - } - } + Menu m = (Menu) e.widget; + MenuItem[] items = m.getItems(); + for (int i = 0; i < items.length; i++) { + items[i].dispose(); + } + fillMenu(m); + } + }); + return menu; + } -} + private void fillMenu(Menu menu) { + if (fMemoryBlock instanceof IMemoryBlockUpdatePolicyProvider) { + IMemoryBlockUpdatePolicyProvider blockPolicy = (IMemoryBlockUpdatePolicyProvider) fMemoryBlock; + + String currentPolicy = blockPolicy.getUpdatePolicy(); + + String policies[] = blockPolicy.getUpdatePolicies(); + for (int i = 0; i < policies.length; i++) { + SelectPolicy action = new SelectPolicy(policies[i], + blockPolicy.getUpdatePolicyDescription(policies[i])); + ActionContributionItem item = new ActionContributionItem(action); + action.setChecked(policies[i].equals(currentPolicy)); + item.fill(menu, -1); + } + } + } + +} diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/DsfSourceDisplayAdapter.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/DsfSourceDisplayAdapter.java index 1023b6d7fe3..b6b52421ac4 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/DsfSourceDisplayAdapter.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/DsfSourceDisplayAdapter.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation * Wind River Systems - initial API and implementation @@ -118,9 +118,9 @@ import org.eclipse.ui.texteditor.ITextEditor; * Debuggers can override the default source editor used by the source display * adapter by registering their own ISourcePresentation adapter. * </p> - * + * * @see ISourcePresentation - * + * * @since 1.0 */ @ThreadSafe @@ -159,7 +159,7 @@ public class DsfSourceDisplayAdapter implements ISourceDisplay, ISteppingControl /** * Test whether the given frame data instance refers to the very same * location. - * + * * @param frameData * @return <code>true</code> if the frame data refers to the same * location @@ -543,7 +543,7 @@ public class DsfSourceDisplayAdapter implements ISourceDisplay, ISteppingControl /** * Scroll the given line into the visible area if it is not yet visible. - * + * * @param focusLine * @see org.eclipse.jface.text.TextViewer#revealRange(int, int) */ @@ -722,10 +722,10 @@ public class DsfSourceDisplayAdapter implements ISourceDisplay, ISteppingControl /** * Configure the delay (in milliseconds) before the selection in the editor * is changed to the IP location. - * + * * @param delay * the delay in milliseconds, a non-negative integer - * + * * @since 1.1 */ public void setSelectionChangeDelay(int delay) { diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/IInstructionPointerPresentation.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/IInstructionPointerPresentation.java index 817b4a634f7..8abb0782f22 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/IInstructionPointerPresentation.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/IInstructionPointerPresentation.java @@ -13,7 +13,6 @@ *******************************************************************************/ package org.eclipse.cdt.dsf.debug.ui.sourcelookup; - import org.eclipse.cdt.dsf.debug.service.IStack.IFrameDMContext; import org.eclipse.jface.text.source.Annotation; import org.eclipse.swt.graphics.Image; @@ -51,7 +50,7 @@ import org.eclipse.ui.IEditorPart; * source for the given stack frame. The image will be positioned based on stack * frame line number and character ranges. * </p> - * + * * @see org.eclipse.debug.ui.IInstructionPointerPresentation * @since 2.0 */ @@ -59,26 +58,26 @@ public interface IInstructionPointerPresentation { /** * Returns an annotation used for the specified stack frame in the specified * editor, or <code>null</code> if a default annotation should be used. - * + * * @param editorPart the editor the debugger has opened * @param frame the stack frame for which the debugger is displaying * source * @return annotation or <code>null</code> */ public Annotation getInstructionPointerAnnotation(IEditorPart editorPart, IFrameDMContext frame); - + /** * Returns an identifier of a <code>org.eclipse.ui.editors.annotationTypes</code> extension used for * the specified stack frame in the specified editor, or <code>null</code> if a default annotation * should be used. - * + * * @param editorPart the editor the debugger has opened * @param frame the stack frame for which the debugger is displaying * source * @return annotation type identifier or <code>null</code> - */ + */ public String getInstructionPointerAnnotationType(IEditorPart editorPart, IFrameDMContext frame); - + /** * Returns the instruction pointer image used for the specified stack frame in the specified * editor, or <code>null</code> if a default image should be used. @@ -90,9 +89,9 @@ public interface IInstructionPointerPresentation { * @param frame the stack frame for which the debugger is displaying * source * @return image or <code>null</code> - */ + */ public Image getInstructionPointerImage(IEditorPart editorPart, IFrameDMContext frame); - + /** * Returns the text to associate with the instruction pointer annotation used for the * specified stack frame in the specified editor, or <code>null</code> if a default @@ -105,6 +104,6 @@ public interface IInstructionPointerPresentation { * @param frame the stack frame for which the debugger is displaying * source * @return message or <code>null</code> - */ + */ public String getInstructionPointerText(IEditorPart editorPart, IFrameDMContext frame); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/InstructionPointerImageProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/InstructionPointerImageProvider.java index 0b78976fb73..b95e2f1ad1e 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/InstructionPointerImageProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/InstructionPointerImageProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ @@ -36,7 +36,7 @@ public class InstructionPointerImageProvider implements IAnnotationImageProvider */ @Override public Image getManagedImage(Annotation annotation) { - return ((IPAnnotation)annotation).getImage(); + return ((IPAnnotation) annotation).getImage(); } /* (non-Javadoc) @@ -54,5 +54,5 @@ public class InstructionPointerImageProvider implements IAnnotationImageProvider public ImageDescriptor getImageDescriptor(String imageDescritporId) { return null; } - + } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/InstructionPointerManager.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/InstructionPointerManager.java index 63cfc09cc86..266584742ec 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/InstructionPointerManager.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/InstructionPointerManager.java @@ -7,14 +7,13 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation * Wind River Systems - Adapter to use with DSF *******************************************************************************/ package org.eclipse.cdt.dsf.debug.ui.sourcelookup; - import java.util.Iterator; import java.util.LinkedList; import java.util.List; @@ -48,132 +47,141 @@ class InstructionPointerManager { /** * Current instruction pointer annotation type. */ - private static final String ID_CURRENT_IP= IDebugUIConstants.ANNOTATION_TYPE_INSTRUCTION_POINTER_CURRENT; - - /** + private static final String ID_CURRENT_IP = IDebugUIConstants.ANNOTATION_TYPE_INSTRUCTION_POINTER_CURRENT; + + /** * Secondary instruction pointer annotation type. */ - private static final String ID_SECONDARY_IP= IDebugUIConstants.ANNOTATION_TYPE_INSTRUCTION_POINTER_SECONDARY; + private static final String ID_SECONDARY_IP = IDebugUIConstants.ANNOTATION_TYPE_INSTRUCTION_POINTER_SECONDARY; /** - * Editor annotation object for instruction pointers. - */ - static class IPAnnotation extends Annotation implements IAnnotationPresentation { - - /** The image for this annotation. */ - private Image fImage; - - /** Frame DMC that this IP is for **/ - private IStack.IFrameDMContext fFrame; - - /** - * Constructs an instruction pointer image. - * - * @param frame stack frame the instruction pointer is associated with - * @param annotationType the type of annotation to display (annotation identifier) - * @param text the message to display with the annotation as hover help - * @param image the image used to display the annotation - */ - IPAnnotation(IStack.IFrameDMContext frame, String annotationType, String text, Image image) { - super(annotationType, false, text); - fFrame = frame; - fImage = image; - } - - /** - * Returns this annotation's image. - * - * @return image - */ - protected Image getImage() { - return fImage; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object other) { - if (other instanceof IPAnnotation) { - return fFrame.equals(((IPAnnotation)other).fFrame); - } - return false; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return fFrame.hashCode(); - } - - /* - * @see org.eclipse.jface.text.source.IAnnotationPresentation#paint(org.eclipse.swt.graphics.GC, org.eclipse.swt.widgets.Canvas, org.eclipse.swt.graphics.Rectangle) - */ - @Override + * Editor annotation object for instruction pointers. + */ + static class IPAnnotation extends Annotation implements IAnnotationPresentation { + + /** The image for this annotation. */ + private Image fImage; + + /** Frame DMC that this IP is for **/ + private IStack.IFrameDMContext fFrame; + + /** + * Constructs an instruction pointer image. + * + * @param frame stack frame the instruction pointer is associated with + * @param annotationType the type of annotation to display (annotation identifier) + * @param text the message to display with the annotation as hover help + * @param image the image used to display the annotation + */ + IPAnnotation(IStack.IFrameDMContext frame, String annotationType, String text, Image image) { + super(annotationType, false, text); + fFrame = frame; + fImage = image; + } + + /** + * Returns this annotation's image. + * + * @return image + */ + protected Image getImage() { + return fImage; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object other) { + if (other instanceof IPAnnotation) { + return fFrame.equals(((IPAnnotation) other).fFrame); + } + return false; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return fFrame.hashCode(); + } + + /* + * @see org.eclipse.jface.text.source.IAnnotationPresentation#paint(org.eclipse.swt.graphics.GC, org.eclipse.swt.widgets.Canvas, org.eclipse.swt.graphics.Rectangle) + */ + @Override public void paint(GC gc, Canvas canvas, Rectangle bounds) { - Rectangle imageBounds = fImage.getBounds(); - gc.drawImage(fImage, bounds.x + (bounds.width - imageBounds.width) / 2 , bounds.y + (bounds.height - imageBounds.height) / 2); - } - - /* - * @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer() - */ - @Override + Rectangle imageBounds = fImage.getBounds(); + gc.drawImage(fImage, bounds.x + (bounds.width - imageBounds.width) / 2, + bounds.y + (bounds.height - imageBounds.height) / 2); + } + + /* + * @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer() + */ + @Override public int getLayer() { - return 5; - } - - } - - /** - * Represents the context for a single instruction pointer. This is a convenience class - * used to store the three objects that comprise an instruction pointer 'context' so it - * can be stored in collections. - */ - static class AnnotationWrapper { - - /** The text editor for this context. */ - private ITextEditor fTextEditor; - - /** Stack frame that this annotation is for */ - private IStack.IFrameDMContext fFrameDmc; - - /** The vertical ruler annotation for this context. */ - private Annotation fAnnotation; - - AnnotationWrapper(ITextEditor textEditor, Annotation annotation, IStack.IFrameDMContext frameDmc) { - fTextEditor = textEditor; - fAnnotation = annotation; - fFrameDmc = frameDmc; - } - - /** - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object other) { - if (other instanceof AnnotationWrapper) { - AnnotationWrapper otherContext = (AnnotationWrapper) other; - return getAnnotation().equals(otherContext.getAnnotation()); - } - return false; - } - - /** - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return getAnnotation().hashCode(); - } - - ITextEditor getTextEditor() { return fTextEditor; } - Annotation getAnnotation() { return fAnnotation; } - IStack.IFrameDMContext getFrameDMC() { return fFrameDmc; } - } - + return 5; + } + + } + + /** + * Represents the context for a single instruction pointer. This is a convenience class + * used to store the three objects that comprise an instruction pointer 'context' so it + * can be stored in collections. + */ + static class AnnotationWrapper { + + /** The text editor for this context. */ + private ITextEditor fTextEditor; + + /** Stack frame that this annotation is for */ + private IStack.IFrameDMContext fFrameDmc; + + /** The vertical ruler annotation for this context. */ + private Annotation fAnnotation; + + AnnotationWrapper(ITextEditor textEditor, Annotation annotation, IStack.IFrameDMContext frameDmc) { + fTextEditor = textEditor; + fAnnotation = annotation; + fFrameDmc = frameDmc; + } + + /** + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object other) { + if (other instanceof AnnotationWrapper) { + AnnotationWrapper otherContext = (AnnotationWrapper) other; + return getAnnotation().equals(otherContext.getAnnotation()); + } + return false; + } + + /** + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return getAnnotation().hashCode(); + } + + ITextEditor getTextEditor() { + return fTextEditor; + } + + Annotation getAnnotation() { + return fAnnotation; + } + + IStack.IFrameDMContext getFrameDMC() { + return fFrameDmc; + } + } + /** * Mapping of IDebugTarget objects to (mappings of IThread objects to lists of instruction * pointer contexts). @@ -194,40 +202,41 @@ class InstructionPointerManager { /** * Clients must not instantiate this class. - * + * * @param presentation * the custom instruction pointer presentation or * <code>null</code> to use the default presentation */ public InstructionPointerManager(IInstructionPointerPresentation presentation) { fPresentation = presentation; - fAnnotationWrappers = new LinkedList<AnnotationWrapper>(); + fAnnotationWrappers = new LinkedList<AnnotationWrapper>(); } - + /** - * Add an instruction pointer annotation in the specified editor for the + * Add an instruction pointer annotation in the specified editor for the * specified stack frame. */ - public void addAnnotation(ITextEditor textEditor, IStack.IFrameDMContext frame, Position position, boolean isTopFrame) { - + public void addAnnotation(ITextEditor textEditor, IStack.IFrameDMContext frame, Position position, + boolean isTopFrame) { + IDocumentProvider docProvider = textEditor.getDocumentProvider(); IEditorInput editorInput = textEditor.getEditorInput(); - // If there is no annotation model, there's nothing more to do - IAnnotationModel annModel = docProvider.getAnnotationModel(editorInput); - if (annModel == null) { - return; - } - - if (isTopFrame) { - // remove other top-frame IP annotation(s) for this execution-context - removeAnnotations(DMContexts.getAncestorOfType(frame.getParents()[0], IExecutionDMContext.class)); - } - Annotation annotation = createAnnotation(textEditor, frame); - + // If there is no annotation model, there's nothing more to do + IAnnotationModel annModel = docProvider.getAnnotationModel(editorInput); + if (annModel == null) { + return; + } + + if (isTopFrame) { + // remove other top-frame IP annotation(s) for this execution-context + removeAnnotations(DMContexts.getAncestorOfType(frame.getParents()[0], IExecutionDMContext.class)); + } + Annotation annotation = createAnnotation(textEditor, frame); + // Add the annotation at the position to the editor's annotation model. annModel.removeAnnotation(annotation); - annModel.addAnnotation(annotation, position); - + annModel.addAnnotation(annotation, position); + // Add to list of existing wrappers synchronized (fAnnotationWrappers) { fAnnotationWrappers.add(new AnnotationWrapper(textEditor, annotation, frame)); @@ -235,9 +244,9 @@ class InstructionPointerManager { } private Annotation createAnnotation(ITextEditor editorPart, IStack.IFrameDMContext frame) { - String id = null; - String text = null; - Image image = null; + String id = null; + String text = null; + Image image = null; if (fPresentation != null) { Annotation annotation = fPresentation.getInstructionPointerAnnotation(editorPart, frame); if (annotation != null) { @@ -250,43 +259,43 @@ class InstructionPointerManager { text = fPresentation.getInstructionPointerText(editorPart, frame); } if (id == null) { - if (frame.getLevel() == 0) { - id = ID_CURRENT_IP; - if (text == null) { - text = Messages.IPAnnotation_primary; - } - if (image == null) { - image = DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_INSTRUCTION_POINTER_TOP); - } - } else { - id = ID_SECONDARY_IP; - if (text == null) { - text = Messages.IPAnnotation_secondary; - } - if (image == null) { - image = DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_INSTRUCTION_POINTER); - } - } - return new IPAnnotation(frame, id, text, image); + if (frame.getLevel() == 0) { + id = ID_CURRENT_IP; + if (text == null) { + text = Messages.IPAnnotation_primary; + } + if (image == null) { + image = DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_INSTRUCTION_POINTER_TOP); + } + } else { + id = ID_SECONDARY_IP; + if (text == null) { + text = Messages.IPAnnotation_secondary; + } + if (image == null) { + image = DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_INSTRUCTION_POINTER); + } + } + return new IPAnnotation(frame, id, text, image); } return new Annotation(id, false, text); } - + /** * Remove all annotations associated with the specified debug target that this class * is tracking. */ public void removeAnnotations(IRunControl.IExecutionDMContext execDmc) { // Retrieve the mapping of threads to context lists - synchronized(fAnnotationWrappers) { - for (Iterator<AnnotationWrapper> wrapperItr = fAnnotationWrappers.iterator(); wrapperItr.hasNext();) { - AnnotationWrapper wrapper = wrapperItr.next(); - if (DMContexts.isAncestorOf(wrapper.getFrameDMC(), execDmc)) { - removeAnnotation(wrapper.getTextEditor(), wrapper.getAnnotation()); - wrapperItr.remove(); - } - } - } + synchronized (fAnnotationWrappers) { + for (Iterator<AnnotationWrapper> wrapperItr = fAnnotationWrappers.iterator(); wrapperItr.hasNext();) { + AnnotationWrapper wrapper = wrapperItr.next(); + if (DMContexts.isAncestorOf(wrapper.getFrameDMC(), execDmc)) { + removeAnnotation(wrapper.getTextEditor(), wrapper.getAnnotation()); + wrapperItr.remove(); + } + } + } } /** @@ -295,28 +304,28 @@ class InstructionPointerManager { */ public void removeTopFrameAnnotations(IRunControl.IExecutionDMContext execDmc) { // Retrieve the mapping of threads to context lists - synchronized(fAnnotationWrappers) { - for (Iterator<AnnotationWrapper> wrapperItr = fAnnotationWrappers.iterator(); wrapperItr.hasNext();) { - AnnotationWrapper wrapper = wrapperItr.next(); - final IFrameDMContext frameDmc= wrapper.getFrameDMC(); + synchronized (fAnnotationWrappers) { + for (Iterator<AnnotationWrapper> wrapperItr = fAnnotationWrappers.iterator(); wrapperItr.hasNext();) { + AnnotationWrapper wrapper = wrapperItr.next(); + final IFrameDMContext frameDmc = wrapper.getFrameDMC(); if (DMContexts.isAncestorOf(frameDmc, execDmc) && frameDmc.getLevel() == 0) { - removeAnnotation(wrapper.getTextEditor(), wrapper.getAnnotation()); - wrapperItr.remove(); - } - } - } + removeAnnotation(wrapper.getTextEditor(), wrapper.getAnnotation()); + wrapperItr.remove(); + } + } + } + } + + /** Removes all annotations tracked by this manager */ + public void removeAllAnnotations() { + synchronized (fAnnotationWrappers) { + for (AnnotationWrapper wrapper : fAnnotationWrappers) { + removeAnnotation(wrapper.getTextEditor(), wrapper.getAnnotation()); + } + fAnnotationWrappers.clear(); + } } - /** Removes all annotations tracked by this manager */ - public void removeAllAnnotations() { - synchronized(fAnnotationWrappers) { - for (AnnotationWrapper wrapper : fAnnotationWrappers) { - removeAnnotation(wrapper.getTextEditor(), wrapper.getAnnotation()); - } - fAnnotationWrappers.clear(); - } - } - /** * Remove the specified annotation from the specified text editor. */ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/Messages.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/Messages.java index c5633805495..1a0dcc0bdeb 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/Messages.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/Messages.java @@ -22,7 +22,7 @@ public class Messages extends NLS { public static String IPAnnotation_primary; public static String IPAnnotation_secondary; - + static { // initialize resource bundle NLS.initializeMessages(Messages.class.getName(), Messages.class); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/SourceLookupResult.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/SourceLookupResult.java index 464a3f79071..644a4f1e83e 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/SourceLookupResult.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/sourcelookup/SourceLookupResult.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -17,111 +17,111 @@ import org.eclipse.cdt.dsf.datamodel.IDMContext; import org.eclipse.ui.IEditorInput; /** - * The result of a source lookup contains the source element, editor id, and + * The result of a source lookup contains the source element, editor id, and * editor input resolved for a debug artifact. - * + * * @since 3.1 */ -class SourceLookupResult { - - /** - * Element that source was resolved for. - */ - private IDMContext fDmc; - /** - * Corresponding source element, or <code>null</code> - * if unknown. - */ - private Object fSourceElement; - /** - * Associated editor id, used to display the source element, - * or <code>null</code> if unknown. - */ - private String fEditorId; - /** - * Associatd editor input, used to display the source element, - * or <code>null</code> if unknown. - */ - private IEditorInput fEditorInput; +class SourceLookupResult { + + /** + * Element that source was resolved for. + */ + private IDMContext fDmc; + /** + * Corresponding source element, or <code>null</code> + * if unknown. + */ + private Object fSourceElement; + /** + * Associated editor id, used to display the source element, + * or <code>null</code> if unknown. + */ + private String fEditorId; + /** + * Associatd editor input, used to display the source element, + * or <code>null</code> if unknown. + */ + private IEditorInput fEditorInput; + + /** + * Creates a source lookup result on the given artifact, source element, + * editor id, and editor input. + */ + public SourceLookupResult(IDMContext dmc, Object sourceElement, String editorId, IEditorInput editorInput) { + fDmc = dmc; + setSourceElement(sourceElement); + setEditorId(editorId); + setEditorInput(editorInput); + } + + /* (non-Javadoc) + * @see org.eclipse.debug.ui.sourcelookup.ISourceLookupResult#getArtifact() + */ + public IDMContext getDmc() { + return fDmc; + } + + /* (non-Javadoc) + * @see org.eclipse.debug.ui.sourcelookup.ISourceLookupResult#getSourceElement() + */ + public Object getSourceElement() { + return fSourceElement; + } + + /** + * Sets the source element resolved for the artifact that source + * lookup was performed for, or <code>null</code> if a source element + * was not resolved. + * + * @param element resolved source element or <code>null</code> if unknown + */ + protected void setSourceElement(Object element) { + fSourceElement = element; + } - /** - * Creates a source lookup result on the given artifact, source element, - * editor id, and editor input. - */ - public SourceLookupResult(IDMContext dmc, Object sourceElement, String editorId, IEditorInput editorInput) { - fDmc = dmc; - setSourceElement(sourceElement); - setEditorId(editorId); - setEditorInput(editorInput); - } - - /* (non-Javadoc) - * @see org.eclipse.debug.ui.sourcelookup.ISourceLookupResult#getArtifact() - */ - public IDMContext getDmc() { - return fDmc; - } - - /* (non-Javadoc) - * @see org.eclipse.debug.ui.sourcelookup.ISourceLookupResult#getSourceElement() - */ - public Object getSourceElement() { - return fSourceElement; - } - - /** - * Sets the source element resolved for the artifact that source - * lookup was performed for, or <code>null</code> if a source element - * was not resolved. - * - * @param element resolved source element or <code>null</code> if unknown - */ - protected void setSourceElement(Object element) { - fSourceElement = element; - } - - /* (non-Javadoc) - * @see org.eclipse.debug.ui.sourcelookup.ISourceLookupResult#getEditorId() - */ - public String getEditorId() { - return fEditorId; - } - - /** - * Sets the identifier of the editor used to display this source - * lookup result's source element, or <code>null</code> if unknown. - * - * @param id the identifier of the editor used to display this source - * lookup result's source element, or <code>null</code> if unknown - */ - protected void setEditorId(String id) { - fEditorId = id; - } + /* (non-Javadoc) + * @see org.eclipse.debug.ui.sourcelookup.ISourceLookupResult#getEditorId() + */ + public String getEditorId() { + return fEditorId; + } + + /** + * Sets the identifier of the editor used to display this source + * lookup result's source element, or <code>null</code> if unknown. + * + * @param id the identifier of the editor used to display this source + * lookup result's source element, or <code>null</code> if unknown + */ + protected void setEditorId(String id) { + fEditorId = id; + } + + /* (non-Javadoc) + * @see org.eclipse.debug.ui.sourcelookup.ISourceLookupResult#getEditorInput() + */ + public IEditorInput getEditorInput() { + return fEditorInput; + } + + /** + * Sets the editor input used to display this source lookup + * result's source element, or <code>null</code> if unknown. + * + * @param input the editor input used to display this source lookup + * result's source element, or <code>null</code> if unknown + */ + protected void setEditorInput(IEditorInput input) { + fEditorInput = input; + } - /* (non-Javadoc) - * @see org.eclipse.debug.ui.sourcelookup.ISourceLookupResult#getEditorInput() - */ - public IEditorInput getEditorInput() { - return fEditorInput; - } - - /** - * Sets the editor input used to display this source lookup - * result's source element, or <code>null</code> if unknown. - * - * @param input the editor input used to display this source lookup - * result's source element, or <code>null</code> if unknown - */ - protected void setEditorInput(IEditorInput input) { - fEditorInput = input; - } - /** * Updates the artifact to refer to the given artifact * if equal. For example, when a source lookup result is resued * for the same stack frame, we still need to update in case * the stack frame is not identical. - * + * * @param artifact new artifact state */ public void updateArtifact(IDMContext dmc) { diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/AbstractDebugVMAdapter.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/AbstractDebugVMAdapter.java index 450ed47e407..4b41f1155c3 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/AbstractDebugVMAdapter.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/AbstractDebugVMAdapter.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -26,56 +26,56 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationCont /** * Base class for VM adapters used for implementing a debugger integration. - * + * * @since 1.1 */ -public class AbstractDebugVMAdapter extends AbstractDMVMAdapter - implements ISteppingControlParticipant -{ - - public AbstractDebugVMAdapter(DsfSession session, final SteppingController controller) { - super(session); - fController = controller; - try { - fController.getExecutor().execute(new DsfRunnable() { - @Override +public class AbstractDebugVMAdapter extends AbstractDMVMAdapter implements ISteppingControlParticipant { + + public AbstractDebugVMAdapter(DsfSession session, final SteppingController controller) { + super(session); + fController = controller; + try { + fController.getExecutor().execute(new DsfRunnable() { + @Override public void run() { - fController.addSteppingControlParticipant(AbstractDebugVMAdapter.this); - } - }); - } catch (RejectedExecutionException e) {} // Do nothing if session is shut down. - } + fController.addSteppingControlParticipant(AbstractDebugVMAdapter.this); + } + }); + } catch (RejectedExecutionException e) { + } // Do nothing if session is shut down. + } + + private final SteppingController fController; - private final SteppingController fController; - @Override - protected IVMProvider createViewModelProvider(IPresentationContext context) { - return null; - } + protected IVMProvider createViewModelProvider(IPresentationContext context) { + return null; + } - @Override - public void doneHandleEvent(Object event) { - if (event instanceof IRunControl.ISuspendedDMEvent) { - final ISuspendedDMEvent suspendedEvent= (IRunControl.ISuspendedDMEvent) event; - fController.getExecutor().execute(new DsfRunnable() { - @Override + @Override + public void doneHandleEvent(Object event) { + if (event instanceof IRunControl.ISuspendedDMEvent) { + final ISuspendedDMEvent suspendedEvent = (IRunControl.ISuspendedDMEvent) event; + fController.getExecutor().execute(new DsfRunnable() { + @Override public void run() { - fController.doneStepping(suspendedEvent.getDMContext(), AbstractDebugVMAdapter.this); - }; - }); - } - } + fController.doneStepping(suspendedEvent.getDMContext(), AbstractDebugVMAdapter.this); + }; + }); + } + } - @Override - public void dispose() { - try { - fController.getExecutor().execute(new DsfRunnable() { - @Override + @Override + public void dispose() { + try { + fController.getExecutor().execute(new DsfRunnable() { + @Override public void run() { - fController.removeSteppingControlParticipant(AbstractDebugVMAdapter.this); - } - }); - } catch (RejectedExecutionException e) {} // Do nothing if session is shut down. - super.dispose(); - } + fController.removeSteppingControlParticipant(AbstractDebugVMAdapter.this); + } + }); + } catch (RejectedExecutionException e) { + } // Do nothing if session is shut down. + super.dispose(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/ErrorLabelForeground.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/ErrorLabelForeground.java index 0f9def3648f..6203b232009 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/ErrorLabelForeground.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/ErrorLabelForeground.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -25,39 +25,39 @@ import org.eclipse.ui.themes.ITheme; import org.eclipse.ui.themes.IThemeManager; /** - * Label attribute that sets the label color to the standard workbench + * Label attribute that sets the label color to the standard workbench * error color. The color is activated when the property update contains - * a status with error codes: {@link IDsfStatusConstants#INTERNAL_ERROR}, - * {@link IDsfStatusConstants#REQUEST_FAILED}, or + * a status with error codes: {@link IDsfStatusConstants#INTERNAL_ERROR}, + * {@link IDsfStatusConstants#REQUEST_FAILED}, or * {@link IDsfStatusConstants#NOT_SUPPORTED}. - * + * * @since 2.2 */ public class ErrorLabelForeground extends LabelForeground { - private static final RGB DEFAULT_COLOR = new RGB(255, 0, 0); - - public ErrorLabelForeground() { - super(DEFAULT_COLOR); - } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - return !status.isOK() && status.getCode() >= IDsfStatusConstants.NOT_SUPPORTED; - } - - @Override - public RGB getForeground() { - IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager(); - ITheme currentTheme = themeManager.getCurrentTheme(); - - ColorRegistry colorRegistry = currentTheme.getColorRegistry(); - - Color color = colorRegistry.get(JFacePreferences.ERROR_COLOR); - - if (color != null) { - return color.getRGB(); - } - return super.getForeground(); - } + private static final RGB DEFAULT_COLOR = new RGB(255, 0, 0); + + public ErrorLabelForeground() { + super(DEFAULT_COLOR); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + return !status.isOK() && status.getCode() >= IDsfStatusConstants.NOT_SUPPORTED; + } + + @Override + public RGB getForeground() { + IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager(); + ITheme currentTheme = themeManager.getCurrentTheme(); + + ColorRegistry colorRegistry = currentTheme.getColorRegistry(); + + Color color = colorRegistry.get(JFacePreferences.ERROR_COLOR); + + if (color != null) { + return color.getRGB(); + } + return super.getForeground(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/ErrorLabelText.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/ErrorLabelText.java index f585aa0e801..d2b2170d0b8 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/ErrorLabelText.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/ErrorLabelText.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,56 +19,56 @@ import org.eclipse.cdt.dsf.ui.viewmodel.properties.LabelText; import org.eclipse.core.runtime.IStatus; /** - * Label attribute that fills in the text of an error status into the label - * column. - * + * Label attribute that fills in the text of an error status into the label + * column. + * * @since 2.0 */ public class ErrorLabelText extends LabelText { - protected final static String PROP_ERROR_MESSAGE = "error_message"; //$NON-NLS-1$ - - public ErrorLabelText() { - this(MessagesForDebugVM.ErrorLabelText__text_format, new String[] {}); - } + protected final static String PROP_ERROR_MESSAGE = "error_message"; //$NON-NLS-1$ + + public ErrorLabelText() { + this(MessagesForDebugVM.ErrorLabelText__text_format, new String[] {}); + } + + public ErrorLabelText(String formatPattern, String[] propertyNames) { + super(formatPattern, addErrorMessageProperty(propertyNames)); + } + + private static String[] addErrorMessageProperty(String[] propertyNames) { + String[] newPropertyNames = new String[propertyNames.length + 1]; + System.arraycopy(propertyNames, 0, newPropertyNames, 0, propertyNames.length); + newPropertyNames[propertyNames.length + 0] = PROP_ERROR_MESSAGE; + return newPropertyNames; + } + + @Override + protected Object getPropertyValue(String propertyName, IStatus status, Map<String, Object> properties) { + if (PROP_ERROR_MESSAGE.equals(propertyName)) { + if (status.getChildren().length < 2) { + return replaceNewlines(status.getMessage()); + } else { + StringBuilder buf = new StringBuilder(status.getMessage()); + for (IStatus childStatus : status.getChildren()) { + buf.append(MessagesForDebugVM.ErrorLabelText_Error_message__text_page_break_delimiter); + buf.append(replaceNewlines(childStatus.getMessage())); + } + return buf.toString(); + } + } + return super.getPropertyValue(propertyName, status, properties); + } - public ErrorLabelText(String formatPattern, String[] propertyNames) { - super(formatPattern, addErrorMessageProperty(propertyNames)); - } - - private static String[] addErrorMessageProperty(String[] propertyNames) { - String[] newPropertyNames = new String[propertyNames.length + 1]; - System.arraycopy(propertyNames, 0, newPropertyNames, 0, propertyNames.length); - newPropertyNames[propertyNames.length + 0] = PROP_ERROR_MESSAGE; - return newPropertyNames; - } + private String replaceNewlines(String message) { + return message.replaceAll("\n", MessagesForDebugVM.ErrorLabelText_Error_message__text_page_break_delimiter); //$NON-NLS-1$ + } - @Override - protected Object getPropertyValue(String propertyName, IStatus status, Map<String, Object> properties) { - if (PROP_ERROR_MESSAGE.equals(propertyName)) { - if (status.getChildren().length < 2) { - return replaceNewlines(status.getMessage()); - } else { - StringBuilder buf = new StringBuilder( status.getMessage() ); - for (IStatus childStatus : status.getChildren()) { - buf.append(MessagesForDebugVM.ErrorLabelText_Error_message__text_page_break_delimiter); - buf.append( replaceNewlines(childStatus.getMessage()) ); - } - return buf.toString(); - } - } - return super.getPropertyValue(propertyName, status, properties); - } - - private String replaceNewlines(String message) { - return message.replaceAll("\n", MessagesForDebugVM.ErrorLabelText_Error_message__text_page_break_delimiter); //$NON-NLS-1$ - } - - @Override - public boolean checkProperty(String propertyName, IStatus status, Map<String,Object> properties) { - if (PROP_ERROR_MESSAGE.equals(propertyName)) { - return !status.isOK(); - } - return super.checkProperty(propertyName, status, properties); - }; + @Override + public boolean checkProperty(String propertyName, IStatus status, Map<String, Object> properties) { + if (PROP_ERROR_MESSAGE.equals(propertyName)) { + return !status.isOK(); + } + return super.checkProperty(propertyName, status, properties); + }; } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/IDebugVMConstants.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/IDebugVMConstants.java index d3ca68c7db1..9075308c8d4 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/IDebugVMConstants.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/IDebugVMConstants.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - Ted Williams - initial API and implementation *******************************************************************************/ @@ -21,103 +21,105 @@ import org.eclipse.debug.internal.ui.elements.adapters.VariableColumnPresentatio /** * Public constants used in the debug view model. - * + * * @since 1.0 */ public interface IDebugVMConstants { - /** - * Standard across the board column IDs. - */ - public static final String ID = DsfUIPlugin.PLUGIN_ID + ".VARIABLES_COLUMN_PRESENTATION_ID"; //$NON-NLS-1$ - public static final String COLUMN_ID__NAME = DsfUIPlugin.PLUGIN_ID + ".COLUMN_ID__NAME"; //$NON-NLS-1$ - public static final String COLUMN_ID__TYPE = DsfUIPlugin.PLUGIN_ID + ".COLUMN_ID__TYPE"; //$NON-NLS-1$ - public static final String COLUMN_ID__VALUE = DsfUIPlugin.PLUGIN_ID + ".COLUMN_ID__VALUE"; //$NON-NLS-1$ - public static final String COLUMN_ID__ADDRESS = DsfUIPlugin.PLUGIN_ID + ".COLUMN_ID__ADDRESS"; //$NON-NLS-1$ - public static final String COLUMN_ID__DESCRIPTION = DsfUIPlugin.PLUGIN_ID + ".COLUMN_ID__DESCRIPTION"; //$NON-NLS-1$ - - /** - * Make expression column ID the same as platform's "name" column ID to - * enable the File->Rename in-line editing action in the expressions view. - */ - @SuppressWarnings("restriction") + /** + * Standard across the board column IDs. + */ + public static final String ID = DsfUIPlugin.PLUGIN_ID + ".VARIABLES_COLUMN_PRESENTATION_ID"; //$NON-NLS-1$ + public static final String COLUMN_ID__NAME = DsfUIPlugin.PLUGIN_ID + ".COLUMN_ID__NAME"; //$NON-NLS-1$ + public static final String COLUMN_ID__TYPE = DsfUIPlugin.PLUGIN_ID + ".COLUMN_ID__TYPE"; //$NON-NLS-1$ + public static final String COLUMN_ID__VALUE = DsfUIPlugin.PLUGIN_ID + ".COLUMN_ID__VALUE"; //$NON-NLS-1$ + public static final String COLUMN_ID__ADDRESS = DsfUIPlugin.PLUGIN_ID + ".COLUMN_ID__ADDRESS"; //$NON-NLS-1$ + public static final String COLUMN_ID__DESCRIPTION = DsfUIPlugin.PLUGIN_ID + ".COLUMN_ID__DESCRIPTION"; //$NON-NLS-1$ + + /** + * Make expression column ID the same as platform's "name" column ID to + * enable the File->Rename in-line editing action in the expressions view. + */ + @SuppressWarnings("restriction") public static final String COLUMN_ID__EXPRESSION = VariableColumnPresentation.COLUMN_VARIABLE_NAME; - /** - * Property name used to store the selected number format in a - * presentation context. - * - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext - * @since 2.0 - */ - public final static String PROP_FORMATTED_VALUE_FORMAT_PREFERENCE = "CurrentNumericStyle" ; //$NON-NLS-1$ + /** + * Property name used to store the selected number format in a + * presentation context. + * + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext + * @since 2.0 + */ + public final static String PROP_FORMATTED_VALUE_FORMAT_PREFERENCE = "CurrentNumericStyle"; //$NON-NLS-1$ + + /** + * Property for an element's value represented in the active number format. + * + * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.numberformat.FormattedValueVMUtil + * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues + * + * @since 2.0 + */ + public static final String PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE = "formatted_value_active_format_value"; //$NON-NLS-1$ - /** - * Property for an element's value represented in the active number format. - * - * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.numberformat.FormattedValueVMUtil - * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues - * - * @since 2.0 - */ - public static final String PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE = "formatted_value_active_format_value"; //$NON-NLS-1$ + /** + * Property for the available number formats for a given element. + * + * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.numberformat.FormattedValueVMUtil + * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues + * + * @since 2.0 + */ + public static final String PROP_FORMATTED_VALUE_AVAILABLE_FORMATS = "formatted_value_available_formats"; //$NON-NLS-1$ - /** - * Property for the available number formats for a given element. - * - * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.numberformat.FormattedValueVMUtil - * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues - * - * @since 2.0 - */ - public static final String PROP_FORMATTED_VALUE_AVAILABLE_FORMATS = "formatted_value_available_formats"; //$NON-NLS-1$ + /** + * Property for the active number format for a given element. + * + * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.numberformat.FormattedValueVMUtil + * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues + * + * @since 2.0 + */ + public static final String PROP_FORMATTED_VALUE_ACTIVE_FORMAT = "formatted_value_active_format"; //$NON-NLS-1$ - /** - * Property for the active number format for a given element. - * - * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.numberformat.FormattedValueVMUtil - * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues - * - * @since 2.0 - */ - public static final String PROP_FORMATTED_VALUE_ACTIVE_FORMAT = "formatted_value_active_format"; //$NON-NLS-1$ - - /** - * Prefix for properties representing a value of an element represented in - * a given number format. - * - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.numberformat.FormattedValueVMUtil#getPropertyForFormatId(String) - * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider - * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues - * - * @since 2.0 - */ - public static final String PROP_FORMATTED_VALUE_BASE = "formatted_value_base"; //$NON-NLS-1$ + /** + * Prefix for properties representing a value of an element represented in + * a given number format. + * + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.numberformat.FormattedValueVMUtil#getPropertyForFormatId(String) + * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider + * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues + * + * @since 2.0 + */ + public static final String PROP_FORMATTED_VALUE_BASE = "formatted_value_base"; //$NON-NLS-1$ - /** - * Property which indicates that the element's value formatted in a string - * format has changed value since the last time a cache has been flushed. - * - * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.numberformat.FormattedValueVMUtil - * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues - * - * @since 2.0 - */ - public static final String PROP_IS_STRING_FORMAT_VALUE_CHANGED = ICachingVMProvider.PROP_IS_CHANGED_PREFIX + FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT, null); + /** + * Property which indicates that the element's value formatted in a string + * format has changed value since the last time a cache has been flushed. + * + * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.numberformat.FormattedValueVMUtil + * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues + * + * @since 2.0 + */ + public static final String PROP_IS_STRING_FORMAT_VALUE_CHANGED = ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT, null); - /** - * Property which indicates that the element's value formatted using the - * element's active number format has changed value since the last time a - * cache has been flushed. - * - * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.numberformat.FormattedValueVMUtil - * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues - * - * @since 2.0 - */ - public static final String PROP_IS_ACTIVE_FORMATTED_VALUE_CHANGED = ICachingVMProvider.PROP_IS_CHANGED_PREFIX + FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.NATURAL_FORMAT, null); + /** + * Property which indicates that the element's value formatted using the + * element's active number format has changed value since the last time a + * cache has been flushed. + * + * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.numberformat.FormattedValueVMUtil + * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues + * + * @since 2.0 + */ + public static final String PROP_IS_ACTIVE_FORMATTED_VALUE_CHANGED = ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.NATURAL_FORMAT, null); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/MessagesForDebugVM.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/MessagesForDebugVM.java index 4279292d5d3..22057995055 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/MessagesForDebugVM.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/MessagesForDebugVM.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems, Inc. - initial API and implementation *******************************************************************************/ @@ -20,13 +20,14 @@ import org.eclipse.osgi.util.NLS; * @noinstantiate This class is not intended to be instantiated by clients. */ public class MessagesForDebugVM extends NLS { - public static String ErrorLabelText__text_format; - public static String ErrorLabelText_Error_message__text_page_break_delimiter; - - static { - // initialize resource bundle - NLS.initializeMessages(MessagesForDebugVM.class.getName(), MessagesForDebugVM.class); - } + public static String ErrorLabelText__text_format; + public static String ErrorLabelText_Error_message__text_page_break_delimiter; + + static { + // initialize resource bundle + NLS.initializeMessages(MessagesForDebugVM.class.getName(), MessagesForDebugVM.class); + } - private MessagesForDebugVM() {} + private MessagesForDebugVM() { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/SimpleMapPersistable.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/SimpleMapPersistable.java index db21bbeaa22..4e7258b1f04 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/SimpleMapPersistable.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/SimpleMapPersistable.java @@ -29,40 +29,40 @@ import org.eclipse.ui.IPersistableElement; * Generic persistable for storing a map of simple values. * <br> * Currently supported value types are {@link Integer} and {@link String}. - * + * * @since 2.5 */ -public class SimpleMapPersistable<V> implements IPersistableElement, IAdaptable { +public class SimpleMapPersistable<V> implements IPersistableElement, IAdaptable { - private static final String KEY_TYPE = "type"; //$NON-NLS-1$ - private static final String KEY_NAME = "name"; //$NON-NLS-1$ - private static final String KEY_VALUE = "value"; //$NON-NLS-1$ + private static final String KEY_TYPE = "type"; //$NON-NLS-1$ + private static final String KEY_NAME = "name"; //$NON-NLS-1$ + private static final String KEY_VALUE = "value"; //$NON-NLS-1$ - private Class<V> fType; + private Class<V> fType; private Map<String, V> fValues = new TreeMap<String, V>(); @SuppressWarnings("unchecked") public SimpleMapPersistable(IMemento memento) throws CoreException { - IMemento type = memento.getChild(KEY_TYPE); - if (type == null) { - throw new CoreException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, - "Missing key for type.", null)); //$NON-NLS-1$ - } - - try { - fType = (Class<V>)Class.forName(type.getTextData()); + IMemento type = memento.getChild(KEY_TYPE); + if (type == null) { + throw new CoreException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, + "Missing key for type.", null)); //$NON-NLS-1$ + } + + try { + fType = (Class<V>) Class.forName(type.getTextData()); } catch (ClassNotFoundException e) { - throw new CoreException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, - e.getMessage(), e)); + throw new CoreException(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, + e.getMessage(), e)); } - + IMemento[] list = memento.getChildren(KEY_NAME); Map<String, V> values = new TreeMap<String, V>(); for (IMemento elem : list) { - values.put(elem.getID(), getValue(elem)); + values.put(elem.getID(), getValue(elem)); } - - synchronized(fValues) { + + synchronized (fValues) { // We should not assign 'values' directly to 'fValues' // if we want synchronization to work. Instead, we must use // the same map as before for 'fValues' @@ -72,51 +72,49 @@ public class SimpleMapPersistable<V> implements IPersistableElement, IAdaptable } public SimpleMapPersistable(Class<V> type) { - fType = type; + fType = type; } - + @Override - public void saveState(IMemento memento) { + public void saveState(IMemento memento) { Map<String, V> values = null; synchronized (fValues) { values = new TreeMap<String, V>(fValues); } - IMemento type = memento.createChild(KEY_TYPE); - synchronized (fType) { - type.putTextData(fType.getName()); - } - for (Map.Entry<String, V> entry : values.entrySet()) { - IMemento value = memento.createChild(KEY_NAME, entry.getKey()); - putValue(value, entry.getValue()); + IMemento type = memento.createChild(KEY_TYPE); + synchronized (fType) { + type.putTextData(fType.getName()); + } + for (Map.Entry<String, V> entry : values.entrySet()) { + IMemento value = memento.createChild(KEY_NAME, entry.getKey()); + putValue(value, entry.getValue()); } } private void putValue(IMemento memento, Object value) { - if (value instanceof String) { - memento.putString(KEY_VALUE, (String)value); - } else if (value instanceof Integer) { - memento.putInteger(KEY_VALUE, (Integer)value); - } - else { - assert false; - } + if (value instanceof String) { + memento.putString(KEY_VALUE, (String) value); + } else if (value instanceof Integer) { + memento.putInteger(KEY_VALUE, (Integer) value); + } else { + assert false; + } } - @SuppressWarnings("unchecked") - private V getValue(IMemento memento) { - synchronized (fType) { - if (String.class.equals(fType)) { - return (V)memento.getString(KEY_VALUE); - } else if (Integer.class.equals(fType)) { - return (V)memento.getInteger(KEY_VALUE); - } else { - assert false; - } - } - return null; - } - + @SuppressWarnings("unchecked") + private V getValue(IMemento memento) { + synchronized (fType) { + if (String.class.equals(fType)) { + return (V) memento.getString(KEY_VALUE); + } else if (Integer.class.equals(fType)) { + return (V) memento.getInteger(KEY_VALUE); + } else { + assert false; + } + } + return null; + } public V getValue(String key) { if (key == null) @@ -144,9 +142,9 @@ public class SimpleMapPersistable<V> implements IPersistableElement, IAdaptable @SuppressWarnings("unchecked") @Override public <T> T getAdapter(Class<T> adapter) { - if (adapter.isInstance(this)) { - return (T)this; - } + if (adapter.isInstance(this)) { + return (T) this; + } return null; } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/SimpleMapPersistableFactory.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/SimpleMapPersistableFactory.java index 47853985c3b..e71746617e9 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/SimpleMapPersistableFactory.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/SimpleMapPersistableFactory.java @@ -23,9 +23,9 @@ import org.eclipse.ui.IMemento; /** * Persistable factory the simple map persistable. - * + * * @since 2.5 - * + * * @see SimpleMapPersistable */ public class SimpleMapPersistableFactory implements IElementFactory { @@ -34,16 +34,15 @@ public class SimpleMapPersistableFactory implements IElementFactory { // Must be the same id as the one used in the plugin.xml file return "org.eclipse.cdt.dsf.ui.simpleMapPersistableFactory"; //$NON-NLS-1$ } - + @Override public IAdaptable createElement(IMemento memento) { try { SimpleMapPersistable<Object> x = new SimpleMapPersistable<>(memento); return x; - } catch (CoreException e) { - DsfUIPlugin.log(new Status( - IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, "Cannot restore persistable." , e)); //$NON-NLS-1$ - } + } catch (CoreException e) { + DsfUIPlugin.log(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, "Cannot restore persistable.", e)); //$NON-NLS-1$ + } return null; } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/SteppingController.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/SteppingController.java index 62ae850b9b3..a559961ddac 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/SteppingController.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/SteppingController.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * John Dallaway - Report command execution error (Bug 539455) @@ -58,39 +58,40 @@ import org.eclipse.jface.util.PropertyChangeEvent; * this class is used, other service implementations, such as stack and * expressions, can use it to avoid requesting data from debugger back end if * another step is about to be executed. - * + * * @since 1.1 */ @ConfinedToDsfExecutor("#getExecutor()") public final class SteppingController { - /** - * Default delay in milliseconds, that it takes the SteppingTimedOutEvent - * event to be issued after a step is started. - * @see SteppingTimedOutEvent - * @see #setStepTimeout(int) - * @see #getStepTimeout() - */ - public final static int STEPPING_TIMEOUT = 500; - - /** - * The depth of the step queue. In other words, the maximum number of steps - * that are queued before the step queue manager is throwing them away. - */ - public final static int STEP_QUEUE_DEPTH = 2; + /** + * Default delay in milliseconds, that it takes the SteppingTimedOutEvent + * event to be issued after a step is started. + * @see SteppingTimedOutEvent + * @see #setStepTimeout(int) + * @see #getStepTimeout() + */ + public final static int STEPPING_TIMEOUT = 500; + + /** + * The depth of the step queue. In other words, the maximum number of steps + * that are queued before the step queue manager is throwing them away. + */ + public final static int STEP_QUEUE_DEPTH = 2; /** * The maximum delay (in milliseconds) between steps when synchronized * stepping is enabled. This also serves as a safeguard in the case stepping * control participants fail to indicate completion of event processing. */ - public final static int MAX_STEP_DELAY= 5000; + public final static int MAX_STEP_DELAY = 5000; - private final static boolean DEBUG = Boolean.parseBoolean(Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/stepping")); //$NON-NLS-1$ + private final static boolean DEBUG = Boolean + .parseBoolean(Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/stepping")); //$NON-NLS-1$ - /** - * Indicates that the given context has been stepping for some time, - * and the UI (views and actions) may need to be updated accordingly. - */ + /** + * Indicates that the given context has been stepping for some time, + * and the UI (views and actions) may need to be updated accordingly. + */ public static final class SteppingTimedOutEvent extends AbstractDMEvent<IExecutionDMContext> { private SteppingTimedOutEvent(IExecutionDMContext execCtx) { super(execCtx); @@ -107,7 +108,7 @@ public final class SteppingController { * blocked until all stepping control participants have indicated completion * of event processing or the maximum timeout * {@link SteppingController#MAX_STEP_DELAY} has been reached. - * + * * @see SteppingController#addSteppingControlParticipant(ISteppingControlParticipant) * @see SteppingController#removeSteppingControlParticipant(ISteppingControlParticipant) */ @@ -116,61 +117,60 @@ public final class SteppingController { private static class StepRequest { IExecutionDMContext fContext; - StepType fStepType; - boolean inProgress = false; - StepRequest(IExecutionDMContext execCtx, StepType type) { - fContext = execCtx; - fStepType = type; - } - } - - private class TimeOutRunnable extends DsfRunnable{ - + StepType fStepType; + boolean inProgress = false; + + StepRequest(IExecutionDMContext execCtx, StepType type) { + fContext = execCtx; + fStepType = type; + } + } + + private class TimeOutRunnable extends DsfRunnable { + TimeOutRunnable(IExecutionDMContext dmc) { fDmc = dmc; } - + private final IExecutionDMContext fDmc; - + @Override public void run() { fTimedOutFutures.remove(fDmc); - if (getSession().isActive()) { - fTimedOutFlags.put(fDmc, Boolean.TRUE); - enableStepping(fDmc); - // Issue the stepping time-out event. - getSession().dispatchEvent( - new SteppingTimedOutEvent(fDmc), - null); - } - } - } - + if (getSession().isActive()) { + fTimedOutFlags.put(fDmc, Boolean.TRUE); + enableStepping(fDmc); + // Issue the stepping time-out event. + getSession().dispatchEvent(new SteppingTimedOutEvent(fDmc), null); + } + } + } + private final DsfSession fSession; private final DsfServicesTracker fServicesTracker; - private IRunControl fRunControl; - private int fQueueDepth = STEP_QUEUE_DEPTH; - - private final Map<IExecutionDMContext,List<StepRequest>> fStepQueues = new HashMap<IExecutionDMContext,List<StepRequest>>(); - private final Map<IExecutionDMContext,Boolean> fTimedOutFlags = new HashMap<IExecutionDMContext,Boolean>(); - private final Map<IExecutionDMContext,ScheduledFuture<?>> fTimedOutFutures = new HashMap<IExecutionDMContext,ScheduledFuture<?>>(); + private IRunControl fRunControl; + private int fQueueDepth = STEP_QUEUE_DEPTH; + + private final Map<IExecutionDMContext, List<StepRequest>> fStepQueues = new HashMap<IExecutionDMContext, List<StepRequest>>(); + private final Map<IExecutionDMContext, Boolean> fTimedOutFlags = new HashMap<IExecutionDMContext, Boolean>(); + private final Map<IExecutionDMContext, ScheduledFuture<?>> fTimedOutFutures = new HashMap<IExecutionDMContext, ScheduledFuture<?>>(); /** * Records the time of the last step for an execution context. */ - private final Map<IExecutionDMContext, Long> fLastStepTimes= new HashMap<IExecutionDMContext, Long>(); + private final Map<IExecutionDMContext, Long> fLastStepTimes = new HashMap<IExecutionDMContext, Long>(); /** * Minimum step interval in milliseconds. */ private volatile int fMinStepInterval; - /** - * Step timeout in milliseconds. - */ - private volatile int fStepTimeout = STEPPING_TIMEOUT; + /** + * Step timeout in milliseconds. + */ + private volatile int fStepTimeout = STEPPING_TIMEOUT; /** * Map of execution contexts for which a step is in progress. @@ -180,81 +180,83 @@ public final class SteppingController { /** * List of registered stepping control participants. */ - private final List<ISteppingControlParticipant> fParticipants = Collections.synchronizedList(new ArrayList<ISteppingControlParticipant>()); + private final List<ISteppingControlParticipant> fParticipants = Collections + .synchronizedList(new ArrayList<ISteppingControlParticipant>()); /** * Property change listener. It updates the stepping control settings. */ private IPropertyChangeListener fPreferencesListener; - public SteppingController(DsfSession session) { - fSession = session; - fServicesTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); - - final IPreferenceStore store= DsfUIPlugin.getDefault().getPreferenceStore(); + public SteppingController(DsfSession session) { + fSession = session; + fServicesTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); + + final IPreferenceStore store = DsfUIPlugin.getDefault().getPreferenceStore(); - fPreferencesListener = new IPropertyChangeListener() { - @Override + fPreferencesListener = new IPropertyChangeListener() { + @Override public void propertyChange(final PropertyChangeEvent event) { - handlePropertyChanged(store, event); - }}; - store.addPropertyChangeListener(fPreferencesListener); - - setMinimumStepInterval(store.getInt(IDsfDebugUIConstants.PREF_MIN_STEP_INTERVAL)); - } - - @ThreadSafe - public void dispose() { - try { - fSession.getExecutor().execute(new DsfRunnable() { - @Override + handlePropertyChanged(store, event); + } + }; + store.addPropertyChangeListener(fPreferencesListener); + + setMinimumStepInterval(store.getInt(IDsfDebugUIConstants.PREF_MIN_STEP_INTERVAL)); + } + + @ThreadSafe + public void dispose() { + try { + fSession.getExecutor().execute(new DsfRunnable() { + @Override public void run() { - if (fRunControl != null) { - getSession().removeServiceEventListener(SteppingController.this); - } - } - }); - } catch (RejectedExecutionException e) { - // Session already gone. - } - - IPreferenceStore store= DsfUIPlugin.getDefault().getPreferenceStore(); - store.removePropertyChangeListener(fPreferencesListener); - - fServicesTracker.dispose(); - } - - /** - * Configure the minimum time (in milliseconds) to wait between steps. - * - * @param interval - */ - @ThreadSafe - public void setMinimumStepInterval(int interval) { - fMinStepInterval = interval; - } - - /** - * Configure the step timeout value. This controls the delay how long it takes - * to send out the {@link SteppingTimedOutEvent} after a step has been issued. - * - * @param timeout The timeout value in milliseconds (must be non-negative). - * @since 2.2 - */ - @ThreadSafe - public void setStepTimeout(int timeout) { - assert timeout >= 0; - fStepTimeout = timeout; - } - - /** - * @return the currently configured step timeout value - * @since 2.2 - */ - @ThreadSafe - public int getStepTimeout() { - return fStepTimeout; - } + if (fRunControl != null) { + getSession().removeServiceEventListener(SteppingController.this); + } + } + }); + } catch (RejectedExecutionException e) { + // Session already gone. + } + + IPreferenceStore store = DsfUIPlugin.getDefault().getPreferenceStore(); + store.removePropertyChangeListener(fPreferencesListener); + + fServicesTracker.dispose(); + } + + /** + * Configure the minimum time (in milliseconds) to wait between steps. + * + * @param interval + */ + @ThreadSafe + public void setMinimumStepInterval(int interval) { + fMinStepInterval = interval; + } + + /** + * Configure the step timeout value. This controls the delay how long it takes + * to send out the {@link SteppingTimedOutEvent} after a step has been issued. + * + * @param timeout The timeout value in milliseconds (must be non-negative). + * @since 2.2 + */ + @ThreadSafe + public void setStepTimeout(int timeout) { + assert timeout >= 0; + fStepTimeout = timeout; + } + + /** + * @return the currently configured step timeout value + * @since 2.2 + */ + @ThreadSafe + public int getStepTimeout() { + return fStepTimeout; + } /** * Register given stepping control participant. @@ -266,53 +268,55 @@ public final class SteppingController { * stepping is disabled until all participants have indicated completion of * processing the event. * </p> - * + * * @param participant */ - @ThreadSafe - public void addSteppingControlParticipant(ISteppingControlParticipant participant) { - fParticipants.add(participant); - } - - /** - * Unregister given stepping control participant. - * - * @param participant - */ - @ThreadSafe - public void removeSteppingControlParticipant(final ISteppingControlParticipant participant) { - fParticipants.remove(participant); - } - - /** - * Indicate that participant has completed processing of the last step. - * - * @param execCtx - */ - public void doneStepping(final IExecutionDMContext execCtx, final ISteppingControlParticipant participant) { - if (DEBUG) System.out.println("[SteppingController] doneStepping participant=" + participant.getClass().getSimpleName()); //$NON-NLS-1$ - List<ISteppingControlParticipant> participants = fStepInProgress.get(execCtx); - if (participants != null) { - participants.remove(participant); - if (participants.isEmpty()) { - doneStepping(execCtx); - } - } else { - for (IExecutionDMContext disabledCtx : fStepInProgress.keySet()) { - if (DMContexts.isAncestorOf(disabledCtx, execCtx)) { - participants = fStepInProgress.get(disabledCtx); - if (participants != null) { - participants.remove(participant); - if (participants.isEmpty()) { - doneStepping(disabledCtx); - } - } - } - } - } - } - - @ThreadSafe + @ThreadSafe + public void addSteppingControlParticipant(ISteppingControlParticipant participant) { + fParticipants.add(participant); + } + + /** + * Unregister given stepping control participant. + * + * @param participant + */ + @ThreadSafe + public void removeSteppingControlParticipant(final ISteppingControlParticipant participant) { + fParticipants.remove(participant); + } + + /** + * Indicate that participant has completed processing of the last step. + * + * @param execCtx + */ + public void doneStepping(final IExecutionDMContext execCtx, final ISteppingControlParticipant participant) { + if (DEBUG) + System.out + .println("[SteppingController] doneStepping participant=" + participant.getClass().getSimpleName()); //$NON-NLS-1$ + List<ISteppingControlParticipant> participants = fStepInProgress.get(execCtx); + if (participants != null) { + participants.remove(participant); + if (participants.isEmpty()) { + doneStepping(execCtx); + } + } else { + for (IExecutionDMContext disabledCtx : fStepInProgress.keySet()) { + if (DMContexts.isAncestorOf(disabledCtx, execCtx)) { + participants = fStepInProgress.get(disabledCtx); + if (participants != null) { + participants.remove(participant); + if (participants.isEmpty()) { + doneStepping(disabledCtx); + } + } + } + } + } + } + + @ThreadSafe public DsfSession getSession() { return fSession; } @@ -321,80 +325,81 @@ public final class SteppingController { * All access to this class should happen through this executor. * @return the executor this class is confined to */ - @ThreadSafe + @ThreadSafe public DsfExecutor getExecutor() { return getSession().getExecutor(); } - + private DsfServicesTracker getServicesTracker() { return fServicesTracker; } private IRunControl getRunControl() { if (fRunControl == null) { - fRunControl = getServicesTracker().getService(IRunControl.class); - getSession().addServiceEventListener(this, null); + fRunControl = getServicesTracker().getService(IRunControl.class); + getSession().addServiceEventListener(this, null); } return fRunControl; } /** - * Checks whether a step command can be queued up for given context. - */ - public void canEnqueueStep(IExecutionDMContext execCtx, StepType stepType, DataRequestMonitor<Boolean> rm) { - if (doCanEnqueueStep(execCtx, stepType)) { - rm.setData(true); - rm.done(); - } else { - getRunControl().canStep(execCtx, stepType, rm); - } - } - - private boolean doCanEnqueueStep(IExecutionDMContext execCtx, StepType stepType) { - return getRunControl().isStepping(execCtx) && !isSteppingTimedOut(execCtx); - } - - /** - * Check whether the next step on the given execution context should be delayed - * based on the configured step delay. - * + * Checks whether a step command can be queued up for given context. + */ + public void canEnqueueStep(IExecutionDMContext execCtx, StepType stepType, DataRequestMonitor<Boolean> rm) { + if (doCanEnqueueStep(execCtx, stepType)) { + rm.setData(true); + rm.done(); + } else { + getRunControl().canStep(execCtx, stepType, rm); + } + } + + private boolean doCanEnqueueStep(IExecutionDMContext execCtx, StepType stepType) { + return getRunControl().isStepping(execCtx) && !isSteppingTimedOut(execCtx); + } + + /** + * Check whether the next step on the given execution context should be delayed + * based on the configured step delay. + * * @param execCtx * @return <code>true</code> if the step should be delayed */ private boolean shouldDelayStep(IExecutionDMContext execCtx) { - final int stepDelay= getStepDelay(execCtx); - if (DEBUG) System.out.println("[SteppingController] shouldDelayStep delay=" + stepDelay); //$NON-NLS-1$ + final int stepDelay = getStepDelay(execCtx); + if (DEBUG) + System.out.println("[SteppingController] shouldDelayStep delay=" + stepDelay); //$NON-NLS-1$ return stepDelay > 0; } /** * Compute the delay in milliseconds before the next step for the given context may be executed. - * + * * @param execCtx * @return the number of milliseconds before the next possible step */ private int getStepDelay(IExecutionDMContext execCtx) { - int minStepInterval = fMinStepInterval; + int minStepInterval = fMinStepInterval; if (minStepInterval > 0) { - for (IExecutionDMContext lastStepCtx : fLastStepTimes.keySet()) { - if (execCtx.equals(lastStepCtx) || DMContexts.isAncestorOf(execCtx, lastStepCtx)) { - long now = System.currentTimeMillis(); - int delay= (int) (fLastStepTimes.get(lastStepCtx) + minStepInterval - now); + for (IExecutionDMContext lastStepCtx : fLastStepTimes.keySet()) { + if (execCtx.equals(lastStepCtx) || DMContexts.isAncestorOf(execCtx, lastStepCtx)) { + long now = System.currentTimeMillis(); + int delay = (int) (fLastStepTimes.get(lastStepCtx) + minStepInterval - now); return Math.max(delay, 0); - } - } + } + } } - return 0; + return 0; } private void updateLastStepTime(IExecutionDMContext execCtx) { - long now = System.currentTimeMillis(); + long now = System.currentTimeMillis(); fLastStepTimes.put(execCtx, now); - for (IExecutionDMContext lastStepCtx : fLastStepTimes.keySet()) { - if (!execCtx.equals(lastStepCtx) && DMContexts.isAncestorOf(execCtx, lastStepCtx)) { + for (IExecutionDMContext lastStepCtx : fLastStepTimes.keySet()) { + if (!execCtx.equals(lastStepCtx) && DMContexts.isAncestorOf(execCtx, lastStepCtx)) { fLastStepTimes.put(lastStepCtx, now); - } - } + } + } } private long getLastStepTime(IExecutionDMContext execCtx) { @@ -410,99 +415,103 @@ public final class SteppingController { } /** - * Returns the number of step commands that are queued for given execution - * context. - */ - public int getPendingStepCount(IExecutionDMContext execCtx) { - List<StepRequest> stepQueue = getStepQueue(execCtx); - if (stepQueue == null) return 0; - return stepQueue.size(); - } - - /** - * Adds a step command to the execution queue for given context. - * @param execCtx Execution context that should perform the step. - * @param stepType Type of step to execute. - */ - public void enqueueStep(final IExecutionDMContext execCtx, final StepType stepType) { - if (DEBUG) System.out.println("[SteppingController] enqueueStep ctx=" + execCtx); //$NON-NLS-1$ - if (!shouldDelayStep(execCtx) || doCanEnqueueStep(execCtx, stepType)) { - doEnqueueStep(execCtx, stepType); - processStepQueue(execCtx); - } - } + * Returns the number of step commands that are queued for given execution + * context. + */ + public int getPendingStepCount(IExecutionDMContext execCtx) { + List<StepRequest> stepQueue = getStepQueue(execCtx); + if (stepQueue == null) + return 0; + return stepQueue.size(); + } + + /** + * Adds a step command to the execution queue for given context. + * @param execCtx Execution context that should perform the step. + * @param stepType Type of step to execute. + */ + public void enqueueStep(final IExecutionDMContext execCtx, final StepType stepType) { + if (DEBUG) + System.out.println("[SteppingController] enqueueStep ctx=" + execCtx); //$NON-NLS-1$ + if (!shouldDelayStep(execCtx) || doCanEnqueueStep(execCtx, stepType)) { + doEnqueueStep(execCtx, stepType); + processStepQueue(execCtx); + } + } private void doStep(final IExecutionDMContext execCtx, final StepType stepType) { - if (DEBUG) System.out.println("[SteppingController] doStep ctx="+execCtx); //$NON-NLS-1$ - disableStepping(execCtx); - updateLastStepTime(execCtx); - + if (DEBUG) + System.out.println("[SteppingController] doStep ctx=" + execCtx); //$NON-NLS-1$ + disableStepping(execCtx); + updateLastStepTime(execCtx); + getRunControl().step(execCtx, stepType, new RequestMonitor(getExecutor(), null) { - @Override - protected void handleSuccess() { - fTimedOutFlags.remove(execCtx); - ScheduledFuture<?> currentTimeOutFuture = fTimedOutFutures.get(execCtx); - if (currentTimeOutFuture != null) { - currentTimeOutFuture.cancel(false); - } - fTimedOutFutures.put(execCtx, getExecutor().schedule(new TimeOutRunnable(execCtx), fStepTimeout, TimeUnit.MILLISECONDS)); - } - - @Override - protected void handleFailure() { - // in case of a failed step - enable stepping again (bug 265267) - enableStepping(execCtx); - if (getStatus().getCode() == IDsfStatusConstants.INVALID_STATE) { - // Ignore errors. During fast stepping there can be expected race - // conditions leading to stepping errors. - return; - } - super.handleFailure(); - } - - @Override - protected void handleError() { - super.handleError(); - CDebugUtils.error(getStatus(), SteppingController.this); - } + @Override + protected void handleSuccess() { + fTimedOutFlags.remove(execCtx); + ScheduledFuture<?> currentTimeOutFuture = fTimedOutFutures.get(execCtx); + if (currentTimeOutFuture != null) { + currentTimeOutFuture.cancel(false); + } + fTimedOutFutures.put(execCtx, + getExecutor().schedule(new TimeOutRunnable(execCtx), fStepTimeout, TimeUnit.MILLISECONDS)); + } + + @Override + protected void handleFailure() { + // in case of a failed step - enable stepping again (bug 265267) + enableStepping(execCtx); + if (getStatus().getCode() == IDsfStatusConstants.INVALID_STATE) { + // Ignore errors. During fast stepping there can be expected race + // conditions leading to stepping errors. + return; + } + super.handleFailure(); + } + + @Override + protected void handleError() { + super.handleError(); + CDebugUtils.error(getStatus(), SteppingController.this); + } }); } /** * Enqueue the given step for later execution. - * + * * @param execCtx * @param stepType */ private void doEnqueueStep(final IExecutionDMContext execCtx, final StepType stepType) { List<StepRequest> stepQueue = fStepQueues.get(execCtx); if (stepQueue == null) { - stepQueue = new LinkedList<StepRequest>(); - fStepQueues.put(execCtx, stepQueue); + stepQueue = new LinkedList<StepRequest>(); + fStepQueues.put(execCtx, stepQueue); } if (stepQueue.size() < fQueueDepth) { - stepQueue.add(new StepRequest(execCtx, stepType)); + stepQueue.add(new StepRequest(execCtx, stepType)); } } - /** - * Returns whether the step instruction for the given context has timed out. - */ - public boolean isSteppingTimedOut(IExecutionDMContext execCtx) { - for (IExecutionDMContext timedOutCtx : fTimedOutFlags.keySet()) { - if (execCtx.equals(timedOutCtx) || DMContexts.isAncestorOf(execCtx, timedOutCtx)) { - return fTimedOutFlags.get(timedOutCtx); - } - } - return false; - } - + /** + * Returns whether the step instruction for the given context has timed out. + */ + public boolean isSteppingTimedOut(IExecutionDMContext execCtx) { + for (IExecutionDMContext timedOutCtx : fTimedOutFlags.keySet()) { + if (execCtx.equals(timedOutCtx) || DMContexts.isAncestorOf(execCtx, timedOutCtx)) { + return fTimedOutFlags.get(timedOutCtx); + } + } + return false; + } + /** * Process next step on queue if any. * @param execCtx */ private void processStepQueue(final IExecutionDMContext execCtx) { - final List<StepRequest> queue = getStepQueue(execCtx); + final List<StepRequest> queue = getStepQueue(execCtx); if (queue != null) { final int stepDelay = getStepDelay(execCtx); if (stepDelay > 0) { @@ -514,49 +523,50 @@ public final class SteppingController { }, stepDelay, TimeUnit.MILLISECONDS); return; } - final StepRequest request = queue.get(0); - if (DEBUG) System.out.println("[SteppingController] processStepQueue request-in-progress="+request.inProgress); //$NON-NLS-1$ - if (!request.inProgress) { - if (isSteppingDisabled(request.fContext)) { - return; - } - request.inProgress = true; - getRunControl().canStep( - request.fContext, request.fStepType, - new DataRequestMonitor<Boolean>(getExecutor(), null) { - @Override - protected void handleCompleted() { - if (isSuccess() && getData()) { - queue.remove(0); - if (queue.isEmpty()) fStepQueues.remove(request.fContext); - doStep(request.fContext, request.fStepType); - } else { - // For whatever reason we can't step anymore, so clear out - // the step queue. - fStepQueues.remove(request.fContext); - } - } - }); - } - } + final StepRequest request = queue.get(0); + if (DEBUG) + System.out.println("[SteppingController] processStepQueue request-in-progress=" + request.inProgress); //$NON-NLS-1$ + if (!request.inProgress) { + if (isSteppingDisabled(request.fContext)) { + return; + } + request.inProgress = true; + getRunControl().canStep(request.fContext, request.fStepType, + new DataRequestMonitor<Boolean>(getExecutor(), null) { + @Override + protected void handleCompleted() { + if (isSuccess() && getData()) { + queue.remove(0); + if (queue.isEmpty()) + fStepQueues.remove(request.fContext); + doStep(request.fContext, request.fStepType); + } else { + // For whatever reason we can't step anymore, so clear out + // the step queue. + fStepQueues.remove(request.fContext); + } + } + }); + } + } } private List<StepRequest> getStepQueue(IExecutionDMContext execCtx) { List<StepRequest> queue = fStepQueues.get(execCtx); if (queue == null) { - for (IExecutionDMContext stepCtx : fStepQueues.keySet()) { - if (DMContexts.isAncestorOf(stepCtx, execCtx)) { - queue = fStepQueues.get(stepCtx); - break; - } - } + for (IExecutionDMContext stepCtx : fStepQueues.keySet()) { + if (DMContexts.isAncestorOf(stepCtx, execCtx)) { + queue = fStepQueues.get(stepCtx); + break; + } + } } return queue; } /** * Disable stepping for the given execution context. - * + * * @param execCtx */ private void disableStepping(IExecutionDMContext execCtx) { @@ -565,25 +575,26 @@ public final class SteppingController { } } - /** - * Indicate that processing of the last step has completed and - * the next step can be issued. - * - * @param execCtx - */ - private void doneStepping(final IExecutionDMContext execCtx) { - if (DEBUG) System.out.println("[SteppingController] doneStepping ctx=" + execCtx); //$NON-NLS-1$ - enableStepping(execCtx); - processStepQueue(execCtx); - } + /** + * Indicate that processing of the last step has completed and + * the next step can be issued. + * + * @param execCtx + */ + private void doneStepping(final IExecutionDMContext execCtx) { + if (DEBUG) + System.out.println("[SteppingController] doneStepping ctx=" + execCtx); //$NON-NLS-1$ + enableStepping(execCtx); + processStepQueue(execCtx); + } /** * Enable stepping for the given execution context. - * + * * @param execCtx */ public void enableStepping(final IExecutionDMContext execCtx) { - fStepInProgress.remove(execCtx); + fStepInProgress.remove(execCtx); for (IExecutionDMContext disabledCtx : fStepInProgress.keySet()) { if (DMContexts.isAncestorOf(disabledCtx, execCtx)) { fStepInProgress.remove(disabledCtx); @@ -592,25 +603,26 @@ public final class SteppingController { } private boolean isSteppingDisabled(IExecutionDMContext execCtx) { - boolean disabled= fStepInProgress.containsKey(execCtx); - if (!disabled) { - for (IExecutionDMContext disabledCtx : fStepInProgress.keySet()) { + boolean disabled = fStepInProgress.containsKey(execCtx); + if (!disabled) { + for (IExecutionDMContext disabledCtx : fStepInProgress.keySet()) { if (DMContexts.isAncestorOf(execCtx, disabledCtx)) { disabled = true; break; } } - } - if (disabled) { - long now = System.currentTimeMillis(); - long lastStepTime = getLastStepTime(execCtx); - if (now - lastStepTime > MAX_STEP_DELAY) { - if (DEBUG) System.out.println("[SteppingController] stepping control participant(s) timed out"); //$NON-NLS-1$ - enableStepping(execCtx); - disabled = false; - } - } - return disabled; + } + if (disabled) { + long now = System.currentTimeMillis(); + long lastStepTime = getLastStepTime(execCtx); + if (now - lastStepTime > MAX_STEP_DELAY) { + if (DEBUG) + System.out.println("[SteppingController] stepping control participant(s) timed out"); //$NON-NLS-1$ + enableStepping(execCtx); + disabled = false; + } + } + return disabled; } protected void handlePropertyChanged(final IPreferenceStore store, final PropertyChangeEvent event) { @@ -620,71 +632,73 @@ public final class SteppingController { } } + /////////////////////////////////////////////////////////////////////////// + + @DsfServiceEventHandler + public void eventDispatched(final ISuspendedDMEvent e) { + // Take care of the stepping time out + boolean timedOut = false; + IExecutionDMContext dmc = e.getDMContext(); + for (Iterator<Map.Entry<IExecutionDMContext, Boolean>> itr = fTimedOutFlags.entrySet().iterator(); itr + .hasNext();) { + Map.Entry<IExecutionDMContext, Boolean> entry = itr.next(); + IExecutionDMContext nextDmc = entry.getKey(); + if (nextDmc.equals(dmc) || DMContexts.isAncestorOf(nextDmc, dmc)) { + if (entry.getValue()) { + // after step timeout do not process queued steps + fStepQueues.remove(dmc); + timedOut = true; + } + itr.remove(); + } + } + + // Cancel all time-out futures related to the event context. I.e. + // - If event is on a container, all child threads are suspended and + // should not issue a stepping time-out event. + // - If event is on a thread, and resumed event was on a container then + // stepping timeout for container should be canceled as it would affect + // suspended thread. + for (Iterator<Map.Entry<IExecutionDMContext, ScheduledFuture<?>>> itr = fTimedOutFutures.entrySet() + .iterator(); itr.hasNext();) { + Map.Entry<IExecutionDMContext, ScheduledFuture<?>> entry = itr.next(); + IExecutionDMContext nextDmc = entry.getKey(); + if (nextDmc.equals(dmc) || DMContexts.isAncestorOf(nextDmc, dmc) || DMContexts.isAncestorOf(dmc, nextDmc)) { + entry.getValue().cancel(false); + itr.remove(); + } + } - /////////////////////////////////////////////////////////////////////////// - - @DsfServiceEventHandler - public void eventDispatched(final ISuspendedDMEvent e) { - // Take care of the stepping time out - boolean timedOut = false; - IExecutionDMContext dmc = e.getDMContext(); - for (Iterator<Map.Entry<IExecutionDMContext, Boolean>> itr = fTimedOutFlags.entrySet().iterator(); itr.hasNext();) { - Map.Entry<IExecutionDMContext,Boolean> entry = itr.next(); - IExecutionDMContext nextDmc = entry.getKey(); - if (nextDmc.equals(dmc) || DMContexts.isAncestorOf(nextDmc, dmc)) { - if (entry.getValue()) { - // after step timeout do not process queued steps - fStepQueues.remove(dmc); - timedOut = true; - } - itr.remove(); - } - } - - // Cancel all time-out futures related to the event context. I.e. - // - If event is on a container, all child threads are suspended and - // should not issue a stepping time-out event. - // - If event is on a thread, and resumed event was on a container then - // stepping timeout for container should be canceled as it would affect - // suspended thread. - for (Iterator<Map.Entry<IExecutionDMContext, ScheduledFuture<?>>> itr = fTimedOutFutures.entrySet().iterator(); itr.hasNext();) { - Map.Entry<IExecutionDMContext, ScheduledFuture<?>> entry = itr.next(); - IExecutionDMContext nextDmc = entry.getKey(); - if (nextDmc.equals(dmc) || DMContexts.isAncestorOf(nextDmc, dmc) || DMContexts.isAncestorOf(dmc, nextDmc)) { - entry.getValue().cancel(false); - itr.remove(); - } - } - - if (e.getReason() != StateChangeReason.STEP) { - // after any non-step suspend reason do not process queued steps for given context - fStepQueues.remove(dmc); - } else if (!timedOut){ - // Check if there's a step pending, if so execute it - processStepQueue(dmc); - } - } - - @DsfServiceEventHandler - public void eventDispatched(final IResumedDMEvent e) { - if (e.getReason().equals(StateChangeReason.STEP)) { - final IExecutionDMContext dmc = e.getDMContext(); - fTimedOutFlags.remove(dmc); - - - // Find any time-out futures for contexts that are children of the - // resumed context, and cancel them as they'll be replaced. - if (!fTimedOutFutures.containsKey(dmc)) { - for (Iterator<Map.Entry<IExecutionDMContext, ScheduledFuture<?>>> itr = fTimedOutFutures.entrySet().iterator(); itr.hasNext();) { - Map.Entry<IExecutionDMContext, ScheduledFuture<?>> entry = itr.next(); - if (DMContexts.isAncestorOf(entry.getKey(), dmc)) { - entry.getValue().cancel(false); - itr.remove(); - } - } - - fTimedOutFutures.put(dmc, getExecutor().schedule(new TimeOutRunnable(dmc), fStepTimeout, TimeUnit.MILLISECONDS)); - } - } - } + if (e.getReason() != StateChangeReason.STEP) { + // after any non-step suspend reason do not process queued steps for given context + fStepQueues.remove(dmc); + } else if (!timedOut) { + // Check if there's a step pending, if so execute it + processStepQueue(dmc); + } + } + + @DsfServiceEventHandler + public void eventDispatched(final IResumedDMEvent e) { + if (e.getReason().equals(StateChangeReason.STEP)) { + final IExecutionDMContext dmc = e.getDMContext(); + fTimedOutFlags.remove(dmc); + + // Find any time-out futures for contexts that are children of the + // resumed context, and cancel them as they'll be replaced. + if (!fTimedOutFutures.containsKey(dmc)) { + for (Iterator<Map.Entry<IExecutionDMContext, ScheduledFuture<?>>> itr = fTimedOutFutures.entrySet() + .iterator(); itr.hasNext();) { + Map.Entry<IExecutionDMContext, ScheduledFuture<?>> entry = itr.next(); + if (DMContexts.isAncestorOf(entry.getKey(), dmc)) { + entry.getValue().cancel(false); + itr.remove(); + } + } + + fTimedOutFutures.put(dmc, + getExecutor().schedule(new TimeOutRunnable(dmc), fStepTimeout, TimeUnit.MILLISECONDS)); + } + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/AbstractVMProviderActionDelegate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/AbstractVMProviderActionDelegate.java index 6e86e74d45a..a189f42f00b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/AbstractVMProviderActionDelegate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/AbstractVMProviderActionDelegate.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Ted R Williams (Wind River Systems, Inc.) - initial implementation *******************************************************************************/ @@ -35,81 +35,86 @@ import org.eclipse.ui.IViewPart; /** * @since 1.1 */ -abstract public class AbstractVMProviderActionDelegate implements IViewActionDelegate, IDebugContextListener, IActionDelegate2 { +abstract public class AbstractVMProviderActionDelegate + implements IViewActionDelegate, IDebugContextListener, IActionDelegate2 { + + private IViewPart fView = null; + private IAction fAction = null; + private ISelection fDebugContext; - private IViewPart fView = null; - private IAction fAction = null; - private ISelection fDebugContext; - - @Override + @Override public void init(IViewPart view) { - fView = view; - - // Get the current selection from the DebugView so we can determine if we want this menu action to be live or not. - IDebugContextService debugContextService = DebugUITools.getDebugContextManager().getContextService(view.getSite().getWorkbenchWindow()); - debugContextService.addPostDebugContextListener(this); - fDebugContext = debugContextService.getActiveContext(); + fView = view; + + // Get the current selection from the DebugView so we can determine if we want this menu action to be live or not. + IDebugContextService debugContextService = DebugUITools.getDebugContextManager() + .getContextService(view.getSite().getWorkbenchWindow()); + debugContextService.addPostDebugContextListener(this); + fDebugContext = debugContextService.getActiveContext(); + } + + @Override + public void selectionChanged(IAction action, ISelection selection) { + if (fAction != action) { + fAction = action; + } + } + + @Override + public void runWithEvent(IAction action, Event event) { + run(action); + } + + @Override + public void init(IAction action) { + fAction = action; + } + + @Override + public void dispose() { + DebugUITools.getDebugContextManager().getContextService(getView().getSite().getWorkbenchWindow()) + .removePostDebugContextListener(this); + } + + @Override + public void debugContextChanged(DebugContextEvent event) { + fDebugContext = event.getContext(); + } + + protected IViewPart getView() { + return fView; + } + + protected IAction getAction() { + return fAction; + } + + protected Object getViewerInput() { + if (fDebugContext instanceof IStructuredSelection) { + return ((IStructuredSelection) fDebugContext).getFirstElement(); + } + return null; } - @Override - public void selectionChanged(IAction action, ISelection selection) { - if (fAction != action) { - fAction = action; - } - } - - @Override - public void runWithEvent(IAction action, Event event) { - run(action); - } - - @Override - public void init(IAction action) { - fAction = action; - } - - @Override - public void dispose() { - DebugUITools.getDebugContextManager().getContextService(getView().getSite().getWorkbenchWindow()).removePostDebugContextListener(this); - } - - @Override - public void debugContextChanged(DebugContextEvent event) { - fDebugContext = event.getContext(); - } - - protected IViewPart getView() { return fView; } - - protected IAction getAction() { return fAction; } - - protected Object getViewerInput() { - if (fDebugContext instanceof IStructuredSelection) { - return ((IStructuredSelection)fDebugContext).getFirstElement(); - } - return null; - } - protected IVMProvider getVMProvider() { - Object viewerInput = getViewerInput(); - IPresentationContext presentationContext = getPresentationContext(); - - if (viewerInput instanceof IAdaptable && presentationContext != null) { - IVMAdapter adapter = ((IAdaptable)viewerInput).getAdapter(IVMAdapter.class); - - if ( adapter != null ) { - return adapter.getVMProvider(presentationContext); - } - } - - return null; + Object viewerInput = getViewerInput(); + IPresentationContext presentationContext = getPresentationContext(); + + if (viewerInput instanceof IAdaptable && presentationContext != null) { + IVMAdapter adapter = ((IAdaptable) viewerInput).getAdapter(IVMAdapter.class); + + if (adapter != null) { + return adapter.getVMProvider(presentationContext); + } + } + + return null; } - protected IPresentationContext getPresentationContext() { - if (fView instanceof AbstractDebugView && - ((AbstractDebugView) fView).getViewer() instanceof TreeModelViewer) - { - return ((TreeModelViewer) ((AbstractDebugView) fView).getViewer()).getPresentationContext(); - } - return null; + protected IPresentationContext getPresentationContext() { + if (fView instanceof AbstractDebugView && ((AbstractDebugView) fView).getViewer() instanceof TreeModelViewer) { + return ((TreeModelViewer) ((AbstractDebugView) fView).getViewer()).getPresentationContext(); + } + return null; } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/DefaultRefreshAllTarget.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/DefaultRefreshAllTarget.java index 6113a373175..b9e4dbfbd7c 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/DefaultRefreshAllTarget.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/DefaultRefreshAllTarget.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -22,37 +22,37 @@ import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; /** - * The default implementation of the refresh all debug target which + * The default implementation of the refresh all debug target which * calls the active VM providers, to ask them to refresh. - * + * * @since 1.1 */ public class DefaultRefreshAllTarget implements IRefreshAllTarget { - @Override + @Override public void refresh(ISelection debugContext) throws CoreException { - IVMAdapter adapter = getActiveVMAdapter( debugContext ); + IVMAdapter adapter = getActiveVMAdapter(debugContext); - if (adapter != null) { - for (IVMProvider provider : adapter.getActiveProviders()) { - if (provider instanceof ICachingVMProvider) { - ((ICachingVMProvider)provider).refresh(); - } - } - } - } + if (adapter != null) { + for (IVMProvider provider : adapter.getActiveProviders()) { + if (provider instanceof ICachingVMProvider) { + ((ICachingVMProvider) provider).refresh(); + } + } + } + } - /** + /** * @since 2.0 */ - protected IVMAdapter getActiveVMAdapter(ISelection debugContext) { - - if (debugContext instanceof IStructuredSelection) { - Object activeElement = ((IStructuredSelection)debugContext).getFirstElement(); - if (activeElement instanceof IAdaptable) { - return ((IAdaptable)activeElement).getAdapter(IVMAdapter.class); - } - } - return null; - } + protected IVMAdapter getActiveVMAdapter(ISelection debugContext) { + + if (debugContext instanceof IStructuredSelection) { + Object activeElement = ((IStructuredSelection) debugContext).getFirstElement(); + if (activeElement instanceof IAdaptable) { + return ((IAdaptable) activeElement).getAdapter(IVMAdapter.class); + } + } + return null; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/IRefreshAllTarget.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/IRefreshAllTarget.java index 4e0e321c682..6de67a789cd 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/IRefreshAllTarget.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/IRefreshAllTarget.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,16 +19,16 @@ import org.eclipse.jface.viewers.ISelection; /** * A retargetable action target which allows a debugger to refresh all of its * active views with fresh data from the debug target. - * + * * @since 1.1 */ public interface IRefreshAllTarget { - - /** - * Refreshes the debugger data of the given debug context. - * @param debugContext The active window debug context. - * - * @throws CoreException - */ - public void refresh(ISelection debugContext) throws CoreException; + + /** + * Refreshes the debugger data of the given debug context. + * @param debugContext The active window debug context. + * + * @throws CoreException + */ + public void refresh(ISelection debugContext) throws CoreException; } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/VMHandlerUtils.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/VMHandlerUtils.java index 473104b2953..6c5a88a239d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/VMHandlerUtils.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/actions/VMHandlerUtils.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Winnie Lai (Texas Instruments) - Individual Element Number Format (Bug 202556) @@ -40,153 +40,149 @@ import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.services.IServiceLocator; /** - * Static utility methods for use with View Model related + * Static utility methods for use with View Model related * commands and handlers. - * + * * @since 1.1 */ public class VMHandlerUtils { - /** - * Retrieves the active VM provider based on the currently active - * selection and part. - * @param serviceLocator Service locator for access to active selection - * and part. - * - * @return The active VM provder. - */ - static public IVMProvider getActiveVMProvider(IServiceLocator serviceLocator) { - ISelection selection = null; - - ISelectionService selectionService = - serviceLocator.getService(ISelectionService.class); - if (selectionService != null) { - selection = selectionService.getSelection(); - } - - if (selection != null && !selection.isEmpty()) { - return getVMProviderForSelection(selection); - } - else { - IWorkbenchPart part = null; - IPartService partService = serviceLocator.getService(IPartService.class); - if (partService != null) { - part = partService.getActivePart(); - return getVMProviderForPart(part); - } - return null; - } - } + /** + * Retrieves the active VM provider based on the currently active + * selection and part. + * @param serviceLocator Service locator for access to active selection + * and part. + * + * @return The active VM provder. + */ + static public IVMProvider getActiveVMProvider(IServiceLocator serviceLocator) { + ISelection selection = null; + + ISelectionService selectionService = serviceLocator.getService(ISelectionService.class); + if (selectionService != null) { + selection = selectionService.getSelection(); + } + + if (selection != null && !selection.isEmpty()) { + return getVMProviderForSelection(selection); + } else { + IWorkbenchPart part = null; + IPartService partService = serviceLocator.getService(IPartService.class); + if (partService != null) { + part = partService.getActivePart(); + return getVMProviderForPart(part); + } + return null; + } + } + + /** + * Retrieves the active VM provider based on the given execution event. + * @param event The execution event which is usually given as an argument + * to the command handler execution call. + * + * @return The active VM provder. + */ + static public IVMProvider getActiveVMProvider(ExecutionEvent event) { + ISelection selection = HandlerUtil.getCurrentSelection(event); + if (selection != null && !selection.isEmpty()) { + return getVMProviderForSelection(selection); + } else { + IWorkbenchPart part = HandlerUtil.getActivePart(event); + return getVMProviderForPart(part); + } + } + + /** + * Retrieves the selection from a given service locator's selection service. + * @param serviceLocator Service locator for access to active selection + * and part. + * + * @return The selection if available; return null otherwise. + * @since 2.2 + */ + static public ISelection getSelection(IServiceLocator serviceLocator) { + ISelectionService selectionService = serviceLocator.getService(ISelectionService.class); + if (selectionService != null) { + return selectionService.getSelection(); + } + return null; + } + + public static IVMProvider getVMProviderForPart(IWorkbenchPart part) { + IDebugContextService contextService = DebugUITools.getDebugContextManager() + .getContextService(part.getSite().getWorkbenchWindow()); + + ISelection debugContext = contextService.getActiveContext(getPartId(part)); + if (debugContext == null) { + debugContext = contextService.getActiveContext(); + } + + Object input = null; + if (debugContext instanceof IStructuredSelection) { + input = ((IStructuredSelection) debugContext).getFirstElement(); + } - /** - * Retrieves the active VM provider based on the given execution event. - * @param event The execution event which is usually given as an argument - * to the command handler execution call. - * - * @return The active VM provder. - */ - static public IVMProvider getActiveVMProvider(ExecutionEvent event) { - ISelection selection = HandlerUtil.getCurrentSelection(event); - if (selection != null && !selection.isEmpty()) { - return getVMProviderForSelection(selection); - } - else { - IWorkbenchPart part = HandlerUtil.getActivePart(event); - return getVMProviderForPart(part); - } - } + if (part instanceof IDebugView) { + Viewer viewer = ((IDebugView) part).getViewer(); + if (input instanceof IAdaptable && viewer instanceof TreeModelViewer) { + IPresentationContext presContext = ((TreeModelViewer) viewer).getPresentationContext(); + IVMAdapter vmAdapter = ((IAdaptable) input).getAdapter(IVMAdapter.class); + if (vmAdapter != null) { + return vmAdapter.getVMProvider(presContext); + } + } + } + return null; + } - /** - * Retrieves the selection from a given service locator's selection service. - * @param serviceLocator Service locator for access to active selection - * and part. - * - * @return The selection if available; return null otherwise. - * @since 2.2 - */ - static public ISelection getSelection(IServiceLocator serviceLocator) { - ISelectionService selectionService = - serviceLocator.getService(ISelectionService.class); - if (selectionService != null) { - return selectionService.getSelection(); - } - return null; - } + private static String getPartId(IWorkbenchPart part) { + if (part instanceof IViewPart) { + IViewSite site = (IViewSite) part.getSite(); + return site.getId() + (site.getSecondaryId() != null ? (":" + site.getSecondaryId()) : ""); //$NON-NLS-1$ //$NON-NLS-2$ + } else { + return part.getSite().getId(); + } + } - public static IVMProvider getVMProviderForPart(IWorkbenchPart part) { - IDebugContextService contextService = - DebugUITools.getDebugContextManager().getContextService(part.getSite().getWorkbenchWindow()); + public static IVMProvider getVMProviderForSelection(ISelection selection) { + if (selection instanceof IStructuredSelection) { + Object element = ((IStructuredSelection) selection).getFirstElement(); + if (element instanceof IVMContext) { + return ((IVMContext) element).getVMNode().getVMProvider(); + } + } + return null; + } - ISelection debugContext = contextService.getActiveContext(getPartId(part)); - if (debugContext == null) { - debugContext = contextService.getActiveContext(); - } - - Object input = null; - if (debugContext instanceof IStructuredSelection) { - input = ((IStructuredSelection)debugContext).getFirstElement(); - } - - if (part instanceof IDebugView) { - Viewer viewer = ((IDebugView)part).getViewer(); - if (input instanceof IAdaptable && viewer instanceof TreeModelViewer) { - IPresentationContext presContext = ((TreeModelViewer)viewer).getPresentationContext(); - IVMAdapter vmAdapter = ((IAdaptable)input).getAdapter(IVMAdapter.class); - if (vmAdapter != null) { - return vmAdapter.getVMProvider(presContext); - } - } - } - return null; - } - - private static String getPartId(IWorkbenchPart part) { - if (part instanceof IViewPart) { - IViewSite site = (IViewSite)part.getSite(); - return site.getId() + (site.getSecondaryId() != null ? (":" + site.getSecondaryId()) : ""); //$NON-NLS-1$ //$NON-NLS-2$ - } else { - return part.getSite().getId(); - } - } - - public static IVMProvider getVMProviderForSelection(ISelection selection) { - if (selection instanceof IStructuredSelection) { - Object element = ((IStructuredSelection)selection).getFirstElement(); - if (element instanceof IVMContext) { - return ((IVMContext)element).getVMNode().getVMProvider(); - } - } - return null; - } - - /** - * Returns the viewer input element for the viewer in the given - * presentation context. The input element is retrieved only if the - * presentation context's view is based on the {@link AbstractDebugView}. - * Returns <code>null</code> if not found. - * @since 2.5 - */ - public static Object getViewerInput(IPresentationContext context) { - if (context.getPart() instanceof AbstractDebugView) { - Viewer viewer = ((AbstractDebugView)context.getPart()).getViewer(); - if (viewer != null) { - return viewer.getInput(); - } - } - return null; - } + /** + * Returns the viewer input element for the viewer in the given + * presentation context. The input element is retrieved only if the + * presentation context's view is based on the {@link AbstractDebugView}. + * Returns <code>null</code> if not found. + * @since 2.5 + */ + public static Object getViewerInput(IPresentationContext context) { + if (context.getPart() instanceof AbstractDebugView) { + Viewer viewer = ((AbstractDebugView) context.getPart()).getViewer(); + if (viewer != null) { + return viewer.getInput(); + } + } + return null; + } - /** - * Returns the {@link IVMNode} associated with the element in the - * given path. Returns <code>null</code> if not found. - * - * @since 2.5 - */ - public static IVMNode getVMNode(Object viewerInput, TreePath path) { - if (path.getSegmentCount() != 0) { - return (IVMNode) DebugPlugin.getAdapter(path.getLastSegment(), IVMNode.class); - } else { - return (IVMNode) DebugPlugin.getAdapter(viewerInput, IVMNode.class); - } - } + /** + * Returns the {@link IVMNode} associated with the element in the + * given path. Returns <code>null</code> if not found. + * + * @since 2.5 + */ + public static IVMNode getVMNode(Object viewerInput, TreePath path) { + if (path.getSegmentCount() != 0) { + return (IVMNode) DebugPlugin.getAdapter(path.getLastSegment(), IVMNode.class); + } else { + return (IVMNode) DebugPlugin.getAdapter(viewerInput, IVMNode.class); + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/AbstractBreakpointVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/AbstractBreakpointVMNode.java index 344cd867f76..7214a946ab0 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/AbstractBreakpointVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/AbstractBreakpointVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -38,270 +38,273 @@ import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IWorkbenchWindow; /** - * Base class for breakpoint VM Nodes. Concrete implementations must - * implement the breakpoint object to be populated into the view. + * Base class for breakpoint VM Nodes. Concrete implementations must + * implement the breakpoint object to be populated into the view. * Also this node only implements the content provider so sub-classes * must also implement a label provider, element editor, etc. - * + * * @since 2.1 */ public abstract class AbstractBreakpointVMNode extends AbstractVMNode { - public AbstractBreakpointVMNode(BreakpointVMProvider provider) { - super(provider); - } + public AbstractBreakpointVMNode(BreakpointVMProvider provider) { + super(provider); + } + + /** + * Class that creates the element object for the corresponding breakpoints. + * This element object will be populated in the breakpoints view to represent + * the given breakpoint. + */ + abstract protected Object createBreakpiontElement(IBreakpoint bp); - /** - * Class that creates the element object for the corresponding breakpoints. - * This element object will be populated in the breakpoints view to represent - * the given breakpoint. - */ - abstract protected Object createBreakpiontElement(IBreakpoint bp); - - @Override + @Override public void update(final IHasChildrenUpdate[] updates) { - for (final IHasChildrenUpdate update : updates) { - if (!checkUpdate(update)) continue; - ((BreakpointVMProvider)getVMProvider()).getNestingCategoryBreakpoints( - update.getElementPath(), - new ViewerDataRequestMonitor<IBreakpoint[]>(getExecutor(), update) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - update.setHasChilren(getData().length != 0); - } else { - update.setHasChilren(false); - } - update.done(); - } - }); - } - } + for (final IHasChildrenUpdate update : updates) { + if (!checkUpdate(update)) + continue; + ((BreakpointVMProvider) getVMProvider()).getNestingCategoryBreakpoints(update.getElementPath(), + new ViewerDataRequestMonitor<IBreakpoint[]>(getExecutor(), update) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + update.setHasChilren(getData().length != 0); + } else { + update.setHasChilren(false); + } + update.done(); + } + }); + } + } - @Override + @Override public void update(final IChildrenCountUpdate[] updates) { - for (final IChildrenCountUpdate update : updates) { - if (!checkUpdate(update)) continue; - ((BreakpointVMProvider)getVMProvider()).getNestingCategoryBreakpoints( - update.getElementPath(), - new ViewerDataRequestMonitor<IBreakpoint[]>(getExecutor(), update) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - update.setChildCount(getData().length); - } else { - update.setChildCount(0); - } - update.done(); - } - }); - } - } - - @Override + for (final IChildrenCountUpdate update : updates) { + if (!checkUpdate(update)) + continue; + ((BreakpointVMProvider) getVMProvider()).getNestingCategoryBreakpoints(update.getElementPath(), + new ViewerDataRequestMonitor<IBreakpoint[]>(getExecutor(), update) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + update.setChildCount(getData().length); + } else { + update.setChildCount(0); + } + update.done(); + } + }); + } + } + + @Override public void update(IChildrenUpdate[] updates) { - for (final IChildrenUpdate update : updates) { - if (!checkUpdate(update)) continue; - ((BreakpointVMProvider)getVMProvider()).getNestingCategoryBreakpoints( - update.getElementPath(), - new ViewerDataRequestMonitor<IBreakpoint[]>(getExecutor(), update) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - @SuppressWarnings("unchecked") - Comparator<Object> comparator = - (Comparator<Object>)getVMProvider().getPresentationContext().getProperty( - IBreakpointUIConstants.PROP_BREAKPOINTS_ELEMENT_COMPARATOR); - if (comparator != null) { - Arrays.sort(getData(), comparator); - } - fillUpdateWithBreakpointElements(update, getData()); - } - update.done(); - } - }); - } - } + for (final IChildrenUpdate update : updates) { + if (!checkUpdate(update)) + continue; + ((BreakpointVMProvider) getVMProvider()).getNestingCategoryBreakpoints(update.getElementPath(), + new ViewerDataRequestMonitor<IBreakpoint[]>(getExecutor(), update) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + @SuppressWarnings("unchecked") + Comparator<Object> comparator = (Comparator<Object>) getVMProvider() + .getPresentationContext() + .getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_ELEMENT_COMPARATOR); + if (comparator != null) { + Arrays.sort(getData(), comparator); + } + fillUpdateWithBreakpointElements(update, getData()); + } + update.done(); + } + }); + } + } + + private void fillUpdateWithBreakpointElements(IChildrenUpdate update, IBreakpoint[] bps) { + int updateIdx = update.getOffset() != -1 ? update.getOffset() : 0; + int endIdx = updateIdx + (update.getLength() != -1 ? update.getLength() : bps.length); + while (updateIdx < endIdx && updateIdx < bps.length) { + update.setChild(createBreakpiontElement(bps[updateIdx]), updateIdx); + updateIdx++; + } + } - private void fillUpdateWithBreakpointElements(IChildrenUpdate update, IBreakpoint[] bps) { - int updateIdx = update.getOffset() != -1 ? update.getOffset() : 0; - int endIdx = updateIdx + (update.getLength() != -1 ? update.getLength() : bps.length); - while (updateIdx < endIdx && updateIdx < bps.length) { - update.setChild(createBreakpiontElement(bps[updateIdx]), updateIdx); - updateIdx++; - } - } - - @Override + @Override public int getDeltaFlags(Object event) { - if (event instanceof BreakpointsChangedEvent) { - BreakpointsChangedEvent bpChangedEvent = ((BreakpointsChangedEvent)event); - if (BreakpointsChangedEvent.Type.ADDED.equals(bpChangedEvent.getType())) { - return IModelDelta.CONTENT | IModelDelta.SELECT | IModelDelta.EXPAND; - } - return IModelDelta.CONTENT; - } - else if (BreakpointVMProvider.isPresentationContextEvent(event)) { - PropertyChangeEvent propertyEvent = (PropertyChangeEvent)event; - if (IBreakpointUIConstants.PROP_BREAKPOINTS_FILTER_SELECTION.equals(propertyEvent.getProperty()) || - IBreakpointUIConstants.PROP_BREAKPOINTS_ELEMENT_COMPARATOR.equals(propertyEvent.getProperty())) - { - return IModelDelta.CONTENT; - } else if (IBreakpointUIConstants.PROP_BREAKPOINTS_ORGANIZERS.equals(propertyEvent.getProperty())) { - return IModelDelta.EXPAND | IModelDelta.CONTENT; - } else if (IBreakpointUIConstants.PROP_BREAKPOINTS_TRACK_SELECTION.equals(propertyEvent.getProperty()) && - Boolean.TRUE.equals(propertyEvent.getNewValue()) ) - { - return IModelDelta.EXPAND | IModelDelta.SELECT; - } - } - else if (event instanceof DebugContextEvent && (((DebugContextEvent)event).getFlags() & DebugContextEvent.ACTIVATED) != 0) { - int flags = IModelDelta.NO_CHANGE; - if ( Boolean.TRUE.equals(getVMProvider().getPresentationContext().getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_FILTER_SELECTION)) ) { - flags |= IModelDelta.CONTENT; - } - if (Boolean.TRUE.equals(getVMProvider().getPresentationContext().getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_TRACK_SELECTION)) ) { - flags |= IModelDelta.EXPAND | IModelDelta.SELECT; - } - return flags; - } else if (event instanceof ModelProxyInstalledEvent) { - // Upon model proxy installed, check whether we need to select a - // breakpoint in linking with Debug view - if (Boolean.TRUE.equals(getVMProvider().getPresentationContext().getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_TRACK_SELECTION)) ) { - return IModelDelta.EXPAND | IModelDelta.SELECT; - } - } - return 0; - } + if (event instanceof BreakpointsChangedEvent) { + BreakpointsChangedEvent bpChangedEvent = ((BreakpointsChangedEvent) event); + if (BreakpointsChangedEvent.Type.ADDED.equals(bpChangedEvent.getType())) { + return IModelDelta.CONTENT | IModelDelta.SELECT | IModelDelta.EXPAND; + } + return IModelDelta.CONTENT; + } else if (BreakpointVMProvider.isPresentationContextEvent(event)) { + PropertyChangeEvent propertyEvent = (PropertyChangeEvent) event; + if (IBreakpointUIConstants.PROP_BREAKPOINTS_FILTER_SELECTION.equals(propertyEvent.getProperty()) + || IBreakpointUIConstants.PROP_BREAKPOINTS_ELEMENT_COMPARATOR.equals(propertyEvent.getProperty())) { + return IModelDelta.CONTENT; + } else if (IBreakpointUIConstants.PROP_BREAKPOINTS_ORGANIZERS.equals(propertyEvent.getProperty())) { + return IModelDelta.EXPAND | IModelDelta.CONTENT; + } else if (IBreakpointUIConstants.PROP_BREAKPOINTS_TRACK_SELECTION.equals(propertyEvent.getProperty()) + && Boolean.TRUE.equals(propertyEvent.getNewValue())) { + return IModelDelta.EXPAND | IModelDelta.SELECT; + } + } else if (event instanceof DebugContextEvent + && (((DebugContextEvent) event).getFlags() & DebugContextEvent.ACTIVATED) != 0) { + int flags = IModelDelta.NO_CHANGE; + if (Boolean.TRUE.equals(getVMProvider().getPresentationContext() + .getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_FILTER_SELECTION))) { + flags |= IModelDelta.CONTENT; + } + if (Boolean.TRUE.equals(getVMProvider().getPresentationContext() + .getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_TRACK_SELECTION))) { + flags |= IModelDelta.EXPAND | IModelDelta.SELECT; + } + return flags; + } else if (event instanceof ModelProxyInstalledEvent) { + // Upon model proxy installed, check whether we need to select a + // breakpoint in linking with Debug view + if (Boolean.TRUE.equals(getVMProvider().getPresentationContext() + .getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_TRACK_SELECTION))) { + return IModelDelta.EXPAND | IModelDelta.SELECT; + } + } + return 0; + } - @Override + @Override public void buildDelta(Object event, VMDelta parent, int nodeOffset, RequestMonitor rm) { - if (event instanceof BreakpointsChangedEvent) { - BreakpointsChangedEvent bpChangedEvent = ((BreakpointsChangedEvent)event); - if (BreakpointsChangedEvent.Type.ADDED.equals(bpChangedEvent.getType())) { - buildBreakpointAddedDelta(bpChangedEvent, parent, nodeOffset, rm); - // Do not call rm.done() in this method! - return; - } else { - parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); - } - } - else if (BreakpointVMProvider.isPresentationContextEvent(event)) { - PropertyChangeEvent propertyEvent = (PropertyChangeEvent)event; - if (IBreakpointUIConstants.PROP_BREAKPOINTS_FILTER_SELECTION.equals(propertyEvent.getProperty()) || - IBreakpointUIConstants.PROP_BREAKPOINTS_ELEMENT_COMPARATOR.equals(propertyEvent.getProperty())) - { - parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); - } else if (IBreakpointUIConstants.PROP_BREAKPOINTS_ORGANIZERS.equals(propertyEvent.getProperty())) { - parent.setFlags(parent.getFlags() | IModelDelta.EXPAND | IModelDelta.CONTENT); - } else if (IBreakpointUIConstants.PROP_BREAKPOINTS_TRACK_SELECTION.equals(propertyEvent.getProperty()) && - Boolean.TRUE.equals(propertyEvent.getNewValue()) ) - { - IWorkbenchWindow window = getVMProvider().getPresentationContext().getWindow(); - if (window != null) { - ISelection activeContext = DebugUITools.getDebugContextManager().getContextService(window).getActiveContext(); - buildTrackSelectionDelta(activeContext, parent, nodeOffset, rm); - // Do not call rm.done() in this method! - return; - } - } - } - else if (event instanceof DebugContextEvent && (((DebugContextEvent)event).getFlags() & DebugContextEvent.ACTIVATED) != 0) { - if ( Boolean.TRUE.equals(getVMProvider().getPresentationContext().getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_FILTER_SELECTION)) ) { - parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); - } - if (Boolean.TRUE.equals(getVMProvider().getPresentationContext().getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_TRACK_SELECTION)) ) { - buildTrackSelectionDelta(((DebugContextEvent)event).getContext(), parent, nodeOffset, rm); - // Do not call rm.done() in this method! - return; - } - } else if (event instanceof ModelProxyInstalledEvent) { - if (Boolean.TRUE.equals(getVMProvider().getPresentationContext().getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_TRACK_SELECTION)) ) { - IWorkbenchWindow window = getVMProvider().getPresentationContext().getWindow(); - if (window != null) { - ISelection activeContext = DebugUITools.getDebugContextManager().getContextService(window).getActiveContext(); - buildTrackSelectionDelta(activeContext, parent, nodeOffset, rm); - return; - } - } - } - - rm.done(); - } + if (event instanceof BreakpointsChangedEvent) { + BreakpointsChangedEvent bpChangedEvent = ((BreakpointsChangedEvent) event); + if (BreakpointsChangedEvent.Type.ADDED.equals(bpChangedEvent.getType())) { + buildBreakpointAddedDelta(bpChangedEvent, parent, nodeOffset, rm); + // Do not call rm.done() in this method! + return; + } else { + parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); + } + } else if (BreakpointVMProvider.isPresentationContextEvent(event)) { + PropertyChangeEvent propertyEvent = (PropertyChangeEvent) event; + if (IBreakpointUIConstants.PROP_BREAKPOINTS_FILTER_SELECTION.equals(propertyEvent.getProperty()) + || IBreakpointUIConstants.PROP_BREAKPOINTS_ELEMENT_COMPARATOR.equals(propertyEvent.getProperty())) { + parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); + } else if (IBreakpointUIConstants.PROP_BREAKPOINTS_ORGANIZERS.equals(propertyEvent.getProperty())) { + parent.setFlags(parent.getFlags() | IModelDelta.EXPAND | IModelDelta.CONTENT); + } else if (IBreakpointUIConstants.PROP_BREAKPOINTS_TRACK_SELECTION.equals(propertyEvent.getProperty()) + && Boolean.TRUE.equals(propertyEvent.getNewValue())) { + IWorkbenchWindow window = getVMProvider().getPresentationContext().getWindow(); + if (window != null) { + ISelection activeContext = DebugUITools.getDebugContextManager().getContextService(window) + .getActiveContext(); + buildTrackSelectionDelta(activeContext, parent, nodeOffset, rm); + // Do not call rm.done() in this method! + return; + } + } + } else if (event instanceof DebugContextEvent + && (((DebugContextEvent) event).getFlags() & DebugContextEvent.ACTIVATED) != 0) { + if (Boolean.TRUE.equals(getVMProvider().getPresentationContext() + .getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_FILTER_SELECTION))) { + parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); + } + if (Boolean.TRUE.equals(getVMProvider().getPresentationContext() + .getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_TRACK_SELECTION))) { + buildTrackSelectionDelta(((DebugContextEvent) event).getContext(), parent, nodeOffset, rm); + // Do not call rm.done() in this method! + return; + } + } else if (event instanceof ModelProxyInstalledEvent) { + if (Boolean.TRUE.equals(getVMProvider().getPresentationContext() + .getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_TRACK_SELECTION))) { + IWorkbenchWindow window = getVMProvider().getPresentationContext().getWindow(); + if (window != null) { + ISelection activeContext = DebugUITools.getDebugContextManager().getContextService(window) + .getActiveContext(); + buildTrackSelectionDelta(activeContext, parent, nodeOffset, rm); + return; + } + } + } + + rm.done(); + } + + private void buildBreakpointAddedDelta(final BreakpointsChangedEvent event, final VMDelta parent, + final int nodeOffset, final RequestMonitor rm) { + getVMProvider().updateNode(this, new VMChildrenUpdate(parent, getVMProvider().getPresentationContext(), -1, -1, + new DataRequestMonitor<List<Object>>(getExecutor(), rm) { + @Override + protected void handleSuccess() { + for (int i = 0; i < event.getBreakpoints().length; i++) { + IBreakpoint eventBp = event.getBreakpoints()[i]; + int bpIndex = findBreakpointIndex(eventBp, getData()); + if (bpIndex >= 0) { + // Select only the first breakpoint that was added + if (i == 0) { + parent.addNode(getData().get(bpIndex), bpIndex, IModelDelta.SELECT); + } + // For all other added breakpoints, expand the parent. + parent.setFlags(parent.getFlags() | IModelDelta.CONTENT | IModelDelta.EXPAND); + } + } + rm.done(); + } + })); + } + + protected void buildTrackSelectionDelta(ISelection debugContext, final VMDelta parent, final int nodeOffset, + final RequestMonitor rm) { + assert getVMProvider() instanceof BreakpointVMProvider; + + ((BreakpointVMProvider) getVMProvider()).getBreakpointsForDebugContext(debugContext, + new DataRequestMonitor<IBreakpoint[]>(getExecutor(), rm) { + @Override + protected void handleSuccess() { + if (getData().length == 0) { + // No breakpoints to select, we're done. + rm.done(); + return; + } + final IBreakpoint[] bpsToSelect = getData(); + + getVMProvider().updateNode(AbstractBreakpointVMNode.this, + new VMChildrenUpdate(parent, getVMProvider().getPresentationContext(), -1, -1, + new DataRequestMonitor<List<Object>>(getExecutor(), rm) { + @Override + protected void handleSuccess() { + for (int i = 0; i < bpsToSelect.length; i++) { + int bpIndex = findBreakpointIndex(bpsToSelect[i], getData()); + if (bpIndex >= 0) { + // Select only the first breakpoint that was added + if (i == 0) { + parent.addNode(getData().get(bpIndex), bpIndex, + IModelDelta.SELECT); + } + // For all other added breakpoints, expand the parent. + parent.setFlags(parent.getFlags() | IModelDelta.EXPAND); + } + } + rm.done(); + } + })); + } + + @Override + protected void handleErrorOrWarning() { + rm.done(); + } + }); + } - private void buildBreakpointAddedDelta(final BreakpointsChangedEvent event, final VMDelta parent, final int nodeOffset, final RequestMonitor rm) { - getVMProvider().updateNode(this, new VMChildrenUpdate( - parent, getVMProvider().getPresentationContext(), -1, -1, - new DataRequestMonitor<List<Object>>(getExecutor(), rm) { - @Override - protected void handleSuccess() { - for (int i = 0; i < event.getBreakpoints().length; i++) { - IBreakpoint eventBp = event.getBreakpoints()[i]; - int bpIndex = findBreakpointIndex(eventBp, getData()); - if (bpIndex >= 0) { - // Select only the first breakpoint that was added - if (i == 0) { - parent.addNode(getData().get(bpIndex), bpIndex, IModelDelta.SELECT); - } - // For all other added breakpoints, expand the parent. - parent.setFlags(parent.getFlags() | IModelDelta.CONTENT | IModelDelta.EXPAND); - } - } - rm.done(); - } - })); - } - - protected void buildTrackSelectionDelta(ISelection debugContext, final VMDelta parent, final int nodeOffset, final RequestMonitor rm) { - assert getVMProvider() instanceof BreakpointVMProvider; - - ((BreakpointVMProvider)getVMProvider()).getBreakpointsForDebugContext( - debugContext, - new DataRequestMonitor<IBreakpoint[]>(getExecutor(), rm) { - @Override - protected void handleSuccess() { - if (getData().length == 0) { - // No breakpoints to select, we're done. - rm.done(); - return; - } - final IBreakpoint[] bpsToSelect = getData(); - - getVMProvider().updateNode(AbstractBreakpointVMNode.this, new VMChildrenUpdate( - parent, getVMProvider().getPresentationContext(), -1, -1, - new DataRequestMonitor<List<Object>>(getExecutor(), rm) { - @Override - protected void handleSuccess() { - for (int i = 0; i < bpsToSelect.length; i++) { - int bpIndex = findBreakpointIndex(bpsToSelect[i], getData()); - if (bpIndex >= 0) { - // Select only the first breakpoint that was added - if (i == 0) { - parent.addNode(getData().get(bpIndex), bpIndex, IModelDelta.SELECT); - } - // For all other added breakpoints, expand the parent. - parent.setFlags(parent.getFlags() | IModelDelta.EXPAND); - } - } - rm.done(); - } - })); - } - - @Override - protected void handleErrorOrWarning() { - rm.done(); - } - }); - } - - private int findBreakpointIndex(IBreakpoint bp, List<Object> bpElements) { - for (int j = 0; j < bpElements.size(); j++) { - IBreakpoint elementBp = (IBreakpoint)DebugPlugin.getAdapter(bpElements.get(j), IBreakpoint.class); - if (elementBp != null && elementBp.equals(bp)) { - return j; - } - } - return -1; - } + private int findBreakpointIndex(IBreakpoint bp, List<Object> bpElements) { + for (int j = 0; j < bpElements.size(); j++) { + IBreakpoint elementBp = (IBreakpoint) DebugPlugin.getAdapter(bpElements.get(j), IBreakpoint.class); + if (elementBp != null && elementBp.equals(bp)) { + return j; + } + } + return -1; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointOrganizerVMContext.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointOrganizerVMContext.java index 89e17af1525..56c9462a2c5 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointOrganizerVMContext.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointOrganizerVMContext.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,62 +20,63 @@ import org.eclipse.debug.internal.ui.breakpoints.provisional.IBreakpointContaine import org.eclipse.debug.internal.ui.breakpoints.provisional.IBreakpointOrganizer; /** - * - * + * + * * @since 2.1 */ public class BreakpointOrganizerVMContext extends AbstractVMContext implements IBreakpointContainer { - private final IAdaptable fCategory; - private final IBreakpoint[] fBreakpoints; - - public BreakpointOrganizerVMContext(BreakpointOrganizerVMNode vmNode, IAdaptable category, IBreakpoint[] breakpoints) { - super(vmNode); - fCategory = category; - fBreakpoints = breakpoints; - } - - @Override - public boolean equals(Object obj) { - return obj instanceof BreakpointOrganizerVMContext && - getVMNode().equals( ((BreakpointOrganizerVMContext)obj).getVMNode() ) && - getOrganizer().equals( ((BreakpointOrganizerVMContext)obj).getOrganizer() ) && - fCategory.equals(((BreakpointOrganizerVMContext)obj).fCategory); - } + private final IAdaptable fCategory; + private final IBreakpoint[] fBreakpoints; + + public BreakpointOrganizerVMContext(BreakpointOrganizerVMNode vmNode, IAdaptable category, + IBreakpoint[] breakpoints) { + super(vmNode); + fCategory = category; + fBreakpoints = breakpoints; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof BreakpointOrganizerVMContext + && getVMNode().equals(((BreakpointOrganizerVMContext) obj).getVMNode()) + && getOrganizer().equals(((BreakpointOrganizerVMContext) obj).getOrganizer()) + && fCategory.equals(((BreakpointOrganizerVMContext) obj).fCategory); + } - @Override - public int hashCode() { - return getOrganizer().hashCode() + getVMNode().hashCode() + fCategory.hashCode(); - } + @Override + public int hashCode() { + return getOrganizer().hashCode() + getVMNode().hashCode() + fCategory.hashCode(); + } - @Override + @Override public IBreakpointOrganizer getOrganizer() { - return ((BreakpointOrganizerVMNode)getVMNode()).getOrganizer(); - } - - @Override + return ((BreakpointOrganizerVMNode) getVMNode()).getOrganizer(); + } + + @Override public IAdaptable getCategory() { - return fCategory; - } - - @Override + return fCategory; + } + + @Override public boolean contains(IBreakpoint breakpoint) { - for (IBreakpoint bp : fBreakpoints) { - if (bp.equals(breakpoint)) { - return true; - } - } - return false; - } - - @Override + for (IBreakpoint bp : fBreakpoints) { + if (bp.equals(breakpoint)) { + return true; + } + } + return false; + } + + @Override public IBreakpoint[] getBreakpoints() { - return fBreakpoints; - } - - @Override - public String toString() { - return fCategory.toString(); - } - + return fBreakpoints; + } + + @Override + public String toString() { + return fCategory.toString(); + } + } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointOrganizerVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointOrganizerVMNode.java index 315a19aad49..dec6580eaae 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointOrganizerVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointOrganizerVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -31,133 +31,130 @@ import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; /** - * - * + * + * * @since 2.1 */ public class BreakpointOrganizerVMNode extends AbstractVMNode { - private final IBreakpointOrganizer fOrganizer; - - private final IPropertyChangeListener fOrganizerListener = new IPropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent event) { - ((BreakpointVMProvider)getVMProvider()).handleEventInExecThread(event); - } - }; - - public BreakpointOrganizerVMNode(BreakpointVMProvider provider, IBreakpointOrganizer organizer) { - super(provider); - fOrganizer = organizer; - fOrganizer.addPropertyChangeListener(fOrganizerListener); - } - - @Override - public void dispose() { - fOrganizer.removePropertyChangeListener(fOrganizerListener); - super.dispose(); - } - - public IBreakpointOrganizer getOrganizer() { - return fOrganizer; - } - - @Override - public void update(final IHasChildrenUpdate[] updates) { - for (final IHasChildrenUpdate update : updates) { - if (!checkUpdate(update)) continue; - ((BreakpointVMProvider)getVMProvider()).getBreakpointOrganizerVMCs( - this, update.getElementPath(), - new ViewerDataRequestMonitor<List<BreakpointOrganizerVMContext>>(getExecutor(), update) { - @Override - protected void handleSuccess() { - update.setHasChilren(!getData().isEmpty()); - update.done(); - } - }); - } - } - - @Override - public void update(final IChildrenCountUpdate[] updates) { - for (final IChildrenCountUpdate update : updates) { - if (!checkUpdate(update)) continue; - ((BreakpointVMProvider)getVMProvider()).getBreakpointOrganizerVMCs( - this, update.getElementPath(), - new ViewerDataRequestMonitor<List<BreakpointOrganizerVMContext>>(getExecutor(), update) { - @Override - protected void handleSuccess() { - update.setChildCount(getData().size()); - update.done(); - } - }); - } - } - - @Override - public void update(IChildrenUpdate[] updates) { - for (final IChildrenUpdate update : updates) { - if (!checkUpdate(update)) continue; - ((BreakpointVMProvider)getVMProvider()).getBreakpointOrganizerVMCs( - this, update.getElementPath(), - new ViewerDataRequestMonitor<List<BreakpointOrganizerVMContext>>(getExecutor(), update) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - int updateIdx = update.getOffset() != -1 ? update.getOffset() : 0; - int endIdx = updateIdx + (update.getLength() != -1 ? update.getLength() : (getData().size())); - while (updateIdx < endIdx && updateIdx < getData().size()) { - update.setChild(getData().get(updateIdx), updateIdx); - updateIdx++; - } - } - update.done(); - } - }); - } - } - - protected BreakpointOrganizerVMContext createVMContext(IAdaptable category, IBreakpoint[] breakpoints) { - return new BreakpointOrganizerVMContext(this, category, breakpoints); - } - - @Override - public int getDeltaFlags(Object event) { - if (event instanceof BreakpointsChangedEvent) { - return IModelDelta.CONTENT; - } - else if (BreakpointVMProvider.isPresentationContextEvent(event)) { - PropertyChangeEvent propertyEvent = (PropertyChangeEvent)event; - if (IBreakpointUIConstants.PROP_BREAKPOINTS_FILTER_SELECTION.equals(propertyEvent.getProperty()) || - IBreakpointUIConstants.PROP_BREAKPOINTS_ELEMENT_COMPARATOR.equals(propertyEvent.getProperty()) || - IBreakpointUIConstants.PROP_BREAKPOINTS_ORGANIZERS.equals(propertyEvent.getProperty())) - { - return IModelDelta.CONTENT; - } - } else if (BreakpointVMProvider.isBreakpointOrganizerEvent(event)) { - return IModelDelta.CONTENT; - } - return 0; - } - - @Override - public void buildDelta(Object event, VMDelta parent, int nodeOffset, RequestMonitor requestMonitor) { - if (event instanceof BreakpointsChangedEvent) { - parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); - } - else if (BreakpointVMProvider.isPresentationContextEvent(event)) { - PropertyChangeEvent propertyEvent = (PropertyChangeEvent)event; - if (IBreakpointUIConstants.PROP_BREAKPOINTS_FILTER_SELECTION.equals(propertyEvent.getProperty()) || - IBreakpointUIConstants.PROP_BREAKPOINTS_ELEMENT_COMPARATOR.equals(propertyEvent.getProperty()) || - IBreakpointUIConstants.PROP_BREAKPOINTS_ORGANIZERS.equals(propertyEvent.getProperty())) - { - parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); - } - } else if (BreakpointVMProvider.isBreakpointOrganizerEvent(event)) { - parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); - } - - requestMonitor.done(); - } + private final IBreakpointOrganizer fOrganizer; + + private final IPropertyChangeListener fOrganizerListener = new IPropertyChangeListener() { + @Override + public void propertyChange(PropertyChangeEvent event) { + ((BreakpointVMProvider) getVMProvider()).handleEventInExecThread(event); + } + }; + + public BreakpointOrganizerVMNode(BreakpointVMProvider provider, IBreakpointOrganizer organizer) { + super(provider); + fOrganizer = organizer; + fOrganizer.addPropertyChangeListener(fOrganizerListener); + } + + @Override + public void dispose() { + fOrganizer.removePropertyChangeListener(fOrganizerListener); + super.dispose(); + } + + public IBreakpointOrganizer getOrganizer() { + return fOrganizer; + } + + @Override + public void update(final IHasChildrenUpdate[] updates) { + for (final IHasChildrenUpdate update : updates) { + if (!checkUpdate(update)) + continue; + ((BreakpointVMProvider) getVMProvider()).getBreakpointOrganizerVMCs(this, update.getElementPath(), + new ViewerDataRequestMonitor<List<BreakpointOrganizerVMContext>>(getExecutor(), update) { + @Override + protected void handleSuccess() { + update.setHasChilren(!getData().isEmpty()); + update.done(); + } + }); + } + } + + @Override + public void update(final IChildrenCountUpdate[] updates) { + for (final IChildrenCountUpdate update : updates) { + if (!checkUpdate(update)) + continue; + ((BreakpointVMProvider) getVMProvider()).getBreakpointOrganizerVMCs(this, update.getElementPath(), + new ViewerDataRequestMonitor<List<BreakpointOrganizerVMContext>>(getExecutor(), update) { + @Override + protected void handleSuccess() { + update.setChildCount(getData().size()); + update.done(); + } + }); + } + } + + @Override + public void update(IChildrenUpdate[] updates) { + for (final IChildrenUpdate update : updates) { + if (!checkUpdate(update)) + continue; + ((BreakpointVMProvider) getVMProvider()).getBreakpointOrganizerVMCs(this, update.getElementPath(), + new ViewerDataRequestMonitor<List<BreakpointOrganizerVMContext>>(getExecutor(), update) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + int updateIdx = update.getOffset() != -1 ? update.getOffset() : 0; + int endIdx = updateIdx + + (update.getLength() != -1 ? update.getLength() : (getData().size())); + while (updateIdx < endIdx && updateIdx < getData().size()) { + update.setChild(getData().get(updateIdx), updateIdx); + updateIdx++; + } + } + update.done(); + } + }); + } + } + + protected BreakpointOrganizerVMContext createVMContext(IAdaptable category, IBreakpoint[] breakpoints) { + return new BreakpointOrganizerVMContext(this, category, breakpoints); + } + + @Override + public int getDeltaFlags(Object event) { + if (event instanceof BreakpointsChangedEvent) { + return IModelDelta.CONTENT; + } else if (BreakpointVMProvider.isPresentationContextEvent(event)) { + PropertyChangeEvent propertyEvent = (PropertyChangeEvent) event; + if (IBreakpointUIConstants.PROP_BREAKPOINTS_FILTER_SELECTION.equals(propertyEvent.getProperty()) + || IBreakpointUIConstants.PROP_BREAKPOINTS_ELEMENT_COMPARATOR.equals(propertyEvent.getProperty()) + || IBreakpointUIConstants.PROP_BREAKPOINTS_ORGANIZERS.equals(propertyEvent.getProperty())) { + return IModelDelta.CONTENT; + } + } else if (BreakpointVMProvider.isBreakpointOrganizerEvent(event)) { + return IModelDelta.CONTENT; + } + return 0; + } + + @Override + public void buildDelta(Object event, VMDelta parent, int nodeOffset, RequestMonitor requestMonitor) { + if (event instanceof BreakpointsChangedEvent) { + parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); + } else if (BreakpointVMProvider.isPresentationContextEvent(event)) { + PropertyChangeEvent propertyEvent = (PropertyChangeEvent) event; + if (IBreakpointUIConstants.PROP_BREAKPOINTS_FILTER_SELECTION.equals(propertyEvent.getProperty()) + || IBreakpointUIConstants.PROP_BREAKPOINTS_ELEMENT_COMPARATOR.equals(propertyEvent.getProperty()) + || IBreakpointUIConstants.PROP_BREAKPOINTS_ORGANIZERS.equals(propertyEvent.getProperty())) { + parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); + } + } else if (BreakpointVMProvider.isBreakpointOrganizerEvent(event)) { + parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); + } + + requestMonitor.done(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMContext.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMContext.java index a8926ba8e08..2c6e1a7b4ea 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMContext.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMContext.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -21,40 +21,39 @@ import org.eclipse.debug.core.model.IBreakpoint; */ public class BreakpointVMContext extends AbstractVMContext { - private final IBreakpoint fBreakpoint; - - public BreakpointVMContext(BreakpointVMNode node, IBreakpoint breakpoint) { - super(node); - fBreakpoint = breakpoint; - } - - public IBreakpoint getBreakpoint() { - return fBreakpoint; - } - - @SuppressWarnings("unchecked") + private final IBreakpoint fBreakpoint; + + public BreakpointVMContext(BreakpointVMNode node, IBreakpoint breakpoint) { + super(node); + fBreakpoint = breakpoint; + } + + public IBreakpoint getBreakpoint() { + return fBreakpoint; + } + + @SuppressWarnings("unchecked") + @Override + public <T> T getAdapter(Class<T> adapter) { + if (adapter.isInstance(fBreakpoint)) { + return (T) fBreakpoint; + } + return super.getAdapter(adapter); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof BreakpointVMContext && getBreakpoint().equals(((BreakpointVMContext) obj).getBreakpoint()) + && fBreakpoint.equals(((BreakpointVMContext) obj).fBreakpoint); + } + + @Override + public int hashCode() { + return fBreakpoint.hashCode(); + } + @Override - public <T> T getAdapter(Class<T> adapter) { - if (adapter.isInstance(fBreakpoint)) { - return (T)fBreakpoint; - } - return super.getAdapter(adapter); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof BreakpointVMContext && - getBreakpoint().equals( ((BreakpointVMContext)obj).getBreakpoint() ) && - fBreakpoint.equals(((BreakpointVMContext)obj).fBreakpoint); - } - - @Override - public int hashCode() { - return fBreakpoint.hashCode(); - } - - @Override - public String toString() { - return fBreakpoint.toString(); - } + public String toString() { + return fBreakpoint.toString(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMInput.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMInput.java index 39c350764a4..477e74813ac 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMInput.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMInput.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -26,41 +26,41 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoRe */ public class BreakpointVMInput extends AbstractVMContext implements IElementMementoProvider, IDMVMContext { - final private IDMContext fDMContext; - - public BreakpointVMInput(IVMNode node, IDMContext dmc) { - super(node); - fDMContext = dmc; - } + final private IDMContext fDMContext; + + public BreakpointVMInput(IVMNode node, IDMContext dmc) { + super(node); + fDMContext = dmc; + } - @Override + @Override public IDMContext getDMContext() { - return fDMContext; - } - - @Override + return fDMContext; + } + + @Override public void encodeElements(IElementMementoRequest[] requests) { - for (IElementMementoRequest request : requests) { - request.getMemento().putString("ELEMENT_NAME", "BreakpointInputMemento"); //$NON-NLS-1$//$NON-NLS-2$ - request.done(); - } - } - - @Override + for (IElementMementoRequest request : requests) { + request.getMemento().putString("ELEMENT_NAME", "BreakpointInputMemento"); //$NON-NLS-1$//$NON-NLS-2$ + request.done(); + } + } + + @Override public void compareElements(IElementCompareRequest[] requests) { - for (IElementCompareRequest request : requests) { - request.setEqual( "BreakpointInputMemento".equals(request.getMemento().getString("ELEMENT_NAME")) ); //$NON-NLS-1$//$NON-NLS-2$ - request.done(); - } - } - - @Override - public boolean equals(Object obj) { - return obj instanceof BreakpointVMInput && ((BreakpointVMInput)obj).getDMContext().equals(fDMContext); - } - - @Override - public int hashCode() { - return fDMContext.hashCode(); - } + for (IElementCompareRequest request : requests) { + request.setEqual("BreakpointInputMemento".equals(request.getMemento().getString("ELEMENT_NAME"))); //$NON-NLS-1$//$NON-NLS-2$ + request.done(); + } + } + + @Override + public boolean equals(Object obj) { + return obj instanceof BreakpointVMInput && ((BreakpointVMInput) obj).getDMContext().equals(fDMContext); + } + + @Override + public int hashCode() { + return fDMContext.hashCode(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMModelProxyStrategy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMModelProxyStrategy.java index 487ac9f02fa..8c1ce8d55d4 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMModelProxyStrategy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMModelProxyStrategy.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -25,40 +25,39 @@ import org.eclipse.jface.viewers.TreePath; /** * Breakpoints VM model proxy that includes an ICheckboxModelProxy implementation. - * + * * @since 2.1 */ public class BreakpointVMModelProxyStrategy extends DefaultVMModelProxyStrategy implements ICheckboxModelProxy { - - public BreakpointVMModelProxyStrategy(AbstractVMProvider provider, Object rootElement) { - super(provider, rootElement); - } - - @Override + + public BreakpointVMModelProxyStrategy(AbstractVMProvider provider, Object rootElement) { + super(provider, rootElement); + } + + @Override public boolean setChecked(IPresentationContext context, Object viewerInput, TreePath path, boolean checked) { - Object lastSegment = path.getLastSegment(); - if (lastSegment instanceof IBreakpointContainer) { - IBreakpoint[] breakpoints = ((IBreakpointContainer) lastSegment).getBreakpoints(); - for (int i = 0; i < breakpoints.length; ++i) { - try { - breakpoints[i].setEnabled(checked); - } catch (CoreException e) { - return false; - } - } - return true; - } - else { - IBreakpoint breakpoint = (IBreakpoint)DebugPlugin.getAdapter(lastSegment, IBreakpoint.class); - if (breakpoint != null) { - try { - breakpoint.setEnabled(checked); - } catch (CoreException e) { - return false; - } - return true; - } - } - return false; - } + Object lastSegment = path.getLastSegment(); + if (lastSegment instanceof IBreakpointContainer) { + IBreakpoint[] breakpoints = ((IBreakpointContainer) lastSegment).getBreakpoints(); + for (int i = 0; i < breakpoints.length; ++i) { + try { + breakpoints[i].setEnabled(checked); + } catch (CoreException e) { + return false; + } + } + return true; + } else { + IBreakpoint breakpoint = (IBreakpoint) DebugPlugin.getAdapter(lastSegment, IBreakpoint.class); + if (breakpoint != null) { + try { + breakpoint.setEnabled(checked); + } catch (CoreException e) { + return false; + } + return true; + } + } + return false; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMNode.java index b9c3c3f9ac9..a68f06667d5 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -34,183 +34,291 @@ import org.eclipse.swt.graphics.RGB; import org.eclipse.ui.IMemento; /** - * Breakpoint VM Node which uses VM Contexts to populate breakpoint elements - * in the view. Any actions or other selection listeners which depend on the - * breakpoint object will not work with these elements unless they use the - * adapter mechanism to obtain the breakpoints. - * + * Breakpoint VM Node which uses VM Contexts to populate breakpoint elements + * in the view. Any actions or other selection listeners which depend on the + * breakpoint object will not work with these elements unless they use the + * adapter mechanism to obtain the breakpoints. + * * @since 2.1 */ -public class BreakpointVMNode extends AbstractBreakpointVMNode implements IElementLabelProvider, IElementMementoProvider { - - public BreakpointVMNode(BreakpointVMProvider provider) { - super(provider); - } - - @Override - protected Object createBreakpiontElement(IBreakpoint bp) { - return new BreakpointVMContext(this, bp); - } - - @Override - public void update(ILabelUpdate[] updates) { - Map<IElementLabelProvider, List<ILabelUpdate>> delegatesMap = new HashMap<IElementLabelProvider, List<ILabelUpdate>>(1,1); - - for (final ILabelUpdate update : updates) { - final IBreakpoint bp = ((BreakpointVMContext)update.getElement()).getBreakpoint(); - IElementLabelProvider provider = bp.getAdapter(IElementLabelProvider.class); - if (provider == null) { - update.done(); - continue; - } - - List<ILabelUpdate> delegatesList = delegatesMap.get(provider); - if (delegatesList == null) { - delegatesList = new ArrayList<ILabelUpdate>(updates.length); - delegatesMap.put(provider, delegatesList); - } - delegatesList.add(new ICheckUpdate() { - @Override - public void setChecked(boolean checked, boolean grayed) { - if (update instanceof ICheckUpdate) { - ((ICheckUpdate)update).setChecked(checked, grayed); - } - } - @Override - public String[] getColumnIds() { return update.getColumnIds(); } - @Override - public void setLabel(String text, int columnIndex) { - update.setLabel(text, columnIndex); - } - @Override - public void setFontData(FontData fontData, int columnIndex) { update.setFontData(fontData, columnIndex); } - @Override - public void setImageDescriptor(ImageDescriptor image, int columnIndex) { update.setImageDescriptor(image, columnIndex); } - @Override - public void setForeground(RGB foreground, int columnIndex) { update.setForeground(foreground, columnIndex); } - @Override - public void setBackground(RGB background, int columnIndex) { update.setBackground(background, columnIndex); } - @Override - public IPresentationContext getPresentationContext() { return update.getPresentationContext(); } - @Override - public Object getElement() { return bp; } - @Override - public TreePath getElementPath() { return update.getElementPath().getParentPath().createChildPath(bp); } - @Override - public Object getViewerInput() { return update.getViewerInput(); } - @Override - public void setStatus(IStatus status) { update.setStatus(status); } - @Override - public IStatus getStatus() { return update.getStatus(); } - @Override - public void done() { update.done(); } - @Override - public void cancel() { update.cancel(); } - @Override - public boolean isCanceled() { return update.isCanceled(); } - }); - } - - for (IElementLabelProvider provider : delegatesMap.keySet()) { - List<ILabelUpdate> updatesList = delegatesMap.get(provider); - provider.update(updatesList.toArray(new ILabelUpdate[updatesList.size()])); - } - } - - @Override - public void encodeElements(IElementMementoRequest[] updates) { - Map<IElementMementoProvider, List<IElementMementoRequest>> delegatesMap = new HashMap<IElementMementoProvider, List<IElementMementoRequest>>(1,1); - - for (final IElementMementoRequest update : updates) { - final IBreakpoint bp = ((BreakpointVMContext)update.getElement()).getBreakpoint(); - IElementMementoProvider provider = bp.getAdapter(IElementMementoProvider.class); - if (provider == null) { - update.done(); - continue; - } - - List<IElementMementoRequest> delegatesList = delegatesMap.get(provider); - if (delegatesList == null) { - delegatesList = new ArrayList<IElementMementoRequest>(updates.length); - delegatesMap.put(provider, delegatesList); - } - delegatesList.add(new IElementMementoRequest() { - @Override - public IMemento getMemento() { return update.getMemento(); } - @Override - public IPresentationContext getPresentationContext() { return update.getPresentationContext(); } - @Override - public Object getElement() { return bp; } - @Override - public TreePath getElementPath() { return update.getElementPath().getParentPath().createChildPath(bp); } - @Override - public Object getViewerInput() { return update.getViewerInput(); } - @Override - public void setStatus(IStatus status) { update.setStatus(status); } - @Override - public IStatus getStatus() { return update.getStatus(); } - @Override - public void done() { update.done(); } - @Override - public void cancel() { update.cancel(); } - @Override - public boolean isCanceled() { return update.isCanceled(); } - }); - } - - for (IElementMementoProvider provider : delegatesMap.keySet()) { - List<IElementMementoRequest> updatesList = delegatesMap.get(provider); - provider.encodeElements(updatesList.toArray(new IElementMementoRequest[updatesList.size()])); - } - } - - @Override - public void compareElements(IElementCompareRequest[] updates) { - Map<IElementMementoProvider, List<IElementCompareRequest>> delegatesMap = new HashMap<IElementMementoProvider, List<IElementCompareRequest>>(1,1); - - for (final IElementCompareRequest update : updates) { - final IBreakpoint bp = ((BreakpointVMContext)update.getElement()).getBreakpoint(); - IElementMementoProvider provider = bp.getAdapter(IElementMementoProvider.class); - if (provider == null) { - update.done(); - continue; - } - - List<IElementCompareRequest> delegatesList = delegatesMap.get(provider); - if (delegatesList == null) { - delegatesList = new ArrayList<IElementCompareRequest>(updates.length); - delegatesMap.put(provider, delegatesList); - } - delegatesList.add(new IElementCompareRequest() { - @Override - public IMemento getMemento() { return update.getMemento(); } - @Override - public void setEqual(boolean equal) { update.setEqual(equal);} - @Override - public IPresentationContext getPresentationContext() { return update.getPresentationContext(); } - @Override - public Object getElement() { return bp; } - @Override - public TreePath getElementPath() { return update.getElementPath().getParentPath().createChildPath(bp); } - @Override - public Object getViewerInput() { return update.getViewerInput(); } - @Override - public void setStatus(IStatus status) { update.setStatus(status); } - @Override - public IStatus getStatus() { return update.getStatus(); } - @Override - public void done() { update.done(); } - @Override - public void cancel() { update.cancel(); } - @Override - public boolean isCanceled() { return update.isCanceled(); } - }); - } - - for (IElementMementoProvider provider : delegatesMap.keySet()) { - List<IElementCompareRequest> updatesList = delegatesMap.get(provider); - provider.compareElements(updatesList.toArray(new IElementCompareRequest[updatesList.size()])); - } - } - +public class BreakpointVMNode extends AbstractBreakpointVMNode + implements IElementLabelProvider, IElementMementoProvider { + + public BreakpointVMNode(BreakpointVMProvider provider) { + super(provider); + } + + @Override + protected Object createBreakpiontElement(IBreakpoint bp) { + return new BreakpointVMContext(this, bp); + } + + @Override + public void update(ILabelUpdate[] updates) { + Map<IElementLabelProvider, List<ILabelUpdate>> delegatesMap = new HashMap<IElementLabelProvider, List<ILabelUpdate>>( + 1, 1); + + for (final ILabelUpdate update : updates) { + final IBreakpoint bp = ((BreakpointVMContext) update.getElement()).getBreakpoint(); + IElementLabelProvider provider = bp.getAdapter(IElementLabelProvider.class); + if (provider == null) { + update.done(); + continue; + } + + List<ILabelUpdate> delegatesList = delegatesMap.get(provider); + if (delegatesList == null) { + delegatesList = new ArrayList<ILabelUpdate>(updates.length); + delegatesMap.put(provider, delegatesList); + } + delegatesList.add(new ICheckUpdate() { + @Override + public void setChecked(boolean checked, boolean grayed) { + if (update instanceof ICheckUpdate) { + ((ICheckUpdate) update).setChecked(checked, grayed); + } + } + + @Override + public String[] getColumnIds() { + return update.getColumnIds(); + } + + @Override + public void setLabel(String text, int columnIndex) { + update.setLabel(text, columnIndex); + } + + @Override + public void setFontData(FontData fontData, int columnIndex) { + update.setFontData(fontData, columnIndex); + } + + @Override + public void setImageDescriptor(ImageDescriptor image, int columnIndex) { + update.setImageDescriptor(image, columnIndex); + } + + @Override + public void setForeground(RGB foreground, int columnIndex) { + update.setForeground(foreground, columnIndex); + } + + @Override + public void setBackground(RGB background, int columnIndex) { + update.setBackground(background, columnIndex); + } + + @Override + public IPresentationContext getPresentationContext() { + return update.getPresentationContext(); + } + + @Override + public Object getElement() { + return bp; + } + + @Override + public TreePath getElementPath() { + return update.getElementPath().getParentPath().createChildPath(bp); + } + + @Override + public Object getViewerInput() { + return update.getViewerInput(); + } + + @Override + public void setStatus(IStatus status) { + update.setStatus(status); + } + + @Override + public IStatus getStatus() { + return update.getStatus(); + } + + @Override + public void done() { + update.done(); + } + + @Override + public void cancel() { + update.cancel(); + } + + @Override + public boolean isCanceled() { + return update.isCanceled(); + } + }); + } + + for (IElementLabelProvider provider : delegatesMap.keySet()) { + List<ILabelUpdate> updatesList = delegatesMap.get(provider); + provider.update(updatesList.toArray(new ILabelUpdate[updatesList.size()])); + } + } + + @Override + public void encodeElements(IElementMementoRequest[] updates) { + Map<IElementMementoProvider, List<IElementMementoRequest>> delegatesMap = new HashMap<IElementMementoProvider, List<IElementMementoRequest>>( + 1, 1); + + for (final IElementMementoRequest update : updates) { + final IBreakpoint bp = ((BreakpointVMContext) update.getElement()).getBreakpoint(); + IElementMementoProvider provider = bp.getAdapter(IElementMementoProvider.class); + if (provider == null) { + update.done(); + continue; + } + + List<IElementMementoRequest> delegatesList = delegatesMap.get(provider); + if (delegatesList == null) { + delegatesList = new ArrayList<IElementMementoRequest>(updates.length); + delegatesMap.put(provider, delegatesList); + } + delegatesList.add(new IElementMementoRequest() { + @Override + public IMemento getMemento() { + return update.getMemento(); + } + + @Override + public IPresentationContext getPresentationContext() { + return update.getPresentationContext(); + } + + @Override + public Object getElement() { + return bp; + } + + @Override + public TreePath getElementPath() { + return update.getElementPath().getParentPath().createChildPath(bp); + } + + @Override + public Object getViewerInput() { + return update.getViewerInput(); + } + + @Override + public void setStatus(IStatus status) { + update.setStatus(status); + } + + @Override + public IStatus getStatus() { + return update.getStatus(); + } + + @Override + public void done() { + update.done(); + } + + @Override + public void cancel() { + update.cancel(); + } + + @Override + public boolean isCanceled() { + return update.isCanceled(); + } + }); + } + + for (IElementMementoProvider provider : delegatesMap.keySet()) { + List<IElementMementoRequest> updatesList = delegatesMap.get(provider); + provider.encodeElements(updatesList.toArray(new IElementMementoRequest[updatesList.size()])); + } + } + + @Override + public void compareElements(IElementCompareRequest[] updates) { + Map<IElementMementoProvider, List<IElementCompareRequest>> delegatesMap = new HashMap<IElementMementoProvider, List<IElementCompareRequest>>( + 1, 1); + + for (final IElementCompareRequest update : updates) { + final IBreakpoint bp = ((BreakpointVMContext) update.getElement()).getBreakpoint(); + IElementMementoProvider provider = bp.getAdapter(IElementMementoProvider.class); + if (provider == null) { + update.done(); + continue; + } + + List<IElementCompareRequest> delegatesList = delegatesMap.get(provider); + if (delegatesList == null) { + delegatesList = new ArrayList<IElementCompareRequest>(updates.length); + delegatesMap.put(provider, delegatesList); + } + delegatesList.add(new IElementCompareRequest() { + @Override + public IMemento getMemento() { + return update.getMemento(); + } + + @Override + public void setEqual(boolean equal) { + update.setEqual(equal); + } + + @Override + public IPresentationContext getPresentationContext() { + return update.getPresentationContext(); + } + + @Override + public Object getElement() { + return bp; + } + + @Override + public TreePath getElementPath() { + return update.getElementPath().getParentPath().createChildPath(bp); + } + + @Override + public Object getViewerInput() { + return update.getViewerInput(); + } + + @Override + public void setStatus(IStatus status) { + update.setStatus(status); + } + + @Override + public IStatus getStatus() { + return update.getStatus(); + } + + @Override + public void done() { + update.done(); + } + + @Override + public void cancel() { + update.cancel(); + } + + @Override + public boolean isCanceled() { + return update.isCanceled(); + } + }); + } + + for (IElementMementoProvider provider : delegatesMap.keySet()) { + List<IElementCompareRequest> updatesList = delegatesMap.get(provider); + provider.compareElements(updatesList.toArray(new IElementCompareRequest[updatesList.size()])); + } + } + } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMProvider.java index 231564282f1..b1ffa773682 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointVMProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -60,324 +60,322 @@ import org.eclipse.jface.viewers.TreePath; import org.eclipse.ui.IWorkbenchWindow; /** - * The breakpoint provider is used to populate the contents of the breakpoints + * The breakpoint provider is used to populate the contents of the breakpoints * view. - * + * * @since 2.1 - */ -public class BreakpointVMProvider extends AbstractVMProvider -{ - private IPropertyChangeListener fPresentationContextListener = new IPropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent event) { - handleEventInExecThread(event); - } - }; - - private IBreakpointsListener fBreakpointsListener = new IBreakpointsListener() { - @Override - public void breakpointsRemoved(IBreakpoint[] breakpoints, IMarkerDelta[] deltas) { - handleEventInExecThread(new BreakpointsChangedEvent(BreakpointsChangedEvent.Type.REMOVED, breakpoints)); - } - - @Override - public void breakpointsChanged(IBreakpoint[] breakpoints, IMarkerDelta[] deltas) { - handleEventInExecThread(new BreakpointsChangedEvent(BreakpointsChangedEvent.Type.CHANGED, breakpoints)); - } - - @Override - public void breakpointsAdded(IBreakpoint[] breakpoints) { - handleEventInExecThread(new BreakpointsChangedEvent(BreakpointsChangedEvent.Type.ADDED, breakpoints)); - } - - }; - - private IDebugContextListener fDebugContextListener = new IDebugContextListener() { - @Override - public void debugContextChanged(final DebugContextEvent event) { - handleEventInExecThread(event); - } - }; - - private class ContainerBreakpointsCache extends DataCache<List<BreakpointOrganizerVMContext>> { - - private BreakpointOrganizerVMNode fOrganizerVMNode; - private TreePath fParentPath; - - public ContainerBreakpointsCache(BreakpointOrganizerVMNode organizerVMNode, TreePath parentPath) { - super(getExecutor()); - fOrganizerVMNode = organizerVMNode; - fParentPath = parentPath; - } - - @Override - protected void retrieve(final DataRequestMonitor<List<BreakpointOrganizerVMContext>> rm) { - getNestingCategoryBreakpoints( - fParentPath, - new DataRequestMonitor<IBreakpoint[]>(getExecutor(), rm) { - @SuppressWarnings({ "cast", "unchecked" }) - @Override - protected void handleSuccess() { - Map<IAdaptable, List<IBreakpoint>> bpsLists = new HashMap<IAdaptable, List<IBreakpoint>>(); - for (IBreakpoint bp : getData()) { - IAdaptable[] bpCategories = fOrganizerVMNode.getOrganizer().getCategories(bp); - if (bpCategories == null || bpCategories.length == 0) { - bpCategories = OtherBreakpointCategory.getCategories(fOrganizerVMNode.getOrganizer()); - } - - for (IAdaptable category : bpCategories) { - List<IBreakpoint> categoryBPs = bpsLists.get(category); - if (categoryBPs == null) { - categoryBPs = new ArrayList<IBreakpoint>(); - bpsLists.put(category, categoryBPs); - } - categoryBPs.add(bp); - } - } - - // Only show the empty containers for the top-level node. - if (fParentPath.getSegmentCount() == 0) { - final IAdaptable[] independentCategories = fOrganizerVMNode.getOrganizer().getCategories(); - if (independentCategories != null) { - for (IAdaptable category : independentCategories) { - if (!bpsLists.containsKey(category)) { - bpsLists.put(category, (List<IBreakpoint>)Collections.EMPTY_LIST); - } - } - } - } - - List<BreakpointOrganizerVMContext> vmcs = new ArrayList<BreakpointOrganizerVMContext>(bpsLists.size()); - for (Map.Entry<IAdaptable, List<IBreakpoint>> entry : bpsLists.entrySet()) { - List<IBreakpoint> bpsList = entry.getValue(); - IBreakpoint[] bpsArray = bpsList.toArray(new IBreakpoint[bpsList.size()]); - - vmcs.add(createBreakpointOrganizerVMContext(fOrganizerVMNode, entry.getKey(), bpsArray)); - } - Comparator<Object> comparator = (Comparator<Object>)getPresentationContext().getProperty( - IBreakpointUIConstants.PROP_BREAKPOINTS_ELEMENT_COMPARATOR); - if (comparator != null) { - Collections.sort(vmcs, comparator); - } - - rm.setData(vmcs); - rm.done(); - } - }); - } - }; - - private final Map<TreePath, ContainerBreakpointsCache> fContainerBreakpointsCacheMap = - new HashMap<TreePath, ContainerBreakpointsCache>(); - - private DataCache<IBreakpoint[]> fFilteredBreakpointsCache = new DataCache<IBreakpoint[]>(getExecutor()) { - @Override - protected void retrieve(org.eclipse.cdt.dsf.concurrent.DataRequestMonitor<IBreakpoint[]> rm) { - calcFileteredBreakpoints(rm); - } - }; - - public BreakpointVMProvider(AbstractVMAdapter adapter, IPresentationContext context) { - super(adapter, context); - - // Create the top level node which provides the anchor starting point. - // This node is referenced by the BreakpointVMInput element so it - // should not change when the view layout is updated. - setRootNode(new RootDMVMNode(this)); - // Configure the rest of the layout nodes. - configureLayout(); - - context.addPropertyChangeListener(fPresentationContextListener); - DebugPlugin.getDefault().getBreakpointManager().addBreakpointListener(fBreakpointsListener); - IWorkbenchWindow window = context.getWindow(); - if (window != null) { - DebugUITools.getDebugContextManager().getContextService(window).addDebugContextListener( - fDebugContextListener); - } - - } - - @Override - protected IVMModelProxy createModelProxyStrategy(Object rootElement) { - return new BreakpointVMModelProxyStrategy(this, rootElement); - } - - protected IVMNode createBreakpointVMNode() { - return new BreakpointVMNode(this); - } - - /** - * Configures the nodes of this provider. This method may be over-ridden by - * sub classes to create an alternate configuration in this provider. - */ - protected void configureLayout() { - IBreakpointOrganizer[] organizers = (IBreakpointOrganizer[]) - getPresentationContext().getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_ORGANIZERS); - - IVMNode parentNode = getRootVMNode(); - if (organizers != null) { - for (IBreakpointOrganizer organizer : organizers) { - IVMNode organizerNode = new BreakpointOrganizerVMNode(this, organizer); - addChildNodes(parentNode, new IVMNode[] {organizerNode}); - parentNode = organizerNode; - } - } - - IVMNode bpsNode = createBreakpointVMNode(); - addChildNodes(parentNode, new IVMNode[] {bpsNode}); - } - - - @Override - public void dispose() { - getPresentationContext().removePropertyChangeListener(fPresentationContextListener); - DebugPlugin.getDefault().getBreakpointManager().removeBreakpointListener(fBreakpointsListener); - IWorkbenchWindow window = getPresentationContext().getWindow(); - if (window != null) { - DebugUITools.getDebugContextManager().getContextService(window).removeDebugContextListener( - fDebugContextListener); - } - super.dispose(); - } - - @Override - public IColumnPresentation createColumnPresentation(IPresentationContext context, Object element) { - return null; - } - - @Override - public String getColumnPresentationId(IPresentationContext context, Object element) { - return null; - } - - @Override - public void update(IViewerInputUpdate update) { - IDMContext activeDMContext = null; - if (update.getElement() instanceof IDMVMContext) { - activeDMContext = ((IDMVMContext)update.getElement()).getDMContext(); - activeDMContext = DMContexts.getAncestorOfType(activeDMContext, IBreakpointsTargetDMContext.class); - } - if (activeDMContext != null) { - update.setInputElement(new BreakpointVMInput(getRootVMNode(), activeDMContext)); - } else { - // If no breakpoints target found in active context, delegate the breakpoint - // presentation to the default: breakpoint manager. - update.setInputElement(new DefaultBreakpointsViewInput(update.getPresentationContext())); - } - update.done(); - } - - public void getNestingCategoryBreakpoints(TreePath path, final DataRequestMonitor<IBreakpoint[]> rm) { - BreakpointOrganizerVMContext nestingOrganizerVmc = null; - while (path.getSegmentCount() > 0) { - if (path.getLastSegment() instanceof BreakpointOrganizerVMContext) { - nestingOrganizerVmc = (BreakpointOrganizerVMContext)path.getLastSegment(); - break; - } - path = path.getParentPath(); - } - if (nestingOrganizerVmc == null) { - getFileteredBreakpoints(rm); - } else { - final BreakpointOrganizerVMContext _nestingOrganizerVmc = nestingOrganizerVmc; - getBreakpointOrganizerVMCs( - (BreakpointOrganizerVMNode)_nestingOrganizerVmc.getVMNode(), path.getParentPath(), - new DataRequestMonitor<List<BreakpointOrganizerVMContext>>(getExecutor(), rm) { - @Override - protected void handleSuccess() { - int newVmcIdx = getData().indexOf(_nestingOrganizerVmc); - - if (newVmcIdx >= 0) { - rm.setData(getData().get(newVmcIdx).getBreakpoints()); - } else { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, "Breakpoint category not found", null)); //$NON-NLS-1$ - } - rm.done(); - } - }); - } - } - - public void getBreakpointOrganizerVMCs(BreakpointOrganizerVMNode organizerVMNode, TreePath path, - DataRequestMonitor<List<BreakpointOrganizerVMContext>> rm) - { - ContainerBreakpointsCache cache = fContainerBreakpointsCacheMap.get(path); - if (cache == null) { - cache = new ContainerBreakpointsCache(organizerVMNode, path); - fContainerBreakpointsCacheMap.put(path, cache); - } - - cache.request(rm); - } - - - protected BreakpointOrganizerVMContext createBreakpointOrganizerVMContext(BreakpointOrganizerVMNode node, IAdaptable category, IBreakpoint[] breakpoints) { - return new BreakpointOrganizerVMContext(node, category, breakpoints); - } - - - public void getFileteredBreakpoints(final DataRequestMonitor<IBreakpoint[]> rm) { - fFilteredBreakpointsCache.request(rm); - } - - protected void calcFileteredBreakpoints(DataRequestMonitor<IBreakpoint[]> rm) { - rm.setData(DebugPlugin.getDefault().getBreakpointManager().getBreakpoints()); - rm.done(); - } - - public void getBreakpointsForDebugContext(ISelection debugContext, DataRequestMonitor<IBreakpoint[]> rm) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "Not supported", null)); //$NON-NLS-1$ - rm.done(); - } - - public void handleEventInExecThread(final Object event) { - getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - handleEvent(event); - } - }); - } - - @Override - public void handleEvent(Object event, RequestMonitor rm) { - if (isPresentationContextEvent(event)) { - PropertyChangeEvent propertyEvent = (PropertyChangeEvent)event; - if (IBreakpointUIConstants.PROP_BREAKPOINTS_ORGANIZERS.equals(propertyEvent.getProperty())) - { - clearNodes(false); - configureLayout(); - } - } - super.handleEvent(event, rm); - } - - public static boolean isPresentationContextEvent(Object event) { - return event instanceof PropertyChangeEvent && ((PropertyChangeEvent)event).getSource() instanceof IPresentationContext; - } - - public static boolean isBreakpointOrganizerEvent(Object event) { - return event instanceof PropertyChangeEvent && ((PropertyChangeEvent)event).getSource() instanceof IBreakpointOrganizerDelegate; - } - - private static final int MODEL_DELTA_CHANGE_FLAGS = IModelDelta.STATE | IModelDelta.CONTENT | IModelDelta.ADDED | IModelDelta.REMOVED | IModelDelta.REPLACED | IModelDelta.INSERTED; - - @Override - protected void handleEvent(IVMModelProxy proxyStrategy, Object event, RequestMonitor rm) { - // Before generating a delta, flush the caches. - int deltaFlags = proxyStrategy.getEventDeltaFlags(event); - if ((deltaFlags & MODEL_DELTA_CHANGE_FLAGS) != 0) { - flushCaches(); - } - - super.handleEvent(proxyStrategy, event, rm); - } - - private void flushCaches() { - fFilteredBreakpointsCache.reset(); - for (DataCache<?> cache : fContainerBreakpointsCacheMap.values()) { - cache.reset(); - } - fContainerBreakpointsCacheMap.clear(); - } + */ +public class BreakpointVMProvider extends AbstractVMProvider { + private IPropertyChangeListener fPresentationContextListener = new IPropertyChangeListener() { + @Override + public void propertyChange(PropertyChangeEvent event) { + handleEventInExecThread(event); + } + }; + + private IBreakpointsListener fBreakpointsListener = new IBreakpointsListener() { + @Override + public void breakpointsRemoved(IBreakpoint[] breakpoints, IMarkerDelta[] deltas) { + handleEventInExecThread(new BreakpointsChangedEvent(BreakpointsChangedEvent.Type.REMOVED, breakpoints)); + } + + @Override + public void breakpointsChanged(IBreakpoint[] breakpoints, IMarkerDelta[] deltas) { + handleEventInExecThread(new BreakpointsChangedEvent(BreakpointsChangedEvent.Type.CHANGED, breakpoints)); + } + + @Override + public void breakpointsAdded(IBreakpoint[] breakpoints) { + handleEventInExecThread(new BreakpointsChangedEvent(BreakpointsChangedEvent.Type.ADDED, breakpoints)); + } + + }; + + private IDebugContextListener fDebugContextListener = new IDebugContextListener() { + @Override + public void debugContextChanged(final DebugContextEvent event) { + handleEventInExecThread(event); + } + }; + + private class ContainerBreakpointsCache extends DataCache<List<BreakpointOrganizerVMContext>> { + + private BreakpointOrganizerVMNode fOrganizerVMNode; + private TreePath fParentPath; + + public ContainerBreakpointsCache(BreakpointOrganizerVMNode organizerVMNode, TreePath parentPath) { + super(getExecutor()); + fOrganizerVMNode = organizerVMNode; + fParentPath = parentPath; + } + + @Override + protected void retrieve(final DataRequestMonitor<List<BreakpointOrganizerVMContext>> rm) { + getNestingCategoryBreakpoints(fParentPath, new DataRequestMonitor<IBreakpoint[]>(getExecutor(), rm) { + @SuppressWarnings({ "cast", "unchecked" }) + @Override + protected void handleSuccess() { + Map<IAdaptable, List<IBreakpoint>> bpsLists = new HashMap<IAdaptable, List<IBreakpoint>>(); + for (IBreakpoint bp : getData()) { + IAdaptable[] bpCategories = fOrganizerVMNode.getOrganizer().getCategories(bp); + if (bpCategories == null || bpCategories.length == 0) { + bpCategories = OtherBreakpointCategory.getCategories(fOrganizerVMNode.getOrganizer()); + } + + for (IAdaptable category : bpCategories) { + List<IBreakpoint> categoryBPs = bpsLists.get(category); + if (categoryBPs == null) { + categoryBPs = new ArrayList<IBreakpoint>(); + bpsLists.put(category, categoryBPs); + } + categoryBPs.add(bp); + } + } + + // Only show the empty containers for the top-level node. + if (fParentPath.getSegmentCount() == 0) { + final IAdaptable[] independentCategories = fOrganizerVMNode.getOrganizer().getCategories(); + if (independentCategories != null) { + for (IAdaptable category : independentCategories) { + if (!bpsLists.containsKey(category)) { + bpsLists.put(category, (List<IBreakpoint>) Collections.EMPTY_LIST); + } + } + } + } + + List<BreakpointOrganizerVMContext> vmcs = new ArrayList<BreakpointOrganizerVMContext>( + bpsLists.size()); + for (Map.Entry<IAdaptable, List<IBreakpoint>> entry : bpsLists.entrySet()) { + List<IBreakpoint> bpsList = entry.getValue(); + IBreakpoint[] bpsArray = bpsList.toArray(new IBreakpoint[bpsList.size()]); + + vmcs.add(createBreakpointOrganizerVMContext(fOrganizerVMNode, entry.getKey(), bpsArray)); + } + Comparator<Object> comparator = (Comparator<Object>) getPresentationContext() + .getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_ELEMENT_COMPARATOR); + if (comparator != null) { + Collections.sort(vmcs, comparator); + } + + rm.setData(vmcs); + rm.done(); + } + }); + } + }; + + private final Map<TreePath, ContainerBreakpointsCache> fContainerBreakpointsCacheMap = new HashMap<TreePath, ContainerBreakpointsCache>(); + + private DataCache<IBreakpoint[]> fFilteredBreakpointsCache = new DataCache<IBreakpoint[]>(getExecutor()) { + @Override + protected void retrieve(org.eclipse.cdt.dsf.concurrent.DataRequestMonitor<IBreakpoint[]> rm) { + calcFileteredBreakpoints(rm); + } + }; + + public BreakpointVMProvider(AbstractVMAdapter adapter, IPresentationContext context) { + super(adapter, context); + + // Create the top level node which provides the anchor starting point. + // This node is referenced by the BreakpointVMInput element so it + // should not change when the view layout is updated. + setRootNode(new RootDMVMNode(this)); + // Configure the rest of the layout nodes. + configureLayout(); + + context.addPropertyChangeListener(fPresentationContextListener); + DebugPlugin.getDefault().getBreakpointManager().addBreakpointListener(fBreakpointsListener); + IWorkbenchWindow window = context.getWindow(); + if (window != null) { + DebugUITools.getDebugContextManager().getContextService(window) + .addDebugContextListener(fDebugContextListener); + } + + } + + @Override + protected IVMModelProxy createModelProxyStrategy(Object rootElement) { + return new BreakpointVMModelProxyStrategy(this, rootElement); + } + + protected IVMNode createBreakpointVMNode() { + return new BreakpointVMNode(this); + } + + /** + * Configures the nodes of this provider. This method may be over-ridden by + * sub classes to create an alternate configuration in this provider. + */ + protected void configureLayout() { + IBreakpointOrganizer[] organizers = (IBreakpointOrganizer[]) getPresentationContext() + .getProperty(IBreakpointUIConstants.PROP_BREAKPOINTS_ORGANIZERS); + + IVMNode parentNode = getRootVMNode(); + if (organizers != null) { + for (IBreakpointOrganizer organizer : organizers) { + IVMNode organizerNode = new BreakpointOrganizerVMNode(this, organizer); + addChildNodes(parentNode, new IVMNode[] { organizerNode }); + parentNode = organizerNode; + } + } + + IVMNode bpsNode = createBreakpointVMNode(); + addChildNodes(parentNode, new IVMNode[] { bpsNode }); + } + + @Override + public void dispose() { + getPresentationContext().removePropertyChangeListener(fPresentationContextListener); + DebugPlugin.getDefault().getBreakpointManager().removeBreakpointListener(fBreakpointsListener); + IWorkbenchWindow window = getPresentationContext().getWindow(); + if (window != null) { + DebugUITools.getDebugContextManager().getContextService(window) + .removeDebugContextListener(fDebugContextListener); + } + super.dispose(); + } + + @Override + public IColumnPresentation createColumnPresentation(IPresentationContext context, Object element) { + return null; + } + + @Override + public String getColumnPresentationId(IPresentationContext context, Object element) { + return null; + } + + @Override + public void update(IViewerInputUpdate update) { + IDMContext activeDMContext = null; + if (update.getElement() instanceof IDMVMContext) { + activeDMContext = ((IDMVMContext) update.getElement()).getDMContext(); + activeDMContext = DMContexts.getAncestorOfType(activeDMContext, IBreakpointsTargetDMContext.class); + } + if (activeDMContext != null) { + update.setInputElement(new BreakpointVMInput(getRootVMNode(), activeDMContext)); + } else { + // If no breakpoints target found in active context, delegate the breakpoint + // presentation to the default: breakpoint manager. + update.setInputElement(new DefaultBreakpointsViewInput(update.getPresentationContext())); + } + update.done(); + } + + public void getNestingCategoryBreakpoints(TreePath path, final DataRequestMonitor<IBreakpoint[]> rm) { + BreakpointOrganizerVMContext nestingOrganizerVmc = null; + while (path.getSegmentCount() > 0) { + if (path.getLastSegment() instanceof BreakpointOrganizerVMContext) { + nestingOrganizerVmc = (BreakpointOrganizerVMContext) path.getLastSegment(); + break; + } + path = path.getParentPath(); + } + if (nestingOrganizerVmc == null) { + getFileteredBreakpoints(rm); + } else { + final BreakpointOrganizerVMContext _nestingOrganizerVmc = nestingOrganizerVmc; + getBreakpointOrganizerVMCs((BreakpointOrganizerVMNode) _nestingOrganizerVmc.getVMNode(), + path.getParentPath(), + new DataRequestMonitor<List<BreakpointOrganizerVMContext>>(getExecutor(), rm) { + @Override + protected void handleSuccess() { + int newVmcIdx = getData().indexOf(_nestingOrganizerVmc); + + if (newVmcIdx >= 0) { + rm.setData(getData().get(newVmcIdx).getBreakpoints()); + } else { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.INVALID_HANDLE, "Breakpoint category not found", null)); //$NON-NLS-1$ + } + rm.done(); + } + }); + } + } + + public void getBreakpointOrganizerVMCs(BreakpointOrganizerVMNode organizerVMNode, TreePath path, + DataRequestMonitor<List<BreakpointOrganizerVMContext>> rm) { + ContainerBreakpointsCache cache = fContainerBreakpointsCacheMap.get(path); + if (cache == null) { + cache = new ContainerBreakpointsCache(organizerVMNode, path); + fContainerBreakpointsCacheMap.put(path, cache); + } + + cache.request(rm); + } + + protected BreakpointOrganizerVMContext createBreakpointOrganizerVMContext(BreakpointOrganizerVMNode node, + IAdaptable category, IBreakpoint[] breakpoints) { + return new BreakpointOrganizerVMContext(node, category, breakpoints); + } + + public void getFileteredBreakpoints(final DataRequestMonitor<IBreakpoint[]> rm) { + fFilteredBreakpointsCache.request(rm); + } + + protected void calcFileteredBreakpoints(DataRequestMonitor<IBreakpoint[]> rm) { + rm.setData(DebugPlugin.getDefault().getBreakpointManager().getBreakpoints()); + rm.done(); + } + + public void getBreakpointsForDebugContext(ISelection debugContext, DataRequestMonitor<IBreakpoint[]> rm) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, + "Not supported", null)); //$NON-NLS-1$ + rm.done(); + } + + public void handleEventInExecThread(final Object event) { + getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + handleEvent(event); + } + }); + } + + @Override + public void handleEvent(Object event, RequestMonitor rm) { + if (isPresentationContextEvent(event)) { + PropertyChangeEvent propertyEvent = (PropertyChangeEvent) event; + if (IBreakpointUIConstants.PROP_BREAKPOINTS_ORGANIZERS.equals(propertyEvent.getProperty())) { + clearNodes(false); + configureLayout(); + } + } + super.handleEvent(event, rm); + } + + public static boolean isPresentationContextEvent(Object event) { + return event instanceof PropertyChangeEvent + && ((PropertyChangeEvent) event).getSource() instanceof IPresentationContext; + } + + public static boolean isBreakpointOrganizerEvent(Object event) { + return event instanceof PropertyChangeEvent + && ((PropertyChangeEvent) event).getSource() instanceof IBreakpointOrganizerDelegate; + } + + private static final int MODEL_DELTA_CHANGE_FLAGS = IModelDelta.STATE | IModelDelta.CONTENT | IModelDelta.ADDED + | IModelDelta.REMOVED | IModelDelta.REPLACED | IModelDelta.INSERTED; + + @Override + protected void handleEvent(IVMModelProxy proxyStrategy, Object event, RequestMonitor rm) { + // Before generating a delta, flush the caches. + int deltaFlags = proxyStrategy.getEventDeltaFlags(event); + if ((deltaFlags & MODEL_DELTA_CHANGE_FLAGS) != 0) { + flushCaches(); + } + + super.handleEvent(proxyStrategy, event, rm); + } + + private void flushCaches() { + fFilteredBreakpointsCache.reset(); + for (DataCache<?> cache : fContainerBreakpointsCacheMap.values()) { + cache.reset(); + } + fContainerBreakpointsCacheMap.clear(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointsChangedEvent.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointsChangedEvent.java index 00322aea4fe..c68618fc7a4 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointsChangedEvent.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/BreakpointsChangedEvent.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,21 +19,23 @@ import org.eclipse.debug.core.model.IBreakpoint; * @since 2.1 */ public class BreakpointsChangedEvent { - public enum Type { ADDED, REMOVED, CHANGED }; - - private final Type fType; - private final IBreakpoint[] fBreakpoints; - - public BreakpointsChangedEvent(Type type, IBreakpoint[] breakpoints) { - fType = type; - fBreakpoints = breakpoints; - } - - public Type getType() { - return fType; - } - - public IBreakpoint[] getBreakpoints() { - return fBreakpoints; - } + public enum Type { + ADDED, REMOVED, CHANGED + }; + + private final Type fType; + private final IBreakpoint[] fBreakpoints; + + public BreakpointsChangedEvent(Type type, IBreakpoint[] breakpoints) { + fType = type; + fBreakpoints = breakpoints; + } + + public Type getType() { + return fType; + } + + public IBreakpoint[] getBreakpoints() { + return fBreakpoints; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/DataCache.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/DataCache.java index 7db64fc5794..9bee9d8381a 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/DataCache.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/DataCache.java @@ -1,19 +1,19 @@ package org.eclipse.cdt.dsf.debug.ui.viewmodel.breakpoints; -/******************************************************************************* - * Copyright (c) 2008, 2012 Wind River Systems, Inc. and others. +/******************************************************************************* + * Copyright (c) 2008, 2012 Wind River Systems, Inc. and others. * - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Wind River Systems - initial API and implementation - *******************************************************************************/ - + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Wind River Systems - initial API and implementation + *******************************************************************************/ + import java.util.LinkedList; import java.util.List; import java.util.concurrent.Executor; @@ -25,199 +25,199 @@ import org.eclipse.cdt.dsf.internal.DsfPlugin; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; -/** +/** * A general purpose cache, which caches the result of a single request. * Sub classes need to implement {@link #retrieve(DataRequestMonitor)} to fetch - * data from the data source. Clients are responsible for calling - * {@link #disable()} and {@link #reset()} to manage the state of the cache in + * data from the data source. Clients are responsible for calling + * {@link #disable()} and {@link #reset()} to manage the state of the cache in * response to events from the data source. * <p> - * This cache requires an executor to use. The executor is used to synchronize - * access to the cache state and data. + * This cache requires an executor to use. The executor is used to synchronize + * access to the cache state and data. * </p> * <p> - * This class is intended as a general utility, but it's not quite ready for + * This class is intended as a general utility, but it's not quite ready for * API, so it's just private class for now. * </p> - * @since 2.1 - */ -@ConfinedToDsfExecutor("fExecutor") -abstract class DataCache<V> { - - final private Executor fExecutor; - - private boolean fValid; - - protected DataRequestMonitor<V> fRm; - private V fData; - private IStatus fStatus; - - private List<DataRequestMonitor<V>> fWaitingList = new LinkedList<DataRequestMonitor<V>>(); - - public DataCache(Executor executor) { - fExecutor = executor; - } - - - /** - * Sub-classes should override this method to retrieve the cache data - * from its source. - * - * @param rm Request monitor for completion of data retrieval. - */ - protected abstract void retrieve(DataRequestMonitor<V> rm); - - /** - * Returns <code>true</code> if the cache is currently valid. I.e. - * whether the cache can return a value immediately without first - * retrieving it from the data source. - */ - public boolean isValid() { - return fValid; - } - - /** - * Returns <code>true</code> if the cache is currently waiting for data - * from the data source. - */ - public boolean isPending() { - return fRm != null; - } - - /** - * Returns the current data value held by this cache. Clients should first - * call isValid() to determine if the data is up to date. - */ - public V getData() { - return fData; - } - - /** - * Returns the status of the source request held by this cache. Clients - * should first call isValid() to determine if the data is up to date. - */ - public IStatus getStatus() { - return fStatus; - } - - /** - * Request data from the cache. If the cache is valid, it will complete the - * request immediately, otherwise data will first be retrieved from the - * source. - * @param req - */ - public void request(final DataRequestMonitor<V> rm) { - if (!fValid) { - boolean first = fWaitingList.isEmpty(); - fWaitingList.add(rm); - if(first) { - fRm = new DataRequestMonitor<V>(fExecutor, null) { - @Override - protected void handleCompleted() { - if (!isCanceled()) { - fValid = true; - fRm = null; - set(super.getData(), super.getStatus()); - } - } - }; - retrieve(fRm); - } - } else { - rm.setData(fData); - rm.setStatus(fStatus); - rm.done(); - } - } - - - private void set(V data, IStatus status) { - fData = data; - fStatus = status; - List<DataRequestMonitor<V>> waitingList = fWaitingList; - fWaitingList = new LinkedList<DataRequestMonitor<V>>(); - - for (DataRequestMonitor<V> rm : waitingList) { - rm.setData(data); - rm.setStatus(status); - rm.done(); - } - } - - /** - * Resets the cache with a data value <code>null</code> and an error - * status with code {@link IDsfStatusConstants#INVALID_STATE}. - * - * @see #reset(Object, IStatus) - */ - public void reset() { - reset(null, new Status(IStatus.ERROR, DsfPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Cache reset", null)); //$NON-NLS-1$ - } - - /** - * Resets the cache with given data and status. Resetting the cache - * forces the cache to be invalid and cancels any current pending requests - * from data source. - * <p> - * This method should be called when the data source has issued an event - * indicating that the source data has changed but data may still be - * retrieved. Clients may need to re-request data following cache reset. - * </p> - * @param data The data that should be returned to any clients currently - * waiting for cache data. - * @status The status that should be returned to any clients currently - * waiting for cache data. - */ - public void reset(V data, IStatus status) { - fValid = false; - if (fRm != null) { - fRm.cancel(); - fRm = null; - } - set(data, status); - } - - /** - * Disables the cache from retrieving data from the source. If the cache - * is already valid the data and status is retained. If the cache is not - * valid, then data value <code>null</code> and an error status with code - * {@link IDsfStatusConstants#INVALID_STATE} are set. - * - * @see #disable(Object, IStatus) - */ - public void disable() { - //TODO: better. - - V data; - IStatus status; - if (fValid) { - data = getData(); - status = getStatus(); - } else { - data = null; - status = new Status(IStatus.ERROR, DsfPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Cache disable", null); //$NON-NLS-1$ - } - disable(data, status); - } - - /** - * Resets the cache then disables it. When a cache is disabled it means - * that it is valid and requests to the data source will not be sent. - * <p> - * This method should be called when the data source has issued an event - * indicating that the source data has changed and future requests for - * data will return the given data and status. Once the source data - * becomes available again, clients should call {@link #reset()}. - * </p> - * @param data The data that should be returned to any clients waiting for - * cache data and for clients requesting data until the cache is reset again. - * @status The status that should be returned to any clients waiting for - * cache data and for clients requesting data until the cache is reset again. - * - * @see #reset(Object, IStatus) - */ - public void disable(V data, IStatus status) { - reset(data, status); - fValid = true; - } -} + * @since 2.1 + */ +@ConfinedToDsfExecutor("fExecutor") +abstract class DataCache<V> { + + final private Executor fExecutor; + + private boolean fValid; + + protected DataRequestMonitor<V> fRm; + private V fData; + private IStatus fStatus; + + private List<DataRequestMonitor<V>> fWaitingList = new LinkedList<DataRequestMonitor<V>>(); + + public DataCache(Executor executor) { + fExecutor = executor; + } + + /** + * Sub-classes should override this method to retrieve the cache data + * from its source. + * + * @param rm Request monitor for completion of data retrieval. + */ + protected abstract void retrieve(DataRequestMonitor<V> rm); + + /** + * Returns <code>true</code> if the cache is currently valid. I.e. + * whether the cache can return a value immediately without first + * retrieving it from the data source. + */ + public boolean isValid() { + return fValid; + } + + /** + * Returns <code>true</code> if the cache is currently waiting for data + * from the data source. + */ + public boolean isPending() { + return fRm != null; + } + + /** + * Returns the current data value held by this cache. Clients should first + * call isValid() to determine if the data is up to date. + */ + public V getData() { + return fData; + } + + /** + * Returns the status of the source request held by this cache. Clients + * should first call isValid() to determine if the data is up to date. + */ + public IStatus getStatus() { + return fStatus; + } + + /** + * Request data from the cache. If the cache is valid, it will complete the + * request immediately, otherwise data will first be retrieved from the + * source. + * @param req + */ + public void request(final DataRequestMonitor<V> rm) { + if (!fValid) { + boolean first = fWaitingList.isEmpty(); + fWaitingList.add(rm); + if (first) { + fRm = new DataRequestMonitor<V>(fExecutor, null) { + @Override + protected void handleCompleted() { + if (!isCanceled()) { + fValid = true; + fRm = null; + set(super.getData(), super.getStatus()); + } + } + }; + retrieve(fRm); + } + } else { + rm.setData(fData); + rm.setStatus(fStatus); + rm.done(); + } + } + + private void set(V data, IStatus status) { + fData = data; + fStatus = status; + List<DataRequestMonitor<V>> waitingList = fWaitingList; + fWaitingList = new LinkedList<DataRequestMonitor<V>>(); + + for (DataRequestMonitor<V> rm : waitingList) { + rm.setData(data); + rm.setStatus(status); + rm.done(); + } + } + + /** + * Resets the cache with a data value <code>null</code> and an error + * status with code {@link IDsfStatusConstants#INVALID_STATE}. + * + * @see #reset(Object, IStatus) + */ + public void reset() { + reset(null, + new Status(IStatus.ERROR, DsfPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Cache reset", null)); //$NON-NLS-1$ + } + + /** + * Resets the cache with given data and status. Resetting the cache + * forces the cache to be invalid and cancels any current pending requests + * from data source. + * <p> + * This method should be called when the data source has issued an event + * indicating that the source data has changed but data may still be + * retrieved. Clients may need to re-request data following cache reset. + * </p> + * @param data The data that should be returned to any clients currently + * waiting for cache data. + * @status The status that should be returned to any clients currently + * waiting for cache data. + */ + public void reset(V data, IStatus status) { + fValid = false; + if (fRm != null) { + fRm.cancel(); + fRm = null; + } + set(data, status); + } + + /** + * Disables the cache from retrieving data from the source. If the cache + * is already valid the data and status is retained. If the cache is not + * valid, then data value <code>null</code> and an error status with code + * {@link IDsfStatusConstants#INVALID_STATE} are set. + * + * @see #disable(Object, IStatus) + */ + public void disable() { + //TODO: better. + + V data; + IStatus status; + if (fValid) { + data = getData(); + status = getStatus(); + } else { + data = null; + status = new Status(IStatus.ERROR, DsfPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Cache disable", //$NON-NLS-1$ + null); + } + disable(data, status); + } + + /** + * Resets the cache then disables it. When a cache is disabled it means + * that it is valid and requests to the data source will not be sent. + * <p> + * This method should be called when the data source has issued an event + * indicating that the source data has changed and future requests for + * data will return the given data and status. Once the source data + * becomes available again, clients should call {@link #reset()}. + * </p> + * @param data The data that should be returned to any clients waiting for + * cache data and for clients requesting data until the cache is reset again. + * @status The status that should be returned to any clients waiting for + * cache data and for clients requesting data until the cache is reset again. + * + * @see #reset(Object, IStatus) + */ + public void disable(V data, IStatus status) { + reset(data, status); + fValid = true; + } +} diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/RawBreakpointVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/RawBreakpointVMNode.java index 98947e01d97..943a45518ba 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/RawBreakpointVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/breakpoints/RawBreakpointVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -16,21 +16,21 @@ package org.eclipse.cdt.dsf.debug.ui.viewmodel.breakpoints; import org.eclipse.debug.core.model.IBreakpoint; /** - * Breakpoint node which uses raw breakpoint objects (without a wrapper) as - * elements which are populated into the view. The breakpoint objects are + * Breakpoint node which uses raw breakpoint objects (without a wrapper) as + * elements which are populated into the view. The breakpoint objects are * responsible for supplying their own label and memento providers, as well * as content provider for any children. - * + * * @since 2.1 */ public class RawBreakpointVMNode extends AbstractBreakpointVMNode { - public RawBreakpointVMNode(BreakpointVMProvider provider) { - super(provider); - } + public RawBreakpointVMNode(BreakpointVMProvider provider) { + super(provider); + } - @Override - protected Object createBreakpiontElement(IBreakpoint bp) { - return bp; - } + @Override + protected Object createBreakpiontElement(IBreakpoint bp) { + return bp; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/AbstractExpressionVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/AbstractExpressionVMNode.java index 3d5d608a63e..dc953cceef6 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/AbstractExpressionVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/AbstractExpressionVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -33,157 +33,154 @@ import org.eclipse.debug.core.model.IExpression; import org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenUpdate; /** - * Base class for VM Nodes which can be used in the expressions view. + * Base class for VM Nodes which can be used in the expressions view. * <p> * This base class uses the methods {@link #canParseExpression(IExpression)} and - * {@link #update(IChildrenUpdate[])} to implement the + * {@link #update(IChildrenUpdate[])} to implement the * {@link IExpressionVMNode#update(IExpressionUpdate)} * method. Two additional abstract protected methods need to be implemented - * by the sub-class as well. + * by the sub-class as well. * </p> */ -public abstract class AbstractExpressionVMNode extends AbstractDMVMNode - implements IExpressionVMNode -{ - /** - * @since 2.0 - */ - protected static final String PROP_ELEMENT_EXPRESSION = "element_expression"; //$NON-NLS-1$ +public abstract class AbstractExpressionVMNode extends AbstractDMVMNode implements IExpressionVMNode { + /** + * @since 2.0 + */ + protected static final String PROP_ELEMENT_EXPRESSION = "element_expression"; //$NON-NLS-1$ - - public AbstractExpressionVMNode(AbstractDMVMProvider provider, DsfSession session, Class<? extends IDMContext> dmcClassType) { - super(provider, session, dmcClassType); - } + public AbstractExpressionVMNode(AbstractDMVMProvider provider, DsfSession session, + Class<? extends IDMContext> dmcClassType) { + super(provider, session, dmcClassType); + } - @Override + @Override public void update(final IExpressionUpdate update) { - if (!canParseExpression(update.getExpression())) { - // This method should not be called if canParseExpression() returns false. - // Return an internal error status. - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, "Cannot parse expression", null)); //$NON-NLS-1$ - update.done(); - return; - } - - // Retrieve the list of all elements from the sub-class. Then compare - // each returned element to the expression in the update, using - // testElementForExpression(). The element that matches the expression - // is returned to the client. - // If no matching element is found, the createInvalidExpressionVMContext() - // method is called to a special context. - update(new IChildrenUpdate[] { new VMChildrenUpdate( - update, -1, -1, - new ViewerDataRequestMonitor<List<Object>>(getExecutor(), update) { - @Override - protected void handleSuccess() { - if (getData().size() == 0) { - update.setExpressionElement(createInvalidExpressionVMContext(update.getExpression())); - update.done(); - } else { - final List<Object> elements = getData(); + if (!canParseExpression(update.getExpression())) { + // This method should not be called if canParseExpression() returns false. + // Return an internal error status. + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, + "Cannot parse expression", null)); //$NON-NLS-1$ + update.done(); + return; + } + + // Retrieve the list of all elements from the sub-class. Then compare + // each returned element to the expression in the update, using + // testElementForExpression(). The element that matches the expression + // is returned to the client. + // If no matching element is found, the createInvalidExpressionVMContext() + // method is called to a special context. + update(new IChildrenUpdate[] { + new VMChildrenUpdate(update, -1, -1, new ViewerDataRequestMonitor<List<Object>>(getExecutor(), update) { + @Override + protected void handleSuccess() { + if (getData().size() == 0) { + update.setExpressionElement(createInvalidExpressionVMContext(update.getExpression())); + update.done(); + } else { + final List<Object> elements = getData(); + + final MultiRequestMonitor<DataRequestMonitor<Boolean>> multiRm = new MultiRequestMonitor<DataRequestMonitor<Boolean>>( + getExecutor(), null) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + boolean foundMatchingContext = false; + for (int i = 0; i < getRequestMonitors().size(); i++) { + if (getRequestMonitors().get(i).getData()) { + Object element = elements.get(i); + associateExpression(element, update.getExpression()); + update.setExpressionElement(element); + foundMatchingContext = true; + break; + } + } + if (!foundMatchingContext) { + update.setExpressionElement( + createInvalidExpressionVMContext(update.getExpression())); + } + } else { + update.setStatus(getStatus()); + } + update.done(); + } + }; + multiRm.requireDoneAdding(); + + for (Object element : elements) { + testElementForExpression(element, update.getExpression(), + multiRm.add(new DataRequestMonitor<Boolean>(getExecutor(), null) { + @Override + protected void handleCompleted() { + multiRm.requestMonitorDone(this); + } + })); + } + multiRm.doneAdding(); + } + } + + @Override + protected void handleFailure() { + update.setStatus(getStatus()); + update.done(); + } + }) }); + + } + + /** + * Tests whether the given element matches the given expression. + * + * @param element Element to test against the given expression. + * @param expression Expression to use to check if the element is matching. + * @param rm The request monitor for the result. + */ + @ConfinedToDsfExecutor("#getSession#getExecutor") + protected void testElementForExpression(Object element, IExpression expression, + final DataRequestMonitor<Boolean> rm) { + rm.setData(false); + rm.done(); + } - final MultiRequestMonitor<DataRequestMonitor<Boolean>> multiRm = new MultiRequestMonitor<DataRequestMonitor<Boolean>>(getExecutor(), null) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - boolean foundMatchingContext = false; - for (int i = 0; i < getRequestMonitors().size(); i++) { - if (getRequestMonitors().get(i).getData()) { - Object element = elements.get(i); - associateExpression(element, update.getExpression()); - update.setExpressionElement(element); - foundMatchingContext = true; - break; - } - } - if (!foundMatchingContext) { - update.setExpressionElement(createInvalidExpressionVMContext(update.getExpression())); - } - } else { - update.setStatus(getStatus()); - } - update.done(); - } - }; - multiRm.requireDoneAdding(); - - for (Object element : elements) { - testElementForExpression( - element, update.getExpression(), - multiRm.add( - new DataRequestMonitor<Boolean>(getExecutor(), null) { - @Override - protected void handleCompleted() { - multiRm.requestMonitorDone(this); - } - })); - } - multiRm.doneAdding(); - } - } - - @Override - protected void handleFailure() { - update.setStatus(getStatus()); - update.done(); - } - })} - ); + /** + * Sets the given expression as the expression belonging to the given + * element. + * <p> + * This base class creates VM context elements using the extending class's + * {@link #update(IChildrenUpdate[])} method. The element matching the + * expression is found using {@link #testElementForExpression(Object, IExpression, DataRequestMonitor)}. + * Once the matching element is found it needs to be linked to the expression + * so that it can be distinguished from other contexts created for identical + * but distinct expressions. This method accomplishes this task. Elements + * which are associated with expressions should use the expression object + * for implementation of {@link #equals(Object)} and {@link #hashCode()} + * methods. + * </p> + * + * @param element + * @param expression + */ + protected void associateExpression(Object element, IExpression expression) { + } - } - - - /** - * Tests whether the given element matches the given expression. - * - * @param element Element to test against the given expression. - * @param expression Expression to use to check if the element is matching. - * @param rm The request monitor for the result. - */ - @ConfinedToDsfExecutor("#getSession#getExecutor") - protected void testElementForExpression(Object element, IExpression expression, final DataRequestMonitor<Boolean> rm) { - rm.setData(false); - rm.done(); - } - - /** - * Sets the given expression as the expression belonging to the given - * element. - * <p> - * This base class creates VM context elements using the extending class's - * {@link #update(IChildrenUpdate[])} method. The element matching the - * expression is found using {@link #testElementForExpression(Object, IExpression, DataRequestMonitor)}. - * Once the matching element is found it needs to be linked to the expression - * so that it can be distinguished from other contexts created for identical - * but distinct expressions. This method accomplishes this task. Elements - * which are associated with expressions should use the expression object - * for implementation of {@link #equals(Object)} and {@link #hashCode()} - * methods. - * </p> - * - * @param element - * @param expression - */ - protected void associateExpression(Object element, IExpression expression) { - } - - /** - * Create a place holder for an invalid expression. If for a given expression, - * this VM node returns true from {@link #canParseExpression(IExpression)}, which - * indicates that the expression matches the node's expected format, but the node - * then is not able to find the element represented by the expression, then an - * "invalid" expression context needs to be created. - * <p> - * This method can be overriden to provide a node-specific invalid expression - * context. - * </p> - * - * @param expression Expression to create the context for. - * @return Returns a VM context object representing an invalid expression with - * - * @since 1.1 - */ - protected IVMContext createInvalidExpressionVMContext(IExpression expression) { - return new InvalidExpressionVMContext(this, expression); - } + /** + * Create a place holder for an invalid expression. If for a given expression, + * this VM node returns true from {@link #canParseExpression(IExpression)}, which + * indicates that the expression matches the node's expected format, but the node + * then is not able to find the element represented by the expression, then an + * "invalid" expression context needs to be created. + * <p> + * This method can be overriden to provide a node-specific invalid expression + * context. + * </p> + * + * @param expression Expression to create the context for. + * @return Returns a VM context object representing an invalid expression with + * + * @since 1.1 + */ + protected IVMContext createInvalidExpressionVMContext(IExpression expression) { + return new InvalidExpressionVMContext(this, expression); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/DisabledExpressionVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/DisabledExpressionVMNode.java index d1324af0979..1ced5ccbc37 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/DisabledExpressionVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/DisabledExpressionVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -46,133 +46,135 @@ import org.eclipse.swt.widgets.Composite; /** * Expression VM Node which handles displaying disabled expressions. - * + * * @since 2.1 */ -public class DisabledExpressionVMNode extends AbstractVMNode - implements IExpressionVMNode, IElementEditor -{ - - /** Cached reference to a cell modifier for editing expression strings of disabled expressions */ - private WatchExpressionCellModifier fWatchExpressionCellModifier = new WatchExpressionCellModifier(); - - - private static class DisabledExpressionVMContext extends InvalidExpressionVMContext { - - private static final MessageFormat NO_COLUMN_FORMAT = new MessageFormat(MessagesForExpressionVM.DisabledExpressionVMNode_disabled_no_columns); - - DisabledExpressionVMContext(IVMNode node, IExpression expression) { - super(node, expression); - } - - /** - * Updates the label for the DisabledExpressionVMNode. - */ - @Override - public void update(ILabelUpdate[] updates) { - for (ILabelUpdate update : updates) { - if (update.getColumnIds() == null) { - update.setLabel(NO_COLUMN_FORMAT.format( new Object[] { getExpression().getExpressionText() }), 0); - update.setImageDescriptor(DebugUITools.getImageDescriptor( IDebugUIConstants.IMG_OBJS_EXPRESSION ), 0); - } else { - String[] columnIds = update.getColumnIds(); - - for (int i = 0; i < update.getColumnIds().length; i++) { - if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnIds[i]) || - IDebugVMConstants.COLUMN_ID__NAME.equals(columnIds[i])) - { - update.setLabel(getExpression().getExpressionText(), i); - update.setImageDescriptor(DebugUITools.getImageDescriptor( IDebugUIConstants.IMG_OBJS_EXPRESSION ), i); - } else { - update.setLabel(MessagesForExpressionVM.DisabledExpressionVMNode_disabled_value, i); - } - update.setFontData(JFaceResources.getFontDescriptor(IDebugUIConstants.PREF_VARIABLE_TEXT_FONT).getFontData()[0], i); - } - } - update.done(); - } - } - - } - - public DisabledExpressionVMNode(IVMProvider provider) { - super(provider); - } - - @Override - public boolean canParseExpression(IExpression expression) { - return expression instanceof IWatchExpression && !((IWatchExpression)expression).isEnabled(); - } - - @Override - public int getDeltaFlagsForExpression(IExpression expression, Object event) { - return IModelDelta.NO_CHANGE; - } - - @Override - public int getDeltaFlags(Object event) { - return IModelDelta.NO_CHANGE; - } - - @Override - public void buildDelta(Object event, VMDelta parent, int nodeOffset, RequestMonitor requestMonitor) { - requestMonitor.done(); - } - - @Override - public void update(IChildrenCountUpdate[] updates) { - for (IViewerUpdate update : updates) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "Not supported", null)); //$NON-NLS-1$ - update.done(); - } - } - - @Override - public void update(IChildrenUpdate[] updates) { - for (IViewerUpdate update : updates) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "Not supported", null)); //$NON-NLS-1$ - update.done(); - } - } - - @Override - public void update(IHasChildrenUpdate[] updates) { - for (IViewerUpdate update : updates) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "Not supported", null)); //$NON-NLS-1$ - update.done(); - } - } - - @Override - public void update(IExpressionUpdate update) { - update.setExpressionElement(new DisabledExpressionVMContext(this, update.getExpression())); - update.done(); - } - - @Override - public void buildDeltaForExpression(IExpression expression, int elementIdx, Object event, VMDelta parentDelta, - TreePath path, RequestMonitor rm) - { - rm.done(); - } - - @Override - public void buildDeltaForExpressionElement(Object element, int elementIdx, Object event, VMDelta parentDelta, - RequestMonitor rm) { - rm.done(); - } - - @Override - public CellEditor getCellEditor(IPresentationContext context, String columnId, Object element, Composite parent) { - if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnId)) { - return new TextCellEditor(parent); - } - return null; - } - - @Override - public ICellModifier getCellModifier(IPresentationContext context, Object element) { - return fWatchExpressionCellModifier; - } +public class DisabledExpressionVMNode extends AbstractVMNode implements IExpressionVMNode, IElementEditor { + + /** Cached reference to a cell modifier for editing expression strings of disabled expressions */ + private WatchExpressionCellModifier fWatchExpressionCellModifier = new WatchExpressionCellModifier(); + + private static class DisabledExpressionVMContext extends InvalidExpressionVMContext { + + private static final MessageFormat NO_COLUMN_FORMAT = new MessageFormat( + MessagesForExpressionVM.DisabledExpressionVMNode_disabled_no_columns); + + DisabledExpressionVMContext(IVMNode node, IExpression expression) { + super(node, expression); + } + + /** + * Updates the label for the DisabledExpressionVMNode. + */ + @Override + public void update(ILabelUpdate[] updates) { + for (ILabelUpdate update : updates) { + if (update.getColumnIds() == null) { + update.setLabel(NO_COLUMN_FORMAT.format(new Object[] { getExpression().getExpressionText() }), 0); + update.setImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_EXPRESSION), + 0); + } else { + String[] columnIds = update.getColumnIds(); + + for (int i = 0; i < update.getColumnIds().length; i++) { + if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnIds[i]) + || IDebugVMConstants.COLUMN_ID__NAME.equals(columnIds[i])) { + update.setLabel(getExpression().getExpressionText(), i); + update.setImageDescriptor( + DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_EXPRESSION), i); + } else { + update.setLabel(MessagesForExpressionVM.DisabledExpressionVMNode_disabled_value, i); + } + update.setFontData(JFaceResources.getFontDescriptor(IDebugUIConstants.PREF_VARIABLE_TEXT_FONT) + .getFontData()[0], i); + } + } + update.done(); + } + } + + } + + public DisabledExpressionVMNode(IVMProvider provider) { + super(provider); + } + + @Override + public boolean canParseExpression(IExpression expression) { + return expression instanceof IWatchExpression && !((IWatchExpression) expression).isEnabled(); + } + + @Override + public int getDeltaFlagsForExpression(IExpression expression, Object event) { + return IModelDelta.NO_CHANGE; + } + + @Override + public int getDeltaFlags(Object event) { + return IModelDelta.NO_CHANGE; + } + + @Override + public void buildDelta(Object event, VMDelta parent, int nodeOffset, RequestMonitor requestMonitor) { + requestMonitor.done(); + } + + @Override + public void update(IChildrenCountUpdate[] updates) { + for (IViewerUpdate update : updates) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, + "Not supported", null)); //$NON-NLS-1$ + update.done(); + } + } + + @Override + public void update(IChildrenUpdate[] updates) { + for (IViewerUpdate update : updates) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, + "Not supported", null)); //$NON-NLS-1$ + update.done(); + } + } + + @Override + public void update(IHasChildrenUpdate[] updates) { + for (IViewerUpdate update : updates) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, + "Not supported", null)); //$NON-NLS-1$ + update.done(); + } + } + + @Override + public void update(IExpressionUpdate update) { + update.setExpressionElement(new DisabledExpressionVMContext(this, update.getExpression())); + update.done(); + } + + @Override + public void buildDeltaForExpression(IExpression expression, int elementIdx, Object event, VMDelta parentDelta, + TreePath path, RequestMonitor rm) { + rm.done(); + } + + @Override + public void buildDeltaForExpressionElement(Object element, int elementIdx, Object event, VMDelta parentDelta, + RequestMonitor rm) { + rm.done(); + } + + @Override + public CellEditor getCellEditor(IPresentationContext context, String columnId, Object element, Composite parent) { + if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnId)) { + return new TextCellEditor(parent); + } + return null; + } + + @Override + public ICellModifier getCellModifier(IPresentationContext context, Object element) { + return fWatchExpressionCellModifier; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionColumnPresentation.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionColumnPresentation.java index d58f3078726..7ae8f9fdea9 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionColumnPresentation.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionColumnPresentation.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,65 +20,68 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationCont import org.eclipse.jface.resource.ImageDescriptor; /** - * + * */ public class ExpressionColumnPresentation implements IColumnPresentation { - public static final String ID = DsfUIPlugin.PLUGIN_ID + ".EXPRESSION_COLUMN_PRESENTATION_ID"; //$NON-NLS-1$ + public static final String ID = DsfUIPlugin.PLUGIN_ID + ".EXPRESSION_COLUMN_PRESENTATION_ID"; //$NON-NLS-1$ - @Override + @Override public void init(IPresentationContext context) { - } - - @Override + } + + @Override public void dispose() { - } + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getAvailableColumns() - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getAvailableColumns() + @Override public String[] getAvailableColumns() { - return new String[] { IDebugVMConstants.COLUMN_ID__EXPRESSION, IDebugVMConstants.COLUMN_ID__NAME, IDebugVMConstants.COLUMN_ID__TYPE, IDebugVMConstants.COLUMN_ID__VALUE, IDebugVMConstants.COLUMN_ID__DESCRIPTION, IDebugVMConstants.COLUMN_ID__ADDRESS }; - } + return new String[] { IDebugVMConstants.COLUMN_ID__EXPRESSION, IDebugVMConstants.COLUMN_ID__NAME, + IDebugVMConstants.COLUMN_ID__TYPE, IDebugVMConstants.COLUMN_ID__VALUE, + IDebugVMConstants.COLUMN_ID__DESCRIPTION, IDebugVMConstants.COLUMN_ID__ADDRESS }; + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getHeader(java.lang.String) - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getHeader(java.lang.String) + @Override public String getHeader(String id) { - if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(id)) { - return MessagesForExpressionVM.ExpressionColumnPresentation_expression; - } else if (IDebugVMConstants.COLUMN_ID__NAME.equals(id)) { - return MessagesForExpressionVM.ExpressionColumnPresentation_name; - } else if (IDebugVMConstants.COLUMN_ID__TYPE.equals(id)) { - return MessagesForExpressionVM.ExpressionColumnPresentation_type; - } else if (IDebugVMConstants.COLUMN_ID__VALUE.equals(id)) { - return MessagesForExpressionVM.ExpressionColumnPresentation_value; - } else if (IDebugVMConstants.COLUMN_ID__DESCRIPTION.equals(id)) { - return MessagesForExpressionVM.ExpressionColumnPresentation_description; - } else if (IDebugVMConstants.COLUMN_ID__ADDRESS.equals(id)) { - return MessagesForExpressionVM.ExpressionColumnPresentation_address; - } - return null; - } + if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(id)) { + return MessagesForExpressionVM.ExpressionColumnPresentation_expression; + } else if (IDebugVMConstants.COLUMN_ID__NAME.equals(id)) { + return MessagesForExpressionVM.ExpressionColumnPresentation_name; + } else if (IDebugVMConstants.COLUMN_ID__TYPE.equals(id)) { + return MessagesForExpressionVM.ExpressionColumnPresentation_type; + } else if (IDebugVMConstants.COLUMN_ID__VALUE.equals(id)) { + return MessagesForExpressionVM.ExpressionColumnPresentation_value; + } else if (IDebugVMConstants.COLUMN_ID__DESCRIPTION.equals(id)) { + return MessagesForExpressionVM.ExpressionColumnPresentation_description; + } else if (IDebugVMConstants.COLUMN_ID__ADDRESS.equals(id)) { + return MessagesForExpressionVM.ExpressionColumnPresentation_address; + } + return null; + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getId() - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getId() + @Override public String getId() { - return ID; - } - - @Override + return ID; + } + + @Override public ImageDescriptor getImageDescriptor(String id) { - return null; - } + return null; + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getInitialColumns() - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getInitialColumns() + @Override public String[] getInitialColumns() { - return new String[] { IDebugVMConstants.COLUMN_ID__EXPRESSION, IDebugVMConstants.COLUMN_ID__TYPE, IDebugVMConstants.COLUMN_ID__VALUE }; - } - - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#isOptional() - @Override + return new String[] { IDebugVMConstants.COLUMN_ID__EXPRESSION, IDebugVMConstants.COLUMN_ID__TYPE, + IDebugVMConstants.COLUMN_ID__VALUE }; + } + + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#isOptional() + @Override public boolean isOptional() { - return true; - } + return true; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionManagerVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionManagerVMNode.java index 68d9ab3be90..750cca28713 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionManagerVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionManagerVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -57,326 +57,316 @@ import org.eclipse.swt.widgets.Composite; * <ol> then to call the configured expression nodes to parse the expression string.</ol> * </li> * <p> - * This node is not intended to have any standard child nodes, therefore - * the implementation of {@link #setChildNodes(IVMNode[])} throws an exception. + * This node is not intended to have any standard child nodes, therefore + * the implementation of {@link #setChildNodes(IVMNode[])} throws an exception. * Instead users should call {@link #setExpressionNodes(IExpressionVMNode[])} * to configure the nodes that this node will delegate to when processing expressions. - * </p> + * </p> */ -public class ExpressionManagerVMNode extends AbstractVMNode - implements IElementLabelProvider, IElementEditor -{ - /** - * VMC for a new expression object to be added. When user clicks on this node to - * edit it, he will create a new expression. - */ - public class NewExpressionVMC extends AbstractVMContext { - public NewExpressionVMC() { - super(ExpressionManagerVMNode.this); - } - - @Override - public <T> T getAdapter(Class<T> adapter) { - return super.getAdapter(adapter); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof NewExpressionVMC; - } - - @Override - public int hashCode() { - return getClass().hashCode(); - } - } - - /** Local reference to the global expression manager */ - private IExpressionManager fManager = DebugPlugin.getDefault().getExpressionManager(); - - /** Cached reference to a cell modifier for editing expression strings of invalid expressions */ - private ICellModifier fWatchExpressionCellModifier = null; - - /** - * @since 2.1 - * - * @return The cell modifier to be used when editing. If you need to provide - * a custom cell editor you would override this method. - */ - protected ICellModifier createCellModifier() { - return new WatchExpressionCellModifier(); - } - - public ExpressionManagerVMNode(ExpressionVMProvider provider) { - super(provider); - } - - @Override - public String toString() { - return "ExpressionManagerVMNode"; //$NON-NLS-1$ - } - - private ExpressionVMProvider getExpressionVMProvider() { - return (ExpressionVMProvider)getVMProvider(); - } - - @Override - public void update(IHasChildrenUpdate[] updates) { - // Test availability of children based on whether there are any expressions - // in the manager. We assume that the getExpressions() will just read - // local state data, so we don't bother using a job to perform this - // operation. - for (int i = 0; i < updates.length; i++) { - boolean hasChildren = fManager.getExpressions().length != 0; - if (!hasChildren && updates[i].getPresentationContext().getColumns() != null) { - hasChildren = true; - } - - updates[i].setHasChilren(hasChildren); - updates[i].done(); - } - } - - @Override - public void update(IChildrenCountUpdate[] updates) { - for (IChildrenCountUpdate update : updates) { - if (!checkUpdate(update)) continue; - - // We assume that the getExpressions() will just read local state data, - // so we don't bother using a job to perform this operation. - int count = fManager.getExpressions().length; - - // Account for "Add New Expression" element - if (update.getPresentationContext().getColumns() != null) { - count += 1; - } - - update.setChildCount(count); - update.done(); - } - } - - @Override - public void update(final IChildrenUpdate[] updates) { - for (IChildrenUpdate update : updates) { - doUpdateChildren(update); - } - } - - public void doUpdateChildren(final IChildrenUpdate update) { - final IExpression[] expressions = fManager.getExpressions(); - - // For each (expression) element in update, find the layout node that can - // parse it. And for each expression that has a corresponding layout node, - // call IExpressionLayoutNode#getElementForExpression to generate a VMC. - // Since the last is an async call, we need to create a multi-RM to wait - // for all the calls to complete. - final CountingRequestMonitor multiRm = new ViewerCountingRequestMonitor(getVMProvider().getExecutor(), update); - int multiRmCount = 0; - - int lowOffset= update.getOffset(); - if (lowOffset < 0) { - lowOffset = 0; - } - int length= update.getLength(); +public class ExpressionManagerVMNode extends AbstractVMNode implements IElementLabelProvider, IElementEditor { + /** + * VMC for a new expression object to be added. When user clicks on this node to + * edit it, he will create a new expression. + */ + public class NewExpressionVMC extends AbstractVMContext { + public NewExpressionVMC() { + super(ExpressionManagerVMNode.this); + } + + @Override + public <T> T getAdapter(Class<T> adapter) { + return super.getAdapter(adapter); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof NewExpressionVMC; + } + + @Override + public int hashCode() { + return getClass().hashCode(); + } + } + + /** Local reference to the global expression manager */ + private IExpressionManager fManager = DebugPlugin.getDefault().getExpressionManager(); + + /** Cached reference to a cell modifier for editing expression strings of invalid expressions */ + private ICellModifier fWatchExpressionCellModifier = null; + + /** + * @since 2.1 + * + * @return The cell modifier to be used when editing. If you need to provide + * a custom cell editor you would override this method. + */ + protected ICellModifier createCellModifier() { + return new WatchExpressionCellModifier(); + } + + public ExpressionManagerVMNode(ExpressionVMProvider provider) { + super(provider); + } + + @Override + public String toString() { + return "ExpressionManagerVMNode"; //$NON-NLS-1$ + } + + private ExpressionVMProvider getExpressionVMProvider() { + return (ExpressionVMProvider) getVMProvider(); + } + + @Override + public void update(IHasChildrenUpdate[] updates) { + // Test availability of children based on whether there are any expressions + // in the manager. We assume that the getExpressions() will just read + // local state data, so we don't bother using a job to perform this + // operation. + for (int i = 0; i < updates.length; i++) { + boolean hasChildren = fManager.getExpressions().length != 0; + if (!hasChildren && updates[i].getPresentationContext().getColumns() != null) { + hasChildren = true; + } + + updates[i].setHasChilren(hasChildren); + updates[i].done(); + } + } + + @Override + public void update(IChildrenCountUpdate[] updates) { + for (IChildrenCountUpdate update : updates) { + if (!checkUpdate(update)) + continue; + + // We assume that the getExpressions() will just read local state data, + // so we don't bother using a job to perform this operation. + int count = fManager.getExpressions().length; + + // Account for "Add New Expression" element + if (update.getPresentationContext().getColumns() != null) { + count += 1; + } + + update.setChildCount(count); + update.done(); + } + } + + @Override + public void update(final IChildrenUpdate[] updates) { + for (IChildrenUpdate update : updates) { + doUpdateChildren(update); + } + } + + public void doUpdateChildren(final IChildrenUpdate update) { + final IExpression[] expressions = fManager.getExpressions(); + + // For each (expression) element in update, find the layout node that can + // parse it. And for each expression that has a corresponding layout node, + // call IExpressionLayoutNode#getElementForExpression to generate a VMC. + // Since the last is an async call, we need to create a multi-RM to wait + // for all the calls to complete. + final CountingRequestMonitor multiRm = new ViewerCountingRequestMonitor(getVMProvider().getExecutor(), update); + int multiRmCount = 0; + + int lowOffset = update.getOffset(); + if (lowOffset < 0) { + lowOffset = 0; + } + int length = update.getLength(); if (length <= 0) { length = expressions.length; } - final int highOffset= lowOffset + length; - // If columns are present, add the "Add New Expression" element. + final int highOffset = lowOffset + length; + // If columns are present, add the "Add New Expression" element. int expressionsLength = expressions.length; if (update.getPresentationContext().getColumns() != null) { - expressionsLength += 1; + expressionsLength += 1; } for (int i = lowOffset; i < highOffset && i < expressionsLength; i++) { - if (i < expressions.length) { - multiRmCount++; - final int childIndex = i; - final IExpression expression = expressions[i]; - // getElementForExpression() accepts a IElementsUpdate as an argument. - // Construct an instance of VMElementsUpdate which will call a - // the request monitor when it is finished. The request monitor - // will in turn set the element in the update argument in this method. - ((ExpressionVMProvider)getVMProvider()).update( - new VMExpressionUpdate( - update, expression, - new DataRequestMonitor<Object>(getVMProvider().getExecutor(), multiRm) { - @Override - protected void handleSuccess() { - update.setChild(getData(), childIndex); - multiRm.done(); - } - - @Override - protected void handleError() { - update.setChild(new InvalidExpressionVMContext(ExpressionManagerVMNode.this, expression), childIndex); - multiRm.done(); - } - }) - ); - } else { - // Last element in the list of expressions is the "add new expression" - // dummy entry. - update.setChild(new NewExpressionVMC(), i); - } - } - - // If no expressions were parsed, we're finished. - // Set the count to the counting RM. - multiRm.setDoneCount(multiRmCount); - } - - @Override + if (i < expressions.length) { + multiRmCount++; + final int childIndex = i; + final IExpression expression = expressions[i]; + // getElementForExpression() accepts a IElementsUpdate as an argument. + // Construct an instance of VMElementsUpdate which will call a + // the request monitor when it is finished. The request monitor + // will in turn set the element in the update argument in this method. + ((ExpressionVMProvider) getVMProvider()).update(new VMExpressionUpdate(update, expression, + new DataRequestMonitor<Object>(getVMProvider().getExecutor(), multiRm) { + @Override + protected void handleSuccess() { + update.setChild(getData(), childIndex); + multiRm.done(); + } + + @Override + protected void handleError() { + update.setChild( + new InvalidExpressionVMContext(ExpressionManagerVMNode.this, expression), + childIndex); + multiRm.done(); + } + })); + } else { + // Last element in the list of expressions is the "add new expression" + // dummy entry. + update.setChild(new NewExpressionVMC(), i); + } + } + + // If no expressions were parsed, we're finished. + // Set the count to the counting RM. + multiRm.setDoneCount(multiRmCount); + } + + @Override public void update(ILabelUpdate[] updates) { - // The label update handler only handles labels for the invalid expression VMCs. - // The expression layout nodes are responsible for supplying label providers - // for their VMCs. - for (ILabelUpdate update : updates) { - if (update.getElement() instanceof NewExpressionVMC) { - updateNewExpressionVMCLabel(update, (NewExpressionVMC) update.getElement()); - } else { - update.done(); - } - } - } - - /** - * Updates the label for the NewExpressionVMC. - */ - private void updateNewExpressionVMCLabel(ILabelUpdate update, NewExpressionVMC vmc) { - String[] columnIds = update.getColumnIds() != null ? - update.getColumnIds() : new String[0]; - - for (int i = 0; i < columnIds.length; i++) { - // Bug 373468: show "Add New Expression" label in name column if - // expression column is not shown. - if ( IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnIds[i]) || - (IDebugVMConstants.COLUMN_ID__NAME.equals(columnIds[i]) && - !Arrays.asList(columnIds).contains(IDebugVMConstants.COLUMN_ID__EXPRESSION)) ) - { - update.setLabel(MessagesForExpressionVM.ExpressionManagerLayoutNode__newExpression_label, i); - update.setImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_LCL_ADD), i); - FontData fontData = JFaceResources.getFontDescriptor(IDebugUIConstants.PREF_VARIABLE_TEXT_FONT).getFontData()[0]; - // Bugzilla 287598: Distinguish 'Add new expression' entry from actual expressions - fontData.setStyle(SWT.ITALIC); - update.setFontData(fontData, i); - } else { - update.setLabel("", i); //$NON-NLS-1$ - } - } - - update.done(); - } - - @Override + // The label update handler only handles labels for the invalid expression VMCs. + // The expression layout nodes are responsible for supplying label providers + // for their VMCs. + for (ILabelUpdate update : updates) { + if (update.getElement() instanceof NewExpressionVMC) { + updateNewExpressionVMCLabel(update, (NewExpressionVMC) update.getElement()); + } else { + update.done(); + } + } + } + + /** + * Updates the label for the NewExpressionVMC. + */ + private void updateNewExpressionVMCLabel(ILabelUpdate update, NewExpressionVMC vmc) { + String[] columnIds = update.getColumnIds() != null ? update.getColumnIds() : new String[0]; + + for (int i = 0; i < columnIds.length; i++) { + // Bug 373468: show "Add New Expression" label in name column if + // expression column is not shown. + if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnIds[i]) + || (IDebugVMConstants.COLUMN_ID__NAME.equals(columnIds[i]) + && !Arrays.asList(columnIds).contains(IDebugVMConstants.COLUMN_ID__EXPRESSION))) { + update.setLabel(MessagesForExpressionVM.ExpressionManagerLayoutNode__newExpression_label, i); + update.setImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_LCL_ADD), i); + FontData fontData = JFaceResources.getFontDescriptor(IDebugUIConstants.PREF_VARIABLE_TEXT_FONT) + .getFontData()[0]; + // Bugzilla 287598: Distinguish 'Add new expression' entry from actual expressions + fontData.setStyle(SWT.ITALIC); + update.setFontData(fontData, i); + } else { + update.setLabel("", i); //$NON-NLS-1$ + } + } + + update.done(); + } + + @Override public int getDeltaFlags(Object event) { - int retVal = 0; - - // Add a flag if the list of expressions in the global expression manager has changed. - if (event instanceof ExpressionsChangedEvent) { - retVal |= IModelDelta.ADDED | IModelDelta.REMOVED | IModelDelta.INSERTED | IModelDelta.CONTENT ; - } - - if ( event instanceof PropertyChangeEvent && - IPresentationContext.PROPERTY_COLUMNS.equals(((PropertyChangeEvent)event).getProperty()) ) - { - retVal |= IModelDelta.CONTENT; - } - - for (IExpression expression : fManager.getExpressions()) { - retVal |= getExpressionVMProvider().getDeltaFlagsForExpression(expression, event); - } - - return retVal; - } - - @Override - public void buildDelta(final Object event, final VMDelta parentDelta, final int nodeOffset, final RequestMonitor requestMonitor) { - if (event instanceof ExpressionsChangedEvent) { - buildDeltaForExpressionsChangedEvent((ExpressionsChangedEvent)event, parentDelta, nodeOffset, requestMonitor); - } - else if ( event instanceof PropertyChangeEvent && - IPresentationContext.PROPERTY_COLUMNS.equals(((PropertyChangeEvent)event).getProperty()) ) - { - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - requestMonitor.done(); - } - else { - - // For each expression, find its corresponding node and ask that - // layout node for its delta flags for given event. If there are delta flags to be - // generated, call the asynchronous method to do so. - CountingRequestMonitor multiRm = new CountingRequestMonitor(getExecutor(), requestMonitor); - - int buildDeltaForExpressionCallCount = 0; - - IExpression[] expressions = fManager.getExpressions(); - for (int i = 0; i < expressions.length; i++ ) { - int flags = getExpressionVMProvider().getDeltaFlagsForExpression(expressions[i], event); - // If the given expression has no delta flags, skip it. - if (flags == IModelDelta.NO_CHANGE) continue; - - int elementOffset = nodeOffset >= 0 ? nodeOffset + i : -1; - getExpressionVMProvider().buildDeltaForExpression( - expressions[i], elementOffset, event, parentDelta, getTreePathFromDelta(parentDelta), - new RequestMonitor(getExecutor(), multiRm)); - buildDeltaForExpressionCallCount++; - } - - multiRm.setDoneCount(buildDeltaForExpressionCallCount); - } - } - - private void buildDeltaForExpressionsChangedEvent(ExpressionsChangedEvent event, VMDelta parentDelta, - int nodeOffset, RequestMonitor requestMonitor) - { - CountingRequestMonitor multiRm = new CountingRequestMonitor(getExecutor(), requestMonitor); - for (int i = 0; i < event.getExpressions().length; i++) { - int expIndex = event.getIndex() != -1 - ? nodeOffset + event.getIndex() + i - : -1; - getExpressionVMProvider().buildDeltaForExpression( - event.getExpressions()[i], expIndex, event, parentDelta, getTreePathFromDelta(parentDelta), - new RequestMonitor(getExecutor(), multiRm)); - } - multiRm.setDoneCount(event.getExpressions().length); - } - - private TreePath getTreePathFromDelta(IModelDelta delta) { - List<Object> elementList = new LinkedList<Object>(); - IModelDelta listDelta = delta; - elementList.add(0, listDelta.getElement()); - while (listDelta.getParentDelta() != null) { - elementList.add(0, listDelta.getElement()); - listDelta = listDelta.getParentDelta(); - } - return new TreePath(elementList.toArray()); - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellEditor(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.String, java.lang.Object, org.eclipse.swt.widgets.Composite) - */ - @Override + int retVal = 0; + + // Add a flag if the list of expressions in the global expression manager has changed. + if (event instanceof ExpressionsChangedEvent) { + retVal |= IModelDelta.ADDED | IModelDelta.REMOVED | IModelDelta.INSERTED | IModelDelta.CONTENT; + } + + if (event instanceof PropertyChangeEvent + && IPresentationContext.PROPERTY_COLUMNS.equals(((PropertyChangeEvent) event).getProperty())) { + retVal |= IModelDelta.CONTENT; + } + + for (IExpression expression : fManager.getExpressions()) { + retVal |= getExpressionVMProvider().getDeltaFlagsForExpression(expression, event); + } + + return retVal; + } + + @Override + public void buildDelta(final Object event, final VMDelta parentDelta, final int nodeOffset, + final RequestMonitor requestMonitor) { + if (event instanceof ExpressionsChangedEvent) { + buildDeltaForExpressionsChangedEvent((ExpressionsChangedEvent) event, parentDelta, nodeOffset, + requestMonitor); + } else if (event instanceof PropertyChangeEvent + && IPresentationContext.PROPERTY_COLUMNS.equals(((PropertyChangeEvent) event).getProperty())) { + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + requestMonitor.done(); + } else { + + // For each expression, find its corresponding node and ask that + // layout node for its delta flags for given event. If there are delta flags to be + // generated, call the asynchronous method to do so. + CountingRequestMonitor multiRm = new CountingRequestMonitor(getExecutor(), requestMonitor); + + int buildDeltaForExpressionCallCount = 0; + + IExpression[] expressions = fManager.getExpressions(); + for (int i = 0; i < expressions.length; i++) { + int flags = getExpressionVMProvider().getDeltaFlagsForExpression(expressions[i], event); + // If the given expression has no delta flags, skip it. + if (flags == IModelDelta.NO_CHANGE) + continue; + + int elementOffset = nodeOffset >= 0 ? nodeOffset + i : -1; + getExpressionVMProvider().buildDeltaForExpression(expressions[i], elementOffset, event, parentDelta, + getTreePathFromDelta(parentDelta), new RequestMonitor(getExecutor(), multiRm)); + buildDeltaForExpressionCallCount++; + } + + multiRm.setDoneCount(buildDeltaForExpressionCallCount); + } + } + + private void buildDeltaForExpressionsChangedEvent(ExpressionsChangedEvent event, VMDelta parentDelta, + int nodeOffset, RequestMonitor requestMonitor) { + CountingRequestMonitor multiRm = new CountingRequestMonitor(getExecutor(), requestMonitor); + for (int i = 0; i < event.getExpressions().length; i++) { + int expIndex = event.getIndex() != -1 ? nodeOffset + event.getIndex() + i : -1; + getExpressionVMProvider().buildDeltaForExpression(event.getExpressions()[i], expIndex, event, parentDelta, + getTreePathFromDelta(parentDelta), new RequestMonitor(getExecutor(), multiRm)); + } + multiRm.setDoneCount(event.getExpressions().length); + } + + private TreePath getTreePathFromDelta(IModelDelta delta) { + List<Object> elementList = new LinkedList<Object>(); + IModelDelta listDelta = delta; + elementList.add(0, listDelta.getElement()); + while (listDelta.getParentDelta() != null) { + elementList.add(0, listDelta.getElement()); + listDelta = listDelta.getParentDelta(); + } + return new TreePath(elementList.toArray()); + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellEditor(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.String, java.lang.Object, org.eclipse.swt.widgets.Composite) + */ + @Override public CellEditor getCellEditor(IPresentationContext context, String columnId, Object element, Composite parent) { - if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnId) || - (IDebugVMConstants.COLUMN_ID__NAME.equals(columnId) && - !Arrays.asList(context.getColumns()).contains(IDebugVMConstants.COLUMN_ID__EXPRESSION)) ) - { - return new TextCellEditor(parent); - } - return null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellModifier(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.Object) - */ - @Override + if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnId) + || (IDebugVMConstants.COLUMN_ID__NAME.equals(columnId) + && !Arrays.asList(context.getColumns()).contains(IDebugVMConstants.COLUMN_ID__EXPRESSION))) { + return new TextCellEditor(parent); + } + return null; + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellModifier(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.Object) + */ + @Override public ICellModifier getCellModifier(IPresentationContext context, Object element) { - if ( fWatchExpressionCellModifier == null ) { - fWatchExpressionCellModifier = createCellModifier(); - } - return fWatchExpressionCellModifier; - } + if (fWatchExpressionCellModifier == null) { + fWatchExpressionCellModifier = createCellModifier(); + } + return fWatchExpressionCellModifier; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionVMProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionVMProvider.java index 1ee89e3096f..3ce6f9265e1 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionVMProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionVMProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -62,387 +62,387 @@ import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.TreePath; /** - * The expression provider is used to populate the contents of the expressions - * view. The node hierarchy in this view is a little different than in a typical + * The expression provider is used to populate the contents of the expressions + * view. The node hierarchy in this view is a little different than in a typical * provider: the expression manager node should be registered as the single child * of the root node and no nodes should be registered as children of expression node. - * Instead the top level expression nodes should be registered with a call to + * Instead the top level expression nodes should be registered with a call to * {@link #setExpressionNodes(IExpressionVMNode[])}. And each expression node can * have its own sub-hierarchy of elements as needed. However all nodes configured - * with this provider (with the exception of the root and the expression manager) + * with this provider (with the exception of the root and the expression manager) * should implement {@link IExpressionVMNode}. - */ + */ @SuppressWarnings("restriction") -public class ExpressionVMProvider extends AbstractElementVMProvider - implements IExpressionsListener2 -{ - private IExpressionVMNode[] fExpressionNodes; +public class ExpressionVMProvider extends AbstractElementVMProvider implements IExpressionsListener2 { + private IExpressionVMNode[] fExpressionNodes; - private IPropertyChangeListener fPreferencesListener = new IPropertyChangeListener() { - @Override + private IPropertyChangeListener fPreferencesListener = new IPropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent event) { - String property = event.getProperty(); + String property = event.getProperty(); if (property.equals(IDsfDebugUIConstants.PREF_WAIT_FOR_VIEW_UPDATE_AFTER_STEP_ENABLE)) { - IPreferenceStore store = DsfDebugUITools.getPreferenceStore(); - setDelayEventHandleForViewUpdate(store.getBoolean(property)); - } - } - }; - - private IPropertyChangeListener fPresentationContextListener = new IPropertyChangeListener() { - @Override + IPreferenceStore store = DsfDebugUITools.getPreferenceStore(); + setDelayEventHandleForViewUpdate(store.getBoolean(property)); + } + } + }; + + private IPropertyChangeListener fPresentationContextListener = new IPropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent event) { - handleEvent(event); - } - }; - - public ExpressionVMProvider(AbstractVMAdapter adapter, IPresentationContext context, DsfSession session) { - super(adapter, context, session); - - context.addPropertyChangeListener(fPresentationContextListener); - - IPreferenceStore store = DsfDebugUITools.getPreferenceStore(); - store.addPropertyChangeListener(fPreferencesListener); - setDelayEventHandleForViewUpdate(store.getBoolean(IDsfDebugUIConstants.PREF_WAIT_FOR_VIEW_UPDATE_AFTER_STEP_ENABLE)); - - // The VM provider has to handle all events that result in model deltas. - // Add the provider as listener to expression changes events. - DebugPlugin.getDefault().getExpressionManager().addExpressionListener(this); - - configureLayout(); - } - - @Override - protected DefaultVMContentProviderStrategy createContentStrategy() { - return new ExpressionVMProviderContentStragegy(this); - } - - @Override - protected IVMModelProxy createModelProxyStrategy(Object rootElement) { - return new ExpressionVMProviderModelProxyStrategy(this, rootElement); - } - - /** - * Updates the given expression element. This method is used by the - * expression manager node to obtain a view model element based on the - * {@link IExpression} retrieved from the expression manager. The - * implementation of this method (which is in the content strategy), - * checks the configured expression nodes to see which one can - * process the given expression, when it finds it it delegates - * to that expression node's {@link IExpressionVMNode#update(IExpressionUpdate)} - * method. - * @param update Expression update to process. - */ - public void update(IExpressionUpdate update) { - ((ExpressionVMProviderContentStragegy)getContentStrategy()).update(update); - } - - /** - * Retrieves the delta flags that can be generated for the given expression - * and the given event. This method is used by the - * expression manager node to obtain the delta flags based on the - * {@link IExpression} retrieved from the expression manager. The - * implementation of this method (which is in the model proxy strategy), - * checks the configured expression nodes to see which one can - * process the given expression, when it finds it it delegates - * to that expression node's {@link IExpressionVMNode#getDeltaFlagsForExpression(IExpression, Object)} - * method. - */ - public int getDeltaFlagsForExpression(IExpression expression, Object event) { - // Workaround: find the first active proxy and use it. - final List<IVMModelProxy> activeModelProxies= getActiveModelProxies(); - int count = activeModelProxies.size(); - if (count > 0) { - return ((ExpressionVMProviderModelProxyStrategy)activeModelProxies.get(count - 1)).getDeltaFlagsForExpression(expression, event); - } - return 0; - } - - /** - * Builds the model delta based on the given expression - * and the given event. This method is used by the - * expression manager to build the delta based on the - * {@link IExpression} retrieved from the expression manager. The - * implementation of this method (which is in the model proxy strategy), - * checks the configured expression nodes to see which one can - * process the given expression, when it finds it it delegates - * to that expression node's {@link IExpressionVMNode#buildDeltaForExpression(IExpression, int, Object, ModelDelta, TreePath, RequestMonitor)} - * and {@link IExpressionVMNode#buildDeltaForExpressionElement(Object, int, Object, ModelDelta, RequestMonitor) - * methods. - */ - public void buildDeltaForExpression(final IExpression expression, final int expressionElementIdx, final Object event, - final VMDelta parentDelta, final TreePath path, final RequestMonitor rm) - { - // Workaround: find the first active proxy and use it. - if (!getActiveModelProxies().isEmpty()) { - ((ExpressionVMProviderModelProxyStrategy)getActiveModelProxies().get(0)).buildDeltaForExpression( - expression, expressionElementIdx, event, parentDelta, path, rm); - } else { - rm.done(); - } - } - - /** - * Configures the given nodes as the top-level expression nodes. - */ - protected void setExpressionNodes(IExpressionVMNode[] nodes) { - fExpressionNodes = nodes; - - // Call the base class to make sure that the nodes are also - // returned by the getAllNodes method. - for (IExpressionVMNode node : nodes) { - addNode(node); - } - } - - /** - * Returns the list of configured top-level expression nodes. - * @return - */ - public IExpressionVMNode[] getExpressionNodes() { - return fExpressionNodes; - } - - /** - * Configures the nodes of this provider. This method may be over-ridden by - * sub classes to create an alternate configuration in this provider. - */ - protected void configureLayout() { - - /* - * Allocate the synchronous data providers. - */ - SyncRegisterDataAccess syncRegDataAccess = new SyncRegisterDataAccess(getSession()); - SyncVariableDataAccess syncvarDataAccess = new SyncVariableDataAccess(getSession()) ; - - /* - * Create the top level node which provides the anchor starting point. - */ - IRootVMNode rootNode = new RootDMVMNode(this); - - /* - * Now the Over-arching management node. - */ - if (IDsfDebugUIConstants.ID_EXPRESSION_HOVER.equals(getPresentationContext().getId())) { - SingleExpressionVMNode expressionManagerNode = new SingleExpressionVMNode(this); - addChildNodes(rootNode, new IVMNode[] { expressionManagerNode }); - } else { - ExpressionManagerVMNode expressionManagerNode = new ExpressionManagerVMNode(this); - addChildNodes(rootNode, new IVMNode[] {expressionManagerNode}); - } - - // Disabled expression node intercepts disabled expressions and prevents them from being - // evaluated by other nodes. - IExpressionVMNode disabledExpressionNode = new DisabledExpressionVMNode(this); - - /* - * The expression view wants to support fully all of the components of the register view. - */ - IExpressionVMNode registerGroupNode = new RegisterGroupVMNode(this, getSession(), syncRegDataAccess); - - IExpressionVMNode registerNode = new RegisterVMNode(this, getSession(), syncRegDataAccess); - addChildNodes(registerGroupNode, new IExpressionVMNode[] {registerNode}); - - /* - * Create the next level which is the bit-field level. - */ - IVMNode bitFieldNode = new RegisterBitFieldVMNode(this, getSession(), syncRegDataAccess); - addChildNodes(registerNode, new IVMNode[] { bitFieldNode }); - - /* - * Create the support for the SubExpressions. Anything which is brought into the expressions - * view comes in as a fully qualified expression so we go directly to the SubExpression layout - * node. - */ - VariableVMNode variableNode = new VariableVMNode(this, getSession(), syncvarDataAccess); - addChildNodes(variableNode, new IExpressionVMNode[] {variableNode}); - - /* - * Hook up IExpressions2 if it exists. - */ - hookUpCastingSupport(syncvarDataAccess, variableNode); - - /* - * Tell the expression node which sub-nodes it will directly support. It is very important - * that the variables node be the last in this chain. The model assumes that there is some - * form of metalanguage expression syntax which each of the nodes evaluates and decides if - * they are dealing with it or not. The variables node assumes that the expression is fully - * qualified and there is no analysis or subdivision of the expression it will parse. So it - * it currently the case that the location of the nodes within the array being passed in is - * the order of search/evaluation. Thus variables wants to be last. Otherwise it would just - * assume what it was passed was for it and the real node which wants to handle it would be - * left out in the cold. - */ - setExpressionNodes(new IExpressionVMNode[] {disabledExpressionNode, registerGroupNode, variableNode}); - - /* - * Let the work know which is the top level node. - */ - setRootNode(rootNode); - } + handleEvent(event); + } + }; + + public ExpressionVMProvider(AbstractVMAdapter adapter, IPresentationContext context, DsfSession session) { + super(adapter, context, session); + + context.addPropertyChangeListener(fPresentationContextListener); + + IPreferenceStore store = DsfDebugUITools.getPreferenceStore(); + store.addPropertyChangeListener(fPreferencesListener); + setDelayEventHandleForViewUpdate( + store.getBoolean(IDsfDebugUIConstants.PREF_WAIT_FOR_VIEW_UPDATE_AFTER_STEP_ENABLE)); + + // The VM provider has to handle all events that result in model deltas. + // Add the provider as listener to expression changes events. + DebugPlugin.getDefault().getExpressionManager().addExpressionListener(this); + + configureLayout(); + } + + @Override + protected DefaultVMContentProviderStrategy createContentStrategy() { + return new ExpressionVMProviderContentStragegy(this); + } + + @Override + protected IVMModelProxy createModelProxyStrategy(Object rootElement) { + return new ExpressionVMProviderModelProxyStrategy(this, rootElement); + } + + /** + * Updates the given expression element. This method is used by the + * expression manager node to obtain a view model element based on the + * {@link IExpression} retrieved from the expression manager. The + * implementation of this method (which is in the content strategy), + * checks the configured expression nodes to see which one can + * process the given expression, when it finds it it delegates + * to that expression node's {@link IExpressionVMNode#update(IExpressionUpdate)} + * method. + * @param update Expression update to process. + */ + public void update(IExpressionUpdate update) { + ((ExpressionVMProviderContentStragegy) getContentStrategy()).update(update); + } + + /** + * Retrieves the delta flags that can be generated for the given expression + * and the given event. This method is used by the + * expression manager node to obtain the delta flags based on the + * {@link IExpression} retrieved from the expression manager. The + * implementation of this method (which is in the model proxy strategy), + * checks the configured expression nodes to see which one can + * process the given expression, when it finds it it delegates + * to that expression node's {@link IExpressionVMNode#getDeltaFlagsForExpression(IExpression, Object)} + * method. + */ + public int getDeltaFlagsForExpression(IExpression expression, Object event) { + // Workaround: find the first active proxy and use it. + final List<IVMModelProxy> activeModelProxies = getActiveModelProxies(); + int count = activeModelProxies.size(); + if (count > 0) { + return ((ExpressionVMProviderModelProxyStrategy) activeModelProxies.get(count - 1)) + .getDeltaFlagsForExpression(expression, event); + } + return 0; + } + + /** + * Builds the model delta based on the given expression + * and the given event. This method is used by the + * expression manager to build the delta based on the + * {@link IExpression} retrieved from the expression manager. The + * implementation of this method (which is in the model proxy strategy), + * checks the configured expression nodes to see which one can + * process the given expression, when it finds it it delegates + * to that expression node's {@link IExpressionVMNode#buildDeltaForExpression(IExpression, int, Object, ModelDelta, TreePath, RequestMonitor)} + * and {@link IExpressionVMNode#buildDeltaForExpressionElement(Object, int, Object, ModelDelta, RequestMonitor) + * methods. + */ + public void buildDeltaForExpression(final IExpression expression, final int expressionElementIdx, + final Object event, final VMDelta parentDelta, final TreePath path, final RequestMonitor rm) { + // Workaround: find the first active proxy and use it. + if (!getActiveModelProxies().isEmpty()) { + ((ExpressionVMProviderModelProxyStrategy) getActiveModelProxies().get(0)) + .buildDeltaForExpression(expression, expressionElementIdx, event, parentDelta, path, rm); + } else { + rm.done(); + } + } + + /** + * Configures the given nodes as the top-level expression nodes. + */ + protected void setExpressionNodes(IExpressionVMNode[] nodes) { + fExpressionNodes = nodes; + + // Call the base class to make sure that the nodes are also + // returned by the getAllNodes method. + for (IExpressionVMNode node : nodes) { + addNode(node); + } + } + + /** + * Returns the list of configured top-level expression nodes. + * @return + */ + public IExpressionVMNode[] getExpressionNodes() { + return fExpressionNodes; + } + + /** + * Configures the nodes of this provider. This method may be over-ridden by + * sub classes to create an alternate configuration in this provider. + */ + protected void configureLayout() { + + /* + * Allocate the synchronous data providers. + */ + SyncRegisterDataAccess syncRegDataAccess = new SyncRegisterDataAccess(getSession()); + SyncVariableDataAccess syncvarDataAccess = new SyncVariableDataAccess(getSession()); + + /* + * Create the top level node which provides the anchor starting point. + */ + IRootVMNode rootNode = new RootDMVMNode(this); + + /* + * Now the Over-arching management node. + */ + if (IDsfDebugUIConstants.ID_EXPRESSION_HOVER.equals(getPresentationContext().getId())) { + SingleExpressionVMNode expressionManagerNode = new SingleExpressionVMNode(this); + addChildNodes(rootNode, new IVMNode[] { expressionManagerNode }); + } else { + ExpressionManagerVMNode expressionManagerNode = new ExpressionManagerVMNode(this); + addChildNodes(rootNode, new IVMNode[] { expressionManagerNode }); + } + + // Disabled expression node intercepts disabled expressions and prevents them from being + // evaluated by other nodes. + IExpressionVMNode disabledExpressionNode = new DisabledExpressionVMNode(this); + + /* + * The expression view wants to support fully all of the components of the register view. + */ + IExpressionVMNode registerGroupNode = new RegisterGroupVMNode(this, getSession(), syncRegDataAccess); + + IExpressionVMNode registerNode = new RegisterVMNode(this, getSession(), syncRegDataAccess); + addChildNodes(registerGroupNode, new IExpressionVMNode[] { registerNode }); + + /* + * Create the next level which is the bit-field level. + */ + IVMNode bitFieldNode = new RegisterBitFieldVMNode(this, getSession(), syncRegDataAccess); + addChildNodes(registerNode, new IVMNode[] { bitFieldNode }); + + /* + * Create the support for the SubExpressions. Anything which is brought into the expressions + * view comes in as a fully qualified expression so we go directly to the SubExpression layout + * node. + */ + VariableVMNode variableNode = new VariableVMNode(this, getSession(), syncvarDataAccess); + addChildNodes(variableNode, new IExpressionVMNode[] { variableNode }); + + /* + * Hook up IExpressions2 if it exists. + */ + hookUpCastingSupport(syncvarDataAccess, variableNode); + + /* + * Tell the expression node which sub-nodes it will directly support. It is very important + * that the variables node be the last in this chain. The model assumes that there is some + * form of metalanguage expression syntax which each of the nodes evaluates and decides if + * they are dealing with it or not. The variables node assumes that the expression is fully + * qualified and there is no analysis or subdivision of the expression it will parse. So it + * it currently the case that the location of the nodes within the array being passed in is + * the order of search/evaluation. Thus variables wants to be last. Otherwise it would just + * assume what it was passed was for it and the real node which wants to handle it would be + * left out in the cold. + */ + setExpressionNodes(new IExpressionVMNode[] { disabledExpressionNode, registerGroupNode, variableNode }); + + /* + * Let the work know which is the top level node. + */ + setRootNode(rootNode); + } private void hookUpCastingSupport(final SyncVariableDataAccess syncvarDataAccess, final VariableVMNode variableNode) { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), getSession().getId()); - IExpressions2 expressions2 = tracker.getService(IExpressions2.class); - if (expressions2 != null) { - variableNode.setCastToTypeSupport(new DsfCastToTypeSupport( - getSession(), ExpressionVMProvider.this, syncvarDataAccess)); - } - tracker.dispose(); - } - }); - } catch (RejectedExecutionException e) { - // Session disposed, ignore. - } + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + getSession().getId()); + IExpressions2 expressions2 = tracker.getService(IExpressions2.class); + if (expressions2 != null) { + variableNode.setCastToTypeSupport( + new DsfCastToTypeSupport(getSession(), ExpressionVMProvider.this, syncvarDataAccess)); + } + tracker.dispose(); + } + }); + } catch (RejectedExecutionException e) { + // Session disposed, ignore. + } + } + + /** + * Finds the expression node which can parse the given expression. This + * method is used by the expression content and model proxy strategies. + * + * @param parentNode The parent of the nodes to search. If <code>null</code>, + * then the top level expressions will be searched. + * @param expression The expression object. + * @return The matching expression node. + */ + public IExpressionVMNode findNodeToParseExpression(IExpressionVMNode parentNode, IExpression expression) { + IVMNode[] childNOdes; + if (parentNode == null) { + childNOdes = getExpressionNodes(); + } else { + childNOdes = getChildVMNodes(parentNode); + } + for (IVMNode childNode : childNOdes) { + if (childNode instanceof IExpressionVMNode) { + IExpressionVMNode childExpressionNode = (IExpressionVMNode) childNode; + if (childExpressionNode.canParseExpression(expression)) { + return childExpressionNode; + } else if (!childExpressionNode.equals(parentNode)) { + // The above check is to make sure that child isn't the same as + // parent to avoid recursive loops. + IExpressionVMNode matchingNode = findNodeToParseExpression(childExpressionNode, expression); + if (matchingNode != null) { + return matchingNode; + } + } + } + } + return null; + } + + @Override + public void dispose() { + DebugPlugin.getDefault().getExpressionManager().removeExpressionListener(this); + DsfDebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferencesListener); + getPresentationContext().removePropertyChangeListener(fPresentationContextListener); + super.dispose(); } - - /** - * Finds the expression node which can parse the given expression. This - * method is used by the expression content and model proxy strategies. - * - * @param parentNode The parent of the nodes to search. If <code>null</code>, - * then the top level expressions will be searched. - * @param expression The expression object. - * @return The matching expression node. - */ - public IExpressionVMNode findNodeToParseExpression(IExpressionVMNode parentNode, IExpression expression) { - IVMNode[] childNOdes; - if (parentNode == null) { - childNOdes = getExpressionNodes(); - } else { - childNOdes = getChildVMNodes(parentNode); - } - for (IVMNode childNode : childNOdes) { - if (childNode instanceof IExpressionVMNode) { - IExpressionVMNode childExpressionNode = (IExpressionVMNode)childNode; - if (childExpressionNode.canParseExpression(expression)) { - return childExpressionNode; - } else if (!childExpressionNode.equals(parentNode)) { - // The above check is to make sure that child isn't the same as - // parent to avoid recursive loops. - IExpressionVMNode matchingNode = - findNodeToParseExpression(childExpressionNode, expression); - if (matchingNode != null) { - return matchingNode; - } - } - } - } - return null; - } - - - @Override - public void dispose() { - DebugPlugin.getDefault().getExpressionManager().removeExpressionListener(this); - DsfDebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferencesListener); - getPresentationContext().removePropertyChangeListener(fPresentationContextListener); - super.dispose(); - } - - @Override - public IColumnPresentation createColumnPresentation(IPresentationContext context, Object element) { - return new ExpressionColumnPresentation(); - } - - @Override - public String getColumnPresentationId(IPresentationContext context, Object element) { - return ExpressionColumnPresentation.ID; - } - - @Override - protected IVMUpdatePolicy[] createUpdateModes() { - return new IVMUpdatePolicy[] { new AutomaticUpdatePolicy(), new ExpressionsManualUpdatePolicy(), - new ExpressionsBreakpointHitUpdatePolicy() }; - } - - @Override + + @Override + public IColumnPresentation createColumnPresentation(IPresentationContext context, Object element) { + return new ExpressionColumnPresentation(); + } + + @Override + public String getColumnPresentationId(IPresentationContext context, Object element) { + return ExpressionColumnPresentation.ID; + } + + @Override + protected IVMUpdatePolicy[] createUpdateModes() { + return new IVMUpdatePolicy[] { new AutomaticUpdatePolicy(), new ExpressionsManualUpdatePolicy(), + new ExpressionsBreakpointHitUpdatePolicy() }; + } + + @Override public void expressionsAdded(IExpression[] expressions) { - expressionsListChanged(ExpressionsChangedEvent.Type.ADDED, expressions, DebugPlugin.getDefault().getExpressionManager().getExpressions().length - expressions.length); - } - - @Override + expressionsListChanged(ExpressionsChangedEvent.Type.ADDED, expressions, + DebugPlugin.getDefault().getExpressionManager().getExpressions().length - expressions.length); + } + + @Override public void expressionsRemoved(IExpression[] expressions) { - expressionsListChanged(ExpressionsChangedEvent.Type.REMOVED, expressions, -1); - } - - @Override + expressionsListChanged(ExpressionsChangedEvent.Type.REMOVED, expressions, -1); + } + + @Override public void expressionsInserted(IExpression[] expressions, int index) { - expressionsListChanged(ExpressionsChangedEvent.Type.INSERTED, expressions, index); - } + expressionsListChanged(ExpressionsChangedEvent.Type.INSERTED, expressions, index); + } - @Override + @Override public void expressionsMoved(IExpression[] expressions, int index) { - expressionsListChanged(ExpressionsChangedEvent.Type.MOVED, expressions, index); - } - - @Override + expressionsListChanged(ExpressionsChangedEvent.Type.MOVED, expressions, index); + } + + @Override public void expressionsChanged(IExpression[] expressions) { - expressionsListChanged(ExpressionsChangedEvent.Type.CHANGED, expressions, -1); - } - - private void expressionsListChanged(ExpressionsChangedEvent.Type type, IExpression[] expressions, int index) { - Set<Object> rootElements = new HashSet<Object>(); - for (IVMModelProxy proxy : getActiveModelProxies()) { - rootElements.add(proxy.getRootElement()); - } - handleEvent(new ExpressionsChangedEvent(type, rootElements, expressions, index)); - } - - @Override - protected boolean canSkipHandlingEvent(Object newEvent, Object eventToSkip) { - // To optimize the performance of the view when stepping rapidly, skip all - // other events when a suspended event is received, including older suspended - // events. - return newEvent instanceof ISuspendedDMEvent; - } - - @Override - public void refresh() { - super.refresh(); - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + expressionsListChanged(ExpressionsChangedEvent.Type.CHANGED, expressions, -1); + } + + private void expressionsListChanged(ExpressionsChangedEvent.Type type, IExpression[] expressions, int index) { + Set<Object> rootElements = new HashSet<Object>(); + for (IVMModelProxy proxy : getActiveModelProxies()) { + rootElements.add(proxy.getRootElement()); + } + handleEvent(new ExpressionsChangedEvent(type, rootElements, expressions, index)); + } + + @Override + protected boolean canSkipHandlingEvent(Object newEvent, Object eventToSkip) { + // To optimize the performance of the view when stepping rapidly, skip all + // other events when a suspended event is received, including older suspended + // events. + return newEvent instanceof ISuspendedDMEvent; + } + + @Override + public void refresh() { + super.refresh(); + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), getSession().getId()); - IExpressions expressionsService = tracker.getService(IExpressions.class); - if (expressionsService instanceof ICachingService) { - ((ICachingService)expressionsService).flushCache(null); - } - IRegisters registerService = tracker.getService(IRegisters.class); - if (registerService instanceof ICachingService) { - ((ICachingService)registerService).flushCache(null); - } - tracker.dispose(); - } - }); - } catch (RejectedExecutionException e) { - // Session disposed, ignore. - } - } - - @Override - public void update(IViewerInputUpdate update) { - if (IDsfDebugUIConstants.ID_EXPRESSION_HOVER.equals(getPresentationContext().getId())) { - Object input = update.getElement(); - if (input instanceof IExpressionDMContext) { - IExpressionDMContext dmc = (IExpressionDMContext) input; - SingleExpressionVMNode vmNode = (SingleExpressionVMNode) getChildVMNodes(getRootVMNode())[0]; - final IDMVMContext viewerInput= vmNode.createVMContext(dmc); + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + getSession().getId()); + IExpressions expressionsService = tracker.getService(IExpressions.class); + if (expressionsService instanceof ICachingService) { + ((ICachingService) expressionsService).flushCache(null); + } + IRegisters registerService = tracker.getService(IRegisters.class); + if (registerService instanceof ICachingService) { + ((ICachingService) registerService).flushCache(null); + } + tracker.dispose(); + } + }); + } catch (RejectedExecutionException e) { + // Session disposed, ignore. + } + } + + @Override + public void update(IViewerInputUpdate update) { + if (IDsfDebugUIConstants.ID_EXPRESSION_HOVER.equals(getPresentationContext().getId())) { + Object input = update.getElement(); + if (input instanceof IExpressionDMContext) { + IExpressionDMContext dmc = (IExpressionDMContext) input; + SingleExpressionVMNode vmNode = (SingleExpressionVMNode) getChildVMNodes(getRootVMNode())[0]; + final IDMVMContext viewerInput = vmNode.createVMContext(dmc); // provide access to viewer (needed by details pane) - getPresentationContext().setProperty("__viewerInput", viewerInput); //$NON-NLS-1$ - - update.setInputElement(viewerInput); - update.done(); - return; - } - } - super.update(update); - } + getPresentationContext().setProperty("__viewerInput", viewerInput); //$NON-NLS-1$ + + update.setInputElement(viewerInput); + update.done(); + return; + } + } + super.update(update); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionVMProviderContentStragegy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionVMProviderContentStragegy.java index 647fc3b4336..3d264891909 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionVMProviderContentStragegy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionVMProviderContentStragegy.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -23,67 +23,62 @@ import org.eclipse.core.runtime.Status; /** * The IElementContentProvider implementation to be used with an expression * view model provider. - * + * * @see ExpressionVMProvider */ public class ExpressionVMProviderContentStragegy extends DefaultVMContentProviderStrategy { - public ExpressionVMProviderContentStragegy(ExpressionVMProvider provider) { - super(provider); - } + public ExpressionVMProviderContentStragegy(ExpressionVMProvider provider) { + super(provider); + } + + private ExpressionVMProvider getExpressionVMProvider() { + return (ExpressionVMProvider) getVMProvider(); + } + + public void update(final IExpressionUpdate update) { + final IExpressionVMNode matchingNode = getExpressionVMProvider().findNodeToParseExpression(null, + update.getExpression()); - private ExpressionVMProvider getExpressionVMProvider() { - return (ExpressionVMProvider)getVMProvider(); - } + if (matchingNode != null) { + updateExpressionWithNode(matchingNode, update); + } else { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, + "Cannot parse expression", null)); //$NON-NLS-1$ + update.done(); + } + } - public void update(final IExpressionUpdate update) { - final IExpressionVMNode matchingNode = - getExpressionVMProvider().findNodeToParseExpression(null, update.getExpression()); + private void updateExpressionWithNode(final IExpressionVMNode node, final IExpressionUpdate update) { + // Call the expression node to parse the expression and fill in the value. + node.update(new VMExpressionUpdate(update, update.getExpression(), + new ViewerDataRequestMonitor<Object>(getVMProvider().getExecutor(), update) { + @Override + protected void handleSuccess() { + // Check if the evaluated node has child expression nodes. + // If it does, check if any of those nodes can evaluate the given + // expression further. If they can, call the child node to further + // process the expression. Otherwise we found our element and + // we're done. + final IExpressionVMNode matchingNode = getExpressionVMProvider().findNodeToParseExpression(node, + update.getExpression()); - if (matchingNode != null) { - updateExpressionWithNode(matchingNode, update); - } else { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "Cannot parse expression", null)); //$NON-NLS-1$ - update.done(); - } - } + if (matchingNode != null && !matchingNode.equals(node)) { + updateExpressionWithNode(matchingNode, new VMExpressionUpdate( + update.getElementPath().createChildPath(getData()), update.getViewerInput(), + update.getPresentationContext(), update.getExpression(), + new ViewerDataRequestMonitor<Object>(getVMProvider().getExecutor(), update) { - private void updateExpressionWithNode(final IExpressionVMNode node, final IExpressionUpdate update) { - // Call the expression node to parse the expression and fill in the value. - node.update( - new VMExpressionUpdate( - update, update.getExpression(), - new ViewerDataRequestMonitor<Object>(getVMProvider().getExecutor(), update) { - @Override - protected void handleSuccess() { - // Check if the evaluated node has child expression nodes. - // If it does, check if any of those nodes can evaluate the given - // expression further. If they can, call the child node to further - // process the expression. Otherwise we found our element and - // we're done. - final IExpressionVMNode matchingNode = getExpressionVMProvider(). - findNodeToParseExpression(node, update.getExpression()); - - if (matchingNode != null && !matchingNode.equals(node)) { - updateExpressionWithNode( - matchingNode, - new VMExpressionUpdate( - update.getElementPath().createChildPath(getData()), update.getViewerInput(), - update.getPresentationContext(), update.getExpression(), - new ViewerDataRequestMonitor<Object>(getVMProvider().getExecutor(), update) { - - @Override - protected void handleSuccess() { - update.setExpressionElement(getData()); - update.done(); - } - }) - ); - } else { - update.setExpressionElement(getData()); - update.done(); - } - } - }) - ); - } + @Override + protected void handleSuccess() { + update.setExpressionElement(getData()); + update.done(); + } + })); + } else { + update.setExpressionElement(getData()); + update.done(); + } + } + })); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionVMProviderModelProxyStrategy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionVMProviderModelProxyStrategy.java index 07446c2cd61..48d1f80c96b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionVMProviderModelProxyStrategy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionVMProviderModelProxyStrategy.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -28,162 +28,155 @@ import org.eclipse.jface.viewers.TreePath; /** * The IModelProxy implementation to be used with an expression * view model provider. - * + * * @see ExpressionVMProvider */ public class ExpressionVMProviderModelProxyStrategy extends DefaultVMModelProxyStrategy { - public ExpressionVMProviderModelProxyStrategy(ExpressionVMProvider provider, Object rootElement) { - super(provider, rootElement); - } - - private ExpressionVMProvider getExpressionVMProvider() { - return (ExpressionVMProvider)getVMProvider(); - } - - public int getDeltaFlagsForExpression(IExpression expression, Object event) { - final IExpressionVMNode matchingNode = getExpressionVMProvider().findNodeToParseExpression(null, expression); - - if (matchingNode != null) { - return getNodeDeltaFlagsForExpression(matchingNode, expression, event); - } - return IModelDelta.NO_CHANGE; - } - - private int getNodeDeltaFlagsForExpression(IExpressionVMNode node, IExpression expression, Object event) { - int flags = node.getDeltaFlagsForExpression(expression, event); - - IExpressionVMNode matchingNode = getExpressionVMProvider().findNodeToParseExpression(node, expression); - if (matchingNode != null && !matchingNode.equals(node)) { - flags = flags | getNodeDeltaFlagsForExpression(matchingNode, expression, event); - } else { - // Check the child nodes of this expression node for additional - // delta flags. - for (IVMNode childNode : getVMProvider().getChildVMNodes(node)) { - if (!childNode.equals(node)) { - int childNodeDeltaFlags = getDeltaFlags(childNode, null, event); - if ((childNodeDeltaFlags & IModelDelta.CONTENT) != 0) { - childNodeDeltaFlags &= ~IModelDelta.CONTENT; - childNodeDeltaFlags |= IModelDelta.STATE; - } - flags |= childNodeDeltaFlags; - } - } - } - return flags; - } - - public void buildDeltaForExpression(IExpression expression, int expressionElementIdx, Object event, - VMDelta parentDelta, TreePath path, RequestMonitor rm) - { - final IExpressionVMNode matchingNode = getExpressionVMProvider().findNodeToParseExpression(null, expression); - - if (matchingNode != null) { - buildNodeDeltaForExpression(matchingNode, expression, expressionElementIdx, event, - parentDelta, path, rm); - } else { - rm.done(); - } - } - - private void buildNodeDeltaForExpression(final IExpressionVMNode node, final IExpression expression, - final int expressionElementIdx, final Object event, final VMDelta parentDelta, final TreePath path, - final RequestMonitor rm) - { - node.buildDeltaForExpression( - expression, expressionElementIdx, event, parentDelta, path, - new RequestMonitor(getVMProvider().getExecutor(), rm) { - @Override - protected void handleSuccess() { - final IExpressionVMNode matchingNode = - getExpressionVMProvider().findNodeToParseExpression(node, expression); - if (matchingNode != null && !matchingNode.equals(node)) { - buildNodeDeltaForExpression( - matchingNode, expression, expressionElementIdx, event, parentDelta, path, rm); - } else { - getExpressionVMProvider().update(new VMExpressionUpdate( - parentDelta, getVMProvider().getPresentationContext(), expression, - new DataRequestMonitor<Object>(getVMProvider().getExecutor(), rm) { - @Override - protected void handleSuccess() { - buildDeltaForExpressionElement( - node, expression, getData(), expressionElementIdx, event, parentDelta, path, rm); - } - - @Override - protected void handleErrorOrWarning() { - // Avoid propagating the error to avoid processing the delta by - // all nodes. - rm.done(); - } - })); - } - } - }); - } - - - private void buildDeltaForExpressionElement(IExpressionVMNode node, IExpression expression, Object expressionElement, - int expressionElementIdx, Object event, VMDelta parentDelta, TreePath path, RequestMonitor rm) - { - CountingRequestMonitor multiRm = new CountingRequestMonitor(getVMProvider().getExecutor(), rm); - int multiRmCount = 0; - - node.buildDeltaForExpressionElement(expressionElement, expressionElementIdx, event, parentDelta, multiRm); - multiRmCount++; - - // Find the child nodes that have deltas for the given event. - Map<IVMNode,Integer> childNodesWithDeltaFlags = getChildNodesWithDeltaFlags(node, parentDelta, event); - - // If no child layout nodes have deltas we can stop here. - if (childNodesWithDeltaFlags.size() != 0) { - callChildNodesToBuildDelta( - node, childNodesWithDeltaFlags, - parentDelta.addNode(expressionElement, expressionElementIdx, IModelDelta.NO_CHANGE), - event, multiRm); - multiRmCount++; - } - - if (event instanceof ExpressionsChangedEvent) { - buildDeltaForExpressionsChangedEvent(expressionElement, expressionElementIdx, - (ExpressionsChangedEvent)event, parentDelta, multiRm); - multiRmCount++; - } - - multiRm.setDoneCount(multiRmCount); - } - - private void buildDeltaForExpressionsChangedEvent(Object element, int elementIdx, ExpressionsChangedEvent event, - VMDelta parentDelta, final RequestMonitor rm) - { - switch (event.getType()) { - case ADDED: - // New expressions are always added one element before last. - // Last element is the "Add new expression" element. - // Note: Index should be calculated when the IExpressionListener.expressionsAdded - // is called. If it's not, try to calculate it here based on parent count. - int parentCount = parentDelta.getChildCount(); - if (elementIdx == -1 && parentCount > 1) { - elementIdx = parentCount - 2; - } - parentDelta.addNode(element, elementIdx, IModelDelta.ADDED); - break; - case CHANGED: - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - break; - case MOVED: - parentDelta.addNode(element, -1, IModelDelta.REMOVED); - parentDelta.addNode(element, elementIdx, IModelDelta.INSERTED); - break; - case REMOVED: - parentDelta.addNode(element, -1, IModelDelta.REMOVED); - break; - case INSERTED: - parentDelta.addNode(element, elementIdx, IModelDelta.INSERTED); - break; - default: - break; - } - rm.done(); - } + public ExpressionVMProviderModelProxyStrategy(ExpressionVMProvider provider, Object rootElement) { + super(provider, rootElement); + } + + private ExpressionVMProvider getExpressionVMProvider() { + return (ExpressionVMProvider) getVMProvider(); + } + + public int getDeltaFlagsForExpression(IExpression expression, Object event) { + final IExpressionVMNode matchingNode = getExpressionVMProvider().findNodeToParseExpression(null, expression); + + if (matchingNode != null) { + return getNodeDeltaFlagsForExpression(matchingNode, expression, event); + } + return IModelDelta.NO_CHANGE; + } + + private int getNodeDeltaFlagsForExpression(IExpressionVMNode node, IExpression expression, Object event) { + int flags = node.getDeltaFlagsForExpression(expression, event); + + IExpressionVMNode matchingNode = getExpressionVMProvider().findNodeToParseExpression(node, expression); + if (matchingNode != null && !matchingNode.equals(node)) { + flags = flags | getNodeDeltaFlagsForExpression(matchingNode, expression, event); + } else { + // Check the child nodes of this expression node for additional + // delta flags. + for (IVMNode childNode : getVMProvider().getChildVMNodes(node)) { + if (!childNode.equals(node)) { + int childNodeDeltaFlags = getDeltaFlags(childNode, null, event); + if ((childNodeDeltaFlags & IModelDelta.CONTENT) != 0) { + childNodeDeltaFlags &= ~IModelDelta.CONTENT; + childNodeDeltaFlags |= IModelDelta.STATE; + } + flags |= childNodeDeltaFlags; + } + } + } + return flags; + } + + public void buildDeltaForExpression(IExpression expression, int expressionElementIdx, Object event, + VMDelta parentDelta, TreePath path, RequestMonitor rm) { + final IExpressionVMNode matchingNode = getExpressionVMProvider().findNodeToParseExpression(null, expression); + + if (matchingNode != null) { + buildNodeDeltaForExpression(matchingNode, expression, expressionElementIdx, event, parentDelta, path, rm); + } else { + rm.done(); + } + } + + private void buildNodeDeltaForExpression(final IExpressionVMNode node, final IExpression expression, + final int expressionElementIdx, final Object event, final VMDelta parentDelta, final TreePath path, + final RequestMonitor rm) { + node.buildDeltaForExpression(expression, expressionElementIdx, event, parentDelta, path, + new RequestMonitor(getVMProvider().getExecutor(), rm) { + @Override + protected void handleSuccess() { + final IExpressionVMNode matchingNode = getExpressionVMProvider().findNodeToParseExpression(node, + expression); + if (matchingNode != null && !matchingNode.equals(node)) { + buildNodeDeltaForExpression(matchingNode, expression, expressionElementIdx, event, + parentDelta, path, rm); + } else { + getExpressionVMProvider().update(new VMExpressionUpdate(parentDelta, + getVMProvider().getPresentationContext(), expression, + new DataRequestMonitor<Object>(getVMProvider().getExecutor(), rm) { + @Override + protected void handleSuccess() { + buildDeltaForExpressionElement(node, expression, getData(), + expressionElementIdx, event, parentDelta, path, rm); + } + + @Override + protected void handleErrorOrWarning() { + // Avoid propagating the error to avoid processing the delta by + // all nodes. + rm.done(); + } + })); + } + } + }); + } + + private void buildDeltaForExpressionElement(IExpressionVMNode node, IExpression expression, + Object expressionElement, int expressionElementIdx, Object event, VMDelta parentDelta, TreePath path, + RequestMonitor rm) { + CountingRequestMonitor multiRm = new CountingRequestMonitor(getVMProvider().getExecutor(), rm); + int multiRmCount = 0; + + node.buildDeltaForExpressionElement(expressionElement, expressionElementIdx, event, parentDelta, multiRm); + multiRmCount++; + + // Find the child nodes that have deltas for the given event. + Map<IVMNode, Integer> childNodesWithDeltaFlags = getChildNodesWithDeltaFlags(node, parentDelta, event); + + // If no child layout nodes have deltas we can stop here. + if (childNodesWithDeltaFlags.size() != 0) { + callChildNodesToBuildDelta(node, childNodesWithDeltaFlags, + parentDelta.addNode(expressionElement, expressionElementIdx, IModelDelta.NO_CHANGE), event, + multiRm); + multiRmCount++; + } + + if (event instanceof ExpressionsChangedEvent) { + buildDeltaForExpressionsChangedEvent(expressionElement, expressionElementIdx, + (ExpressionsChangedEvent) event, parentDelta, multiRm); + multiRmCount++; + } + + multiRm.setDoneCount(multiRmCount); + } + + private void buildDeltaForExpressionsChangedEvent(Object element, int elementIdx, ExpressionsChangedEvent event, + VMDelta parentDelta, final RequestMonitor rm) { + switch (event.getType()) { + case ADDED: + // New expressions are always added one element before last. + // Last element is the "Add new expression" element. + // Note: Index should be calculated when the IExpressionListener.expressionsAdded + // is called. If it's not, try to calculate it here based on parent count. + int parentCount = parentDelta.getChildCount(); + if (elementIdx == -1 && parentCount > 1) { + elementIdx = parentCount - 2; + } + parentDelta.addNode(element, elementIdx, IModelDelta.ADDED); + break; + case CHANGED: + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + break; + case MOVED: + parentDelta.addNode(element, -1, IModelDelta.REMOVED); + parentDelta.addNode(element, elementIdx, IModelDelta.INSERTED); + break; + case REMOVED: + parentDelta.addNode(element, -1, IModelDelta.REMOVED); + break; + case INSERTED: + parentDelta.addNode(element, elementIdx, IModelDelta.INSERTED); + break; + default: + break; + } + rm.done(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsBreakpointHitUpdatePolicy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsBreakpointHitUpdatePolicy.java index 8655d5c5aa1..63c36763365 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsBreakpointHitUpdatePolicy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsBreakpointHitUpdatePolicy.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -17,16 +17,16 @@ import org.eclipse.cdt.dsf.debug.ui.viewmodel.update.BreakpointHitUpdatePolicy; import org.eclipse.cdt.dsf.ui.viewmodel.update.IElementUpdateTester; /** - * Manual update policy which selectively clears the cache when the expressions - * in the expression manager are modified. + * Manual update policy which selectively clears the cache when the expressions + * in the expression manager are modified. */ public class ExpressionsBreakpointHitUpdatePolicy extends BreakpointHitUpdatePolicy { - @Override - public IElementUpdateTester getElementUpdateTester(Object event) { - if (event instanceof ExpressionsChangedEvent) { - return new ExpressionsChangedUpdateTester((ExpressionsChangedEvent)event); - } - return super.getElementUpdateTester(event); - } + @Override + public IElementUpdateTester getElementUpdateTester(Object event) { + if (event instanceof ExpressionsChangedEvent) { + return new ExpressionsChangedUpdateTester((ExpressionsChangedEvent) event); + } + return super.getElementUpdateTester(event); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsChangedEvent.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsChangedEvent.java index 2aa52e6d744..93e79695234 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsChangedEvent.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsChangedEvent.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,53 +19,62 @@ import java.util.Set; import org.eclipse.debug.core.model.IExpression; /** - * Object representing a change in configured expressions. This event is + * Object representing a change in configured expressions. This event is * object is used when generating a model delta. */ public class ExpressionsChangedEvent { - /** - * Enumeration for the type of change in expressions. - * @since 2.2 - */ - public enum Type {ADDED, CHANGED, REMOVED, MOVED, INSERTED} + /** + * Enumeration for the type of change in expressions. + * @since 2.2 + */ + public enum Type { + ADDED, CHANGED, REMOVED, MOVED, INSERTED + } + + private final Set<Object> fExpressionManagerElements; + private final ExpressionsChangedEvent.Type fType; + private final IExpression[] fExpressions; + private final int fIndex; + + public ExpressionsChangedEvent(ExpressionsChangedEvent.Type type, Set<Object> expressionManagerElements, + IExpression[] expressions, int index) { + fExpressionManagerElements = expressionManagerElements; + fType = type; + fExpressions = expressions; + fIndex = index; + } + + /** + * The set of root elements of the expressions view model. + */ + public Set<Object> getExpressionManagerElements() { + return fExpressionManagerElements; + } + + /** + * Returns the type of change. + */ + public ExpressionsChangedEvent.Type getType() { + return fType; + } + + /** + * Returns expressions affected by the change. + */ + public IExpression[] getExpressions() { + return fExpressions; + } + + /** + * Returns index of the affected expression. + */ + public int getIndex() { + return fIndex; + } - private final Set<Object> fExpressionManagerElements; - private final ExpressionsChangedEvent.Type fType; - private final IExpression[] fExpressions; - private final int fIndex; - - public ExpressionsChangedEvent(ExpressionsChangedEvent.Type type, Set<Object> expressionManagerElements, - IExpression[] expressions, int index) - { - fExpressionManagerElements = expressionManagerElements; - fType = type; - fExpressions = expressions; - fIndex = index; - } - - /** - * The set of root elements of the expressions view model. - */ - public Set<Object> getExpressionManagerElements() { return fExpressionManagerElements; } - - /** - * Returns the type of change. - */ - public ExpressionsChangedEvent.Type getType() { return fType; } - - /** - * Returns expressions affected by the change. - */ - public IExpression[] getExpressions() { return fExpressions; } - - /** - * Returns index of the affected expression. - */ - public int getIndex() { return fIndex; } - - @Override - public String toString() { - return Arrays.asList(fExpressions).toString() + " " + fType + "@" + fIndex; //$NON-NLS-1$ //$NON-NLS-2$ - } + @Override + public String toString() { + return Arrays.asList(fExpressions).toString() + " " + fType + "@" + fIndex; //$NON-NLS-1$ //$NON-NLS-2$ + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsChangedUpdateTester.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsChangedUpdateTester.java index 21f7a5379aa..086436df0c1 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsChangedUpdateTester.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsChangedUpdateTester.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,55 +19,55 @@ import org.eclipse.debug.core.model.IExpression; import org.eclipse.jface.viewers.TreePath; class ExpressionsChangedUpdateTester implements IElementUpdateTester { - - private final ExpressionsChangedEvent fEvent; - - public ExpressionsChangedUpdateTester(ExpressionsChangedEvent event) { - fEvent = event; - } - @Override + private final ExpressionsChangedEvent fEvent; + + public ExpressionsChangedUpdateTester(ExpressionsChangedEvent event) { + fEvent = event; + } + + @Override public int getUpdateFlags(Object viewerInput, TreePath path) { - // Check whether the element in the cache matches the expression manager element. - Object element = path.getSegmentCount() == 0 ? viewerInput : path.getLastSegment(); - if (fEvent.getExpressionManagerElements().contains(element)) { - return ExpressionsManualUpdatePolicy.FLUSH; - } - - // If the expressions were modified, flush the entries which are under the - // given expression. To do that, check whether the element path contains one - // of the changed expressions. - if (fEvent.getType().equals(ExpressionsChangedEvent.Type.CHANGED)) { - for (int i = 0; i < path.getSegmentCount(); i++) { - if (eventContainsElement(path.getSegment(i))) { - return ExpressionsManualUpdatePolicy.FLUSH; - } - } - } - return 0; - } - - private boolean eventContainsElement(Object element) { - if (element instanceof IAdaptable) { - IExpression expression = ((IAdaptable)element).getAdapter(IExpression.class); - if (expression != null) { - for (int i = 0; i < fEvent.getExpressions().length; i++) { - if (expression.equals(fEvent.getExpressions()[i])) { - return true; - } - } - } - } - return false; - } - - @Override + // Check whether the element in the cache matches the expression manager element. + Object element = path.getSegmentCount() == 0 ? viewerInput : path.getLastSegment(); + if (fEvent.getExpressionManagerElements().contains(element)) { + return ExpressionsManualUpdatePolicy.FLUSH; + } + + // If the expressions were modified, flush the entries which are under the + // given expression. To do that, check whether the element path contains one + // of the changed expressions. + if (fEvent.getType().equals(ExpressionsChangedEvent.Type.CHANGED)) { + for (int i = 0; i < path.getSegmentCount(); i++) { + if (eventContainsElement(path.getSegment(i))) { + return ExpressionsManualUpdatePolicy.FLUSH; + } + } + } + return 0; + } + + private boolean eventContainsElement(Object element) { + if (element instanceof IAdaptable) { + IExpression expression = ((IAdaptable) element).getAdapter(IExpression.class); + if (expression != null) { + for (int i = 0; i < fEvent.getExpressions().length; i++) { + if (expression.equals(fEvent.getExpressions()[i])) { + return true; + } + } + } + } + return false; + } + + @Override public boolean includes(IElementUpdateTester tester) { - return tester instanceof ExpressionsChangedUpdateTester; - } - - @Override - public String toString() { - return "(" + fEvent + ") update tester"; //$NON-NLS-1$ //$NON-NLS-2$ - } + return tester instanceof ExpressionsChangedUpdateTester; + } + + @Override + public String toString() { + return "(" + fEvent + ") update tester"; //$NON-NLS-1$ //$NON-NLS-2$ + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsManualUpdatePolicy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsManualUpdatePolicy.java index 1ddc7e46501..23a31d64e57 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsManualUpdatePolicy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/ExpressionsManualUpdatePolicy.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Winnie Lai (Texas Instruments) - Individual Element Number Format (Bug 202556) @@ -18,19 +18,19 @@ import org.eclipse.cdt.dsf.debug.ui.viewmodel.update.DebugManualUpdatePolicy; import org.eclipse.cdt.dsf.ui.viewmodel.update.IElementUpdateTester; /** - * Manual update policy which selectively clears the cache when the expressions - * in the expression manager are modified. + * Manual update policy which selectively clears the cache when the expressions + * in the expression manager are modified. * Inherit from DebugManualUpdatePolicy so that expression view can return * proper update testers for preference format change event and element format * change event just like what variables view and registers view do. (Bug 202556) */ public class ExpressionsManualUpdatePolicy extends DebugManualUpdatePolicy { - @Override - public IElementUpdateTester getElementUpdateTester(Object event) { - if (event instanceof ExpressionsChangedEvent) { - return new ExpressionsChangedUpdateTester((ExpressionsChangedEvent)event); - } - return super.getElementUpdateTester(event); - } + @Override + public IElementUpdateTester getElementUpdateTester(Object event) { + if (event instanceof ExpressionsChangedEvent) { + return new ExpressionsChangedUpdateTester((ExpressionsChangedEvent) event); + } + return super.getElementUpdateTester(event); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/IExpressionUpdate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/IExpressionUpdate.java index af667997ec0..e21f2a740df 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/IExpressionUpdate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/IExpressionUpdate.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -23,14 +23,14 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; */ public interface IExpressionUpdate extends IViewerUpdate { - /** - * Returns the expression object for this update. - */ - public IExpression getExpression(); - - /** - * Sets the element to the update. The element is to be calculated by the provider - * handling the update. - */ - public void setExpressionElement(Object element); + /** + * Returns the expression object for this update. + */ + public IExpression getExpression(); + + /** + * Sets the element to the update. The element is to be calculated by the provider + * handling the update. + */ + public void setExpressionElement(Object element); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/IExpressionVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/IExpressionVMNode.java index 0c1baaeb459..323a61932fb 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/IExpressionVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/IExpressionVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,47 +20,48 @@ import org.eclipse.debug.core.model.IExpression; import org.eclipse.jface.viewers.TreePath; /** - * Interface for view model nodes that can be used within the expression view. - * The methods of this interface allow the {@link ExpressionManagerVMNode} - * to use this node to delegate expression parsing to this node, and to + * Interface for view model nodes that can be used within the expression view. + * The methods of this interface allow the {@link ExpressionManagerVMNode} + * to use this node to delegate expression parsing to this node, and to * generate deltas for expressions that are owned by this node. */ public interface IExpressionVMNode extends IVMNode { - - /** - * Returns whether the given expression node recognizes and can parse the given - * expression. - * @param expression Expression that needs to be parsed. - * @return true if expression can be parsed - */ - public boolean canParseExpression(IExpression expression); - - /** - * Asynchronously fills in the given expression update. - * @param update Update to complete. - */ - public void update(IExpressionUpdate update); - - /** - * Returns the flags that this node can generate for the given expression and - * event. - */ - public int getDeltaFlagsForExpression(IExpression expression, Object event); - - /** - * Adds delta flags to the given parent delta based on the expression - * object given. The nodes add flags to the expression view's root - * delta using this method, regardless of whether the node is directly - * below the expression manager or not. - * - */ - public void buildDeltaForExpression(IExpression expression, int elementIdx, Object event, VMDelta parentDelta, - TreePath path, RequestMonitor rm); - - /** - * Adds delta to the given parent delta based on the given element that - * was created base on an expression parsed by this node. The VM nodes can - * add a new delta node to the parentDela by implementing this method. - */ - public void buildDeltaForExpressionElement(Object element, int elementIdx, Object event, VMDelta parentDelta, final RequestMonitor rm); + + /** + * Returns whether the given expression node recognizes and can parse the given + * expression. + * @param expression Expression that needs to be parsed. + * @return true if expression can be parsed + */ + public boolean canParseExpression(IExpression expression); + + /** + * Asynchronously fills in the given expression update. + * @param update Update to complete. + */ + public void update(IExpressionUpdate update); + + /** + * Returns the flags that this node can generate for the given expression and + * event. + */ + public int getDeltaFlagsForExpression(IExpression expression, Object event); + + /** + * Adds delta flags to the given parent delta based on the expression + * object given. The nodes add flags to the expression view's root + * delta using this method, regardless of whether the node is directly + * below the expression manager or not. + * + */ + public void buildDeltaForExpression(IExpression expression, int elementIdx, Object event, VMDelta parentDelta, + TreePath path, RequestMonitor rm); + + /** + * Adds delta to the given parent delta based on the given element that + * was created base on an expression parsed by this node. The VM nodes can + * add a new delta node to the parentDela by implementing this method. + */ + public void buildDeltaForExpressionElement(Object element, int elementIdx, Object event, VMDelta parentDelta, + final RequestMonitor rm); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/InvalidExpressionVMContext.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/InvalidExpressionVMContext.java index 32a48807e33..30d5a11acce 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/InvalidExpressionVMContext.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/InvalidExpressionVMContext.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -24,77 +24,84 @@ import org.eclipse.debug.ui.IDebugUIConstants; import org.eclipse.jface.resource.JFaceResources; /** - * VMC of an expression object that failed to get parsed by any of the + * VMC of an expression object that failed to get parsed by any of the * configured expression layout nodes. It is only used to display an - * error message in the view, and to allow the user to edit the + * error message in the view, and to allow the user to edit the * expression. * <p> - * Note: VM Nodes using this invalid expression VM context should - * provide a cell modifier to edit the expressions. The cell modifier + * Note: VM Nodes using this invalid expression VM context should + * provide a cell modifier to edit the expressions. The cell modifier * should subclass {@link WatchExpressionCellModifier}. - * </p> - * + * </p> + * * @since 1.1 */ public class InvalidExpressionVMContext extends AbstractVMContext implements IElementLabelProvider { - - final private IExpression fExpression; - - public InvalidExpressionVMContext(IVMNode node, IExpression expression) { - super(node); - fExpression = expression; - } - @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Object getAdapter(Class adapter) { - if (adapter.isAssignableFrom(fExpression.getClass())) { - return fExpression; - } else { - return super.getAdapter(adapter); - } - } - - public IExpression getExpression() { - return fExpression; - } - - @Override - public boolean equals(Object obj) { - return obj instanceof InvalidExpressionVMContext && ((InvalidExpressionVMContext)obj).fExpression.equals(fExpression); - } - - @Override - public int hashCode() { - return fExpression.hashCode(); - } - - /** - * Updates the label for the InvalidExpressionVMC. - */ - @Override + final private IExpression fExpression; + + public InvalidExpressionVMContext(IVMNode node, IExpression expression) { + super(node); + fExpression = expression; + } + + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public Object getAdapter(Class adapter) { + if (adapter.isAssignableFrom(fExpression.getClass())) { + return fExpression; + } else { + return super.getAdapter(adapter); + } + } + + public IExpression getExpression() { + return fExpression; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof InvalidExpressionVMContext + && ((InvalidExpressionVMContext) obj).fExpression.equals(fExpression); + } + + @Override + public int hashCode() { + return fExpression.hashCode(); + } + + /** + * Updates the label for the InvalidExpressionVMC. + */ + @Override public void update(ILabelUpdate[] updates) { - for (ILabelUpdate update : updates) { - String[] columnIds = update.getColumnIds() != null ? - update.getColumnIds() : new String[] { IDebugVMConstants.COLUMN_ID__NAME }; - - for (int i = 0; i < columnIds.length; i++) { - if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnIds[i])) { - update.setLabel(getExpression().getExpressionText(), i); - update.setImageDescriptor(DebugUITools.getImageDescriptor( IDebugUIConstants.IMG_OBJS_EXPRESSION ), i); - } else if (IDebugVMConstants.COLUMN_ID__NAME.equals(columnIds[i])) { - update.setLabel(getExpression().getExpressionText(), i); - update.setImageDescriptor(DebugUITools.getImageDescriptor( IDebugUIConstants.IMG_OBJS_EXPRESSION ), i); - } else if (IDebugVMConstants.COLUMN_ID__VALUE.equals(columnIds[i])) { - update.setLabel(MessagesForExpressionVM.ExpressionManagerLayoutNode__invalidExpression_valueColumn_label, i); - } else { - update.setLabel("", i); //$NON-NLS-1$ - } - update.setFontData(JFaceResources.getFontDescriptor(IDebugUIConstants.PREF_VARIABLE_TEXT_FONT).getFontData()[0], i); - } + for (ILabelUpdate update : updates) { + String[] columnIds = update.getColumnIds() != null ? update.getColumnIds() + : new String[] { IDebugVMConstants.COLUMN_ID__NAME }; + + for (int i = 0; i < columnIds.length; i++) { + if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnIds[i])) { + update.setLabel(getExpression().getExpressionText(), i); + update.setImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_EXPRESSION), + i); + } else if (IDebugVMConstants.COLUMN_ID__NAME.equals(columnIds[i])) { + update.setLabel(getExpression().getExpressionText(), i); + update.setImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_EXPRESSION), + i); + } else if (IDebugVMConstants.COLUMN_ID__VALUE.equals(columnIds[i])) { + update.setLabel( + MessagesForExpressionVM.ExpressionManagerLayoutNode__invalidExpression_valueColumn_label, + i); + } else { + update.setLabel("", i); //$NON-NLS-1$ + } + update.setFontData( + JFaceResources.getFontDescriptor(IDebugUIConstants.PREF_VARIABLE_TEXT_FONT).getFontData()[0], + i); + } - update.done(); - } - } + update.done(); + } + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/MessagesForExpressionVM.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/MessagesForExpressionVM.java index cca27865052..89649273eda 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/MessagesForExpressionVM.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/MessagesForExpressionVM.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,26 +19,26 @@ import org.eclipse.osgi.util.NLS; * @noinstantiate This class is not intended to be instantiated by clients. */ public class MessagesForExpressionVM extends NLS { - public static String ExpressionColumnPresentation_expression; - public static String ExpressionColumnPresentation_name; - public static String ExpressionColumnPresentation_type; - public static String ExpressionColumnPresentation_value; - public static String ExpressionColumnPresentation_address; - public static String ExpressionColumnPresentation_description; + public static String ExpressionColumnPresentation_expression; + public static String ExpressionColumnPresentation_name; + public static String ExpressionColumnPresentation_type; + public static String ExpressionColumnPresentation_value; + public static String ExpressionColumnPresentation_address; + public static String ExpressionColumnPresentation_description; + + public static String ExpressionManagerLayoutNode__invalidExpression_nameColumn_label; + public static String ExpressionManagerLayoutNode__invalidExpression_valueColumn_label; - public static String ExpressionManagerLayoutNode__invalidExpression_nameColumn_label; - public static String ExpressionManagerLayoutNode__invalidExpression_valueColumn_label; + public static String ExpressionManagerLayoutNode__newExpression_label; - public static String ExpressionManagerLayoutNode__newExpression_label; - - public static String DisabledExpressionVMNode_disabled_value; - public static String DisabledExpressionVMNode_disabled_no_columns; + public static String DisabledExpressionVMNode_disabled_value; + public static String DisabledExpressionVMNode_disabled_no_columns; - static { - // initialize resource bundle - NLS.initializeMessages(MessagesForExpressionVM.class.getName(), MessagesForExpressionVM.class); - } + static { + // initialize resource bundle + NLS.initializeMessages(MessagesForExpressionVM.class.getName(), MessagesForExpressionVM.class); + } - private MessagesForExpressionVM() { - } + private MessagesForExpressionVM() { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/SingleExpressionVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/SingleExpressionVMNode.java index c437e0815c3..dfef8f40583 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/SingleExpressionVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/SingleExpressionVMNode.java @@ -42,280 +42,286 @@ import org.eclipse.jface.viewers.TreePath; /** * A VM node for displaying a single expression in the expression hover. - * + * * @since 2.1 */ public class SingleExpressionVMNode extends AbstractVMNode implements IElementLabelProvider { private static class RootDMVMContext extends AbstractVMContext implements IDMVMContext { private final IDMContext fDmc; + public RootDMVMContext(IVMNode node, IDMContext dmc) { super(node); fDmc = dmc; } - @Override + + @Override public IDMContext getDMContext() { return fDmc; } + @SuppressWarnings("unchecked") @Override public <T> T getAdapter(Class<T> adapter) { - T superAdapter = super.getAdapter(adapter); - if (superAdapter != null) { - return superAdapter; - } else { - // Delegate to the Data Model to find the context. - if (adapter.isInstance(fDmc)) { - return (T)fDmc; - } else { - return fDmc.getAdapter(adapter); - } - } + T superAdapter = super.getAdapter(adapter); + if (superAdapter != null) { + return superAdapter; + } else { + // Delegate to the Data Model to find the context. + if (adapter.isInstance(fDmc)) { + return (T) fDmc; + } else { + return fDmc.getAdapter(adapter); + } + } } @Override public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other instanceof RootDMVMContext) { - RootDMVMContext otherVmc = (RootDMVMContext)other; - return getVMNode().equals(otherVmc.getVMNode()) && fDmc.equals(otherVmc.fDmc); - } - return false; + if (this == other) { + return true; + } + if (other instanceof RootDMVMContext) { + RootDMVMContext otherVmc = (RootDMVMContext) other; + return getVMNode().equals(otherVmc.getVMNode()) && fDmc.equals(otherVmc.fDmc); + } + return false; } @Override public int hashCode() { - return getVMNode().hashCode() + fDmc.hashCode(); + return getVMNode().hashCode() + fDmc.hashCode(); } - @Override - public String toString() { - return fDmc.toString(); - } + @Override + public String toString() { + return fDmc.toString(); + } } private static class SimpleExpression implements IExpression { private String fExpressionText; + SimpleExpression(String text) { fExpressionText = text; } - @Override + + @Override public void dispose() { } - @Override + + @Override public IDebugTarget getDebugTarget() { return null; } - @Override + + @Override public String getExpressionText() { return fExpressionText; } - @Override + + @Override public IValue getValue() { return null; } - @Override + + @Override public ILaunch getLaunch() { return null; } - @Override + + @Override public String getModelIdentifier() { return null; } - @Override + + @Override public <T> T getAdapter(Class<T> adapter) { return null; } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof SimpleExpression) { - return fExpressionText.equals(((SimpleExpression) obj).getExpressionText()); - } - return false; - } - @Override - public int hashCode() { - return fExpressionText.hashCode(); - } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof SimpleExpression) { + return fExpressionText.equals(((SimpleExpression) obj).getExpressionText()); + } + return false; + } + + @Override + public int hashCode() { + return fExpressionText.hashCode(); + } } - public SingleExpressionVMNode(ExpressionVMProvider provider) { - super(provider); - } + public SingleExpressionVMNode(ExpressionVMProvider provider) { + super(provider); + } + + @Override + public String toString() { + return "SingleExpressionVMNode"; //$NON-NLS-1$ + } + + private ExpressionVMProvider getExpressionVMProvider() { + return (ExpressionVMProvider) getVMProvider(); + } + + private IExpressionDMContext getUpdateExpressionDMC(IViewerUpdate update) { + if (update.getElement() instanceof IDMVMContext) { + IDMContext dmc = ((IDMVMContext) update.getElement()).getDMContext(); + if (dmc instanceof IExpressionDMContext) { + return (IExpressionDMContext) dmc; + } + } + return null; + } @Override - public String toString() { - return "SingleExpressionVMNode"; //$NON-NLS-1$ - } - - private ExpressionVMProvider getExpressionVMProvider() { - return (ExpressionVMProvider)getVMProvider(); - } - - private IExpressionDMContext getUpdateExpressionDMC(IViewerUpdate update) { - if (update.getElement() instanceof IDMVMContext) { - IDMContext dmc = ((IDMVMContext)update.getElement()).getDMContext(); - if (dmc instanceof IExpressionDMContext) { - return (IExpressionDMContext)dmc; - } - } - return null; - } - - - @Override public void update(IHasChildrenUpdate[] updates) { - for (int i = 0; i < updates.length; i++) { - updates[i].setHasChilren(getUpdateExpressionDMC(updates[i]) != null); - updates[i].done(); - } - } - - @Override + for (int i = 0; i < updates.length; i++) { + updates[i].setHasChilren(getUpdateExpressionDMC(updates[i]) != null); + updates[i].done(); + } + } + + @Override public void update(IChildrenCountUpdate[] updates) { - for (IChildrenCountUpdate update : updates) { - if (!checkUpdate(update)) continue; - - // We assume that the getExpressions() will just read local state data, - // so we don't bother using a job to perform this operation. - update.setChildCount(getUpdateExpressionDMC(update) != null ? 1 : 0); - update.done(); - } - } - - @Override + for (IChildrenCountUpdate update : updates) { + if (!checkUpdate(update)) + continue; + + // We assume that the getExpressions() will just read local state data, + // so we don't bother using a job to perform this operation. + update.setChildCount(getUpdateExpressionDMC(update) != null ? 1 : 0); + update.done(); + } + } + + @Override public void update(final IChildrenUpdate[] updates) { - for (IChildrenUpdate update : updates) { - IExpressionDMContext dmc = getUpdateExpressionDMC(update); - if (dmc != null) { - doUpdateChildren(update, new SimpleExpression(dmc.getExpression())); - } - else { - handleFailedUpdate(update); - } - } - } - - public void doUpdateChildren(final IChildrenUpdate update, final IExpression expression) { - // getElementForExpression() accepts a IElementsUpdate as an argument. - // Construct an instance of VMElementsUpdate which will call a - // the request monitor when it is finished. The request monitor - // will in turn set the element in the update argument in this method. - ((ExpressionVMProvider)getVMProvider()).update( - new VMExpressionUpdate( - update, expression, - new ViewerDataRequestMonitor<Object>(getVMProvider().getExecutor(), update) { - @Override - protected void handleSuccess() { - update.setChild(getData(), 0); - update.done(); - } - - @Override - protected void handleError() { - update.setChild(new InvalidExpressionVMContext(SingleExpressionVMNode.this, expression), 0); - update.done(); - } - }) - ); - } - - @Override - public void update(ILabelUpdate[] updates) { - // The label update handler only handles labels for the invalid expression VMCs. - // The expression layout nodes are responsible for supplying label providers - // for their VMCs. - for (ILabelUpdate update : updates) { - update.done(); - } - } - - @Override - public int getDeltaFlags(Object event) { - int retVal = 0; - - // Add a flag if the list of expressions in the global expression manager has changed. - if (event instanceof ExpressionsChangedEvent) { - retVal |= IModelDelta.ADDED | IModelDelta.REMOVED | IModelDelta.INSERTED | IModelDelta.CONTENT ; - } - - // The expression in the hover is not known here, so assume that all - // expression nodes need to provide delta flags for event. Iterate - // through them here and collect the flags. - for (IExpressionVMNode node : getExpressionVMProvider().getExpressionNodes()) { - retVal |= getDeltaFlagsForNode(node, event); - } - - return retVal; - } - - private int getDeltaFlagsForNode(IVMNode node, Object event) { - int retVal = node.getDeltaFlags(event); - for (IVMNode child : getVMProvider().getChildVMNodes(node)) { - if (!node.equals(child)) { - retVal |= getDeltaFlagsForNode(child, event); - } - } - return retVal; - } - - @Override - public void buildDelta(final Object event, final VMDelta parentDelta, final int nodeOffset, final RequestMonitor requestMonitor) { - if (event instanceof ExpressionsChangedEvent) { - buildDeltaForExpressionsChangedEvent((ExpressionsChangedEvent)event, parentDelta, nodeOffset, requestMonitor); - } else { - Object parent = parentDelta.getElement(); - if (parent instanceof IDMVMContext) { - IDMContext dmc = ((IDMVMContext)parent).getDMContext(); - if (dmc instanceof IExpressionDMContext) { - IExpression expression = new SimpleExpression( ((IExpressionDMContext)dmc).getExpression() ); - int flags = getExpressionVMProvider().getDeltaFlagsForExpression(expression, event); - // If the given expression has no delta flags, skip it. - if (flags != IModelDelta.NO_CHANGE) { - getExpressionVMProvider().buildDeltaForExpression( - expression, nodeOffset, event, parentDelta, getTreePathFromDelta(parentDelta), - requestMonitor); - return; - } - } - } - requestMonitor.done(); - } - } - - private void buildDeltaForExpressionsChangedEvent(ExpressionsChangedEvent event, VMDelta parentDelta, - int nodeOffset, RequestMonitor requestMonitor) - { - CountingRequestMonitor multiRm = new CountingRequestMonitor(getExecutor(), requestMonitor); - for (int i = 0; i < event.getExpressions().length; i++) { - int expIndex = event.getIndex() != -1 - ? nodeOffset + event.getIndex() + i - : -1; - getExpressionVMProvider().buildDeltaForExpression( - event.getExpressions()[i], expIndex, event, parentDelta, getTreePathFromDelta(parentDelta), - new RequestMonitor(getExecutor(), multiRm)); - } - multiRm.setDoneCount(event.getExpressions().length); - } - - private TreePath getTreePathFromDelta(IModelDelta delta) { - List<Object> elementList = new LinkedList<Object>(); - IModelDelta listDelta = delta; - elementList.add(0, listDelta.getElement()); - while (listDelta.getParentDelta() != null) { - elementList.add(0, listDelta.getElement()); - listDelta = listDelta.getParentDelta(); - } - return new TreePath(elementList.toArray()); - } + for (IChildrenUpdate update : updates) { + IExpressionDMContext dmc = getUpdateExpressionDMC(update); + if (dmc != null) { + doUpdateChildren(update, new SimpleExpression(dmc.getExpression())); + } else { + handleFailedUpdate(update); + } + } + } + + public void doUpdateChildren(final IChildrenUpdate update, final IExpression expression) { + // getElementForExpression() accepts a IElementsUpdate as an argument. + // Construct an instance of VMElementsUpdate which will call a + // the request monitor when it is finished. The request monitor + // will in turn set the element in the update argument in this method. + ((ExpressionVMProvider) getVMProvider()).update(new VMExpressionUpdate(update, expression, + new ViewerDataRequestMonitor<Object>(getVMProvider().getExecutor(), update) { + @Override + protected void handleSuccess() { + update.setChild(getData(), 0); + update.done(); + } + + @Override + protected void handleError() { + update.setChild(new InvalidExpressionVMContext(SingleExpressionVMNode.this, expression), 0); + update.done(); + } + })); + } + + @Override + public void update(ILabelUpdate[] updates) { + // The label update handler only handles labels for the invalid expression VMCs. + // The expression layout nodes are responsible for supplying label providers + // for their VMCs. + for (ILabelUpdate update : updates) { + update.done(); + } + } + + @Override + public int getDeltaFlags(Object event) { + int retVal = 0; + + // Add a flag if the list of expressions in the global expression manager has changed. + if (event instanceof ExpressionsChangedEvent) { + retVal |= IModelDelta.ADDED | IModelDelta.REMOVED | IModelDelta.INSERTED | IModelDelta.CONTENT; + } + + // The expression in the hover is not known here, so assume that all + // expression nodes need to provide delta flags for event. Iterate + // through them here and collect the flags. + for (IExpressionVMNode node : getExpressionVMProvider().getExpressionNodes()) { + retVal |= getDeltaFlagsForNode(node, event); + } + + return retVal; + } + + private int getDeltaFlagsForNode(IVMNode node, Object event) { + int retVal = node.getDeltaFlags(event); + for (IVMNode child : getVMProvider().getChildVMNodes(node)) { + if (!node.equals(child)) { + retVal |= getDeltaFlagsForNode(child, event); + } + } + return retVal; + } + + @Override + public void buildDelta(final Object event, final VMDelta parentDelta, final int nodeOffset, + final RequestMonitor requestMonitor) { + if (event instanceof ExpressionsChangedEvent) { + buildDeltaForExpressionsChangedEvent((ExpressionsChangedEvent) event, parentDelta, nodeOffset, + requestMonitor); + } else { + Object parent = parentDelta.getElement(); + if (parent instanceof IDMVMContext) { + IDMContext dmc = ((IDMVMContext) parent).getDMContext(); + if (dmc instanceof IExpressionDMContext) { + IExpression expression = new SimpleExpression(((IExpressionDMContext) dmc).getExpression()); + int flags = getExpressionVMProvider().getDeltaFlagsForExpression(expression, event); + // If the given expression has no delta flags, skip it. + if (flags != IModelDelta.NO_CHANGE) { + getExpressionVMProvider().buildDeltaForExpression(expression, nodeOffset, event, parentDelta, + getTreePathFromDelta(parentDelta), requestMonitor); + return; + } + } + } + requestMonitor.done(); + } + } + + private void buildDeltaForExpressionsChangedEvent(ExpressionsChangedEvent event, VMDelta parentDelta, + int nodeOffset, RequestMonitor requestMonitor) { + CountingRequestMonitor multiRm = new CountingRequestMonitor(getExecutor(), requestMonitor); + for (int i = 0; i < event.getExpressions().length; i++) { + int expIndex = event.getIndex() != -1 ? nodeOffset + event.getIndex() + i : -1; + getExpressionVMProvider().buildDeltaForExpression(event.getExpressions()[i], expIndex, event, parentDelta, + getTreePathFromDelta(parentDelta), new RequestMonitor(getExecutor(), multiRm)); + } + multiRm.setDoneCount(event.getExpressions().length); + } + + private TreePath getTreePathFromDelta(IModelDelta delta) { + List<Object> elementList = new LinkedList<Object>(); + IModelDelta listDelta = delta; + elementList.add(0, listDelta.getElement()); + while (listDelta.getParentDelta() != null) { + elementList.add(0, listDelta.getElement()); + listDelta = listDelta.getParentDelta(); + } + return new TreePath(elementList.toArray()); + } public IDMVMContext createVMContext(IDMContext dmc) { - return new RootDMVMContext(getVMProvider().getRootVMNode(), dmc); - } + return new RootDMVMContext(getVMProvider().getRootVMNode(), dmc); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/VMExpressionUpdate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/VMExpressionUpdate.java index dfb0d45ed9a..fb6eb636204 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/VMExpressionUpdate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/VMExpressionUpdate.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -29,67 +29,66 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; import org.eclipse.jface.viewers.TreePath; /** - * + * */ class VMExpressionUpdate extends VMViewerUpdate implements IExpressionUpdate { - private final IExpression fExpression; - private Object fExpressionElement; - - public VMExpressionUpdate(IViewerUpdate clientUpdate, IExpression expression, DataRequestMonitor<Object> rm) - { - super(clientUpdate, rm); - fExpression = expression; - } + private final IExpression fExpression; + private Object fExpressionElement; - public VMExpressionUpdate(IModelDelta delta, IPresentationContext presentationContext, IExpression expression, DataRequestMonitor<Object> rm) - { - super(delta, presentationContext, rm); - fExpression = expression; - } - - public VMExpressionUpdate(TreePath elementPath, Object viewerInput, IPresentationContext presentationContext, IExpression expression, DataRequestMonitor<Object> rm) - { - super(elementPath, viewerInput, presentationContext, rm); - fExpression = expression; - } + public VMExpressionUpdate(IViewerUpdate clientUpdate, IExpression expression, DataRequestMonitor<Object> rm) { + super(clientUpdate, rm); + fExpression = expression; + } + public VMExpressionUpdate(IModelDelta delta, IPresentationContext presentationContext, IExpression expression, + DataRequestMonitor<Object> rm) { + super(delta, presentationContext, rm); + fExpression = expression; + } - @Override - public IExpression getExpression() { - return fExpression; - } + public VMExpressionUpdate(TreePath elementPath, Object viewerInput, IPresentationContext presentationContext, + IExpression expression, DataRequestMonitor<Object> rm) { + super(elementPath, viewerInput, presentationContext, rm); + fExpression = expression; + } + @Override + public IExpression getExpression() { + return fExpression; + } - @Override + @Override public void setExpressionElement(Object element) { - fExpressionElement = element; - } + fExpressionElement = element; + } + + @Override + public String toString() { + return "VMExpressionUpdate for elements under parent = " + getElement() + ", in for expression " //$NON-NLS-1$//$NON-NLS-2$ + + getExpression().getExpressionText(); + } + + @Override + public void done() { + @SuppressWarnings("unchecked") + + DataRequestMonitor<Object> rm = (DataRequestMonitor<Object>) getRequestMonitor(); + if (fExpressionElement != null) { + rm.setData(fExpressionElement); + } else if (rm.isSuccess()) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, + "Incomplete elements of updates", null)); //$NON-NLS-1$ + } - @Override - public String toString() { - return "VMExpressionUpdate for elements under parent = " + getElement() + ", in for expression " + getExpression().getExpressionText(); //$NON-NLS-1$ //$NON-NLS-2$ - } + // trace our result + if (VMViewerUpdateTracing.DEBUG_VMUPDATES && !isCanceled() + && VMViewerUpdateTracing.matchesFilterRegex(this.getClass())) { + DsfUIPlugin.debug(DsfPlugin.getDebugTime() + " " + LoggingUtils.toString(this) + " marked done; element = " //$NON-NLS-1$//$NON-NLS-2$ + + LoggingUtils.toString(getElement()) + "\n expression = " + + (fExpressionElement != null ? LoggingUtils.toString(fExpressionElement) : "<unset>")); //$NON-NLS-1$ + } - @Override - public void done() { - @SuppressWarnings("unchecked") - - DataRequestMonitor<Object> rm = (DataRequestMonitor<Object>)getRequestMonitor(); - if (fExpressionElement != null) { - rm.setData(fExpressionElement); - } else if (rm.isSuccess()) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "Incomplete elements of updates", null)); //$NON-NLS-1$ - } - - // trace our result - if (VMViewerUpdateTracing.DEBUG_VMUPDATES && !isCanceled() && VMViewerUpdateTracing.matchesFilterRegex(this.getClass())) { - DsfUIPlugin.debug(DsfPlugin.getDebugTime() - + " " + LoggingUtils.toString(this) + " marked done; element = " + LoggingUtils.toString(getElement()) + //$NON-NLS-1$ //$NON-NLS-2$ - "\n expression = " //$NON-NLS-1$ - + (fExpressionElement != null ? LoggingUtils.toString(fExpressionElement) : "<unset>")); //$NON-NLS-1$ - } - - super.done(); - } + super.done(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/WatchExpressionCellModifier.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/WatchExpressionCellModifier.java index ad6eb44b7db..8d96619db13 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/WatchExpressionCellModifier.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/WatchExpressionCellModifier.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Winnie Lai (Texas Instruments) - Individual Element Number Format in editing (Bug 343021) @@ -43,81 +43,80 @@ import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IWorkbenchPart; /** - * + * */ @ThreadSafeAndProhibitedFromDsfExecutor("") public class WatchExpressionCellModifier implements ICellModifier { - /** - * Constructor for the modifier requires a valid DSF session in order to - * initialize the service tracker. - * @param session DSF session this modifier will use. - */ - public WatchExpressionCellModifier() { - } + /** + * Constructor for the modifier requires a valid DSF session in order to + * initialize the service tracker. + * @param session DSF session this modifier will use. + */ + public WatchExpressionCellModifier() { + } - @Override + @Override public boolean canModify(Object element, String property) { - if (element instanceof NewExpressionVMC) { - return IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(property) || - IDebugVMConstants.COLUMN_ID__NAME.equals(property); - } else { - return IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(property) && - getWatchExpression(element) != null; - } - } + if (element instanceof NewExpressionVMC) { + return IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(property) + || IDebugVMConstants.COLUMN_ID__NAME.equals(property); + } else { + return IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(property) && getWatchExpression(element) != null; + } + } - @Override + @Override public Object getValue(Object element, String property) { - if (!IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(property) && - !IDebugVMConstants.COLUMN_ID__NAME.equals(property)) - { - return ""; //$NON-NLS-1$ - } + if (!IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(property) + && !IDebugVMConstants.COLUMN_ID__NAME.equals(property)) { + return ""; //$NON-NLS-1$ + } + + IWatchExpression expression = getWatchExpression(element); - IWatchExpression expression = getWatchExpression(element); - - if (expression != null) { - return expression.getExpressionText(); - } - return ""; //$NON-NLS-1$ - } + if (expression != null) { + return expression.getExpressionText(); + } + return ""; //$NON-NLS-1$ + } - @Override + @Override public void modify(Object element, String property, Object value) { - if (!IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(property) && - !IDebugVMConstants.COLUMN_ID__NAME.equals(property)) - { - return; - } - if (!(value instanceof String)) return; - - String origStrValue = (String) value; - String strValue = origStrValue.trim(); - IWatchExpression expression = getWatchExpression(element); - IExpressionManager expressionManager = DebugPlugin.getDefault().getExpressionManager(); - if (expression != null) { - if (strValue.length() != 0) { - expression.setExpressionText(origStrValue); - } else { - // (bug 233111) If user entered a blank string, remove the expression. - expressionManager.removeExpression(expression); - } - } else if (element instanceof NewExpressionVMC && strValue.length() != 0) { - IWatchExpression watchExpression = expressionManager.newWatchExpression(origStrValue); - expressionManager.addExpression(watchExpression); - } - } + if (!IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(property) + && !IDebugVMConstants.COLUMN_ID__NAME.equals(property)) { + return; + } + if (!(value instanceof String)) + return; - /** - * Use query to get element format for a vm context from a given provider for given presentation context. - * One use of this method is in cell modifier's getValue() and modify(). - * @param provider given provider - * @param presCtx given presentation context - * @param ctx vm context - * @return element format, null if not available - */ - protected String queryElementFormat(final IElementFormatProvider provider, final IPresentationContext presCtx, final IVMContext ctx) { + String origStrValue = (String) value; + String strValue = origStrValue.trim(); + IWatchExpression expression = getWatchExpression(element); + IExpressionManager expressionManager = DebugPlugin.getDefault().getExpressionManager(); + if (expression != null) { + if (strValue.length() != 0) { + expression.setExpressionText(origStrValue); + } else { + // (bug 233111) If user entered a blank string, remove the expression. + expressionManager.removeExpression(expression); + } + } else if (element instanceof NewExpressionVMC && strValue.length() != 0) { + IWatchExpression watchExpression = expressionManager.newWatchExpression(origStrValue); + expressionManager.addExpression(watchExpression); + } + } + + /** + * Use query to get element format for a vm context from a given provider for given presentation context. + * One use of this method is in cell modifier's getValue() and modify(). + * @param provider given provider + * @param presCtx given presentation context + * @param ctx vm context + * @return element format, null if not available + */ + protected String queryElementFormat(final IElementFormatProvider provider, final IPresentationContext presCtx, + final IVMContext ctx) { DsfSession session = null; if (ctx instanceof IDMVMContext) { IDMContext dmctx = ((IDMVMContext) ctx).getDMContext(); @@ -135,8 +134,8 @@ public class WatchExpressionCellModifier implements ICellModifier { // is just the leaf; this is somewhat different than how // FormatValueRetriever pass in a fully qualified tree path to // the IElementFormatProvider. It is believed that IVMContext - // can be used to get its parents when needed. - TreePath treePath = new TreePath(new Object[] {ctx}); + // can be used to get its parents when needed. + TreePath treePath = new TreePath(new Object[] { ctx }); Object viewerInput = null; IWorkbenchPart part = presCtx.getPart(); if (part instanceof IDebugView) { @@ -147,12 +146,12 @@ public class WatchExpressionCellModifier implements ICellModifier { } provider.getActiveFormat(presCtx, ctx.getVMNode(), viewerInput, treePath, new DataRequestMonitor<String>(ImmediateExecutor.getInstance(), rm) { - @Override - protected void handleSuccess() { - rm.setData(this.getData()); - super.handleSuccess(); - } - }); + @Override + protected void handleSuccess() { + rm.setData(this.getData()); + super.handleSuccess(); + } + }); } }; session.getExecutor().execute(query); @@ -173,28 +172,28 @@ public class WatchExpressionCellModifier implements ICellModifier { * if the vm provider associated with the vm context supports individual element format. * If the vm provider does not support individual element format or queryElementFormat * returns null, this method returns the preferred format of the view. - * One use of this method is in cell modifier's getValue() and modify(). + * One use of this method is in cell modifier's getValue() and modify(). * @param ctx the given vm context * @return the format */ protected String queryFormat(IVMContext ctx) { String formatId = null; - IVMProvider vmprovider = ctx.getVMNode().getVMProvider(); - IPresentationContext presCtx = vmprovider.getPresentationContext(); - if (vmprovider instanceof IElementFormatProvider) { - formatId = queryElementFormat((IElementFormatProvider) vmprovider, presCtx, ctx); - } - if (formatId == null) { - formatId = FormattedValueVMUtil.getPreferredFormat(presCtx); - } + IVMProvider vmprovider = ctx.getVMNode().getVMProvider(); + IPresentationContext presCtx = vmprovider.getPresentationContext(); + if (vmprovider instanceof IElementFormatProvider) { + formatId = queryElementFormat((IElementFormatProvider) vmprovider, presCtx, ctx); + } + if (formatId == null) { + formatId = FormattedValueVMUtil.getPreferredFormat(presCtx); + } return formatId; } private IWatchExpression getWatchExpression(Object element) { - if (element instanceof IAdaptable) { - return ((IAdaptable)element).getAdapter(IWatchExpression.class); - } - return null; - } + if (element instanceof IAdaptable) { + return ((IAdaptable) element).getAdapter(IWatchExpression.class); + } + return null; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/WatchExpressionDelegate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/WatchExpressionDelegate.java index 24b364ae01b..6b829f5c562 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/WatchExpressionDelegate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/expression/WatchExpressionDelegate.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -21,22 +21,36 @@ import org.eclipse.debug.core.model.IWatchExpressionListener; import org.eclipse.debug.core.model.IWatchExpressionResult; /** - * + * */ public class WatchExpressionDelegate implements IWatchExpressionDelegate { - @Override + @Override public void evaluateExpression(final String expression, IDebugElement context, IWatchExpressionListener listener) { - listener.watchEvaluationFinished(new IWatchExpressionResult() { - @Override - public String[] getErrorMessages() { return new String[0]; } - @Override - public DebugException getException() { return null; } - @Override - public String getExpressionText() { return expression; } - @Override - public IValue getValue() { return null; } - @Override - public boolean hasErrors() { return false; } - }); - } + listener.watchEvaluationFinished(new IWatchExpressionResult() { + @Override + public String[] getErrorMessages() { + return new String[0]; + } + + @Override + public DebugException getException() { + return null; + } + + @Override + public String getExpressionText() { + return expression; + } + + @Override + public IValue getValue() { + return null; + } + + @Override + public boolean hasErrors() { + return false; + } + }); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractContainerVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractContainerVMNode.java index 2470afb3062..3080c3a15bc 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractContainerVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractContainerVMNode.java @@ -11,7 +11,7 @@ * Contributors: * Wind River Systems - initial API and implementation * Patrick Chuong (Texas Instruments) - Add support for icon overlay in the debug view (Bug 334566) - * Dobrin Alexiev (Texas Instruments) - user groups support (bug 240208) + * Dobrin Alexiev (Texas Instruments) - user groups support (bug 240208) *******************************************************************************/ package org.eclipse.cdt.dsf.debug.ui.viewmodel.launch; @@ -66,409 +66,406 @@ import org.eclipse.debug.ui.IDebugUIConstants; /** * Abstract implementation of a container view model node. * Clients need to implement {@link #updateLabelInSessionThread(ILabelUpdate[])}. - * + * * @since 1.1 */ -public abstract class AbstractContainerVMNode extends AbstractExecutionContextVMNode - implements IElementLabelProvider, IElementPropertiesProvider - { - /** - * The label provider delegate. This VM node will delegate label updates to this provider - * which can be created by sub-classes. - * - * @since 2.0 - */ - private IElementLabelProvider fLabelProvider; - +public abstract class AbstractContainerVMNode extends AbstractExecutionContextVMNode + implements IElementLabelProvider, IElementPropertiesProvider { + /** + * The label provider delegate. This VM node will delegate label updates to this provider + * which can be created by sub-classes. + * + * @since 2.0 + */ + private IElementLabelProvider fLabelProvider; + public AbstractContainerVMNode(AbstractDMVMProvider provider, DsfSession session) { super(provider, session, IRunControl.IContainerDMContext.class); fLabelProvider = createLabelProvider(); } - /** - * Creates the label provider delegate. This VM node will delegate label - * updates to this provider which can be created by sub-classes. - * - * @return Returns the label provider for this node. - * - * @since 2.0 - */ - protected IElementLabelProvider createLabelProvider() { - PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); - - provider.setColumnInfo( - PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, - new LabelColumnInfo(new LabelAttribute[] { - new ExecutionContextLabelText( - MessagesForLaunchVM.AbstractContainerVMNode_No_columns__text_format, - new String[] { - ExecutionContextLabelText.PROP_NAME_KNOWN, - PROP_NAME, - ExecutionContextLabelText.PROP_ID_KNOWN, - ILaunchVMConstants.PROP_ID }), - new LabelText(MessagesForLaunchVM.AbstractContainerVMNode_No_columns__Error__label, new String[0]), - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_DEBUG_TARGET_SUSPENDED)) { - { setPropertyNames(new String[] { ILaunchVMConstants.PROP_IS_SUSPENDED }); } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - return Boolean.TRUE.equals(properties.get(ILaunchVMConstants.PROP_IS_SUSPENDED)); - }; - }, - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_DEBUG_TARGET)), - })); - - return provider; - } - - + /** + * Creates the label provider delegate. This VM node will delegate label + * updates to this provider which can be created by sub-classes. + * + * @return Returns the label provider for this node. + * + * @since 2.0 + */ + protected IElementLabelProvider createLabelProvider() { + PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); + + provider.setColumnInfo(PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, + new LabelColumnInfo(new LabelAttribute[] { + new ExecutionContextLabelText( + MessagesForLaunchVM.AbstractContainerVMNode_No_columns__text_format, + new String[] { ExecutionContextLabelText.PROP_NAME_KNOWN, PROP_NAME, + ExecutionContextLabelText.PROP_ID_KNOWN, ILaunchVMConstants.PROP_ID }), + new LabelText(MessagesForLaunchVM.AbstractContainerVMNode_No_columns__Error__label, + new String[0]), + new LabelImage( + DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_DEBUG_TARGET_SUSPENDED)) { + { + setPropertyNames(new String[] { ILaunchVMConstants.PROP_IS_SUSPENDED }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + return Boolean.TRUE.equals(properties.get(ILaunchVMConstants.PROP_IS_SUSPENDED)); + }; + }, + new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_DEBUG_TARGET)), })); + + return provider; + } + @Override public void update(final ILabelUpdate[] updates) { - fLabelProvider.update(updates); - } - - /** - * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) - * - * @since 2.0 - */ - @Override + fLabelProvider.update(updates); + } + + /** + * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) + * + * @since 2.0 + */ + @Override public void update(final IPropertiesUpdate[] updates) { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - updatePropertiesInSessionThread(updates); - }}); - } catch (RejectedExecutionException e) { - for (IPropertiesUpdate update : updates) { - handleFailedUpdate(update); - } - } - } - - /** - * @since 2.0 - */ - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { - IRunControl service = getServicesTracker().getService(IRunControl.class); - - for (final IPropertiesUpdate update : updates) { - if (service == null) { - handleFailedUpdate(update); - continue; - } - - IExecutionDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IExecutionDMContext.class); - if (dmc == null) { - handleFailedUpdate(update); - continue; - } - - update.setProperty(ILaunchVMConstants.PROP_IS_SUSPENDED, service.isSuspended(dmc)); - update.setProperty(ILaunchVMConstants.PROP_IS_STEPPING, service.isStepping(dmc)); - - service.getExecutionData( - dmc, - new ViewerDataRequestMonitor<IExecutionDMData>(getSession().getExecutor(), update) { - @Override - protected void handleSuccess() { - fillExecutionDataProperties(update, getData()); - update.done(); - } - }); - } - } - - protected void fillExecutionDataProperties(IPropertiesUpdate update, IExecutionDMData data) { - StateChangeReason reason = data.getStateChangeReason(); - if (reason != null) { - update.setProperty(ILaunchVMConstants.PROP_STATE_CHANGE_REASON, data.getStateChangeReason().name()); - } - - if (data instanceof IExecutionDMData2) { - String details = ((IExecutionDMData2)data).getDetails(); - if (details != null) { - update.setProperty(ILaunchVMConstants.PROP_STATE_CHANGE_DETAILS, details); - } - } - } - - @Override - public void getContextsForEvent(VMDelta parentDelta, Object e, final DataRequestMonitor<IVMContext[]> rm) { - if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { - getContainerVMCForModelProxyInstallEvent( - parentDelta, - new DataRequestMonitor<VMContextInfo>(getExecutor(), rm) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - rm.setData(new IVMContext[] { getData().fVMContext }); - } else { - rm.setData(new IVMContext[0]); - } - rm.done(); - } - }); - } else { - super.getContextsForEvent(parentDelta, e, rm); - } - } - - private static class VMContextInfo { - final IVMContext fVMContext; - final int fIndex; - final boolean fIsSuspended; - VMContextInfo(IVMContext vmContext, int index, boolean isSuspended) { - fVMContext = vmContext; - fIndex = index; - fIsSuspended = isSuspended; - } - } - - private void getContainerVMCForModelProxyInstallEvent(VMDelta parentDelta, final DataRequestMonitor<VMContextInfo> rm) { - getVMProvider().updateNode(this, new VMChildrenUpdate( - parentDelta, getVMProvider().getPresentationContext(), -1, -1, - new DataRequestMonitor<List<Object>>(getExecutor(), rm) { - @Override - protected void handleSuccess() { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - final IRunControl runControl = getServicesTracker().getService(IRunControl.class); - if (runControl != null) { - int vmcIdx = -1; - int suspendedVmcIdx = -1; - - for (int i = 0; i < getData().size(); i++) { - if (getData().get(i) instanceof IDMVMContext) { - IDMVMContext vmc = (IDMVMContext)getData().get(i); - IContainerDMContext containerDmc = DMContexts.getAncestorOfType( - vmc.getDMContext(), IContainerDMContext.class); - if (containerDmc != null) { - vmcIdx = vmcIdx < 0 ? i : vmcIdx; - if (runControl.isSuspended(containerDmc)) { - suspendedVmcIdx = suspendedVmcIdx < 0 ? i : suspendedVmcIdx; - } - } - } - } - if (suspendedVmcIdx >= 0) { - rm.setData(new VMContextInfo( - (IVMContext)getData().get(suspendedVmcIdx), suspendedVmcIdx, true)); - } else if (vmcIdx >= 0) { - rm.setData(new VMContextInfo((IVMContext)getData().get(vmcIdx), vmcIdx, false)); - } else { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "No container available", null)); //$NON-NLS-1$ - } - rm.done(); - } else { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "No container available", null)); //$NON-NLS-1$ - rm.done(); - } - } - }); - } catch (RejectedExecutionException e) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "", null)); //$NON-NLS-1$ - rm.done(); - } - } - })); - } - - @Override + updatePropertiesInSessionThread(updates); + } + }); + } catch (RejectedExecutionException e) { + for (IPropertiesUpdate update : updates) { + handleFailedUpdate(update); + } + } + } + + /** + * @since 2.0 + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { + IRunControl service = getServicesTracker().getService(IRunControl.class); + + for (final IPropertiesUpdate update : updates) { + if (service == null) { + handleFailedUpdate(update); + continue; + } + + IExecutionDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IExecutionDMContext.class); + if (dmc == null) { + handleFailedUpdate(update); + continue; + } + + update.setProperty(ILaunchVMConstants.PROP_IS_SUSPENDED, service.isSuspended(dmc)); + update.setProperty(ILaunchVMConstants.PROP_IS_STEPPING, service.isStepping(dmc)); + + service.getExecutionData(dmc, + new ViewerDataRequestMonitor<IExecutionDMData>(getSession().getExecutor(), update) { + @Override + protected void handleSuccess() { + fillExecutionDataProperties(update, getData()); + update.done(); + } + }); + } + } + + protected void fillExecutionDataProperties(IPropertiesUpdate update, IExecutionDMData data) { + StateChangeReason reason = data.getStateChangeReason(); + if (reason != null) { + update.setProperty(ILaunchVMConstants.PROP_STATE_CHANGE_REASON, data.getStateChangeReason().name()); + } + + if (data instanceof IExecutionDMData2) { + String details = ((IExecutionDMData2) data).getDetails(); + if (details != null) { + update.setProperty(ILaunchVMConstants.PROP_STATE_CHANGE_DETAILS, details); + } + } + } + + @Override + public void getContextsForEvent(VMDelta parentDelta, Object e, final DataRequestMonitor<IVMContext[]> rm) { + if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { + getContainerVMCForModelProxyInstallEvent(parentDelta, + new DataRequestMonitor<VMContextInfo>(getExecutor(), rm) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + rm.setData(new IVMContext[] { getData().fVMContext }); + } else { + rm.setData(new IVMContext[0]); + } + rm.done(); + } + }); + } else { + super.getContextsForEvent(parentDelta, e, rm); + } + } + + private static class VMContextInfo { + final IVMContext fVMContext; + final int fIndex; + final boolean fIsSuspended; + + VMContextInfo(IVMContext vmContext, int index, boolean isSuspended) { + fVMContext = vmContext; + fIndex = index; + fIsSuspended = isSuspended; + } + } + + private void getContainerVMCForModelProxyInstallEvent(VMDelta parentDelta, + final DataRequestMonitor<VMContextInfo> rm) { + getVMProvider().updateNode(this, new VMChildrenUpdate(parentDelta, getVMProvider().getPresentationContext(), -1, + -1, new DataRequestMonitor<List<Object>>(getExecutor(), rm) { + @Override + protected void handleSuccess() { + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + final IRunControl runControl = getServicesTracker().getService(IRunControl.class); + if (runControl != null) { + int vmcIdx = -1; + int suspendedVmcIdx = -1; + + for (int i = 0; i < getData().size(); i++) { + if (getData().get(i) instanceof IDMVMContext) { + IDMVMContext vmc = (IDMVMContext) getData().get(i); + IContainerDMContext containerDmc = DMContexts.getAncestorOfType( + vmc.getDMContext(), IContainerDMContext.class); + if (containerDmc != null) { + vmcIdx = vmcIdx < 0 ? i : vmcIdx; + if (runControl.isSuspended(containerDmc)) { + suspendedVmcIdx = suspendedVmcIdx < 0 ? i : suspendedVmcIdx; + } + } + } + } + if (suspendedVmcIdx >= 0) { + rm.setData(new VMContextInfo((IVMContext) getData().get(suspendedVmcIdx), + suspendedVmcIdx, true)); + } else if (vmcIdx >= 0) { + rm.setData(new VMContextInfo((IVMContext) getData().get(vmcIdx), vmcIdx, + false)); + } else { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.REQUEST_FAILED, "No container available", //$NON-NLS-1$ + null)); + } + rm.done(); + } else { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.REQUEST_FAILED, "No container available", null)); //$NON-NLS-1$ + rm.done(); + } + } + }); + } catch (RejectedExecutionException e) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.NOT_SUPPORTED, "", null)); //$NON-NLS-1$ + rm.done(); + } + } + })); + } + + @Override public int getDeltaFlags(Object e) { - IDMContext dmc = e instanceof IDMEvent<?> ? ((IDMEvent<?>)e).getDMContext() : null; - - if (e instanceof IContainerResumedDMEvent) { - if (((IContainerResumedDMEvent)e).getReason() != IRunControl.StateChangeReason.STEP) - { - return IModelDelta.CONTENT; - } - } else if (e instanceof IContainerSuspendedDMEvent) { - return IModelDelta.NO_CHANGE; - } else if (e instanceof SteppingTimedOutEvent) { - if (dmc instanceof IContainerDMContext) - { - return IModelDelta.CONTENT; - } - } else if (e instanceof IExitedDMEvent) { - return IModelDelta.CONTENT; - } else if (e instanceof IStartedDMEvent) { - if (dmc instanceof IContainerDMContext) { - return IModelDelta.EXPAND | IModelDelta.SELECT; - } else { - return IModelDelta.CONTENT; - } - } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { - return IModelDelta.SELECT | IModelDelta.EXPAND; - } else if (e instanceof StateChangedEvent) { - return IModelDelta.STATE; - } else if (e instanceof FullStackRefreshEvent && - (((FullStackRefreshEvent)e).getTriggeringEvent() instanceof IContainerSuspendedDMEvent)) { - return IModelDelta.CONTENT; - } else if (e instanceof IResumedDMEvent) { - return IModelDelta.STATE; - } - - return IModelDelta.NO_CHANGE; + IDMContext dmc = e instanceof IDMEvent<?> ? ((IDMEvent<?>) e).getDMContext() : null; + + if (e instanceof IContainerResumedDMEvent) { + if (((IContainerResumedDMEvent) e).getReason() != IRunControl.StateChangeReason.STEP) { + return IModelDelta.CONTENT; + } + } else if (e instanceof IContainerSuspendedDMEvent) { + return IModelDelta.NO_CHANGE; + } else if (e instanceof SteppingTimedOutEvent) { + if (dmc instanceof IContainerDMContext) { + return IModelDelta.CONTENT; + } + } else if (e instanceof IExitedDMEvent) { + return IModelDelta.CONTENT; + } else if (e instanceof IStartedDMEvent) { + if (dmc instanceof IContainerDMContext) { + return IModelDelta.EXPAND | IModelDelta.SELECT; + } else { + return IModelDelta.CONTENT; + } + } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { + return IModelDelta.SELECT | IModelDelta.EXPAND; + } else if (e instanceof StateChangedEvent) { + return IModelDelta.STATE; + } else if (e instanceof FullStackRefreshEvent + && (((FullStackRefreshEvent) e).getTriggeringEvent() instanceof IContainerSuspendedDMEvent)) { + return IModelDelta.CONTENT; + } else if (e instanceof IResumedDMEvent) { + return IModelDelta.STATE; + } + + return IModelDelta.NO_CHANGE; } @Override - public void buildDelta(Object e, final VMDelta parentDelta, final int nodeOffset, final RequestMonitor requestMonitor) { - IDMContext dmc = e instanceof IDMEvent<?> ? ((IDMEvent<?>)e).getDMContext() : null; - - if(e instanceof IContainerResumedDMEvent) { - // Container resumed: - // - If not stepping, update the container and the execution - // contexts under it. - // - If stepping, do nothing to avoid too many updates. If a - // time-out is reached before the step completes, the - // ISteppingTimedOutEvent will trigger a full refresh. - if (((IContainerResumedDMEvent)e).getReason() != IRunControl.StateChangeReason.STEP) - { - parentDelta.addNode(createVMContext(((IDMEvent<?>)e).getDMContext()), IModelDelta.CONTENT); - } + public void buildDelta(Object e, final VMDelta parentDelta, final int nodeOffset, + final RequestMonitor requestMonitor) { + IDMContext dmc = e instanceof IDMEvent<?> ? ((IDMEvent<?>) e).getDMContext() : null; + + if (e instanceof IContainerResumedDMEvent) { + // Container resumed: + // - If not stepping, update the container and the execution + // contexts under it. + // - If stepping, do nothing to avoid too many updates. If a + // time-out is reached before the step completes, the + // ISteppingTimedOutEvent will trigger a full refresh. + if (((IContainerResumedDMEvent) e).getReason() != IRunControl.StateChangeReason.STEP) { + parentDelta.addNode(createVMContext(((IDMEvent<?>) e).getDMContext()), IModelDelta.CONTENT); + } } else if (e instanceof IContainerSuspendedDMEvent) { - // Container suspended. Do nothing here to give the stack the - // priority in updating. The container and threads will update as - // a result of FullStackRefreshEvent. + // Container suspended. Do nothing here to give the stack the + // priority in updating. The container and threads will update as + // a result of FullStackRefreshEvent. } else if (e instanceof SteppingTimedOutEvent) { - // Stepping time-out indicates that a step operation is taking - // a long time, and the view needs to be refreshed to show - // the user that the program is running. - // If the step was issued for the whole container refresh - // the whole container. - if (dmc instanceof IContainerDMContext) { - parentDelta.addNode(createVMContext(dmc), IModelDelta.CONTENT); - } + // Stepping time-out indicates that a step operation is taking + // a long time, and the view needs to be refreshed to show + // the user that the program is running. + // If the step was issued for the whole container refresh + // the whole container. + if (dmc instanceof IContainerDMContext) { + parentDelta.addNode(createVMContext(dmc), IModelDelta.CONTENT); + } } else if (e instanceof IExitedDMEvent) { - // An exited event could either be for a thread within a container - // or for the container itself. - // If a container exited, refresh the parent element so that the - // container may be removed. - // If a thread exited within a container, refresh that container. + // An exited event could either be for a thread within a container + // or for the container itself. + // If a container exited, refresh the parent element so that the + // container may be removed. + // If a thread exited within a container, refresh that container. if (dmc instanceof IContainerDMContext) { - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } else { - IContainerDMContext containerCtx = DMContexts.getAncestorOfType(dmc, IContainerDMContext.class); - if (containerCtx != null) { - parentDelta.addNode(createVMContext(containerCtx), IModelDelta.CONTENT); - } - } - } else if (e instanceof IStartedDMEvent) { - // A started event could either be for a thread within a container - // or for the container itself. - // If a container started, issue an expand and select event to - // show the threads in the new container. - // Note: the EXPAND flag implies refreshing the parent element. + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } else { + IContainerDMContext containerCtx = DMContexts.getAncestorOfType(dmc, IContainerDMContext.class); + if (containerCtx != null) { + parentDelta.addNode(createVMContext(containerCtx), IModelDelta.CONTENT); + } + } + } else if (e instanceof IStartedDMEvent) { + // A started event could either be for a thread within a container + // or for the container itself. + // If a container started, issue an expand and select event to + // show the threads in the new container. + // Note: the EXPAND flag implies refreshing the parent element. if (dmc instanceof IContainerDMContext) { - parentDelta.addNode(createVMContext(dmc), IModelDelta.EXPAND | IModelDelta.SELECT); + parentDelta.addNode(createVMContext(dmc), IModelDelta.EXPAND | IModelDelta.SELECT); } else { IContainerDMContext containerCtx = DMContexts.getAncestorOfType(dmc, IContainerDMContext.class); if (containerCtx != null) { parentDelta.addNode(createVMContext(containerCtx), IModelDelta.CONTENT); } } - } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { - // Model Proxy install event is generated when the model is first - // populated into the view. This happens when a new debug session - // is started or when the view is first opened. - // In both cases, if there are already thread containers in the debug model, - // the desired user behavior is to show the containers and to select - // the first thread. - // If the container is suspended, do not select it, instead, - // one of its threads will be selected. - getContainerVMCForModelProxyInstallEvent( - parentDelta, - new DataRequestMonitor<VMContextInfo>(getExecutor(), requestMonitor) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - parentDelta.addNode( - getData().fVMContext, nodeOffset + getData().fIndex, - IModelDelta.EXPAND | (getData().fIsSuspended ? 0 : IModelDelta.SELECT)); - } - requestMonitor.done(); - } - }); - return; - } else if (e instanceof StateChangedEvent) { - // If there is a state change needed on the container, update the container - if (dmc instanceof IContainerDMContext) - parentDelta.addNode(createVMContext(dmc), IModelDelta.STATE); - } else if (e instanceof FullStackRefreshEvent) { - FullStackRefreshEvent refreshEvent = (FullStackRefreshEvent)e; - if (refreshEvent.getTriggeringEvent() instanceof IContainerSuspendedDMEvent) { - // For a full container suspended event, issue a single change when we get - // a FullStackRefreshEvent. This avoids refreshing all threads, even those - // that are not visible - // bug 386175 - IContainerSuspendedDMEvent containerTriggerEvent = - (IContainerSuspendedDMEvent)refreshEvent.getTriggeringEvent(); - buildDeltaForFullStackRefreshEvent((IContainerDMContext)refreshEvent.getDMContext(), - containerTriggerEvent.getTriggeringContexts(), parentDelta, nodeOffset, requestMonitor); - return; - } - } else if (e instanceof IResumedDMEvent) { - // update the container node label - IContainerDMContext containerCtx = DMContexts.getAncestorOfType(dmc, IContainerDMContext.class); - parentDelta.addNode(createVMContext(containerCtx), IModelDelta.STATE); - } - + } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { + // Model Proxy install event is generated when the model is first + // populated into the view. This happens when a new debug session + // is started or when the view is first opened. + // In both cases, if there are already thread containers in the debug model, + // the desired user behavior is to show the containers and to select + // the first thread. + // If the container is suspended, do not select it, instead, + // one of its threads will be selected. + getContainerVMCForModelProxyInstallEvent(parentDelta, + new DataRequestMonitor<VMContextInfo>(getExecutor(), requestMonitor) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + parentDelta.addNode(getData().fVMContext, nodeOffset + getData().fIndex, + IModelDelta.EXPAND | (getData().fIsSuspended ? 0 : IModelDelta.SELECT)); + } + requestMonitor.done(); + } + }); + return; + } else if (e instanceof StateChangedEvent) { + // If there is a state change needed on the container, update the container + if (dmc instanceof IContainerDMContext) + parentDelta.addNode(createVMContext(dmc), IModelDelta.STATE); + } else if (e instanceof FullStackRefreshEvent) { + FullStackRefreshEvent refreshEvent = (FullStackRefreshEvent) e; + if (refreshEvent.getTriggeringEvent() instanceof IContainerSuspendedDMEvent) { + // For a full container suspended event, issue a single change when we get + // a FullStackRefreshEvent. This avoids refreshing all threads, even those + // that are not visible + // bug 386175 + IContainerSuspendedDMEvent containerTriggerEvent = (IContainerSuspendedDMEvent) refreshEvent + .getTriggeringEvent(); + buildDeltaForFullStackRefreshEvent((IContainerDMContext) refreshEvent.getDMContext(), + containerTriggerEvent.getTriggeringContexts(), parentDelta, nodeOffset, requestMonitor); + return; + } + } else if (e instanceof IResumedDMEvent) { + // update the container node label + IContainerDMContext containerCtx = DMContexts.getAncestorOfType(dmc, IContainerDMContext.class); + parentDelta.addNode(createVMContext(containerCtx), IModelDelta.STATE); + } + requestMonitor.done(); - } - - /** - * Builds a delta in response to automatic refresh event generated after - * every suspend event. - * <p> - * As opposed to the StackFrameVMNode handling of the refresh event, the - * container handles only the refresh events for container suspended events, - * and it refreshes the entire container. - * <p> - * The default behavior is to check if the thread is still stepping or - * suspended and refresh the stack trace. - */ - protected void buildDeltaForFullStackRefreshEvent(final IContainerDMContext containerCtx, - final IExecutionDMContext[] triggeringCtxs, final VMDelta parentDelta, final int nodeOffset, - final RequestMonitor rm) - { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - IRunControl runControlService = getServicesTracker().getService(IRunControl.class); - if (runControlService == null) { - // Required services have not initialized yet. Ignore the event. - rm.done(); - return; - } - - // Refresh the whole list of stack frames unless the target is already stepping the next command. In - // which case, the refresh will occur when the stepping sequence slows down or stops. Trying to - // refresh the whole stack trace with every step would slow down stepping too much. - boolean isStepping = false; - for (IExecutionDMContext triggeringCtx : triggeringCtxs) { - if (runControlService.isStepping(triggeringCtx)) { - isStepping = true; - break; - } - } - if (!isStepping) { - parentDelta.addNode(createVMContext(containerCtx), IModelDelta.CONTENT); - } - - rm.done(); - } - }); - } catch (RejectedExecutionException e) { - // Session shut down, no delta to build. - rm.done(); - } - } + } + + /** + * Builds a delta in response to automatic refresh event generated after + * every suspend event. + * <p> + * As opposed to the StackFrameVMNode handling of the refresh event, the + * container handles only the refresh events for container suspended events, + * and it refreshes the entire container. + * <p> + * The default behavior is to check if the thread is still stepping or + * suspended and refresh the stack trace. + */ + protected void buildDeltaForFullStackRefreshEvent(final IContainerDMContext containerCtx, + final IExecutionDMContext[] triggeringCtxs, final VMDelta parentDelta, final int nodeOffset, + final RequestMonitor rm) { + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + IRunControl runControlService = getServicesTracker().getService(IRunControl.class); + if (runControlService == null) { + // Required services have not initialized yet. Ignore the event. + rm.done(); + return; + } + + // Refresh the whole list of stack frames unless the target is already stepping the next command. In + // which case, the refresh will occur when the stepping sequence slows down or stops. Trying to + // refresh the whole stack trace with every step would slow down stepping too much. + boolean isStepping = false; + for (IExecutionDMContext triggeringCtx : triggeringCtxs) { + if (runControlService.isStepping(triggeringCtx)) { + isStepping = true; + break; + } + } + if (!isStepping) { + parentDelta.addNode(createVMContext(containerCtx), IModelDelta.CONTENT); + } + rm.done(); + } + }); + } catch (RejectedExecutionException e) { + // Session shut down, no delta to build. + rm.done(); + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractExecutionContextVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractExecutionContextVMNode.java index 344d92ccfd0..3a048326042 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractExecutionContextVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractExecutionContextVMNode.java @@ -39,46 +39,44 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDelta; /** * This class is a base class of AbstractThreadVMNode and AbstractContainerVMNode. * It contains common functionality between these classes. - * - * The main reason this class is introduced is to allow the debug view to - * show multiple levels of execution containers and properly handle the delta generation. - * - * In the longer term we would like to merge the classes AbstractContainerVMNode and - * AbstractThreadVMNode. That will make the implementation of both classes + * + * The main reason this class is introduced is to allow the debug view to + * show multiple levels of execution containers and properly handle the delta generation. + * + * In the longer term we would like to merge the classes AbstractContainerVMNode and + * AbstractThreadVMNode. That will make the implementation of both classes * more generic and robust in the case of recursive containers. - * - * Having this class as a base for both AbstractContainerVMNode and + * + * Having this class as a base for both AbstractContainerVMNode and * AbstractThreadVMNode enables us to merge them in the future. - * - * Originally DefaultVMModelProxyStrategy didn't accept recursive containers for + * + * Originally DefaultVMModelProxyStrategy didn't accept recursive containers for * generating deltas, even though they are accepted and supported by - * AbstractDMVMProvider for viewing. - * The approach I took to support recursive containers for delta generation is to have - * the VMNodes generate their deltas level by level, instead of one whole delta at once. - * That required changes in identifying which is the correct context for each of the events. + * AbstractDMVMProvider for viewing. + * The approach I took to support recursive containers for delta generation is to have + * the VMNodes generate their deltas level by level, instead of one whole delta at once. + * That required changes in identifying which is the correct context for each of the events. * * See: https://bugs.eclipse.org/bugs/show_bug.cgi?id=240208 - * + * * @since 2.2 * @experimental */ -public abstract class AbstractExecutionContextVMNode extends AbstractDMVMNode -{ +public abstract class AbstractExecutionContextVMNode extends AbstractDMVMNode { /** - * List that keeps track of which events are considered leaf events for - * delta creation. + * List that keeps track of which events are considered leaf events for + * delta creation. */ - protected ArrayList<Class<?>> leafEventTypes = new ArrayList<>(); - + protected ArrayList<Class<?>> leafEventTypes = new ArrayList<>(); + /** - * List that keeps track of which events are considered container events for - * delta creation. + * List that keeps track of which events are considered container events for + * delta creation. */ - protected ArrayList<Class<?>> containerEventTypes = new ArrayList<>(); - + protected ArrayList<Class<?>> containerEventTypes = new ArrayList<>(); - public AbstractExecutionContextVMNode(AbstractDMVMProvider provider, - DsfSession session, Class<? extends IDMContext> dmcClassType) { + public AbstractExecutionContextVMNode(AbstractDMVMProvider provider, DsfSession session, + Class<? extends IDMContext> dmcClassType) { super(provider, session, dmcClassType); } @@ -87,39 +85,39 @@ public abstract class AbstractExecutionContextVMNode extends AbstractDMVMNode */ protected void addCommonEventTypes() { - // non container events. - addEventType(ISuspendedDMEvent.class,false); - addEventType(IResumedDMEvent.class, false); - addEventType(FullStackRefreshEvent.class, false); - addEventType(SteppingTimedOutEvent.class, false); - addEventType(ExpandStackEvent.class, false); - - // container events. - addEventType(IContainerSuspendedDMEvent.class,true); - addEventType(IContainerResumedDMEvent.class, true); + // non container events. + addEventType(ISuspendedDMEvent.class, false); + addEventType(IResumedDMEvent.class, false); + addEventType(FullStackRefreshEvent.class, false); + addEventType(SteppingTimedOutEvent.class, false); + addEventType(ExpandStackEvent.class, false); + + // container events. + addEventType(IContainerSuspendedDMEvent.class, true); + addEventType(IContainerResumedDMEvent.class, true); } /** * When DSF debuggers define custom events for which the container and thread - * nodes need to be updated, they need to register these events using this - * function, so the proper recursive deltas are created. - * + * nodes need to be updated, they need to register these events using this + * function, so the proper recursive deltas are created. + * * @param eventClass The event class to keep track of * @param containerEvent Is the event a container event or now */ protected void addEventType(Class<? extends IDMEvent<?>> eventClass, boolean containerEvent) { - if (containerEvent) { + if (containerEvent) { containerEventTypes.add(eventClass); - } else { + } else { leafEventTypes.add(eventClass); } } /** - * If DSF debuggers override the behavior of AbstractThreadVMNode + * If DSF debuggers override the behavior of AbstractThreadVMNode * or AbstractContainerVMNode, some events may no longer be needed - * and the derived VMNode can call this method to remove such events. - * + * and the derived VMNode can call this method to remove such events. + * * @param eventClass The event class to remove * @param containerEvent Is the event a container event or now */ @@ -130,117 +128,116 @@ public abstract class AbstractExecutionContextVMNode extends AbstractDMVMNode leafEventTypes.remove(eventClass); } } - - + /** * When we support recursive containers we want to make sure the immediate parent is returned only. * - * @return true if the context is set by the method. + * @return true if the context is set by the method. */ - protected boolean getContextsForRecursiveVMNode(VMDelta parentDelta, Object e, DataRequestMonitor<IVMContext[]> rm) { - - IExecutionDMContext leafContext = null; - if (isExecutionContainerEvent(e)) { - leafContext = getLeafContextForContainerEvent(e); - } - else if (isExecutionLeafEvent(e)) { - leafContext = getLeafContextForLeafEvent(e); - } + protected boolean getContextsForRecursiveVMNode(VMDelta parentDelta, Object e, + DataRequestMonitor<IVMContext[]> rm) { + + IExecutionDMContext leafContext = null; + if (isExecutionContainerEvent(e)) { + leafContext = getLeafContextForContainerEvent(e); + } else if (isExecutionLeafEvent(e)) { + leafContext = getLeafContextForLeafEvent(e); + } if (leafContext != null) { setImmediateParentAsContexts(leafContext, parentDelta, rm); return true; - } + } return false; - } - - /** - * Make sure we build the delta for the recursive containers one level at a time. - * - * @param e - the event - * @return true if the delta is built by this method. - */ - protected boolean buildDeltaForRecursiveVMNode(Object e, final VMDelta parentDelta, int nodeOffset, RequestMonitor rm) { + } + + /** + * Make sure we build the delta for the recursive containers one level at a time. + * + * @param e - the event + * @return true if the delta is built by this method. + */ + protected boolean buildDeltaForRecursiveVMNode(Object e, final VMDelta parentDelta, int nodeOffset, + RequestMonitor rm) { - IExecutionDMContext leafContext = null; - if (isExecutionContainerEvent(e)) { - leafContext = getLeafContextForContainerEvent(e); - } - else if (isExecutionLeafEvent(e)) { - leafContext = getLeafContextForLeafEvent(e); - } + IExecutionDMContext leafContext = null; + if (isExecutionContainerEvent(e)) { + leafContext = getLeafContextForContainerEvent(e); + } else if (isExecutionLeafEvent(e)) { + leafContext = getLeafContextForLeafEvent(e); + } if (leafContext != null) { addOneLevelToDelta(leafContext, parentDelta, rm); return true; - } + } return false; } - - /** - * When the deltas are generated one level at a time we need to distinguish - * between container and regular events to return the proper context for the event. - */ + + /** + * When the deltas are generated one level at a time we need to distinguish + * between container and regular events to return the proper context for the event. + */ protected IExecutionDMContext getLeafContextForContainerEvent(Object event) { - - IExecutionDMContext leafEC = null; - IExecutionDMContext[] triggeringContext = null; - if (isExecutionContainerEvent(event)) { + IExecutionDMContext leafEC = null; + IExecutionDMContext[] triggeringContext = null; + + if (isExecutionContainerEvent(event)) { if (event instanceof IContainerSuspendedDMEvent) { - IContainerSuspendedDMEvent typedEvent = (IContainerSuspendedDMEvent)event; + IContainerSuspendedDMEvent typedEvent = (IContainerSuspendedDMEvent) event; triggeringContext = typedEvent.getTriggeringContexts(); } if (event instanceof IContainerResumedDMEvent) { - IContainerResumedDMEvent typedEvent = (IContainerResumedDMEvent)event; + IContainerResumedDMEvent typedEvent = (IContainerResumedDMEvent) event; triggeringContext = typedEvent.getTriggeringContexts(); } - } - - if (triggeringContext != null && triggeringContext.length > 0){ + } + + if (triggeringContext != null && triggeringContext.length > 0) { leafEC = triggeringContext[0]; } - + return leafEC; - } + } - /** - * When the deltas are generated one level at a time we need to distinguish - * between container and regular events to return the proper context for the event. - */ + /** + * When the deltas are generated one level at a time we need to distinguish + * between container and regular events to return the proper context for the event. + */ protected IExecutionDMContext getLeafContextForLeafEvent(Object event) { - - IExecutionDMContext leafEC = null; - - if (event instanceof IDMEvent<?>) { - if (isExecutionLeafEvent(event)) { - IDMEvent<?> typedEvent = (IDMEvent<?>)event; - IDMContext dmContext = typedEvent.getDMContext(); - if (dmContext instanceof IExecutionDMContext) { - leafEC = (IExecutionDMContext)dmContext; - } - } - } - + + IExecutionDMContext leafEC = null; + + if (event instanceof IDMEvent<?>) { + if (isExecutionLeafEvent(event)) { + IDMEvent<?> typedEvent = (IDMEvent<?>) event; + IDMContext dmContext = typedEvent.getDMContext(); + if (dmContext instanceof IExecutionDMContext) { + leafEC = (IExecutionDMContext) dmContext; + } + } + } + return leafEC; - } - + } + /** - * Considers the parent delta when we construct the next level. + * Considers the parent delta when we construct the next level. */ - protected void addOneLevelToDelta(IExecutionDMContext leafContext, VMDelta parentDelta, RequestMonitor requestMonitor) { - assert leafContext != null; + protected void addOneLevelToDelta(IExecutionDMContext leafContext, VMDelta parentDelta, + RequestMonitor requestMonitor) { + assert leafContext != null; if (parentDelta.getElement() instanceof ILaunch) { - IContainerDMContext topContainer = - DMContexts.getTopMostAncestorOfType(leafContext, IContainerDMContext.class); - + IContainerDMContext topContainer = DMContexts.getTopMostAncestorOfType(leafContext, + IContainerDMContext.class); + // It is possible for a thread node to be an immediate child of a launch node - // with no container node in between. + // with no container node in between. if (topContainer != null) { parentDelta.addNode(createVMContext(topContainer), 0, IModelDelta.NO_CHANGE); } - } - else if (parentDelta.getElement() instanceof IDMVMContext) { - IDMVMContext vmContext = (IDMVMContext)parentDelta.getElement(); - IDMContext dmContext = vmContext.getDMContext(); + } else if (parentDelta.getElement() instanceof IDMVMContext) { + IDMVMContext vmContext = (IDMVMContext) parentDelta.getElement(); + IDMContext dmContext = vmContext.getDMContext(); IExecutionDMContext current = DMContexts.getParentOfType(leafContext, IContainerDMContext.class); while (current != null) { IContainerDMContext parent = DMContexts.getParentOfType(current, IContainerDMContext.class); @@ -252,36 +249,34 @@ public abstract class AbstractExecutionContextVMNode extends AbstractDMVMNode } } requestMonitor.done(); - } + } - /** - * Based on the event (container or not), set the proper context that is the immediate - * parent one level at a time. - */ - protected void setImmediateParentAsContexts(IExecutionDMContext leafContext, - VMDelta parentDelta, DataRequestMonitor<IVMContext[]> rm){ + /** + * Based on the event (container or not), set the proper context that is the immediate + * parent one level at a time. + */ + protected void setImmediateParentAsContexts(IExecutionDMContext leafContext, VMDelta parentDelta, + DataRequestMonitor<IVMContext[]> rm) { - assert leafContext != null; - IVMContext[] all = null; + assert leafContext != null; + IVMContext[] all = null; if (parentDelta.getElement() instanceof ILaunch) { - IContainerDMContext topContainer = - DMContexts.getTopMostAncestorOfType(leafContext, IContainerDMContext.class); + IContainerDMContext topContainer = DMContexts.getTopMostAncestorOfType(leafContext, + IContainerDMContext.class); if (topContainer != null) { all = new IVMContext[] { createVMContext(topContainer) }; - } - else { + } else { // the thread is directly a child node of the launch node (no container in the middle). all = new IVMContext[] { createVMContext(leafContext) }; } - } - else if (parentDelta.getElement() instanceof IDMVMContext) { - IDMVMContext vmContext = (IDMVMContext)parentDelta.getElement(); - IDMContext dmContext = vmContext.getDMContext(); + } else if (parentDelta.getElement() instanceof IDMVMContext) { + IDMVMContext vmContext = (IDMVMContext) parentDelta.getElement(); + IDMContext dmContext = vmContext.getDMContext(); IExecutionDMContext current = leafContext; while (current != null) { IContainerDMContext parent = DMContexts.getParentOfType(current, IContainerDMContext.class); if (dmContext.equals(parent)) { - all = new IVMContext[] { createVMContext(current)}; + all = new IVMContext[] { createVMContext(current) }; break; } current = parent; @@ -293,31 +288,31 @@ public abstract class AbstractExecutionContextVMNode extends AbstractDMVMNode rm.setData(all); rm.done(); } - - /** - * Returns whether the event should be considered a container event or not. - */ - protected boolean isExecutionContainerEvent(Object event) { - if (event != null) { - for (Class<?> clazz : containerEventTypes) - if (clazz.isAssignableFrom(event.getClass())) { - return true; - } - } - return false; + + /** + * Returns whether the event should be considered a container event or not. + */ + protected boolean isExecutionContainerEvent(Object event) { + if (event != null) { + for (Class<?> clazz : containerEventTypes) + if (clazz.isAssignableFrom(event.getClass())) { + return true; + } + } + return false; } - /** - * Returns whether the event should be use to generate deltas for each of the levels. - */ - protected boolean isExecutionLeafEvent(Object event) { - if (event != null) { - for (Class<?> clazz : leafEventTypes) { - if (clazz.isAssignableFrom(event.getClass())) { - return true; - } - } - } - return false; + /** + * Returns whether the event should be use to generate deltas for each of the levels. + */ + protected boolean isExecutionLeafEvent(Object event) { + if (event != null) { + for (Class<?> clazz : leafEventTypes) { + if (clazz.isAssignableFrom(event.getClass())) { + return true; + } + } + } + return false; } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractLaunchVMProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractLaunchVMProvider.java index 6a445ca46df..215496a40f5 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractLaunchVMProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractLaunchVMProvider.java @@ -7,10 +7,10 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation - * Ericsson - Modified for new functionality + * Ericsson - Modified for new functionality *******************************************************************************/ package org.eclipse.cdt.dsf.debug.ui.viewmodel.launch; @@ -58,267 +58,274 @@ import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; - /** * @since 1.1 */ -public class AbstractLaunchVMProvider extends AbstractDMVMProvider - implements IDebugEventSetListener, ILaunchesListener2 -{ - /** +public class AbstractLaunchVMProvider extends AbstractDMVMProvider + implements IDebugEventSetListener, ILaunchesListener2 { + /** * Delay (in milliseconds) before a full stack trace will be requested. */ - private static final int FRAME_UPDATE_DELAY= 200; - - private final Map<IExecutionDMContext,ScheduledFuture<?>> fRefreshStackFramesFutures = new HashMap<IExecutionDMContext,ScheduledFuture<?>>(); + private static final int FRAME_UPDATE_DELAY = 200; + + private final Map<IExecutionDMContext, ScheduledFuture<?>> fRefreshStackFramesFutures = new HashMap<IExecutionDMContext, ScheduledFuture<?>>(); private IPropertyChangeListener fPreferencesListener; @ThreadSafe - public AbstractLaunchVMProvider(AbstractVMAdapter adapter, IPresentationContext presentationContext, DsfSession session) - { - super(adapter, presentationContext, session); - - final IPreferenceStore store= DsfUIPlugin.getDefault().getPreferenceStore(); - if (store.getBoolean(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT_ENABLE)) { - getPresentationContext().setProperty(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT, store.getInt(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT)); - } - - fPreferencesListener = new IPropertyChangeListener() { + public AbstractLaunchVMProvider(AbstractVMAdapter adapter, IPresentationContext presentationContext, + DsfSession session) { + super(adapter, presentationContext, session); + + final IPreferenceStore store = DsfUIPlugin.getDefault().getPreferenceStore(); + if (store.getBoolean(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT_ENABLE)) { + getPresentationContext().setProperty(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT, + store.getInt(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT)); + } + + fPreferencesListener = new IPropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent event) { handlePropertyChanged(store, event); - }}; - store.addPropertyChangeListener(fPreferencesListener); + } + }; + store.addPropertyChangeListener(fPreferencesListener); - final IPreferenceStore cStore= CDebugUIPlugin.getDefault().getPreferenceStore(); - getPresentationContext().setProperty(IDsfDebugUIConstants.DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY, cStore.getBoolean(IDsfDebugUIConstants.DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY)); + final IPreferenceStore cStore = CDebugUIPlugin.getDefault().getPreferenceStore(); + getPresentationContext().setProperty(IDsfDebugUIConstants.DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY, + cStore.getBoolean(IDsfDebugUIConstants.DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY)); cStore.addPropertyChangeListener(fPreferencesListener); - - // Register the LaunchVM provider as a listener to debug and launch - // events. These events are used by the launch and processes nodes. - DebugPlugin.getDefault().addDebugEventListener(this); - DebugPlugin.getDefault().getLaunchManager().addLaunchListener(this); - } - - @Override + + // Register the LaunchVM provider as a listener to debug and launch + // events. These events are used by the launch and processes nodes. + DebugPlugin.getDefault().addDebugEventListener(this); + DebugPlugin.getDefault().getLaunchManager().addLaunchListener(this); + } + + @Override protected IVMUpdatePolicy[] createUpdateModes() { - return new IVMUpdatePolicy[] { - new DelayedStackRefreshUpdatePolicy(new AutomaticUpdatePolicy()), - new DelayedStackRefreshUpdatePolicy(new ManualUpdatePolicy()) - }; - } - - @Override + return new IVMUpdatePolicy[] { new DelayedStackRefreshUpdatePolicy(new AutomaticUpdatePolicy()), + new DelayedStackRefreshUpdatePolicy(new ManualUpdatePolicy()) }; + } + + @Override public void handleDebugEvents(final DebugEvent[] events) { - if (isDisposed()) return; - + if (isDisposed()) + return; + // We're in session's executor thread. Re-dispatch to our executor thread // and then call root layout node. - try { - getExecutor().execute(new Runnable() { - @Override + try { + getExecutor().execute(new Runnable() { + @Override public void run() { - if (isDisposed()) return; - - for (final DebugEvent event : events) { - handleEvent(event); - } - }}); - } catch (RejectedExecutionException e) { - // Ignore. This exception could be thrown if the provider is being - // shut down. - } - } - - @Override - public void handleEvent(Object event, final RequestMonitor rm) { - if (event instanceof DoubleClickEvent && !isDisposed()) { - final ISelection selection= ((DoubleClickEvent) event).getSelection(); - if (selection instanceof IStructuredSelection) { - Object element= ((IStructuredSelection) selection).getFirstElement(); - if (element instanceof IncompleteStackVMContext) { - IncompleteStackVMContext incStackVmc = ((IncompleteStackVMContext) element); - IVMNode node = incStackVmc.getVMNode(); - if (node instanceof StackFramesVMNode && node.getVMProvider() == this) { - IExecutionDMContext exeCtx= incStackVmc.getExecutionDMContext(); + if (isDisposed()) + return; + + for (final DebugEvent event : events) { + handleEvent(event); + } + } + }); + } catch (RejectedExecutionException e) { + // Ignore. This exception could be thrown if the provider is being + // shut down. + } + } + + @Override + public void handleEvent(Object event, final RequestMonitor rm) { + if (event instanceof DoubleClickEvent && !isDisposed()) { + final ISelection selection = ((DoubleClickEvent) event).getSelection(); + if (selection instanceof IStructuredSelection) { + Object element = ((IStructuredSelection) selection).getFirstElement(); + if (element instanceof IncompleteStackVMContext) { + IncompleteStackVMContext incStackVmc = ((IncompleteStackVMContext) element); + IVMNode node = incStackVmc.getVMNode(); + if (node instanceof StackFramesVMNode && node.getVMProvider() == this) { + IExecutionDMContext exeCtx = incStackVmc.getExecutionDMContext(); ((StackFramesVMNode) node).incrementStackFrameLimit(exeCtx); // replace double click event with expand stack event final ExpandStackEvent expandStackEvent = new ExpandStackEvent(exeCtx); getExecutor().execute(new DsfRunnable() { - @Override + @Override public void run() { - handleEvent(expandStackEvent, null); - } + handleEvent(expandStackEvent, null); + } }); - } - if (rm != null) { - rm.done(); - } - return; - } - } - } else if (event instanceof IRunControl.ISuspendedDMEvent) { - final IRunControl.ISuspendedDMEvent suspendEvent = (IRunControl.ISuspendedDMEvent)event; - final IExecutionDMContext exeContext= suspendEvent.getDMContext(); - ScheduledFuture<?> refreshStackFramesFuture = getRefreshFuture(exeContext); - // trigger delayed full stack frame update - if (refreshStackFramesFuture != null) { - // cancel previously scheduled frame update - refreshStackFramesFuture.cancel(false); - } - - try { - refreshStackFramesFuture = getSession().getExecutor().schedule( - new DsfRunnable() { - @Override - public void run() { - if (getSession().isActive()) { - getExecutor().execute(new Runnable() { - @Override - public void run() { - // trigger full stack frame update - ScheduledFuture<?> future= fRefreshStackFramesFutures.get(exeContext); - if (future != null && !isDisposed()) { - fRefreshStackFramesFutures.remove(exeContext); - handleEvent(new FullStackRefreshEvent(exeContext, suspendEvent), null); - } - }}); - } - } - }, - FRAME_UPDATE_DELAY, TimeUnit.MILLISECONDS); - fRefreshStackFramesFutures.put(exeContext, refreshStackFramesFuture); - } catch (RejectedExecutionException e) {} - } else if (event instanceof IRunControl.IResumedDMEvent) { - IExecutionDMContext exeContext= ((IRunControl.IResumedDMEvent) event).getDMContext(); - ScheduledFuture<?> refreshStackFramesFuture= fRefreshStackFramesFutures.get(exeContext); - if (refreshStackFramesFuture != null) { - // cancel previously scheduled frame update - refreshStackFramesFuture.cancel(false); - fRefreshStackFramesFutures.remove(exeContext); - } - } - - super.handleEvent(event, rm); - } - - /** - * Returns the future for the given execution context or for any child of the - * given execution context. - */ - private ScheduledFuture<?> getRefreshFuture(IExecutionDMContext execCtx) { - for (IExecutionDMContext refreshCtx : fRefreshStackFramesFutures.keySet()) { - if (refreshCtx.equals(execCtx) || DMContexts.isAncestorOf(refreshCtx, execCtx)) { - return fRefreshStackFramesFutures.remove(refreshCtx); - } - } - return null; - } - - @Override - public void dispose() { - DebugPlugin.getDefault().removeDebugEventListener(this); - DebugPlugin.getDefault().getLaunchManager().removeLaunchListener(this); - - final IPreferenceStore store= DsfUIPlugin.getDefault().getPreferenceStore(); - store.removePropertyChangeListener(fPreferencesListener); - - final IPreferenceStore cStore= CDebugUIPlugin.getDefault().getPreferenceStore(); - cStore.removePropertyChangeListener(fPreferencesListener); - - super.dispose(); - } - - @Override + } + if (rm != null) { + rm.done(); + } + return; + } + } + } else if (event instanceof IRunControl.ISuspendedDMEvent) { + final IRunControl.ISuspendedDMEvent suspendEvent = (IRunControl.ISuspendedDMEvent) event; + final IExecutionDMContext exeContext = suspendEvent.getDMContext(); + ScheduledFuture<?> refreshStackFramesFuture = getRefreshFuture(exeContext); + // trigger delayed full stack frame update + if (refreshStackFramesFuture != null) { + // cancel previously scheduled frame update + refreshStackFramesFuture.cancel(false); + } + + try { + refreshStackFramesFuture = getSession().getExecutor().schedule(new DsfRunnable() { + @Override + public void run() { + if (getSession().isActive()) { + getExecutor().execute(new Runnable() { + @Override + public void run() { + // trigger full stack frame update + ScheduledFuture<?> future = fRefreshStackFramesFutures.get(exeContext); + if (future != null && !isDisposed()) { + fRefreshStackFramesFutures.remove(exeContext); + handleEvent(new FullStackRefreshEvent(exeContext, suspendEvent), null); + } + } + }); + } + } + }, FRAME_UPDATE_DELAY, TimeUnit.MILLISECONDS); + fRefreshStackFramesFutures.put(exeContext, refreshStackFramesFuture); + } catch (RejectedExecutionException e) { + } + } else if (event instanceof IRunControl.IResumedDMEvent) { + IExecutionDMContext exeContext = ((IRunControl.IResumedDMEvent) event).getDMContext(); + ScheduledFuture<?> refreshStackFramesFuture = fRefreshStackFramesFutures.get(exeContext); + if (refreshStackFramesFuture != null) { + // cancel previously scheduled frame update + refreshStackFramesFuture.cancel(false); + fRefreshStackFramesFutures.remove(exeContext); + } + } + + super.handleEvent(event, rm); + } + + /** + * Returns the future for the given execution context or for any child of the + * given execution context. + */ + private ScheduledFuture<?> getRefreshFuture(IExecutionDMContext execCtx) { + for (IExecutionDMContext refreshCtx : fRefreshStackFramesFutures.keySet()) { + if (refreshCtx.equals(execCtx) || DMContexts.isAncestorOf(refreshCtx, execCtx)) { + return fRefreshStackFramesFutures.remove(refreshCtx); + } + } + return null; + } + + @Override + public void dispose() { + DebugPlugin.getDefault().removeDebugEventListener(this); + DebugPlugin.getDefault().getLaunchManager().removeLaunchListener(this); + + final IPreferenceStore store = DsfUIPlugin.getDefault().getPreferenceStore(); + store.removePropertyChangeListener(fPreferencesListener); + + final IPreferenceStore cStore = CDebugUIPlugin.getDefault().getPreferenceStore(); + cStore.removePropertyChangeListener(fPreferencesListener); + + super.dispose(); + } + + @Override public void launchesAdded(ILaunch[] launches) { - handleLaunchesEvent(new LaunchesEvent(launches, LaunchesEvent.Type.ADDED)); - } - - @Override + handleLaunchesEvent(new LaunchesEvent(launches, LaunchesEvent.Type.ADDED)); + } + + @Override public void launchesRemoved(ILaunch[] launches) { - handleLaunchesEvent(new LaunchesEvent(launches, LaunchesEvent.Type.REMOVED)); - } - - @Override + handleLaunchesEvent(new LaunchesEvent(launches, LaunchesEvent.Type.REMOVED)); + } + + @Override public void launchesChanged(ILaunch[] launches) { - handleLaunchesEvent(new LaunchesEvent(launches, LaunchesEvent.Type.CHANGED)); - } - - @Override + handleLaunchesEvent(new LaunchesEvent(launches, LaunchesEvent.Type.CHANGED)); + } + + @Override public void launchesTerminated(ILaunch[] launches) { - handleLaunchesEvent(new LaunchesEvent(launches, LaunchesEvent.Type.TERMINATED)); - } - - private void handleLaunchesEvent(final LaunchesEvent event) { - if (isDisposed()) return; - + handleLaunchesEvent(new LaunchesEvent(launches, LaunchesEvent.Type.TERMINATED)); + } + + private void handleLaunchesEvent(final LaunchesEvent event) { + if (isDisposed()) + return; + // We're in session's executor thread. Re-dispach to our executor thread // and then call root layout node. - try { - getExecutor().execute(new Runnable() { - @Override + try { + getExecutor().execute(new Runnable() { + @Override public void run() { - if (isDisposed()) return; - - IRootVMNode rootLayoutNode = getRootVMNode(); - if (rootLayoutNode != null && rootLayoutNode.getDeltaFlags(event) != IModelDelta.NO_CHANGE) { - handleEvent(event); - } - }}); - } catch (RejectedExecutionException e) { - // Ignore. This exception could be thrown if the provider is being - // shut down. - } - } - - @Override - protected boolean canSkipHandlingEvent(Object newEvent, Object eventToSkip) { - // To optimize view performance when stepping rapidly, skip events that came - // before the last suspended events. However, the debug view can get suspended - // events for different threads, so make sure to skip only the events if they - // were in the same hierarchy as the last suspended event. - // Note: Avoid skipping thread started/exited events which require a larger - // scope refresh than some suspended events. - if (newEvent instanceof IStartedDMEvent || newEvent instanceof IExitedDMEvent) { - return false; - } - - if (newEvent instanceof ISuspendedDMEvent && eventToSkip instanceof IDMEvent<?>) { - IDMContext newEventDmc = ((IDMEvent<?>)newEvent).getDMContext(); - IDMContext eventToSkipDmc = ((IDMEvent<?>)eventToSkip).getDMContext(); - - if (newEventDmc.equals(eventToSkipDmc) || DMContexts.isAncestorOf(eventToSkipDmc, newEventDmc)) { - return true; - } - } - - return false; - } + if (isDisposed()) + return; + + IRootVMNode rootLayoutNode = getRootVMNode(); + if (rootLayoutNode != null && rootLayoutNode.getDeltaFlags(event) != IModelDelta.NO_CHANGE) { + handleEvent(event); + } + } + }); + } catch (RejectedExecutionException e) { + // Ignore. This exception could be thrown if the provider is being + // shut down. + } + } + + @Override + protected boolean canSkipHandlingEvent(Object newEvent, Object eventToSkip) { + // To optimize view performance when stepping rapidly, skip events that came + // before the last suspended events. However, the debug view can get suspended + // events for different threads, so make sure to skip only the events if they + // were in the same hierarchy as the last suspended event. + // Note: Avoid skipping thread started/exited events which require a larger + // scope refresh than some suspended events. + if (newEvent instanceof IStartedDMEvent || newEvent instanceof IExitedDMEvent) { + return false; + } + + if (newEvent instanceof ISuspendedDMEvent && eventToSkip instanceof IDMEvent<?>) { + IDMContext newEventDmc = ((IDMEvent<?>) newEvent).getDMContext(); + IDMContext eventToSkipDmc = ((IDMEvent<?>) eventToSkip).getDMContext(); + + if (newEventDmc.equals(eventToSkipDmc) || DMContexts.isAncestorOf(eventToSkipDmc, newEventDmc)) { + return true; + } + } + + return false; + } protected void handlePropertyChanged(final IPreferenceStore store, final PropertyChangeEvent event) { String property = event.getProperty(); boolean processEvent = false; - + if (IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT_ENABLE.equals(property) || IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT.equals(property)) { if (store.getBoolean(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT_ENABLE)) { - getPresentationContext().setProperty(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT, store.getInt(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT)); + getPresentationContext().setProperty(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT, + store.getInt(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT)); } else { - getPresentationContext().setProperty(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT, null); + getPresentationContext().setProperty(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT, null); } processEvent = true; } else if (IDsfDebugUIConstants.DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY.equals(property)) { - getPresentationContext().setProperty(IDsfDebugUIConstants.DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY, event.getNewValue()); + getPresentationContext().setProperty(IDsfDebugUIConstants.DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY, + event.getNewValue()); processEvent = true; } - + if (processEvent) { getExecutor().execute(new DsfRunnable() { - @Override + @Override public void run() { - handleEvent(event); - } + handleEvent(event); + } }); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractThreadVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractThreadVMNode.java index 7f10bf8f0c3..d512be5d092 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractThreadVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/AbstractThreadVMNode.java @@ -7,12 +7,12 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Ericsson - Modified for multi threaded functionality * Patrick Chuong (Texas Instruments) - Add support for icon overlay in the debug view (Bug 334566) - * Dobrin Alexiev (Texas Instruments) - user groups support (bug 240208) + * Dobrin Alexiev (Texas Instruments) - user groups support (bug 240208) *******************************************************************************/ package org.eclipse.cdt.dsf.debug.ui.viewmodel.launch; @@ -64,367 +64,358 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDelta; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.debug.ui.IDebugUIConstants; - /** * Abstract implementation of a thread view model node. * Clients need to implement {@link #updateLabelInSessionThread(ILabelUpdate[])}. - * + * * @since 1.1 */ public abstract class AbstractThreadVMNode extends AbstractExecutionContextVMNode - implements IElementLabelProvider, IElementPropertiesProvider -{ - /** - * The label provider delegate. This VM node will delegate label updates to this provider - * which can be created by sub-classes. - * - * @since 2.0 - */ - private IElementLabelProvider fLabelProvider; + implements IElementLabelProvider, IElementPropertiesProvider { + /** + * The label provider delegate. This VM node will delegate label updates to this provider + * which can be created by sub-classes. + * + * @since 2.0 + */ + private IElementLabelProvider fLabelProvider; - public AbstractThreadVMNode(AbstractDMVMProvider provider, DsfSession session) { - super(provider, session, IExecutionDMContext.class); - fLabelProvider = createLabelProvider(); - } + public AbstractThreadVMNode(AbstractDMVMProvider provider, DsfSession session) { + super(provider, session, IExecutionDMContext.class); + fLabelProvider = createLabelProvider(); + } - - /** - * Creates the label provider delegate. This VM node will delegate label - * updates to this provider which can be created by sub-classes. - * - * @return Returns the label provider for this node. - * - * @since 2.0 - */ - protected IElementLabelProvider createLabelProvider() { - PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); + /** + * Creates the label provider delegate. This VM node will delegate label + * updates to this provider which can be created by sub-classes. + * + * @return Returns the label provider for this node. + * + * @since 2.0 + */ + protected IElementLabelProvider createLabelProvider() { + PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); - provider.setColumnInfo( - PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, - new LabelColumnInfo(new LabelAttribute[] { - // Text is made of the thread name followed by its state and state change reason. - new ExecutionContextLabelText( - MessagesForLaunchVM.AbstractThreadVMNode_No_columns__text_format, - new String[] { - ExecutionContextLabelText.PROP_NAME_KNOWN, - PROP_NAME, - ExecutionContextLabelText.PROP_ID_KNOWN, - ILaunchVMConstants.PROP_ID, - ILaunchVMConstants.PROP_IS_SUSPENDED, - ExecutionContextLabelText.PROP_STATE_CHANGE_REASON_KNOWN, - ILaunchVMConstants.PROP_STATE_CHANGE_REASON, - ExecutionContextLabelText.PROP_STATE_CHANGE_DETAILS_KNOWN, - ILaunchVMConstants.PROP_STATE_CHANGE_DETAILS }), - new LabelText(MessagesForLaunchVM.AbstractThreadVMNode_No_columns__Error__label, new String[0]), - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_THREAD_RUNNING)) { - { setPropertyNames(new String[] { ILaunchVMConstants.PROP_IS_SUSPENDED }); } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - return Boolean.FALSE.equals(properties.get(ILaunchVMConstants.PROP_IS_SUSPENDED)); - }; - }, - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_THREAD_SUSPENDED)), - })); - return provider; - } - - @Override - protected void updateElementsInSessionThread(final IChildrenUpdate update) { - IRunControl runControl = getServicesTracker().getService(IRunControl.class); - final IContainerDMContext contDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IContainerDMContext.class); - if (runControl == null || contDmc == null) { - handleFailedUpdate(update); - return; - } + provider.setColumnInfo(PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, + new LabelColumnInfo(new LabelAttribute[] { + // Text is made of the thread name followed by its state and state change reason. + new ExecutionContextLabelText(MessagesForLaunchVM.AbstractThreadVMNode_No_columns__text_format, + new String[] { ExecutionContextLabelText.PROP_NAME_KNOWN, PROP_NAME, + ExecutionContextLabelText.PROP_ID_KNOWN, ILaunchVMConstants.PROP_ID, + ILaunchVMConstants.PROP_IS_SUSPENDED, + ExecutionContextLabelText.PROP_STATE_CHANGE_REASON_KNOWN, + ILaunchVMConstants.PROP_STATE_CHANGE_REASON, + ExecutionContextLabelText.PROP_STATE_CHANGE_DETAILS_KNOWN, + ILaunchVMConstants.PROP_STATE_CHANGE_DETAILS }), + new LabelText(MessagesForLaunchVM.AbstractThreadVMNode_No_columns__Error__label, new String[0]), + new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_THREAD_RUNNING)) { + { + setPropertyNames(new String[] { ILaunchVMConstants.PROP_IS_SUSPENDED }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + return Boolean.FALSE.equals(properties.get(ILaunchVMConstants.PROP_IS_SUSPENDED)); + }; + }, new LabelImage( + DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_THREAD_SUSPENDED)), })); + return provider; + } - runControl.getExecutionContexts(contDmc, - new ViewerDataRequestMonitor<IExecutionDMContext[]>(getSession().getExecutor(), update){ - @Override - public void handleCompleted() { - if (!isSuccess()) { - handleFailedUpdate(update); - return; - } - fillUpdateWithVMCs(update, getData()); - update.done(); - } - }); - } + @Override + protected void updateElementsInSessionThread(final IChildrenUpdate update) { + IRunControl runControl = getServicesTracker().getService(IRunControl.class); + final IContainerDMContext contDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IContainerDMContext.class); + if (runControl == null || contDmc == null) { + handleFailedUpdate(update); + return; + } + runControl.getExecutionContexts(contDmc, + new ViewerDataRequestMonitor<IExecutionDMContext[]>(getSession().getExecutor(), update) { + @Override + public void handleCompleted() { + if (!isSuccess()) { + handleFailedUpdate(update); + return; + } + fillUpdateWithVMCs(update, getData()); + update.done(); + } + }); + } - - @Override + @Override public void update(final ILabelUpdate[] updates) { - fLabelProvider.update(updates); - } + fLabelProvider.update(updates); + } - /** - * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) - * - * @since 2.0 - */ - @Override + /** + * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) + * + * @since 2.0 + */ + @Override public void update(final IPropertiesUpdate[] updates) { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - updatePropertiesInSessionThread(updates); - }}); - } catch (RejectedExecutionException e) { - for (IPropertiesUpdate update : updates) { - handleFailedUpdate(update); - } - } - } + updatePropertiesInSessionThread(updates); + } + }); + } catch (RejectedExecutionException e) { + for (IPropertiesUpdate update : updates) { + handleFailedUpdate(update); + } + } + } + + /** + * @since 2.0 + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { + IRunControl service = getServicesTracker().getService(IRunControl.class); + + for (final IPropertiesUpdate update : updates) { + if (service == null) { + handleFailedUpdate(update); + continue; + } - /** - * @since 2.0 - */ - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { - IRunControl service = getServicesTracker().getService(IRunControl.class); - - for (final IPropertiesUpdate update : updates) { - if (service == null) { - handleFailedUpdate(update); - continue; - } + IExecutionDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IExecutionDMContext.class); + if (dmc == null) { + handleFailedUpdate(update); + continue; + } - IExecutionDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IExecutionDMContext.class); - if (dmc == null) { - handleFailedUpdate(update); - continue; - } + update.setProperty(ILaunchVMConstants.PROP_IS_SUSPENDED, service.isSuspended(dmc)); + update.setProperty(ILaunchVMConstants.PROP_IS_STEPPING, service.isStepping(dmc)); - update.setProperty(ILaunchVMConstants.PROP_IS_SUSPENDED, service.isSuspended(dmc)); - update.setProperty(ILaunchVMConstants.PROP_IS_STEPPING, service.isStepping(dmc)); - - service.getExecutionData( - dmc, - new ViewerDataRequestMonitor<IExecutionDMData>(getSession().getExecutor(), update) { - @Override - protected void handleSuccess() { - fillExecutionDataProperties(update, getData()); - update.done(); - } - }); - } - } - - protected void fillExecutionDataProperties(IPropertiesUpdate update, IExecutionDMData data) { - StateChangeReason reason = data.getStateChangeReason(); - if (reason != null) { - update.setProperty(ILaunchVMConstants.PROP_STATE_CHANGE_REASON, data.getStateChangeReason().name()); - } + service.getExecutionData(dmc, + new ViewerDataRequestMonitor<IExecutionDMData>(getSession().getExecutor(), update) { + @Override + protected void handleSuccess() { + fillExecutionDataProperties(update, getData()); + update.done(); + } + }); + } + } - if (data instanceof IExecutionDMData2) { - String details = ((IExecutionDMData2)data).getDetails(); - if (details != null) { - update.setProperty(ILaunchVMConstants.PROP_STATE_CHANGE_DETAILS, details); - } - } - } - - @Override - public void getContextsForEvent(VMDelta parentDelta, Object e, final DataRequestMonitor<IVMContext[]> rm) { - if(e instanceof IContainerResumedDMEvent) { - IExecutionDMContext[] triggerContexts = ((IContainerResumedDMEvent)e).getTriggeringContexts(); - if (triggerContexts.length != 0) { - rm.setData(new IVMContext[] { createVMContext(triggerContexts[0]) }); - rm.done(); - return; - } - } else if(e instanceof IContainerSuspendedDMEvent) { - IExecutionDMContext[] triggerContexts = ((IContainerSuspendedDMEvent)e).getTriggeringContexts(); - if (triggerContexts.length != 0) { - rm.setData(new IVMContext[] { createVMContext(triggerContexts[0]) }); - rm.done(); - return; - } - } else if (e instanceof SteppingTimedOutEvent && - ((SteppingTimedOutEvent)e).getDMContext() instanceof IContainerDMContext) - { - // The timed out event occurred on a container and not on a thread. Do not - // return a context for this event, which will force the view model to generate - // a delta for all the threads. - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "", null)); //$NON-NLS-1$ - rm.done(); - return; - } else if (e instanceof FullStackRefreshEvent && - ((FullStackRefreshEvent)e).getDMContext() instanceof IContainerDMContext) - { - // The step sequence end event occurred on a container and not on a thread. Do not - // return a context for this event, which will force the view model to generate - // a delta for all the threads. - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "", null)); //$NON-NLS-1$ - rm.done(); - return; - } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { - getThreadVMCForModelProxyInstallEvent( - parentDelta, - new DataRequestMonitor<VMContextInfo>(getExecutor(), rm) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - rm.setData(new IVMContext[] { getData().fVMContext }); - } else { - rm.setData(new IVMContext[0]); - } - rm.done(); - } - }); - return; - } - super.getContextsForEvent(parentDelta, e, rm); - } - - private static class VMContextInfo { - final IVMContext fVMContext; - final int fIndex; - final boolean fIsSuspended; - VMContextInfo(IVMContext vmContext, int index, boolean isSuspended) { - fVMContext = vmContext; - fIndex = index; - fIsSuspended = isSuspended; - } - } - - private void getThreadVMCForModelProxyInstallEvent(VMDelta parentDelta, final DataRequestMonitor<VMContextInfo> rm) { - getVMProvider().updateNode(this, new VMChildrenUpdate( - parentDelta, getVMProvider().getPresentationContext(), -1, -1, - new DataRequestMonitor<List<Object>>(getExecutor(), rm) { - @Override - protected void handleSuccess() { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - final IRunControl runControl = getServicesTracker().getService(IRunControl.class); - if (runControl != null) { - int vmcIdx = -1; - int suspendedVmcIdx = -1; - - for (int i = 0; i < getData().size(); i++) { - if (getData().get(i) instanceof IDMVMContext) { - IDMVMContext vmc = (IDMVMContext)getData().get(i); - IExecutionDMContext execDmc = DMContexts.getAncestorOfType( - vmc.getDMContext(), IExecutionDMContext.class); - if (execDmc != null) { - vmcIdx = vmcIdx < 0 ? i : vmcIdx; - if (runControl.isSuspended(execDmc)) { - suspendedVmcIdx = suspendedVmcIdx < 0 ? i : suspendedVmcIdx; - } - } - } - } - if (suspendedVmcIdx >= 0) { - rm.setData(new VMContextInfo( - (IVMContext)getData().get(suspendedVmcIdx), suspendedVmcIdx, true)); - } else if (vmcIdx >= 0) { - rm.setData(new VMContextInfo((IVMContext)getData().get(vmcIdx), vmcIdx, false)); - } else { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "No threads available", null)); //$NON-NLS-1$ - } - rm.done(); - } else { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "No threads available", null)); //$NON-NLS-1$ - rm.done(); - } - } - }); - } catch (RejectedExecutionException e) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "", null)); //$NON-NLS-1$ - rm.done(); - } - } - })); - } - - - @Override + protected void fillExecutionDataProperties(IPropertiesUpdate update, IExecutionDMData data) { + StateChangeReason reason = data.getStateChangeReason(); + if (reason != null) { + update.setProperty(ILaunchVMConstants.PROP_STATE_CHANGE_REASON, data.getStateChangeReason().name()); + } + + if (data instanceof IExecutionDMData2) { + String details = ((IExecutionDMData2) data).getDetails(); + if (details != null) { + update.setProperty(ILaunchVMConstants.PROP_STATE_CHANGE_DETAILS, details); + } + } + } + + @Override + public void getContextsForEvent(VMDelta parentDelta, Object e, final DataRequestMonitor<IVMContext[]> rm) { + if (e instanceof IContainerResumedDMEvent) { + IExecutionDMContext[] triggerContexts = ((IContainerResumedDMEvent) e).getTriggeringContexts(); + if (triggerContexts.length != 0) { + rm.setData(new IVMContext[] { createVMContext(triggerContexts[0]) }); + rm.done(); + return; + } + } else if (e instanceof IContainerSuspendedDMEvent) { + IExecutionDMContext[] triggerContexts = ((IContainerSuspendedDMEvent) e).getTriggeringContexts(); + if (triggerContexts.length != 0) { + rm.setData(new IVMContext[] { createVMContext(triggerContexts[0]) }); + rm.done(); + return; + } + } else if (e instanceof SteppingTimedOutEvent + && ((SteppingTimedOutEvent) e).getDMContext() instanceof IContainerDMContext) { + // The timed out event occurred on a container and not on a thread. Do not + // return a context for this event, which will force the view model to generate + // a delta for all the threads. + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "", null)); //$NON-NLS-1$ + rm.done(); + return; + } else if (e instanceof FullStackRefreshEvent + && ((FullStackRefreshEvent) e).getDMContext() instanceof IContainerDMContext) { + // The step sequence end event occurred on a container and not on a thread. Do not + // return a context for this event, which will force the view model to generate + // a delta for all the threads. + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "", null)); //$NON-NLS-1$ + rm.done(); + return; + } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { + getThreadVMCForModelProxyInstallEvent(parentDelta, + new DataRequestMonitor<VMContextInfo>(getExecutor(), rm) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + rm.setData(new IVMContext[] { getData().fVMContext }); + } else { + rm.setData(new IVMContext[0]); + } + rm.done(); + } + }); + return; + } + super.getContextsForEvent(parentDelta, e, rm); + } + + private static class VMContextInfo { + final IVMContext fVMContext; + final int fIndex; + final boolean fIsSuspended; + + VMContextInfo(IVMContext vmContext, int index, boolean isSuspended) { + fVMContext = vmContext; + fIndex = index; + fIsSuspended = isSuspended; + } + } + + private void getThreadVMCForModelProxyInstallEvent(VMDelta parentDelta, + final DataRequestMonitor<VMContextInfo> rm) { + getVMProvider().updateNode(this, new VMChildrenUpdate(parentDelta, getVMProvider().getPresentationContext(), -1, + -1, new DataRequestMonitor<List<Object>>(getExecutor(), rm) { + @Override + protected void handleSuccess() { + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + final IRunControl runControl = getServicesTracker().getService(IRunControl.class); + if (runControl != null) { + int vmcIdx = -1; + int suspendedVmcIdx = -1; + + for (int i = 0; i < getData().size(); i++) { + if (getData().get(i) instanceof IDMVMContext) { + IDMVMContext vmc = (IDMVMContext) getData().get(i); + IExecutionDMContext execDmc = DMContexts.getAncestorOfType( + vmc.getDMContext(), IExecutionDMContext.class); + if (execDmc != null) { + vmcIdx = vmcIdx < 0 ? i : vmcIdx; + if (runControl.isSuspended(execDmc)) { + suspendedVmcIdx = suspendedVmcIdx < 0 ? i : suspendedVmcIdx; + } + } + } + } + if (suspendedVmcIdx >= 0) { + rm.setData(new VMContextInfo((IVMContext) getData().get(suspendedVmcIdx), + suspendedVmcIdx, true)); + } else if (vmcIdx >= 0) { + rm.setData(new VMContextInfo((IVMContext) getData().get(vmcIdx), vmcIdx, + false)); + } else { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.REQUEST_FAILED, "No threads available", null)); //$NON-NLS-1$ + } + rm.done(); + } else { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.REQUEST_FAILED, "No threads available", null)); //$NON-NLS-1$ + rm.done(); + } + } + }); + } catch (RejectedExecutionException e) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.NOT_SUPPORTED, "", null)); //$NON-NLS-1$ + rm.done(); + } + } + })); + } + + @Override public int getDeltaFlags(Object e) { - IDMContext dmc = e instanceof IDMEvent<?> ? ((IDMEvent<?>)e).getDMContext() : null; + IDMContext dmc = e instanceof IDMEvent<?> ? ((IDMEvent<?>) e).getDMContext() : null; - if (dmc instanceof IContainerDMContext) { - return IModelDelta.NO_CHANGE; - } else if (e instanceof IResumedDMEvent && - ((IResumedDMEvent)e).getReason() != IRunControl.StateChangeReason.STEP) - { - return IModelDelta.CONTENT; - } else if (e instanceof ISuspendedDMEvent) { - return IModelDelta.NO_CHANGE; - } else if (e instanceof SteppingTimedOutEvent) { - return IModelDelta.CONTENT; - } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { - return IModelDelta.SELECT | IModelDelta.EXPAND; - } else if (e instanceof StateChangedEvent) { - return IModelDelta.STATE; - } - return IModelDelta.NO_CHANGE; - } + if (dmc instanceof IContainerDMContext) { + return IModelDelta.NO_CHANGE; + } else if (e instanceof IResumedDMEvent + && ((IResumedDMEvent) e).getReason() != IRunControl.StateChangeReason.STEP) { + return IModelDelta.CONTENT; + } else if (e instanceof ISuspendedDMEvent) { + return IModelDelta.NO_CHANGE; + } else if (e instanceof SteppingTimedOutEvent) { + return IModelDelta.CONTENT; + } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { + return IModelDelta.SELECT | IModelDelta.EXPAND; + } else if (e instanceof StateChangedEvent) { + return IModelDelta.STATE; + } + return IModelDelta.NO_CHANGE; + } - @Override + @Override public void buildDelta(Object e, final VMDelta parentDelta, final int nodeOffset, final RequestMonitor rm) { - IDMContext dmc = e instanceof IDMEvent<?> ? ((IDMEvent<?>)e).getDMContext() : null; + IDMContext dmc = e instanceof IDMEvent<?> ? ((IDMEvent<?>) e).getDMContext() : null; - if(dmc instanceof IContainerDMContext) { - // The IContainerDMContext sub-classes IExecutionDMContext. - // Also IContainerResumedDMEvent sub-classes IResumedDMEvent and - // IContainerSuspendedDMEvnet sub-classes ISuspendedEvent. - // Because of this relationship, the thread VM node can be called - // with data-model events for the containers. This statement - // filters out those event. - rm.done(); - } else if(e instanceof IResumedDMEvent) { - // Resumed: - // - If not stepping, update the thread and its content (its stack). - // - If stepping, do nothing to avoid too many updates. If a - // time-out is reached before the step completes, the - // ISteppingTimedOutEvent will trigger a refresh. - if (((IResumedDMEvent)e).getReason() != IRunControl.StateChangeReason.STEP) { - parentDelta.addNode(createVMContext(dmc), IModelDelta.CONTENT); - } - rm.done(); - } else if (e instanceof ISuspendedDMEvent) { - // Container suspended. Do nothing here to give the stack the - // priority in updating. The thread will update as a result of - // FullStackRefreshEvent. - rm.done(); - } else if (e instanceof SteppingTimedOutEvent) { - // Stepping time-out indicates that a step operation is taking - // a long time, and the view needs to be refreshed to show - // the user that the program is running. - parentDelta.addNode(createVMContext(dmc), IModelDelta.CONTENT); - rm.done(); - } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { - // Model Proxy install event is generated when the model is first - // populated into the view. This happens when a new debug session - // is started or when the view is first opened. - // In both cases, if there are already threads in the debug model, - // the desired user behavior is to show the threads and to select - // the first thread. - // If the thread is suspended, do not select the thread, instead, - // its top stack frame will be selected. - getThreadVMCForModelProxyInstallEvent( - parentDelta, - new DataRequestMonitor<VMContextInfo>(getExecutor(), rm) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - parentDelta.addNode( - getData().fVMContext, nodeOffset + getData().fIndex, - IModelDelta.EXPAND | (getData().fIsSuspended ? 0 : IModelDelta.SELECT)); - } - rm.done(); - } - }); - } else if (e instanceof StateChangedEvent) { - parentDelta.addNode(createVMContext(dmc), IModelDelta.STATE); - rm.done(); - } else { - rm.done(); - } - } + if (dmc instanceof IContainerDMContext) { + // The IContainerDMContext sub-classes IExecutionDMContext. + // Also IContainerResumedDMEvent sub-classes IResumedDMEvent and + // IContainerSuspendedDMEvnet sub-classes ISuspendedEvent. + // Because of this relationship, the thread VM node can be called + // with data-model events for the containers. This statement + // filters out those event. + rm.done(); + } else if (e instanceof IResumedDMEvent) { + // Resumed: + // - If not stepping, update the thread and its content (its stack). + // - If stepping, do nothing to avoid too many updates. If a + // time-out is reached before the step completes, the + // ISteppingTimedOutEvent will trigger a refresh. + if (((IResumedDMEvent) e).getReason() != IRunControl.StateChangeReason.STEP) { + parentDelta.addNode(createVMContext(dmc), IModelDelta.CONTENT); + } + rm.done(); + } else if (e instanceof ISuspendedDMEvent) { + // Container suspended. Do nothing here to give the stack the + // priority in updating. The thread will update as a result of + // FullStackRefreshEvent. + rm.done(); + } else if (e instanceof SteppingTimedOutEvent) { + // Stepping time-out indicates that a step operation is taking + // a long time, and the view needs to be refreshed to show + // the user that the program is running. + parentDelta.addNode(createVMContext(dmc), IModelDelta.CONTENT); + rm.done(); + } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { + // Model Proxy install event is generated when the model is first + // populated into the view. This happens when a new debug session + // is started or when the view is first opened. + // In both cases, if there are already threads in the debug model, + // the desired user behavior is to show the threads and to select + // the first thread. + // If the thread is suspended, do not select the thread, instead, + // its top stack frame will be selected. + getThreadVMCForModelProxyInstallEvent(parentDelta, + new DataRequestMonitor<VMContextInfo>(getExecutor(), rm) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + parentDelta.addNode(getData().fVMContext, nodeOffset + getData().fIndex, + IModelDelta.EXPAND | (getData().fIsSuspended ? 0 : IModelDelta.SELECT)); + } + rm.done(); + } + }); + } else if (e instanceof StateChangedEvent) { + parentDelta.addNode(createVMContext(dmc), IModelDelta.STATE); + rm.done(); + } else { + rm.done(); + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/DefaultDsfModelSelectionPolicyFactory.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/DefaultDsfModelSelectionPolicyFactory.java index b9a3161566a..68a2ce18363 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/DefaultDsfModelSelectionPolicyFactory.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/DefaultDsfModelSelectionPolicyFactory.java @@ -34,8 +34,8 @@ public class DefaultDsfModelSelectionPolicyFactory implements IModelSelectionPol public IModelSelectionPolicy createModelSelectionPolicyAdapter(Object element, IPresentationContext context) { if (IDebugUIConstants.ID_DEBUG_VIEW.equals(context.getId())) { if (element instanceof IDMVMContext) { - IDMVMContext dmvmContext= (IDMVMContext) element; - IDMContext dmContext= dmvmContext.getDMContext(); + IDMVMContext dmvmContext = (IDMVMContext) element; + IDMContext dmContext = dmvmContext.getDMContext(); if (dmContext != null) { return new DefaultDsfSelectionPolicy(dmContext); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/DefaultDsfSelectionPolicy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/DefaultDsfSelectionPolicy.java index 95775c27a54..adc5fa78f80 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/DefaultDsfSelectionPolicy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/DefaultDsfSelectionPolicy.java @@ -49,11 +49,11 @@ public class DefaultDsfSelectionPolicy implements IModelSelectionPolicy { /** * Create selection policy instance for the given data model context. - * + * * @param dmContext */ public DefaultDsfSelectionPolicy(IDMContext dmContext) { - fDMContext= dmContext; + fDMContext = dmContext; } /* @@ -63,11 +63,11 @@ public class DefaultDsfSelectionPolicy implements IModelSelectionPolicy { public boolean contains(ISelection selection, IPresentationContext context) { if (IDebugUIConstants.ID_DEBUG_VIEW.equals(context.getId())) { if (selection instanceof IStructuredSelection) { - IStructuredSelection ss= (IStructuredSelection) selection; - Object element= ss.getFirstElement(); + IStructuredSelection ss = (IStructuredSelection) selection; + Object element = ss.getFirstElement(); if (element instanceof IDMVMContext) { - IDMVMContext dmvmContext= (IDMVMContext) element; - IDMContext dmContext= dmvmContext.getDMContext(); + IDMVMContext dmvmContext = (IDMVMContext) element; + IDMContext dmContext = dmvmContext.getDMContext(); if (dmContext != null) { return fDMContext.getSessionId().equals(dmContext.getSessionId()); } @@ -84,8 +84,8 @@ public class DefaultDsfSelectionPolicy implements IModelSelectionPolicy { public boolean isSticky(ISelection selection, IPresentationContext context) { if (IDebugUIConstants.ID_DEBUG_VIEW.equals(context.getId())) { if (selection instanceof IStructuredSelection) { - IStructuredSelection ss= (IStructuredSelection) selection; - Object element= ss.getFirstElement(); + IStructuredSelection ss = (IStructuredSelection) selection; + Object element = ss.getFirstElement(); return isSticky(element); } } @@ -94,21 +94,23 @@ public class DefaultDsfSelectionPolicy implements IModelSelectionPolicy { protected boolean isSticky(Object element) { if (element instanceof IDMVMContext) { - IDMVMContext dmvmContext= (IDMVMContext) element; - final IDMContext dmContext= dmvmContext.getDMContext(); + IDMVMContext dmvmContext = (IDMVMContext) element; + final IDMContext dmContext = dmvmContext.getDMContext(); if (dmContext instanceof IFrameDMContext) { - final IExecutionDMContext execContext= DMContexts.getAncestorOfType(dmContext, IExecutionDMContext.class); + final IExecutionDMContext execContext = DMContexts.getAncestorOfType(dmContext, + IExecutionDMContext.class); if (execContext != null) { Query<Boolean> query = new Query<Boolean>() { @Override protected void execute(DataRequestMonitor<Boolean> rm) { - DsfServicesTracker servicesTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), dmContext.getSessionId()); + DsfServicesTracker servicesTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + dmContext.getSessionId()); try { - IRunControl runControl= servicesTracker.getService(IRunControl.class); + IRunControl runControl = servicesTracker.getService(IRunControl.class); if (runControl != null) { rm.setData(runControl.isSuspended(execContext)); } else { - rm.setData(false); + rm.setData(false); } } finally { servicesTracker.dispose(); @@ -153,7 +155,6 @@ public class DefaultDsfSelectionPolicy implements IModelSelectionPolicy { return true; } - protected boolean overrides(Object existing, Object candidate) { if (existing == null || existing.equals(candidate)) { return true; @@ -162,88 +163,88 @@ public class DefaultDsfSelectionPolicy implements IModelSelectionPolicy { IDMContext curr = ((IDMVMContext) existing).getDMContext(); IDMContext cand = ((IDMVMContext) candidate).getDMContext(); if (curr instanceof IFrameDMContext && cand instanceof IFrameDMContext) { - IExecutionDMContext currExecContext= DMContexts.getAncestorOfType(curr, IExecutionDMContext.class); + IExecutionDMContext currExecContext = DMContexts.getAncestorOfType(curr, IExecutionDMContext.class); if (currExecContext != null) { - IExecutionDMContext candExecContext= DMContexts.getAncestorOfType(cand, IExecutionDMContext.class); - return currExecContext.equals(candExecContext) || - !isSticky(existing) || - frameOverrides((IFrameDMContext)curr, (IFrameDMContext)cand); + IExecutionDMContext candExecContext = DMContexts.getAncestorOfType(cand, IExecutionDMContext.class); + return currExecContext.equals(candExecContext) || !isSticky(existing) + || frameOverrides((IFrameDMContext) curr, (IFrameDMContext) cand); } } } return !isSticky(existing); } - + /** * Last test for whether a stack frame overrides another stack frame. - * If two stack frames are from the same execution container (process) and - * the entire process has stopped (as in all-stop run control), and the + * If two stack frames are from the same execution container (process) and + * the entire process has stopped (as in all-stop run control), and the * current frame's thread was stopped due to the container stopping, then * the new frame selection should override the current one. This is because - * the new thread is most likely a the thread that triggered the container - * to stop. + * the new thread is most likely a the thread that triggered the container + * to stop. * @param curr Currently selected stack frame. * @param cand Candidate stack frame to be selected. - * @return <code>true</code> if the new frame should override current selection. + * @return <code>true</code> if the new frame should override current selection. */ private boolean frameOverrides(final IFrameDMContext curr, final IFrameDMContext cand) { - // We're assuming that frames are from different execution contexts. - - // Check if they are from the same container context: - final IContainerDMContext currContContext= DMContexts.getAncestorOfType(curr, IContainerDMContext.class); - IContainerDMContext candContContext= DMContexts.getAncestorOfType(cand, IContainerDMContext.class); - if (currContContext == null || !currContContext.equals(candContContext)) { - // If from different containers, frames should not override each other. - return false; - } - - Query<Boolean> query = new Query<Boolean>() { - @Override - protected void execute(final DataRequestMonitor<Boolean> rm) { - DsfServicesTracker servicesTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), curr.getSessionId()); + // We're assuming that frames are from different execution contexts. + + // Check if they are from the same container context: + final IContainerDMContext currContContext = DMContexts.getAncestorOfType(curr, IContainerDMContext.class); + IContainerDMContext candContContext = DMContexts.getAncestorOfType(cand, IContainerDMContext.class); + if (currContContext == null || !currContContext.equals(candContContext)) { + // If from different containers, frames should not override each other. + return false; + } + + Query<Boolean> query = new Query<Boolean>() { + @Override + protected void execute(final DataRequestMonitor<Boolean> rm) { + DsfServicesTracker servicesTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + curr.getSessionId()); + + // Check if container is not suspended. + IRunControl runControl = servicesTracker.getService(IRunControl.class); + if (runControl != null && runControl.isSuspended(currContContext)) { + IExecutionDMContext execDmc = DMContexts.getAncestorOfType(curr, IExecutionDMContext.class); + // If container is suspended, check whether the current thread was stopped due + // to container suspended event. + runControl.getExecutionData(execDmc, + new DataRequestMonitor<IExecutionDMData>(ImmediateExecutor.getInstance(), rm) { + @Override + protected void handleSuccess() { + rm.setData(getData() + .getStateChangeReason() == IRunControl.StateChangeReason.CONTAINER); + rm.done(); + }; + }); + } else { + // If container is not suspended it's running, then do not override the selection. + rm.setData(false); + rm.done(); + } + // In either case, we won't need the services tracker anymore. + servicesTracker.dispose(); + } + }; - // Check if container is not suspended. - IRunControl runControl= servicesTracker.getService(IRunControl.class); - if (runControl != null && runControl.isSuspended(currContContext)) { - IExecutionDMContext execDmc = DMContexts.getAncestorOfType(curr, IExecutionDMContext.class); - // If container is suspended, check whether the current thread was stopped due - // to container suspended event. - runControl.getExecutionData( - execDmc, - new DataRequestMonitor<IExecutionDMData>(ImmediateExecutor.getInstance(), rm) { - @Override - protected void handleSuccess() { - rm.setData( getData().getStateChangeReason() == IRunControl.StateChangeReason.CONTAINER ); - rm.done(); - }; - }); - } else { - // If container is not suspended it's running, then do not override the selection. - rm.setData(false); - rm.done(); - } - // In either case, we won't need the services tracker anymore. - servicesTracker.dispose(); - } - }; - - DsfSession session = DsfSession.getSession(curr.getSessionId()); - if (session != null) { - if (session.getExecutor().isInExecutorThread()) { - query.run(); - } else { - session.getExecutor().execute(query); - } - try { - Boolean result = query.get(); - return result != null && result.booleanValue(); - } catch (InterruptedException exc) { - Thread.currentThread().interrupt(); - } catch (ExecutionException exc) { - DsfUIPlugin.log(exc); - } - } - return false; + DsfSession session = DsfSession.getSession(curr.getSessionId()); + if (session != null) { + if (session.getExecutor().isInExecutorThread()) { + query.run(); + } else { + session.getExecutor().execute(query); + } + try { + Boolean result = query.get(); + return result != null && result.booleanValue(); + } catch (InterruptedException exc) { + Thread.currentThread().interrupt(); + } catch (ExecutionException exc) { + DsfUIPlugin.log(exc); + } + } + return false; } /* @@ -251,16 +252,16 @@ public class DefaultDsfSelectionPolicy implements IModelSelectionPolicy { */ @Override public ISelection replaceInvalidSelection(ISelection invalidSelection, ISelection newSelection) { - if (invalidSelection instanceof ITreeSelection) { - ITreeSelection treeSelection = (ITreeSelection)invalidSelection; - if (treeSelection.getPaths().length == 1) { - TreePath path = treeSelection.getPaths()[0]; - if (path.getSegmentCount() > 1) { - return new TreeSelection(path.getParentPath()); - } - } - } - return newSelection; + if (invalidSelection instanceof ITreeSelection) { + ITreeSelection treeSelection = (ITreeSelection) invalidSelection; + if (treeSelection.getPaths().length == 1) { + TreePath path = treeSelection.getPaths()[0]; + if (path.getSegmentCount() > 1) { + return new TreeSelection(path.getParentPath()); + } + } + } + return newSelection; } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/DelayedStackRefreshUpdatePolicy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/DelayedStackRefreshUpdatePolicy.java index 3fefa23d3f5..4fa63f67375 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/DelayedStackRefreshUpdatePolicy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/DelayedStackRefreshUpdatePolicy.java @@ -31,30 +31,31 @@ import org.eclipse.jface.viewers.TreePath; * An update strategy decorator specialized for delayed stack frame refresh. The * strategy flushes only the cached top stack frame in case of an normal {@link ISuspendedDMEvent}, * while in case of a special {@link FullStackRefreshEvent} everything is invalidated. - * + * * <p> * The underlying base update policy is considered for container contexts only. * In other cases the cache data is always flushed. * </p> - * + * * @since 1.1 */ public class DelayedStackRefreshUpdatePolicy extends UpdatePolicyDecorator { private static final class DelayedStackRefreshUpdateTester implements IElementUpdateTester { - private final IElementUpdateTester fBaseTester; - - /** Indicates whether only the top stack frame should be updated */ - private final boolean fLazyStackFrameMode; + private final IElementUpdateTester fBaseTester; + + /** Indicates whether only the top stack frame should be updated */ + private final boolean fLazyStackFrameMode; DelayedStackRefreshUpdateTester(IElementUpdateTester baseTester, boolean lazyStackFrameMode) { - fBaseTester = baseTester; - fLazyStackFrameMode = lazyStackFrameMode; + fBaseTester = baseTester; + fLazyStackFrameMode = lazyStackFrameMode; } + @Override public int getUpdateFlags(Object viewerInput, TreePath path) { - Object element = path.getSegmentCount() != 0 ? path.getLastSegment() : viewerInput; + Object element = path.getSegmentCount() != 0 ? path.getLastSegment() : viewerInput; if (element instanceof IDMVMContext) { IDMContext dmc = ((IDMVMContext) element).getDMContext(); if (fLazyStackFrameMode) { @@ -75,92 +76,92 @@ public class DelayedStackRefreshUpdatePolicy extends UpdatePolicyDecorator { @Override public boolean includes(IElementUpdateTester tester) { - // A non-lazy tester includes a lazy tester, but not vice versa. - // This allows entries that were marked as dirty by a flush with - // the lazy mode to be superseded by a non-lazy update which - // actually clears the entries that were marked as dirty. + // A non-lazy tester includes a lazy tester, but not vice versa. + // This allows entries that were marked as dirty by a flush with + // the lazy mode to be superseded by a non-lazy update which + // actually clears the entries that were marked as dirty. if (tester instanceof DelayedStackRefreshUpdateTester) { - DelayedStackRefreshUpdateTester sfTester = (DelayedStackRefreshUpdateTester)tester; - if (fLazyStackFrameMode) { - if (sfTester.fLazyStackFrameMode) { - return fBaseTester.includes(sfTester.fBaseTester); - } - } else { - if (!sfTester.fLazyStackFrameMode) { - return fBaseTester.includes(sfTester.fBaseTester); - } - // non-lazy includes lazy - return true; - } + DelayedStackRefreshUpdateTester sfTester = (DelayedStackRefreshUpdateTester) tester; + if (fLazyStackFrameMode) { + if (sfTester.fLazyStackFrameMode) { + return fBaseTester.includes(sfTester.fBaseTester); + } + } else { + if (!sfTester.fLazyStackFrameMode) { + return fBaseTester.includes(sfTester.fBaseTester); + } + // non-lazy includes lazy + return true; + } } return false; } - - @Override - public String toString() { - return "Delayed stack refresh (lazy = " + fLazyStackFrameMode + ", base = " + fBaseTester + ") update tester"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } + + @Override + public String toString() { + return "Delayed stack refresh (lazy = " + fLazyStackFrameMode + ", base = " + fBaseTester //$NON-NLS-1$//$NON-NLS-2$ + + ") update tester"; //$NON-NLS-1$ + } } private static final class ThreadsUpdateTester implements IElementUpdateTester { - private final IElementUpdateTester fBaseTester; - - private final boolean fRefreshAll; - - ThreadsUpdateTester(IElementUpdateTester baseTester, boolean refreshAll) { - fBaseTester = baseTester; - fRefreshAll = refreshAll; - } + private final IElementUpdateTester fBaseTester; + + private final boolean fRefreshAll; - @Override + ThreadsUpdateTester(IElementUpdateTester baseTester, boolean refreshAll) { + fBaseTester = baseTester; + fRefreshAll = refreshAll; + } + + @Override public int getUpdateFlags(Object viewerInput, TreePath path) { - Object element = path.getSegmentCount() != 0 ? path.getLastSegment() : viewerInput; - - if (!fRefreshAll && element instanceof IDMVMContext) { - IDMContext dmc = ((IDMVMContext) element).getDMContext(); - if (dmc instanceof IContainerDMContext) { - return fBaseTester.getUpdateFlags(viewerInput, path); - } - } - - // If the element is not a container or if the flush all flag is set, - // always flush it. - return FLUSH; - } - - @Override + Object element = path.getSegmentCount() != 0 ? path.getLastSegment() : viewerInput; + + if (!fRefreshAll && element instanceof IDMVMContext) { + IDMContext dmc = ((IDMVMContext) element).getDMContext(); + if (dmc instanceof IContainerDMContext) { + return fBaseTester.getUpdateFlags(viewerInput, path); + } + } + + // If the element is not a container or if the flush all flag is set, + // always flush it. + return FLUSH; + } + + @Override public boolean includes(IElementUpdateTester tester) { - // A refresh-all tester includes a non-refresh-all tester, but not - // vice versa. This allows entries that were marked as dirty by - // a flush with - // the non-refresh-all to be superseded by a refresh-all update which - // actually clears the entries that were marked as dirty. - if (tester instanceof ThreadsUpdateTester) { - ThreadsUpdateTester threadsTester = (ThreadsUpdateTester)tester; - if (fRefreshAll) { - if (threadsTester.fRefreshAll) { - return fBaseTester.includes(threadsTester.fBaseTester); - } - // refresh-all includes the non-refresh-all - return true; - } else { - if (!threadsTester.fRefreshAll) { - return fBaseTester.includes(threadsTester.fBaseTester); - } - } - } - return false; - } - - @Override - public String toString() { - return "Threads update tester (base = " + fBaseTester + ") update tester"; //$NON-NLS-1$ //$NON-NLS-2$ - } + // A refresh-all tester includes a non-refresh-all tester, but not + // vice versa. This allows entries that were marked as dirty by + // a flush with + // the non-refresh-all to be superseded by a refresh-all update which + // actually clears the entries that were marked as dirty. + if (tester instanceof ThreadsUpdateTester) { + ThreadsUpdateTester threadsTester = (ThreadsUpdateTester) tester; + if (fRefreshAll) { + if (threadsTester.fRefreshAll) { + return fBaseTester.includes(threadsTester.fBaseTester); + } + // refresh-all includes the non-refresh-all + return true; + } else { + if (!threadsTester.fRefreshAll) { + return fBaseTester.includes(threadsTester.fBaseTester); + } + } + } + return false; + } + + @Override + public String toString() { + return "Threads update tester (base = " + fBaseTester + ") update tester"; //$NON-NLS-1$ //$NON-NLS-2$ + } } - public DelayedStackRefreshUpdatePolicy(IVMUpdatePolicy base) { super(base); } @@ -170,24 +171,23 @@ public class DelayedStackRefreshUpdatePolicy extends UpdatePolicyDecorator { if (event instanceof ISuspendedDMEvent) { return new DelayedStackRefreshUpdateTester(getBaseUpdatePolicy().getElementUpdateTester(event), true); } else if (event instanceof FullStackRefreshEvent) { - return new DelayedStackRefreshUpdateTester(getBaseUpdatePolicy().getElementUpdateTester(event), false); - } else if (event instanceof IExitedDMEvent && - ((IExitedDMEvent)event).getDMContext() instanceof IContainerDMContext) - { - // container exit should always trigger a refresh - return new ThreadsUpdateTester(super.getElementUpdateTester(event), true); + return new DelayedStackRefreshUpdateTester(getBaseUpdatePolicy().getElementUpdateTester(event), false); + } else if (event instanceof IExitedDMEvent + && ((IExitedDMEvent) event).getDMContext() instanceof IContainerDMContext) { + // container exit should always trigger a refresh + return new ThreadsUpdateTester(super.getElementUpdateTester(event), true); } else { - return new ThreadsUpdateTester(super.getElementUpdateTester(event), false); + return new ThreadsUpdateTester(super.getElementUpdateTester(event), false); } } - + @Override public Object[] getInitialRootElementChildren(Object rootElement) { - return null; + return null; } - @Override + @Override public Map<String, Object> getInitialRootElementProperties(Object rootElement) { - return null; - } + return null; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/ExecutionContextLabelText.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/ExecutionContextLabelText.java index 71b94d0ce6e..de5511ebe52 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/ExecutionContextLabelText.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/ExecutionContextLabelText.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -24,107 +24,104 @@ import org.eclipse.core.runtime.IStatus; * @since 2.0 */ public class ExecutionContextLabelText extends LabelText { - - /** - * Value <code>0</code> means it's not known. Value <code>1</code>, means it's known. - */ - public static final String PROP_STATE_CHANGE_REASON_KNOWN = "state_change_reason_known"; //$NON-NLS-1$ - /** - * Value <code>0</code> means it's not known. Value <code>1</code>, means it's known. - * @since 2.1 - */ - public static final String PROP_STATE_CHANGE_DETAILS_KNOWN = "state_change_details_known"; //$NON-NLS-1$ + /** + * Value <code>0</code> means it's not known. Value <code>1</code>, means it's known. + */ + public static final String PROP_STATE_CHANGE_REASON_KNOWN = "state_change_reason_known"; //$NON-NLS-1$ + + /** + * Value <code>0</code> means it's not known. Value <code>1</code>, means it's known. + * @since 2.1 + */ + public static final String PROP_STATE_CHANGE_DETAILS_KNOWN = "state_change_details_known"; //$NON-NLS-1$ + + /** + * Value <code>0</code> means it's not known. Value <code>1</code>, means it's known. + */ + public static final String PROP_ID_KNOWN = "id_known"; //$NON-NLS-1$ + + /** + * Value <code>0</code> means it's not known. Value <code>1</code>, means it's known. + */ + public static final String PROP_NAME_KNOWN = "name_known"; //$NON-NLS-1$ + + public ExecutionContextLabelText(String formatPattern, String[] propertyNames) { + super(formatPattern, propertyNames); + } - /** - * Value <code>0</code> means it's not known. Value <code>1</code>, means it's known. - */ - public static final String PROP_ID_KNOWN = "id_known"; //$NON-NLS-1$ + @Override + protected Object getPropertyValue(String propertyName, IStatus status, Map<String, Object> properties) { + if (ILaunchVMConstants.PROP_STATE_CHANGE_REASON.equals(propertyName)) { + String reason = (String) properties.get(ILaunchVMConstants.PROP_STATE_CHANGE_REASON); + String reasonLabel = "invalid reason"; //$NON-NLS-1$ + if (reason == null) { + // In non-stop mode threads that are running have no state change reason + reasonLabel = ""; //$NON-NLS-1$ + } else if (StateChangeReason.BREAKPOINT.name().equals(reason)) { + reasonLabel = MessagesForLaunchVM.State_change_reason__Breakpoint__label; + } else if (StateChangeReason.CONTAINER.name().equals(reason)) { + reasonLabel = MessagesForLaunchVM.State_change_reason__Container__label; + } else if (StateChangeReason.ERROR.name().equals(reason)) { + reasonLabel = MessagesForLaunchVM.State_change_reason__Error__label; + } else if (StateChangeReason.EVALUATION.name().equals(reason)) { + reasonLabel = MessagesForLaunchVM.State_change_reason__Evaluation__label; + } else if (StateChangeReason.EXCEPTION.name().equals(reason)) { + reasonLabel = MessagesForLaunchVM.State_change_reason__Exception__label; + } else if (StateChangeReason.SHAREDLIB.name().equals(reason)) { + reasonLabel = MessagesForLaunchVM.State_change_reason__Shared_lib__label; + } else if (StateChangeReason.SIGNAL.name().equals(reason)) { + reasonLabel = MessagesForLaunchVM.State_change_reason__Signal__label; + } else if (StateChangeReason.STEP.name().equals(reason)) { + reasonLabel = MessagesForLaunchVM.State_change_reason__Step__label; + } else if (StateChangeReason.USER_REQUEST.name().equals(reason)) { + reasonLabel = MessagesForLaunchVM.State_change_reason__User_request__label; + } else if (StateChangeReason.WATCHPOINT.name().equals(reason)) { + reasonLabel = MessagesForLaunchVM.State_change_reason__Watchpoint__label; + } else if (StateChangeReason.EVENT_BREAKPOINT.name().equals(reason)) { + reasonLabel = MessagesForLaunchVM.State_change_reason__EventBreakpoint__label; + } else if (StateChangeReason.UNKNOWN.name().equals(reason)) { + reasonLabel = MessagesForLaunchVM.State_change_reason__Unknown__label; + } else { + assert false : "unexpected state change reason: " + reason; //$NON-NLS-1$ + } - /** - * Value <code>0</code> means it's not known. Value <code>1</code>, means it's known. - */ - public static final String PROP_NAME_KNOWN = "name_known"; //$NON-NLS-1$ - - public ExecutionContextLabelText(String formatPattern, String[] propertyNames) { - super(formatPattern, propertyNames); - } - - @Override - protected Object getPropertyValue(String propertyName, IStatus status, Map<String, Object> properties) { - if ( ILaunchVMConstants.PROP_STATE_CHANGE_REASON.equals(propertyName) ) { - String reason = (String)properties.get(ILaunchVMConstants.PROP_STATE_CHANGE_REASON); - String reasonLabel = "invalid reason"; //$NON-NLS-1$ - if (reason == null) { - // In non-stop mode threads that are running have no state change reason - reasonLabel = ""; //$NON-NLS-1$ - } else if (StateChangeReason.BREAKPOINT.name().equals(reason)) { - reasonLabel = MessagesForLaunchVM.State_change_reason__Breakpoint__label; - } else if (StateChangeReason.CONTAINER.name().equals(reason)) { - reasonLabel = MessagesForLaunchVM.State_change_reason__Container__label; - } else if (StateChangeReason.ERROR.name().equals(reason)) { - reasonLabel = MessagesForLaunchVM.State_change_reason__Error__label; - } else if (StateChangeReason.EVALUATION.name().equals(reason)) { - reasonLabel = MessagesForLaunchVM.State_change_reason__Evaluation__label; - } else if (StateChangeReason.EXCEPTION.name().equals(reason)) { - reasonLabel = MessagesForLaunchVM.State_change_reason__Exception__label; - } else if (StateChangeReason.SHAREDLIB.name().equals(reason)) { - reasonLabel = MessagesForLaunchVM.State_change_reason__Shared_lib__label; - } else if (StateChangeReason.SIGNAL.name().equals(reason)) { - reasonLabel = MessagesForLaunchVM.State_change_reason__Signal__label; - } else if (StateChangeReason.STEP.name().equals(reason)) { - reasonLabel = MessagesForLaunchVM.State_change_reason__Step__label; - } else if (StateChangeReason.USER_REQUEST.name().equals(reason)) { - reasonLabel = MessagesForLaunchVM.State_change_reason__User_request__label; - } else if (StateChangeReason.WATCHPOINT.name().equals(reason)) { - reasonLabel = MessagesForLaunchVM.State_change_reason__Watchpoint__label; - } else if (StateChangeReason.EVENT_BREAKPOINT.name().equals(reason)) { - reasonLabel = MessagesForLaunchVM.State_change_reason__EventBreakpoint__label; - } else if (StateChangeReason.UNKNOWN.name().equals(reason)) { - reasonLabel = MessagesForLaunchVM.State_change_reason__Unknown__label; - } else { - assert false : "unexpected state change reason: " + reason; //$NON-NLS-1$ - } - - return reasonLabel; - } else if ( ILaunchVMConstants.PROP_STATE_CHANGE_DETAILS.equals(propertyName) ) { - return properties.get(propertyName); - } else if ( ILaunchVMConstants.PROP_IS_SUSPENDED.equals(propertyName) ) { - Boolean suspended = (Boolean)properties.get(propertyName); - return suspended ? 1 : 0; - } else if ( PROP_STATE_CHANGE_REASON_KNOWN.equals(propertyName) ) { - String reason = (String)properties.get(ILaunchVMConstants.PROP_STATE_CHANGE_REASON); - return (reason != null && !StateChangeReason.UNKNOWN.name().equals(reason)) ? 1 : 0; - } else if ( PROP_STATE_CHANGE_DETAILS_KNOWN.equals(propertyName) ) { - String details = (String)properties.get(ILaunchVMConstants.PROP_STATE_CHANGE_DETAILS); - return (details != null) ? 1 : 0; - } else if (PROP_NAME_KNOWN.equals(propertyName)) { - return properties.get(IElementPropertiesProvider.PROP_NAME) != null ? 1 : 0; - } else if (IElementPropertiesProvider.PROP_NAME.equals(propertyName)) { - Object val = properties.get(IElementPropertiesProvider.PROP_NAME); - return val != null ? val : ""; //$NON-NLS-1$ - } else if (PROP_ID_KNOWN.equals(propertyName)) { - return properties.get(ILaunchVMConstants.PROP_ID) != null ? 1 : 0; - } else if (ILaunchVMConstants.PROP_ID.equals(propertyName)) { - Object val = properties.get(ILaunchVMConstants.PROP_ID); - return val != null ? val : ""; //$NON-NLS-1$ - } - return super.getPropertyValue(propertyName, status, properties); - } + return reasonLabel; + } else if (ILaunchVMConstants.PROP_STATE_CHANGE_DETAILS.equals(propertyName)) { + return properties.get(propertyName); + } else if (ILaunchVMConstants.PROP_IS_SUSPENDED.equals(propertyName)) { + Boolean suspended = (Boolean) properties.get(propertyName); + return suspended ? 1 : 0; + } else if (PROP_STATE_CHANGE_REASON_KNOWN.equals(propertyName)) { + String reason = (String) properties.get(ILaunchVMConstants.PROP_STATE_CHANGE_REASON); + return (reason != null && !StateChangeReason.UNKNOWN.name().equals(reason)) ? 1 : 0; + } else if (PROP_STATE_CHANGE_DETAILS_KNOWN.equals(propertyName)) { + String details = (String) properties.get(ILaunchVMConstants.PROP_STATE_CHANGE_DETAILS); + return (details != null) ? 1 : 0; + } else if (PROP_NAME_KNOWN.equals(propertyName)) { + return properties.get(IElementPropertiesProvider.PROP_NAME) != null ? 1 : 0; + } else if (IElementPropertiesProvider.PROP_NAME.equals(propertyName)) { + Object val = properties.get(IElementPropertiesProvider.PROP_NAME); + return val != null ? val : ""; //$NON-NLS-1$ + } else if (PROP_ID_KNOWN.equals(propertyName)) { + return properties.get(ILaunchVMConstants.PROP_ID) != null ? 1 : 0; + } else if (ILaunchVMConstants.PROP_ID.equals(propertyName)) { + Object val = properties.get(ILaunchVMConstants.PROP_ID); + return val != null ? val : ""; //$NON-NLS-1$ + } + return super.getPropertyValue(propertyName, status, properties); + } - @Override - protected boolean checkProperty(String propertyName, IStatus status, Map<String, Object> properties) { - if (PROP_NAME_KNOWN.equals(propertyName) || - IElementPropertiesProvider.PROP_NAME.equals(propertyName) || - PROP_STATE_CHANGE_REASON_KNOWN.equals(propertyName) || - ILaunchVMConstants.PROP_STATE_CHANGE_REASON.equals(propertyName) || - PROP_STATE_CHANGE_DETAILS_KNOWN.equals(propertyName) || - ILaunchVMConstants.PROP_STATE_CHANGE_DETAILS.equals(propertyName) || - PROP_ID_KNOWN.equals(propertyName) || - ILaunchVMConstants.PROP_ID.equals(propertyName)) - { - return true; - } - return super.checkProperty(propertyName, status, properties); - } + @Override + protected boolean checkProperty(String propertyName, IStatus status, Map<String, Object> properties) { + if (PROP_NAME_KNOWN.equals(propertyName) || IElementPropertiesProvider.PROP_NAME.equals(propertyName) + || PROP_STATE_CHANGE_REASON_KNOWN.equals(propertyName) + || ILaunchVMConstants.PROP_STATE_CHANGE_REASON.equals(propertyName) + || PROP_STATE_CHANGE_DETAILS_KNOWN.equals(propertyName) + || ILaunchVMConstants.PROP_STATE_CHANGE_DETAILS.equals(propertyName) + || PROP_ID_KNOWN.equals(propertyName) || ILaunchVMConstants.PROP_ID.equals(propertyName)) { + return true; + } + return super.checkProperty(propertyName, status, properties); + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/ExpandStackEvent.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/ExpandStackEvent.java index aa35b1adeb1..51f5811a706 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/ExpandStackEvent.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/ExpandStackEvent.java @@ -18,13 +18,13 @@ import org.eclipse.cdt.dsf.debug.service.IRunControl.IExecutionDMContext; /** * Event to increase the stack frame limit for an execution context. - * + * * @since 1.1 */ public class ExpandStackEvent extends AbstractDMEvent<IExecutionDMContext> { - - public ExpandStackEvent(IExecutionDMContext execCtx) { - super(execCtx); - } + + public ExpandStackEvent(IExecutionDMContext execCtx) { + super(execCtx); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/FullStackRefreshEvent.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/FullStackRefreshEvent.java index 87a51a60723..7f63c1c6713 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/FullStackRefreshEvent.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/FullStackRefreshEvent.java @@ -21,23 +21,23 @@ import org.eclipse.cdt.dsf.debug.service.IRunControl.IExecutionDMContext; /** * Indicates the end of a sequence of steps. Should be handled like a suspended * event to trigger a full refresh of stack frames. - * + * * @since 1.1 */ public class FullStackRefreshEvent extends AbstractDMEvent<IExecutionDMContext> { - - private final IDMEvent<? extends IDMContext> fTriggeringEvent; - - public FullStackRefreshEvent(IExecutionDMContext execCtx) { - this(execCtx, null); - } - - public FullStackRefreshEvent(IExecutionDMContext execCtx, IDMEvent<? extends IDMContext> triggeringEvent) { - super(execCtx); - fTriggeringEvent = triggeringEvent; - } - public IDMEvent<? extends IDMContext> getTriggeringEvent() { - return fTriggeringEvent; - } + private final IDMEvent<? extends IDMContext> fTriggeringEvent; + + public FullStackRefreshEvent(IExecutionDMContext execCtx) { + this(execCtx, null); + } + + public FullStackRefreshEvent(IExecutionDMContext execCtx, IDMEvent<? extends IDMContext> triggeringEvent) { + super(execCtx); + fTriggeringEvent = triggeringEvent; + } + + public IDMEvent<? extends IDMContext> getTriggeringEvent() { + return fTriggeringEvent; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/ILaunchVMConstants.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/ILaunchVMConstants.java index 951d63efd97..348d7f6bc41 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/ILaunchVMConstants.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/ILaunchVMConstants.java @@ -7,41 +7,40 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.dsf.debug.ui.viewmodel.launch; - /** * @since 2.0 */ public interface ILaunchVMConstants { - public static final String PROP_ID = "id"; //$NON-NLS-1$ - - public static final String PROP_IS_SUSPENDED = "is_suspended"; //$NON-NLS-1$ + public static final String PROP_ID = "id"; //$NON-NLS-1$ + + public static final String PROP_IS_SUSPENDED = "is_suspended"; //$NON-NLS-1$ + + public static final String PROP_IS_STEPPING = "is_stepping"; //$NON-NLS-1$ - public static final String PROP_IS_STEPPING = "is_stepping"; //$NON-NLS-1$ + public static final String PROP_FRAME_ADDRESS = "frame_address"; //$NON-NLS-1$ - public static final String PROP_FRAME_ADDRESS = "frame_address"; //$NON-NLS-1$ + public static final String PROP_FRAME_FUNCTION = "frame_function"; //$NON-NLS-1$ - public static final String PROP_FRAME_FUNCTION = "frame_function"; //$NON-NLS-1$ + public static final String PROP_FRAME_FILE = "frame_file"; //$NON-NLS-1$ - public static final String PROP_FRAME_FILE = "frame_file"; //$NON-NLS-1$ + public static final String PROP_FRAME_LINE = "frame_line"; //$NON-NLS-1$ - public static final String PROP_FRAME_LINE = "frame_line"; //$NON-NLS-1$ + public static final String PROP_FRAME_COLUMN = "frame_column"; //$NON-NLS-1$ - public static final String PROP_FRAME_COLUMN = "frame_column"; //$NON-NLS-1$ + public static final String PROP_FRAME_MODULE = "frame_module"; //$NON-NLS-1$ - public static final String PROP_FRAME_MODULE = "frame_module"; //$NON-NLS-1$ - - public static final String PROP_STATE_CHANGE_REASON = "state_change_reason"; //$NON-NLS-1$ + public static final String PROP_STATE_CHANGE_REASON = "state_change_reason"; //$NON-NLS-1$ - /** - * @since 2.1 - */ - public static final String PROP_STATE_CHANGE_DETAILS = "state_change_details"; //$NON-NLS-1$ + /** + * @since 2.1 + */ + public static final String PROP_STATE_CHANGE_DETAILS = "state_change_details"; //$NON-NLS-1$ } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/LaunchRootVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/LaunchRootVMNode.java index 787792f1cf9..2e6517216f7 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/LaunchRootVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/LaunchRootVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -36,106 +36,104 @@ import org.eclipse.debug.core.model.IProcess; import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDelta; /** - * Layout node for the standard ILaunch object. This node can only be used at + * Layout node for the standard ILaunch object. This node can only be used at * the root of a hierarchy. It does not implement the label provider - * functionality, so the default adapters should be used to retrieve the label. + * functionality, so the default adapters should be used to retrieve the label. */ -public class LaunchRootVMNode extends RootVMNode - implements IRootVMNode -{ - public static class LaunchesEvent { - public enum Type { ADDED, REMOVED, CHANGED, TERMINATED } - public final ILaunch[] fLaunches; - public final Type fType; - - public LaunchesEvent(ILaunch[] launches, Type type) { - fLaunches = launches; - fType = type; - } - } - - - public LaunchRootVMNode(AbstractVMProvider provider) { - super(provider); - } - - @Override - public String toString() { - return "LaunchRootVMNode"; //$NON-NLS-1$ - } - - @Override - public boolean isDeltaEvent(Object rootObject, Object e) { - if (e instanceof DebugEvent) { - DebugEvent de = (DebugEvent)e; - if (de.getSource() instanceof IProcess && - !((IProcess)de.getSource()).getLaunch().equals(rootObject) ) - { - return false; - } - else if (de.getSource() instanceof IDebugElement && - !rootObject.equals(((IDebugElement)de.getSource()).getLaunch())) - { - return false; - } - } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { - return true; - } - - return super.isDeltaEvent(rootObject, e); - } - - @Override - public int getDeltaFlags(Object e) { - int flags = 0; - if (e instanceof LaunchesEvent) { - LaunchesEvent le = (LaunchesEvent)e; - if (le.fType == LaunchesEvent.Type.CHANGED || le.fType == LaunchesEvent.Type.TERMINATED) { - flags = IModelDelta.STATE | IModelDelta.CONTENT; - } - } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { - flags = IModelDelta.EXPAND | IModelDelta.SELECT; - } - - return flags; - } - - @Override - public void createRootDelta(Object rootObject, Object event, final DataRequestMonitor<VMDelta> rm) { - if (!(rootObject instanceof ILaunch)) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Invalid root element configured with launch root node.", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - ILaunch rootLaunch = (ILaunch)rootObject; - - /* - * Create the root of the delta. Since the launch object is not at the - * root of the view, create the delta with the path to the launch. - */ - ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager(); - List<ILaunch> launchList = Arrays.asList(manager.getLaunches()); - final VMDelta viewRootDelta = new VMDelta(manager, 0, IModelDelta.NO_CHANGE, launchList.size()); - final VMDelta rootDelta = viewRootDelta.addNode(rootLaunch, launchList.indexOf(rootLaunch), IModelDelta.NO_CHANGE); - - // Generate delta for launch node. - if (event instanceof LaunchesEvent) { - LaunchesEvent le = (LaunchesEvent)event; - for (ILaunch launch : le.fLaunches) { - if (rootLaunch == launch) { - if (le.fType == LaunchesEvent.Type.CHANGED) { - rootDelta.setFlags(rootDelta.getFlags() | IModelDelta.STATE | IModelDelta.CONTENT); - } else if (le.fType == LaunchesEvent.Type.TERMINATED) { - rootDelta.setFlags(rootDelta.getFlags() | IModelDelta.STATE | IModelDelta.CONTENT); - } - } - } - } else if (event instanceof ModelProxyInstalledEvent || event instanceof DataModelInitializedEvent) { - rootDelta.setFlags(rootDelta.getFlags() | IModelDelta.EXPAND | IModelDelta.SELECT); - } - rm.setData(rootDelta); - rm.done(); - } - +public class LaunchRootVMNode extends RootVMNode implements IRootVMNode { + public static class LaunchesEvent { + public enum Type { + ADDED, REMOVED, CHANGED, TERMINATED + } + + public final ILaunch[] fLaunches; + public final Type fType; + + public LaunchesEvent(ILaunch[] launches, Type type) { + fLaunches = launches; + fType = type; + } + } + + public LaunchRootVMNode(AbstractVMProvider provider) { + super(provider); + } + + @Override + public String toString() { + return "LaunchRootVMNode"; //$NON-NLS-1$ + } + + @Override + public boolean isDeltaEvent(Object rootObject, Object e) { + if (e instanceof DebugEvent) { + DebugEvent de = (DebugEvent) e; + if (de.getSource() instanceof IProcess && !((IProcess) de.getSource()).getLaunch().equals(rootObject)) { + return false; + } else if (de.getSource() instanceof IDebugElement + && !rootObject.equals(((IDebugElement) de.getSource()).getLaunch())) { + return false; + } + } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { + return true; + } + + return super.isDeltaEvent(rootObject, e); + } + + @Override + public int getDeltaFlags(Object e) { + int flags = 0; + if (e instanceof LaunchesEvent) { + LaunchesEvent le = (LaunchesEvent) e; + if (le.fType == LaunchesEvent.Type.CHANGED || le.fType == LaunchesEvent.Type.TERMINATED) { + flags = IModelDelta.STATE | IModelDelta.CONTENT; + } + } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { + flags = IModelDelta.EXPAND | IModelDelta.SELECT; + } + + return flags; + } + + @Override + public void createRootDelta(Object rootObject, Object event, final DataRequestMonitor<VMDelta> rm) { + if (!(rootObject instanceof ILaunch)) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Invalid root element configured with launch root node.", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + ILaunch rootLaunch = (ILaunch) rootObject; + + /* + * Create the root of the delta. Since the launch object is not at the + * root of the view, create the delta with the path to the launch. + */ + ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager(); + List<ILaunch> launchList = Arrays.asList(manager.getLaunches()); + final VMDelta viewRootDelta = new VMDelta(manager, 0, IModelDelta.NO_CHANGE, launchList.size()); + final VMDelta rootDelta = viewRootDelta.addNode(rootLaunch, launchList.indexOf(rootLaunch), + IModelDelta.NO_CHANGE); + + // Generate delta for launch node. + if (event instanceof LaunchesEvent) { + LaunchesEvent le = (LaunchesEvent) event; + for (ILaunch launch : le.fLaunches) { + if (rootLaunch == launch) { + if (le.fType == LaunchesEvent.Type.CHANGED) { + rootDelta.setFlags(rootDelta.getFlags() | IModelDelta.STATE | IModelDelta.CONTENT); + } else if (le.fType == LaunchesEvent.Type.TERMINATED) { + rootDelta.setFlags(rootDelta.getFlags() | IModelDelta.STATE | IModelDelta.CONTENT); + } + } + } + } else if (event instanceof ModelProxyInstalledEvent || event instanceof DataModelInitializedEvent) { + rootDelta.setFlags(rootDelta.getFlags() | IModelDelta.EXPAND | IModelDelta.SELECT); + } + rm.setData(rootDelta); + rm.done(); + } + } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/LaunchVMUpdateMessages.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/LaunchVMUpdateMessages.java index e6b4165d10e..6d07d6c65aa 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/LaunchVMUpdateMessages.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/LaunchVMUpdateMessages.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,14 +19,14 @@ import org.eclipse.osgi.util.NLS; * @since 1.1 */ public class LaunchVMUpdateMessages extends NLS { - public static String ThreadsAutomaticUpdatePolicy_name; - public static String ThreadsManualUpdatePolicy_name; - - static { - // load message values from bundle file - NLS.initializeMessages(LaunchVMUpdateMessages.class.getName(), LaunchVMUpdateMessages.class); - } + public static String ThreadsAutomaticUpdatePolicy_name; + public static String ThreadsManualUpdatePolicy_name; + + static { + // load message values from bundle file + NLS.initializeMessages(LaunchVMUpdateMessages.class.getName(), LaunchVMUpdateMessages.class); + } - private LaunchVMUpdateMessages() { - } + private LaunchVMUpdateMessages() { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/MessagesForLaunchVM.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/MessagesForLaunchVM.java index 0f62a3e5370..def8147a884 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/MessagesForLaunchVM.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/MessagesForLaunchVM.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,40 +20,40 @@ import org.eclipse.osgi.util.NLS; * @noinstantiate This class is not intended to be instantiated by clients. */ public class MessagesForLaunchVM extends NLS { - public static String StackFramesVMNode_No_columns__Incomplete_stack_marker__text_format; - public static String StackFramesVMNode_No_columns__text_format; - public static String StackFramesVMNode_No_columns__add_parens__text_format; - public static String StackFramesVMNode_No_columns__No_line__text_format; + public static String StackFramesVMNode_No_columns__Incomplete_stack_marker__text_format; + public static String StackFramesVMNode_No_columns__text_format; + public static String StackFramesVMNode_No_columns__add_parens__text_format; + public static String StackFramesVMNode_No_columns__No_line__text_format; public static String StackFramesVMNode_No_columns__No_line__add_parens__text_format; - public static String StackFramesVMNode_No_columns__No_function__text_format; - public static String StackFramesVMNode_No_columns__No_module__text_format; + public static String StackFramesVMNode_No_columns__No_function__text_format; + public static String StackFramesVMNode_No_columns__No_module__text_format; public static String StackFramesVMNode_No_columns__No_module__add_parens__text_format; - public static String StackFramesVMNode_No_columns__Address_only__text_format; - - public static String AbstractContainerVMNode_No_columns__text_format; - public static String AbstractContainerVMNode_No_columns__Error__label; - - public static String AbstractThreadVMNode_No_columns__text_format; - public static String AbstractThreadVMNode_No_columns__Error__label; - - public static String State_change_reason__Unknown__label; - public static String State_change_reason__User_request__label; - public static String State_change_reason__Step__label; - public static String State_change_reason__Breakpoint__label; - public static String State_change_reason__Exception__label; - public static String State_change_reason__Container__label; - public static String State_change_reason__Watchpoint__label; - public static String State_change_reason__Signal__label; - public static String State_change_reason__Shared_lib__label; - public static String State_change_reason__Error__label; - public static String State_change_reason__Evaluation__label; - public static String State_change_reason__EventBreakpoint__label; - - static { - // initialize resource bundle - NLS.initializeMessages(MessagesForLaunchVM.class.getName(), MessagesForLaunchVM.class); - } - - private MessagesForLaunchVM() { - } + public static String StackFramesVMNode_No_columns__Address_only__text_format; + + public static String AbstractContainerVMNode_No_columns__text_format; + public static String AbstractContainerVMNode_No_columns__Error__label; + + public static String AbstractThreadVMNode_No_columns__text_format; + public static String AbstractThreadVMNode_No_columns__Error__label; + + public static String State_change_reason__Unknown__label; + public static String State_change_reason__User_request__label; + public static String State_change_reason__Step__label; + public static String State_change_reason__Breakpoint__label; + public static String State_change_reason__Exception__label; + public static String State_change_reason__Container__label; + public static String State_change_reason__Watchpoint__label; + public static String State_change_reason__Signal__label; + public static String State_change_reason__Shared_lib__label; + public static String State_change_reason__Error__label; + public static String State_change_reason__Evaluation__label; + public static String State_change_reason__EventBreakpoint__label; + + static { + // initialize resource bundle + NLS.initializeMessages(MessagesForLaunchVM.class.getName(), MessagesForLaunchVM.class); + } + + private MessagesForLaunchVM() { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/StackFramesVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/StackFramesVMNode.java index fe30fca80a1..819f36ee75a 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/StackFramesVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/StackFramesVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -74,17 +74,16 @@ import org.eclipse.debug.ui.IDebugUIConstants; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.ui.IMemento; -public class StackFramesVMNode extends AbstractDMVMNode - implements IElementLabelProvider, IElementMementoProvider, IElementPropertiesProvider -{ - /** - * @since 2.0 - */ - public static final String PROP_IS_INCOMPLETE_STACK_MARKER = "is_incomplete_stack_marker"; //$NON-NLS-1$ - +public class StackFramesVMNode extends AbstractDMVMNode + implements IElementLabelProvider, IElementMementoProvider, IElementPropertiesProvider { + /** + * @since 2.0 + */ + public static final String PROP_IS_INCOMPLETE_STACK_MARKER = "is_incomplete_stack_marker"; //$NON-NLS-1$ + /** * View model context representing the end of an incomplete stack. - * + * * @since 1.1 */ public class IncompleteStackVMContext extends AbstractVMContext { @@ -96,16 +95,18 @@ public class StackFramesVMNode extends AbstractDMVMNode fDmc = dmc; fLevel = level; } + public int getLevel() { return fLevel; } + public IExecutionDMContext getExecutionDMContext() { return fDmc; } + @Override public boolean equals(Object obj) { - return obj instanceof IncompleteStackVMContext && - ((IncompleteStackVMContext)obj).fDmc.equals(fDmc); + return obj instanceof IncompleteStackVMContext && ((IncompleteStackVMContext) obj).fDmc.equals(fDmc); } @Override @@ -119,877 +120,828 @@ public class StackFramesVMNode extends AbstractDMVMNode */ private Map<IExecutionDMContext, Integer> fTemporaryLimits = new HashMap<IExecutionDMContext, Integer>(); - /** - * The label provider delegate. This VM node will delegate label updates to this provider - * which can be created by sub-classes. - * - * @since 2.0 - */ - private IElementLabelProvider fLabelProvider; + /** + * The label provider delegate. This VM node will delegate label updates to this provider + * which can be created by sub-classes. + * + * @since 2.0 + */ + private IElementLabelProvider fLabelProvider; public StackFramesVMNode(AbstractDMVMProvider provider, DsfSession session) { - super(provider, session, IStack.IFrameDMContext.class); - fLabelProvider = createLabelProvider(); - } - - @Override - public String toString() { - return "StackFramesVMNode(" + getSession().getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - } - - /** - * Creates the label provider delegate. This VM node will delegate label - * updates to this provider which can be created by sub-classes. - * - * @return Returns the label provider for this node. - * - * @since 2.0 - */ - protected IElementLabelProvider createLabelProvider() { - PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); - - provider.setColumnInfo( - PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForLaunchVM.StackFramesVMNode_No_columns__Incomplete_stack_marker__text_format, - new String[] { PROP_IS_INCOMPLETE_STACK_MARKER }) - { - @Override - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - return Boolean.TRUE.equals(properties.get(PROP_IS_INCOMPLETE_STACK_MARKER)); - } - - }, - new LabelText( - MessagesForLaunchVM.StackFramesVMNode_No_columns__text_format, - new String[] { - ILaunchVMConstants.PROP_FRAME_ADDRESS, - ILaunchVMConstants.PROP_FRAME_FUNCTION, - ILaunchVMConstants.PROP_FRAME_FILE, - ILaunchVMConstants.PROP_FRAME_LINE, - ILaunchVMConstants.PROP_FRAME_COLUMN, - ILaunchVMConstants.PROP_FRAME_MODULE}) - { - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - Integer line = (Integer)properties.get(ILaunchVMConstants.PROP_FRAME_LINE); - String file = (String)properties.get(ILaunchVMConstants.PROP_FRAME_FILE); - String function = (String)properties.get(ILaunchVMConstants.PROP_FRAME_FUNCTION); - return line != null && line >= 0 && file != null && !file.isEmpty() && - function != null && function.contains(")"); //$NON-NLS-1$ - }; - }, - new LabelText( - MessagesForLaunchVM.StackFramesVMNode_No_columns__add_parens__text_format, - new String[] { - ILaunchVMConstants.PROP_FRAME_ADDRESS, - ILaunchVMConstants.PROP_FRAME_FUNCTION, - ILaunchVMConstants.PROP_FRAME_FILE, - ILaunchVMConstants.PROP_FRAME_LINE, - ILaunchVMConstants.PROP_FRAME_COLUMN, - ILaunchVMConstants.PROP_FRAME_MODULE}) - { - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - Integer line = (Integer)properties.get(ILaunchVMConstants.PROP_FRAME_LINE); - String file = (String)properties.get(ILaunchVMConstants.PROP_FRAME_FILE); - String function = (String)properties.get(ILaunchVMConstants.PROP_FRAME_FUNCTION); - return line != null && line >= 0 && file != null && !file.isEmpty() && - (function == null || !function.contains(")")); //$NON-NLS-1$ - }; - }, - new LabelText( - MessagesForLaunchVM.StackFramesVMNode_No_columns__No_line__text_format, - new String[] { - ILaunchVMConstants.PROP_FRAME_ADDRESS, - ILaunchVMConstants.PROP_FRAME_FUNCTION, - ILaunchVMConstants.PROP_FRAME_MODULE}) - { - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - String function = (String)properties.get(ILaunchVMConstants.PROP_FRAME_FUNCTION); - String module = (String)properties.get(ILaunchVMConstants.PROP_FRAME_MODULE); - return function != null && !function.isEmpty() && function.contains(")") && //$NON-NLS-1$ - module != null && !module.isEmpty(); - }; - }, - new LabelText( - MessagesForLaunchVM.StackFramesVMNode_No_columns__No_line__add_parens__text_format, - new String[] { - ILaunchVMConstants.PROP_FRAME_ADDRESS, - ILaunchVMConstants.PROP_FRAME_FUNCTION, - ILaunchVMConstants.PROP_FRAME_MODULE}) - { - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - String function = (String)properties.get(ILaunchVMConstants.PROP_FRAME_FUNCTION); - String module = (String)properties.get(ILaunchVMConstants.PROP_FRAME_MODULE); - return function != null && !function.isEmpty() && !function.contains(")") && //$NON-NLS-1$ - module != null && !module.isEmpty(); - }; - }, - new LabelText( - MessagesForLaunchVM.StackFramesVMNode_No_columns__No_function__text_format, - new String[] { - ILaunchVMConstants.PROP_FRAME_ADDRESS, - ILaunchVMConstants.PROP_FRAME_MODULE}) - { - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - String module = (String)properties.get(ILaunchVMConstants.PROP_FRAME_MODULE); - return module != null && !module.isEmpty(); - }; - }, - new LabelText( - MessagesForLaunchVM.StackFramesVMNode_No_columns__No_module__text_format, - new String[] { - ILaunchVMConstants.PROP_FRAME_ADDRESS, - ILaunchVMConstants.PROP_FRAME_FUNCTION}) - { - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - String function = (String)properties.get(ILaunchVMConstants.PROP_FRAME_FUNCTION); - return function != null && !function.isEmpty() && function.contains(")"); //$NON-NLS-1$ - }; - }, - new LabelText( - MessagesForLaunchVM.StackFramesVMNode_No_columns__No_module__add_parens__text_format, - new String[] { - ILaunchVMConstants.PROP_FRAME_ADDRESS, - ILaunchVMConstants.PROP_FRAME_FUNCTION}) - { - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - String function = (String)properties.get(ILaunchVMConstants.PROP_FRAME_FUNCTION); - return function != null && !function.isEmpty() && !function.contains(")"); //$NON-NLS-1$ - }; - }, - new LabelText( - MessagesForLaunchVM.StackFramesVMNode_No_columns__Address_only__text_format, - new String[] { ILaunchVMConstants.PROP_FRAME_ADDRESS }), - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_STACKFRAME_RUNNING)) { - { setPropertyNames(new String[] { ILaunchVMConstants.PROP_IS_SUSPENDED }); } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - return Boolean.FALSE.equals( properties.get(ILaunchVMConstants.PROP_IS_SUSPENDED) ); - }; - }, - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_STACKFRAME)) - })); - - return provider; - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#updateHasElementsInSessionThread(org.eclipse.debug.internal.ui.viewers.model.provisional.IHasChildrenUpdate) - */ - @Override - protected void updateHasElementsInSessionThread(IHasChildrenUpdate update) { - IRunControl runControl = getServicesTracker().getService(IRunControl.class); - IExecutionDMContext execCtx = findDmcInPath(update.getViewerInput(), update.getElementPath(), IExecutionDMContext.class); - if (runControl == null || execCtx == null) { - handleFailedUpdate(update); - return; - } - - update.setHasChilren(runControl.isSuspended(execCtx) || runControl.isStepping(execCtx)); - update.done(); - } - - @Override - protected void updateElementCountInSessionThread(final IChildrenCountUpdate update) { - IStack stackService = getServicesTracker().getService(IStack.class); - final IExecutionDMContext execDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IExecutionDMContext.class); - if (stackService == null || execDmc == null) { - handleFailedUpdate(update); - return; - } - - final int stackFrameLimit= getStackFrameLimit(execDmc); - stackService.getStackDepth( - execDmc, stackFrameLimit == Integer.MAX_VALUE ? 0 : stackFrameLimit + 1, - new ViewerDataRequestMonitor<Integer>(getSession().getExecutor(), update) { - @Override - public void handleCompleted() { - if (!isSuccess()) { - handleFailedUpdate(update); - return; - } - int stackDepth= getData(); - if (stackFrameLimit < stackDepth) { - stackDepth = stackFrameLimit + 1; - } - update.setChildCount(stackDepth); - update.done(); - } - }); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#updateElementsInSessionThread(org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenUpdate) - */ - @Override - protected void updateElementsInSessionThread(final IChildrenUpdate update) { - IStack stackService = getServicesTracker().getService(IStack.class); - final IExecutionDMContext execDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IExecutionDMContext.class); - if (stackService == null || execDmc == null) { - handleFailedUpdate(update); - return; - } - - final int stackFrameLimit= getStackFrameLimit(execDmc); - final int startIndex= update.getOffset(); + super(provider, session, IStack.IFrameDMContext.class); + fLabelProvider = createLabelProvider(); + } + + @Override + public String toString() { + return "StackFramesVMNode(" + getSession().getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Creates the label provider delegate. This VM node will delegate label + * updates to this provider which can be created by sub-classes. + * + * @return Returns the label provider for this node. + * + * @since 2.0 + */ + protected IElementLabelProvider createLabelProvider() { + PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); + + provider.setColumnInfo(PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, + new LabelColumnInfo(new LabelAttribute[] { new LabelText( + MessagesForLaunchVM.StackFramesVMNode_No_columns__Incomplete_stack_marker__text_format, + new String[] { PROP_IS_INCOMPLETE_STACK_MARKER }) { + @Override + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + return Boolean.TRUE.equals(properties.get(PROP_IS_INCOMPLETE_STACK_MARKER)); + } + + }, new LabelText(MessagesForLaunchVM.StackFramesVMNode_No_columns__text_format, + new String[] { ILaunchVMConstants.PROP_FRAME_ADDRESS, ILaunchVMConstants.PROP_FRAME_FUNCTION, + ILaunchVMConstants.PROP_FRAME_FILE, ILaunchVMConstants.PROP_FRAME_LINE, + ILaunchVMConstants.PROP_FRAME_COLUMN, ILaunchVMConstants.PROP_FRAME_MODULE }) { + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + Integer line = (Integer) properties.get(ILaunchVMConstants.PROP_FRAME_LINE); + String file = (String) properties.get(ILaunchVMConstants.PROP_FRAME_FILE); + String function = (String) properties.get(ILaunchVMConstants.PROP_FRAME_FUNCTION); + return line != null && line >= 0 && file != null && !file.isEmpty() && function != null + && function.contains(")"); //$NON-NLS-1$ + }; + }, new LabelText(MessagesForLaunchVM.StackFramesVMNode_No_columns__add_parens__text_format, + new String[] { ILaunchVMConstants.PROP_FRAME_ADDRESS, ILaunchVMConstants.PROP_FRAME_FUNCTION, + ILaunchVMConstants.PROP_FRAME_FILE, ILaunchVMConstants.PROP_FRAME_LINE, + ILaunchVMConstants.PROP_FRAME_COLUMN, ILaunchVMConstants.PROP_FRAME_MODULE }) { + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + Integer line = (Integer) properties.get(ILaunchVMConstants.PROP_FRAME_LINE); + String file = (String) properties.get(ILaunchVMConstants.PROP_FRAME_FILE); + String function = (String) properties.get(ILaunchVMConstants.PROP_FRAME_FUNCTION); + return line != null && line >= 0 && file != null && !file.isEmpty() + && (function == null || !function.contains(")")); //$NON-NLS-1$ + }; + }, new LabelText(MessagesForLaunchVM.StackFramesVMNode_No_columns__No_line__text_format, + new String[] { ILaunchVMConstants.PROP_FRAME_ADDRESS, ILaunchVMConstants.PROP_FRAME_FUNCTION, + ILaunchVMConstants.PROP_FRAME_MODULE }) { + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + String function = (String) properties.get(ILaunchVMConstants.PROP_FRAME_FUNCTION); + String module = (String) properties.get(ILaunchVMConstants.PROP_FRAME_MODULE); + return function != null && !function.isEmpty() && function.contains(")") && //$NON-NLS-1$ + module != null && !module.isEmpty(); + }; + }, new LabelText(MessagesForLaunchVM.StackFramesVMNode_No_columns__No_line__add_parens__text_format, + new String[] { ILaunchVMConstants.PROP_FRAME_ADDRESS, ILaunchVMConstants.PROP_FRAME_FUNCTION, + ILaunchVMConstants.PROP_FRAME_MODULE }) { + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + String function = (String) properties.get(ILaunchVMConstants.PROP_FRAME_FUNCTION); + String module = (String) properties.get(ILaunchVMConstants.PROP_FRAME_MODULE); + return function != null && !function.isEmpty() && !function.contains(")") && //$NON-NLS-1$ + module != null && !module.isEmpty(); + }; + }, new LabelText(MessagesForLaunchVM.StackFramesVMNode_No_columns__No_function__text_format, + new String[] { ILaunchVMConstants.PROP_FRAME_ADDRESS, ILaunchVMConstants.PROP_FRAME_MODULE }) { + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + String module = (String) properties.get(ILaunchVMConstants.PROP_FRAME_MODULE); + return module != null && !module.isEmpty(); + }; + }, new LabelText(MessagesForLaunchVM.StackFramesVMNode_No_columns__No_module__text_format, + new String[] { ILaunchVMConstants.PROP_FRAME_ADDRESS, + ILaunchVMConstants.PROP_FRAME_FUNCTION }) { + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + String function = (String) properties.get(ILaunchVMConstants.PROP_FRAME_FUNCTION); + return function != null && !function.isEmpty() && function.contains(")"); //$NON-NLS-1$ + }; + }, new LabelText(MessagesForLaunchVM.StackFramesVMNode_No_columns__No_module__add_parens__text_format, + new String[] { ILaunchVMConstants.PROP_FRAME_ADDRESS, + ILaunchVMConstants.PROP_FRAME_FUNCTION }) { + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + String function = (String) properties.get(ILaunchVMConstants.PROP_FRAME_FUNCTION); + return function != null && !function.isEmpty() && !function.contains(")"); //$NON-NLS-1$ + }; + }, new LabelText(MessagesForLaunchVM.StackFramesVMNode_No_columns__Address_only__text_format, + new String[] { ILaunchVMConstants.PROP_FRAME_ADDRESS }), + new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_STACKFRAME_RUNNING)) { + { + setPropertyNames(new String[] { ILaunchVMConstants.PROP_IS_SUSPENDED }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + return Boolean.FALSE.equals(properties.get(ILaunchVMConstants.PROP_IS_SUSPENDED)); + }; + }, new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_STACKFRAME)) })); + + return provider; + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#updateHasElementsInSessionThread(org.eclipse.debug.internal.ui.viewers.model.provisional.IHasChildrenUpdate) + */ + @Override + protected void updateHasElementsInSessionThread(IHasChildrenUpdate update) { + IRunControl runControl = getServicesTracker().getService(IRunControl.class); + IExecutionDMContext execCtx = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IExecutionDMContext.class); + if (runControl == null || execCtx == null) { + handleFailedUpdate(update); + return; + } + + update.setHasChilren(runControl.isSuspended(execCtx) || runControl.isStepping(execCtx)); + update.done(); + } + + @Override + protected void updateElementCountInSessionThread(final IChildrenCountUpdate update) { + IStack stackService = getServicesTracker().getService(IStack.class); + final IExecutionDMContext execDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IExecutionDMContext.class); + if (stackService == null || execDmc == null) { + handleFailedUpdate(update); + return; + } + + final int stackFrameLimit = getStackFrameLimit(execDmc); + stackService.getStackDepth(execDmc, stackFrameLimit == Integer.MAX_VALUE ? 0 : stackFrameLimit + 1, + new ViewerDataRequestMonitor<Integer>(getSession().getExecutor(), update) { + @Override + public void handleCompleted() { + if (!isSuccess()) { + handleFailedUpdate(update); + return; + } + int stackDepth = getData(); + if (stackFrameLimit < stackDepth) { + stackDepth = stackFrameLimit + 1; + } + update.setChildCount(stackDepth); + update.done(); + } + }); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#updateElementsInSessionThread(org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenUpdate) + */ + @Override + protected void updateElementsInSessionThread(final IChildrenUpdate update) { + IStack stackService = getServicesTracker().getService(IStack.class); + final IExecutionDMContext execDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IExecutionDMContext.class); + if (stackService == null || execDmc == null) { + handleFailedUpdate(update); + return; + } + + final int stackFrameLimit = getStackFrameLimit(execDmc); + final int startIndex = update.getOffset(); if (startIndex == 0 && update.getLength() == 1) { - // Requesting top stack frame only - stackService.getTopFrame( - execDmc, - new ViewerDataRequestMonitor<IFrameDMContext>(getSession().getExecutor(), update) { - @Override - public void handleCompleted() { - if (!isSuccess()) { - handleFailedUpdate(update); - return; - } - update.setChild(createVMContext(getData()), 0); - update.done(); - } - }); - - } else { - if (startIndex >= 0 && update.getLength() > 0) { - // partial stack dump - int endIndex= startIndex + update.getLength() - 1; - if (startIndex < stackFrameLimit && endIndex >= stackFrameLimit) { - endIndex = stackFrameLimit - 1; - } - stackService.getFrames( - execDmc, - startIndex, - endIndex, - new ViewerDataRequestMonitor<IFrameDMContext[]>(getSession().getExecutor(), update) { - @Override - public void handleCompleted() { - if (!isSuccess()) { - handleFailedUpdate(update); - return; - } - IFrameDMContext[] frames = getData(); - fillUpdateWithVMCs(update, frames, startIndex); - if (startIndex + update.getLength() > stackFrameLimit) { - update.setChild(new IncompleteStackVMContext(execDmc, stackFrameLimit), stackFrameLimit); + // Requesting top stack frame only + stackService.getTopFrame(execDmc, + new ViewerDataRequestMonitor<IFrameDMContext>(getSession().getExecutor(), update) { + @Override + public void handleCompleted() { + if (!isSuccess()) { + handleFailedUpdate(update); + return; + } + update.setChild(createVMContext(getData()), 0); + update.done(); + } + }); + + } else { + if (startIndex >= 0 && update.getLength() > 0) { + // partial stack dump + int endIndex = startIndex + update.getLength() - 1; + if (startIndex < stackFrameLimit && endIndex >= stackFrameLimit) { + endIndex = stackFrameLimit - 1; + } + stackService.getFrames(execDmc, startIndex, endIndex, + new ViewerDataRequestMonitor<IFrameDMContext[]>(getSession().getExecutor(), update) { + @Override + public void handleCompleted() { + if (!isSuccess()) { + handleFailedUpdate(update); + return; + } + IFrameDMContext[] frames = getData(); + fillUpdateWithVMCs(update, frames, startIndex); + if (startIndex + update.getLength() > stackFrameLimit) { + update.setChild(new IncompleteStackVMContext(execDmc, stackFrameLimit), + stackFrameLimit); + } + update.done(); + } + }); + } else { + // full stack dump + stackService.getFrames(execDmc, + new ViewerDataRequestMonitor<IFrameDMContext[]>(getSession().getExecutor(), update) { + @Override + public void handleCompleted() { + if (!isSuccess()) { + handleFailedUpdate(update); + return; + } + IFrameDMContext[] frames = getData(); + if (frames.length > stackFrameLimit) { + IFrameDMContext[] tmpFrames = new IFrameDMContext[stackFrameLimit]; + System.arraycopy(frames, 0, tmpFrames, 0, stackFrameLimit); + frames = tmpFrames; + update.setChild(new IncompleteStackVMContext(execDmc, stackFrameLimit), + stackFrameLimit); + } + fillUpdateWithVMCs(update, frames); + update.done(); + } + }); + } + } + } + + @Override + public void update(final ILabelUpdate[] updates) { + fLabelProvider.update(updates); + } + + /** + * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) + * + * @since 2.0 + */ + @Override + public void update(final IPropertiesUpdate[] updates) { + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + updatePropertiesInSessionThread(updates); + } + }); + } catch (RejectedExecutionException e) { + for (IPropertiesUpdate update : updates) { + handleFailedUpdate(update); + } + } + } + + /** + * @since 2.0 + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { + IStack service = getServicesTracker().getService(IStack.class); + + for (final IPropertiesUpdate update : updates) { + if (service == null) { + handleFailedUpdate(update); + continue; + } + + if (update.getElement() instanceof IncompleteStackVMContext) { + update.setProperty(PROP_IS_INCOMPLETE_STACK_MARKER, Boolean.TRUE); + update.done(); + continue; + } + + IFrameDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IFrameDMContext.class); + if (dmc == null) { + handleFailedUpdate(update); + continue; + } + + IRunControl runControlService = getServicesTracker().getService(IRunControl.class); + IExecutionDMContext execDmc = DMContexts.getAncestorOfType(dmc, IExecutionDMContext.class); + if (execDmc != null && runControlService != null) { + update.setProperty(ILaunchVMConstants.PROP_IS_SUSPENDED, runControlService.isSuspended(execDmc)); + update.setProperty(ILaunchVMConstants.PROP_IS_STEPPING, runControlService.isStepping(execDmc)); + } else { + update.setStatus(DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_HANDLE, + "Invalid context or service not available", null)); //$NON-NLS-1$ + } + + service.getFrameData(dmc, new ViewerDataRequestMonitor<IFrameDMData>(getSession().getExecutor(), update) { + @Override + protected void handleSuccess() { + fillFrameDataProperties(update, getData()); + update.done(); + } + }); + } + } + + protected void fillFrameDataProperties(IPropertiesUpdate update, IFrameDMData data) { + IAddress address = data.getAddress(); + if (address != null) { + update.setProperty(ILaunchVMConstants.PROP_FRAME_ADDRESS, "0x" + address.toString(16)); //$NON-NLS-1$ + } + + String fileName = data.getFile(); + if (fileName != null) { + Object showFullPathPreference = getVMProvider().getPresentationContext() + .getProperty(IDsfDebugUIConstants.DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY); + if (showFullPathPreference instanceof Boolean && (Boolean) showFullPathPreference == false) { + fileName = new Path(fileName).lastSegment(); + } + } + update.setProperty(ILaunchVMConstants.PROP_FRAME_FILE, fileName); + + update.setProperty(ILaunchVMConstants.PROP_FRAME_FUNCTION, data.getFunction()); + update.setProperty(ILaunchVMConstants.PROP_FRAME_LINE, data.getLine()); + update.setProperty(ILaunchVMConstants.PROP_FRAME_COLUMN, data.getColumn()); + update.setProperty(ILaunchVMConstants.PROP_FRAME_MODULE, data.getModule()); + } + + protected void fillColumnLabel(IFrameDMContext dmContext, IFrameDMData dmData, String columnId, int idx, + ILabelUpdate update) { + if (idx != 0) + return; + + final IExecutionDMContext execDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IExecutionDMContext.class); + if (execDmc == null) { + return; + } + IRunControl runControlService = getServicesTracker().getService(IRunControl.class); + SteppingController stepQueueMgr = execDmc.getAdapter(SteppingController.class); + if (runControlService == null || stepQueueMgr == null) + return; + + String imageKey = null; + if (runControlService.isSuspended(execDmc) + || (runControlService.isStepping(execDmc) && !stepQueueMgr.isSteppingTimedOut(execDmc))) { + imageKey = IDebugUIConstants.IMG_OBJS_STACKFRAME; + } else { + imageKey = IDebugUIConstants.IMG_OBJS_STACKFRAME_RUNNING; + } + update.setImageDescriptor(DebugUITools.getImageDescriptor(imageKey), 0); + + // + // Finally, if all goes well, set the label. + // + StringBuilder label = new StringBuilder(); + + // Add the function name + if (dmData.getFunction() != null && dmData.getFunction().length() != 0) { + label.append(" "); //$NON-NLS-1$ + label.append(dmData.getFunction()); + label.append("()"); //$NON-NLS-1$ + } + + boolean hasFileName = dmData.getFile() != null && dmData.getFile().length() != 0; + + // Add full file name + if (hasFileName) { + label.append(" at "); //$NON-NLS-1$ + label.append(dmData.getFile()); + } + + // Add line number + if (dmData.getLine() >= 0) { + label.append(":"); //$NON-NLS-1$ + label.append(dmData.getLine()); + label.append(" "); //$NON-NLS-1$ + } + + // Add module + if (!hasFileName && (dmData.getModule() != null && dmData.getModule().length() != 0)) { + label.append(" "); //$NON-NLS-1$ + label.append(dmData.getModule()); + label.append(" "); //$NON-NLS-1$ + } + + // Add the address + if (dmData.getAddress() != null) { + label.append("- 0x").append(dmData.getAddress().toString(16)); //$NON-NLS-1$ + } + + // Set the label to the result listener + update.setLabel(label.toString(), 0); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#getContextsForEvent(org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, java.lang.Object, org.eclipse.cdt.dsf.concurrent.DataRequestMonitor) + */ + @Override + public void getContextsForEvent(final VMDelta parentDelta, Object e, final DataRequestMonitor<IVMContext[]> rm) { + if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { + // Retrieve the list of stack frames, and mark the top frame to be selected. + getVMProvider().updateNode(this, new VMChildrenUpdate(parentDelta, getVMProvider().getPresentationContext(), + 0, 1, new DataRequestMonitor<List<Object>>(getExecutor(), rm) { + @Override + public void handleCompleted() { + if (isSuccess() && getData().size() != 0) { + rm.setData(new IVMContext[] { (IVMContext) getData().get(0) }); + } else { + // In case of errors, return an empty set of frames. + rm.setData(new IVMContext[0]); } - update.done(); - } - }); - } else { - // full stack dump - stackService.getFrames( - execDmc, - new ViewerDataRequestMonitor<IFrameDMContext[]>(getSession().getExecutor(), update) { - @Override - public void handleCompleted() { - if (!isSuccess()) { - handleFailedUpdate(update); - return; - } - IFrameDMContext[] frames = getData(); - if (frames.length > stackFrameLimit) { - IFrameDMContext[] tmpFrames = new IFrameDMContext[stackFrameLimit]; - System.arraycopy(frames, 0, tmpFrames, 0, stackFrameLimit); - frames = tmpFrames; - update.setChild(new IncompleteStackVMContext(execDmc, stackFrameLimit), stackFrameLimit); - } - fillUpdateWithVMCs(update, frames); - update.done(); - } - }); - } - } - } - - @Override - public void update(final ILabelUpdate[] updates) { - fLabelProvider.update(updates); - } - - /** - * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) - * - * @since 2.0 - */ - @Override - public void update(final IPropertiesUpdate[] updates) { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - updatePropertiesInSessionThread(updates); - }}); - } catch (RejectedExecutionException e) { - for (IPropertiesUpdate update : updates) { - handleFailedUpdate(update); - } - } - } - - /** - * @since 2.0 - */ - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { - IStack service = getServicesTracker().getService(IStack.class); - - for (final IPropertiesUpdate update : updates) { - if (service == null) { - handleFailedUpdate(update); - continue; - } - - if (update.getElement() instanceof IncompleteStackVMContext) { - update.setProperty(PROP_IS_INCOMPLETE_STACK_MARKER, Boolean.TRUE); - update.done(); - continue; - } - - IFrameDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IFrameDMContext.class); - if (dmc == null) { - handleFailedUpdate(update); - continue; - } - - IRunControl runControlService = getServicesTracker().getService(IRunControl.class); - IExecutionDMContext execDmc = DMContexts.getAncestorOfType(dmc, IExecutionDMContext.class); - if (execDmc != null && runControlService != null) { - update.setProperty(ILaunchVMConstants.PROP_IS_SUSPENDED, runControlService.isSuspended(execDmc)); - update.setProperty(ILaunchVMConstants.PROP_IS_STEPPING, runControlService.isStepping(execDmc)); - } else { - update.setStatus(DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_HANDLE, "Invalid context or service not available", null)); //$NON-NLS-1$ - } - - service.getFrameData( - dmc, - new ViewerDataRequestMonitor<IFrameDMData>(getSession().getExecutor(), update) { - @Override - protected void handleSuccess() { - fillFrameDataProperties(update, getData()); - update.done(); - } - }); - } - } - - protected void fillFrameDataProperties(IPropertiesUpdate update, IFrameDMData data) { - IAddress address = data.getAddress(); - if (address != null) { - update.setProperty(ILaunchVMConstants.PROP_FRAME_ADDRESS, "0x" + address.toString(16)); //$NON-NLS-1$ - } - - String fileName = data.getFile(); - if (fileName != null) { - Object showFullPathPreference = getVMProvider().getPresentationContext().getProperty(IDsfDebugUIConstants.DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY); - if (showFullPathPreference instanceof Boolean && (Boolean)showFullPathPreference == false) { - fileName = new Path(fileName).lastSegment(); - } - } - update.setProperty(ILaunchVMConstants.PROP_FRAME_FILE, fileName); - - update.setProperty(ILaunchVMConstants.PROP_FRAME_FUNCTION, data.getFunction()); - update.setProperty(ILaunchVMConstants.PROP_FRAME_LINE, data.getLine()); - update.setProperty(ILaunchVMConstants.PROP_FRAME_COLUMN, data.getColumn()); - update.setProperty(ILaunchVMConstants.PROP_FRAME_MODULE, data.getModule()); - } - - protected void fillColumnLabel(IFrameDMContext dmContext, IFrameDMData dmData, String columnId, int idx, ILabelUpdate update) - { - if (idx != 0) return; - - final IExecutionDMContext execDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IExecutionDMContext.class); - if (execDmc == null) { - return; - } - IRunControl runControlService = getServicesTracker().getService(IRunControl.class); - SteppingController stepQueueMgr = execDmc.getAdapter(SteppingController.class); - if (runControlService == null || stepQueueMgr == null) return; - - String imageKey = null; - if (runControlService.isSuspended(execDmc) || - (runControlService.isStepping(execDmc) && !stepQueueMgr.isSteppingTimedOut(execDmc))) - { - imageKey = IDebugUIConstants.IMG_OBJS_STACKFRAME; - } else { - imageKey = IDebugUIConstants.IMG_OBJS_STACKFRAME_RUNNING; - } - update.setImageDescriptor(DebugUITools.getImageDescriptor(imageKey), 0); - - // - // Finally, if all goes well, set the label. - // - StringBuilder label = new StringBuilder(); - - // Add the function name - if (dmData.getFunction() != null && dmData.getFunction().length() != 0) { - label.append(" "); //$NON-NLS-1$ - label.append(dmData.getFunction()); - label.append("()"); //$NON-NLS-1$ - } - - boolean hasFileName = dmData.getFile() != null && dmData.getFile().length() != 0; - - // Add full file name - if (hasFileName) { - label.append(" at "); //$NON-NLS-1$ - label.append(dmData.getFile()); - } - - // Add line number - if (dmData.getLine() >= 0) { - label.append(":"); //$NON-NLS-1$ - label.append(dmData.getLine()); - label.append(" "); //$NON-NLS-1$ - } - - // Add module - if (!hasFileName && (dmData.getModule() != null && dmData.getModule().length() != 0)) { - label.append(" "); //$NON-NLS-1$ - label.append(dmData.getModule()); - label.append(" "); //$NON-NLS-1$ - } - - // Add the address - if (dmData.getAddress() != null) { - label.append("- 0x").append(dmData.getAddress().toString(16)); //$NON-NLS-1$ - } - - // Set the label to the result listener - update.setLabel(label.toString(), 0); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#getContextsForEvent(org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, java.lang.Object, org.eclipse.cdt.dsf.concurrent.DataRequestMonitor) - */ - @Override - public void getContextsForEvent(final VMDelta parentDelta, Object e, final DataRequestMonitor<IVMContext[]> rm) { - if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { - // Retrieve the list of stack frames, and mark the top frame to be selected. - getVMProvider().updateNode( - this, - new VMChildrenUpdate( - parentDelta, getVMProvider().getPresentationContext(), 0, 1, - new DataRequestMonitor<List<Object>>(getExecutor(), rm) { - @Override - public void handleCompleted() { - if (isSuccess() && getData().size() != 0) { - rm.setData(new IVMContext[] { (IVMContext)getData().get(0) }); - } else { - // In case of errors, return an empty set of frames. - rm.setData(new IVMContext[0]); - } - rm.done(); - } - }) - ); - return; - } - super.getContextsForEvent(parentDelta, e, rm); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.IVMNode#getDeltaFlags(java.lang.Object) - */ - @Override - public int getDeltaFlags(Object e) { - // This node generates delta if the timers have changed, or if the - // label has changed. - if (e instanceof ISuspendedDMEvent) { - return IModelDelta.CONTENT | IModelDelta.EXPAND | IModelDelta.SELECT; - } else if (e instanceof FullStackRefreshEvent && - !(((FullStackRefreshEvent)e).getTriggeringEvent() instanceof IContainerSuspendedDMEvent) ) - { - return IModelDelta.CONTENT; - } else if (e instanceof SteppingTimedOutEvent) { - return IModelDelta.CONTENT; - } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { - return IModelDelta.SELECT | IModelDelta.EXPAND; - } else if (e instanceof ExpandStackEvent) { - return IModelDelta.CONTENT; - } else if (e instanceof IExitedDMEvent) { - // Do not generate a delta for this event, but do clear the - // internal stack frame limit to avoid a memory leak. - resetStackFrameLimit( ((IExitedDMEvent)e).getDMContext() ); - return IModelDelta.NO_CHANGE; - } else if (e instanceof PropertyChangeEvent) { - String property = ((PropertyChangeEvent)e).getProperty(); - if (IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT_ENABLE.equals(property) - || IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT.equals(property)) - { - return IModelDelta.CONTENT; - } else if (IDsfDebugUIConstants.DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY.equals(property)) { - return IModelDelta.STATE; - } - } else { - } - - return IModelDelta.NO_CHANGE; - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.IVMNode#buildDelta(java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, int, org.eclipse.cdt.dsf.concurrent.RequestMonitor) - */ - @Override - public void buildDelta(final Object e, final VMDelta parent, final int nodeOffset, final RequestMonitor rm) { - if (e instanceof IContainerSuspendedDMEvent) { - // Clear the limit on the stack frames for all stack frames under a given container. - resetStackFrameLimit( ((IContainerSuspendedDMEvent)e).getDMContext() ); - - IContainerSuspendedDMEvent csEvent = (IContainerSuspendedDMEvent)e; - - IExecutionDMContext triggeringCtx = csEvent.getTriggeringContexts().length != 0 - ? csEvent.getTriggeringContexts()[0] : null; - - if (parent.getElement() instanceof IDMVMContext) { - IExecutionDMContext threadDmc = null; - threadDmc = DMContexts.getAncestorOfType( ((IDMVMContext)parent.getElement()).getDMContext(), IExecutionDMContext.class); - buildDeltaForSuspendedEvent(threadDmc, triggeringCtx, parent, nodeOffset, rm); - } else { - rm.done(); - } - } else if (e instanceof FullStackRefreshEvent) { - FullStackRefreshEvent refreshEvent = (FullStackRefreshEvent)e; - if ( !(refreshEvent.getTriggeringEvent() instanceof IContainerSuspendedDMEvent)) { - // Don't refresh each stack frame when we get an event for the entire container - // Bug 386175 - IExecutionDMContext execDmc = ((FullStackRefreshEvent)e).getDMContext(); - buildDeltaForFullStackRefreshEvent(execDmc, execDmc, parent, nodeOffset, rm); - } else { - rm.done(); - } - } else if (e instanceof ISuspendedDMEvent) { - resetStackFrameLimit( ((ISuspendedDMEvent)e).getDMContext() ); - IExecutionDMContext execDmc = ((ISuspendedDMEvent)e).getDMContext(); - buildDeltaForSuspendedEvent(execDmc, execDmc, parent, nodeOffset, rm); - } else if (e instanceof SteppingTimedOutEvent) { - buildDeltaForSteppingTimedOutEvent((SteppingTimedOutEvent)e, parent, nodeOffset, rm); - } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { - buildDeltaForModelProxyInstalledEvent(parent, nodeOffset, rm); - } else if (e instanceof ExpandStackEvent) { - IExecutionDMContext execDmc = ((ExpandStackEvent)e).getDMContext(); - buildDeltaForExpandStackEvent(execDmc, parent, rm); - } else if (e instanceof PropertyChangeEvent) { - String property = ((PropertyChangeEvent)e).getProperty(); - if (IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT_ENABLE.equals(property) - || IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT.equals(property)) - { - buildDeltaForStackFrameLimitPreferenceChangedEvent(parent, rm); - } else if (IDsfDebugUIConstants.DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY.equals(property)) { - buildDeltaForShowFullPathPreferenceChangedEvent(parent, rm); - } else { - rm.done(); - } - } else { - rm.done(); - } - } - - /** - * Builds the delta in response to a suspended event. - * <p> - * Default behavior is to expand the thread, repaint <strong>only</strong> - * the top stack frame and select it. The rest of the frames will be - * repainted after a short delay. - * - * @since 2.1 - */ - protected void buildDeltaForSuspendedEvent(final IExecutionDMContext executionCtx, final IExecutionDMContext triggeringCtx, final VMDelta parentDelta, final int nodeOffset, final RequestMonitor rm) { - // Check if we are building a delta for the thread that triggered the event. - // Only then expand the stack frames and select the top one. - if (executionCtx.equals(triggeringCtx)) { - // Always expand the thread node to show the stack frames. - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.EXPAND); - - // Retrieve the list of stack frames, and mark the top frame to be selected. - getVMProvider().updateNode( - this, - new VMChildrenUpdate( - parentDelta, getVMProvider().getPresentationContext(), 0, 1, - new DataRequestMonitor<List<Object>>(getExecutor(), rm) { - @Override - public void handleCompleted() { - final List<Object> data= getData(); + rm.done(); + } + })); + return; + } + super.getContextsForEvent(parentDelta, e, rm); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.IVMNode#getDeltaFlags(java.lang.Object) + */ + @Override + public int getDeltaFlags(Object e) { + // This node generates delta if the timers have changed, or if the + // label has changed. + if (e instanceof ISuspendedDMEvent) { + return IModelDelta.CONTENT | IModelDelta.EXPAND | IModelDelta.SELECT; + } else if (e instanceof FullStackRefreshEvent + && !(((FullStackRefreshEvent) e).getTriggeringEvent() instanceof IContainerSuspendedDMEvent)) { + return IModelDelta.CONTENT; + } else if (e instanceof SteppingTimedOutEvent) { + return IModelDelta.CONTENT; + } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { + return IModelDelta.SELECT | IModelDelta.EXPAND; + } else if (e instanceof ExpandStackEvent) { + return IModelDelta.CONTENT; + } else if (e instanceof IExitedDMEvent) { + // Do not generate a delta for this event, but do clear the + // internal stack frame limit to avoid a memory leak. + resetStackFrameLimit(((IExitedDMEvent) e).getDMContext()); + return IModelDelta.NO_CHANGE; + } else if (e instanceof PropertyChangeEvent) { + String property = ((PropertyChangeEvent) e).getProperty(); + if (IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT_ENABLE.equals(property) + || IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT.equals(property)) { + return IModelDelta.CONTENT; + } else if (IDsfDebugUIConstants.DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY.equals(property)) { + return IModelDelta.STATE; + } + } else { + } + + return IModelDelta.NO_CHANGE; + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.IVMNode#buildDelta(java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, int, org.eclipse.cdt.dsf.concurrent.RequestMonitor) + */ + @Override + public void buildDelta(final Object e, final VMDelta parent, final int nodeOffset, final RequestMonitor rm) { + if (e instanceof IContainerSuspendedDMEvent) { + // Clear the limit on the stack frames for all stack frames under a given container. + resetStackFrameLimit(((IContainerSuspendedDMEvent) e).getDMContext()); + + IContainerSuspendedDMEvent csEvent = (IContainerSuspendedDMEvent) e; + + IExecutionDMContext triggeringCtx = csEvent.getTriggeringContexts().length != 0 + ? csEvent.getTriggeringContexts()[0] + : null; + + if (parent.getElement() instanceof IDMVMContext) { + IExecutionDMContext threadDmc = null; + threadDmc = DMContexts.getAncestorOfType(((IDMVMContext) parent.getElement()).getDMContext(), + IExecutionDMContext.class); + buildDeltaForSuspendedEvent(threadDmc, triggeringCtx, parent, nodeOffset, rm); + } else { + rm.done(); + } + } else if (e instanceof FullStackRefreshEvent) { + FullStackRefreshEvent refreshEvent = (FullStackRefreshEvent) e; + if (!(refreshEvent.getTriggeringEvent() instanceof IContainerSuspendedDMEvent)) { + // Don't refresh each stack frame when we get an event for the entire container + // Bug 386175 + IExecutionDMContext execDmc = ((FullStackRefreshEvent) e).getDMContext(); + buildDeltaForFullStackRefreshEvent(execDmc, execDmc, parent, nodeOffset, rm); + } else { + rm.done(); + } + } else if (e instanceof ISuspendedDMEvent) { + resetStackFrameLimit(((ISuspendedDMEvent) e).getDMContext()); + IExecutionDMContext execDmc = ((ISuspendedDMEvent) e).getDMContext(); + buildDeltaForSuspendedEvent(execDmc, execDmc, parent, nodeOffset, rm); + } else if (e instanceof SteppingTimedOutEvent) { + buildDeltaForSteppingTimedOutEvent((SteppingTimedOutEvent) e, parent, nodeOffset, rm); + } else if (e instanceof ModelProxyInstalledEvent || e instanceof DataModelInitializedEvent) { + buildDeltaForModelProxyInstalledEvent(parent, nodeOffset, rm); + } else if (e instanceof ExpandStackEvent) { + IExecutionDMContext execDmc = ((ExpandStackEvent) e).getDMContext(); + buildDeltaForExpandStackEvent(execDmc, parent, rm); + } else if (e instanceof PropertyChangeEvent) { + String property = ((PropertyChangeEvent) e).getProperty(); + if (IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT_ENABLE.equals(property) + || IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT.equals(property)) { + buildDeltaForStackFrameLimitPreferenceChangedEvent(parent, rm); + } else if (IDsfDebugUIConstants.DEBUG_VIEW_SHOW_FULL_PATH_PROPERTY.equals(property)) { + buildDeltaForShowFullPathPreferenceChangedEvent(parent, rm); + } else { + rm.done(); + } + } else { + rm.done(); + } + } + + /** + * Builds the delta in response to a suspended event. + * <p> + * Default behavior is to expand the thread, repaint <strong>only</strong> + * the top stack frame and select it. The rest of the frames will be + * repainted after a short delay. + * + * @since 2.1 + */ + protected void buildDeltaForSuspendedEvent(final IExecutionDMContext executionCtx, + final IExecutionDMContext triggeringCtx, final VMDelta parentDelta, final int nodeOffset, + final RequestMonitor rm) { + // Check if we are building a delta for the thread that triggered the event. + // Only then expand the stack frames and select the top one. + if (executionCtx.equals(triggeringCtx)) { + // Always expand the thread node to show the stack frames. + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.EXPAND); + + // Retrieve the list of stack frames, and mark the top frame to be selected. + getVMProvider().updateNode(this, new VMChildrenUpdate(parentDelta, getVMProvider().getPresentationContext(), + 0, 1, new DataRequestMonitor<List<Object>>(getExecutor(), rm) { + @Override + public void handleCompleted() { + final List<Object> data = getData(); if (data != null && data.size() != 0) { parentDelta.addNode(data.get(0), 0, IModelDelta.SELECT | IModelDelta.STATE); - } - // Even in case of errors, complete the request monitor. - rm.done(); - } - }) - ); - } else { - rm.done(); - } - } - + } + // Even in case of errors, complete the request monitor. + rm.done(); + } + })); + } else { + rm.done(); + } + } + /** - * Builds a delta in response to automatic refresh event generated after - * every suspend event. + * Builds a delta in response to automatic refresh event generated after + * every suspend event. * <p> * The default behavior is to check if the thread is * still stepping or suspended and refresh the stack trace. - * + * * @since 2.1 */ - protected void buildDeltaForFullStackRefreshEvent(final IExecutionDMContext executionCtx, final IExecutionDMContext triggeringCtx, final VMDelta parentDelta, final int nodeOffset, final RequestMonitor rm) { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + protected void buildDeltaForFullStackRefreshEvent(final IExecutionDMContext executionCtx, + final IExecutionDMContext triggeringCtx, final VMDelta parentDelta, final int nodeOffset, + final RequestMonitor rm) { + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - IRunControl runControlService = getServicesTracker().getService(IRunControl.class); - IStack stackService = getServicesTracker().getService(IStack.class); - if (stackService == null || runControlService == null) { - // Required services have not initialized yet. Ignore the event. - rm.done(); - return; - } - - // Refresh the whole list of stack frames unless the target is already stepping the next command. In - // which case, the refresh will occur when the stepping sequence slows down or stops. Trying to - // refresh the whole stack trace with every step would slow down stepping too much. - if (triggeringCtx == null || !runControlService.isStepping(triggeringCtx)) { - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } - - rm.done(); - } - }); - } catch (RejectedExecutionException e) { - // Session shut down, no delta to build. - rm.done(); - } + IRunControl runControlService = getServicesTracker().getService(IRunControl.class); + IStack stackService = getServicesTracker().getService(IStack.class); + if (stackService == null || runControlService == null) { + // Required services have not initialized yet. Ignore the event. + rm.done(); + return; + } + + // Refresh the whole list of stack frames unless the target is already stepping the next command. In + // which case, the refresh will occur when the stepping sequence slows down or stops. Trying to + // refresh the whole stack trace with every step would slow down stepping too much. + if (triggeringCtx == null || !runControlService.isStepping(triggeringCtx)) { + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } + + rm.done(); + } + }); + } catch (RejectedExecutionException e) { + // Session shut down, no delta to build. + rm.done(); + } + } + + /** + * Builds the delta in response to a time-out after stepping over a long + * executing function. + * <p> + * The default behavior is to repainting the stack frame images to + * show the running symbol. + * + * @since 2.1 + */ + protected void buildDeltaForSteppingTimedOutEvent(final SteppingTimedOutEvent e, final VMDelta parentDelta, + final int nodeOffset, final RequestMonitor rm) { + // Repaint the stack frame images to have the running symbol. + //parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + rm.done(); } - - /** - * Builds the delta in response to a time-out after stepping over a long - * executing function. - * <p> - * The default behavior is to repainting the stack frame images to - * show the running symbol. - * - * @since 2.1 - */ - protected void buildDeltaForSteppingTimedOutEvent(final SteppingTimedOutEvent e, final VMDelta parentDelta, final int nodeOffset, final RequestMonitor rm) { - // Repaint the stack frame images to have the running symbol. - //parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - rm.done(); - } - - /** - * Builds the delta in response the debug view being opened. - * <p> - * The default behavior is to retrieve the list of stack frames, - * and mark the top frame to be selected. - * - * @since 2.1 - */ - protected void buildDeltaForModelProxyInstalledEvent(final VMDelta parentDelta, final int nodeOffset, final RequestMonitor rm) { - getVMProvider().updateNode( - this, - new VMChildrenUpdate( - parentDelta, getVMProvider().getPresentationContext(), -1, -1, - new DataRequestMonitor<List<Object>>(getExecutor(), rm) { - @Override - public void handleCompleted() { - if (isSuccess() && getData().size() != 0) { - parentDelta.addNode( getData().get(0), 0, IModelDelta.SELECT | IModelDelta.EXPAND); - } - rm.done(); - } - }) - ); - } - - /** - * Builds the delta in response to the user requesting to retrieve - * additional stack frames (changing the current stack frames limit). - * <p> - * The default behavior is to refresh the stack frames, and to select the - * first frame of the new frames that are retrieved. - * - * @since 2.1 - */ - protected void buildDeltaForExpandStackEvent(IExecutionDMContext execDmc, final VMDelta parentDelta, final RequestMonitor rm) { - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - // Retrieve the list of new stack frames, and mark the first frame to be selected. - final int offset = getStackFrameLimit(execDmc) / 2; - getVMProvider().updateNode( - this, - new VMChildrenUpdate( - parentDelta, getVMProvider().getPresentationContext(), offset, offset, - new DataRequestMonitor<List<Object>>(getExecutor(), rm) { - @Override - public void handleCompleted() { - final List<Object> data= getData(); + + /** + * Builds the delta in response the debug view being opened. + * <p> + * The default behavior is to retrieve the list of stack frames, + * and mark the top frame to be selected. + * + * @since 2.1 + */ + protected void buildDeltaForModelProxyInstalledEvent(final VMDelta parentDelta, final int nodeOffset, + final RequestMonitor rm) { + getVMProvider().updateNode(this, new VMChildrenUpdate(parentDelta, getVMProvider().getPresentationContext(), -1, + -1, new DataRequestMonitor<List<Object>>(getExecutor(), rm) { + @Override + public void handleCompleted() { + if (isSuccess() && getData().size() != 0) { + parentDelta.addNode(getData().get(0), 0, IModelDelta.SELECT | IModelDelta.EXPAND); + } + rm.done(); + } + })); + } + + /** + * Builds the delta in response to the user requesting to retrieve + * additional stack frames (changing the current stack frames limit). + * <p> + * The default behavior is to refresh the stack frames, and to select the + * first frame of the new frames that are retrieved. + * + * @since 2.1 + */ + protected void buildDeltaForExpandStackEvent(IExecutionDMContext execDmc, final VMDelta parentDelta, + final RequestMonitor rm) { + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + // Retrieve the list of new stack frames, and mark the first frame to be selected. + final int offset = getStackFrameLimit(execDmc) / 2; + getVMProvider().updateNode(this, new VMChildrenUpdate(parentDelta, getVMProvider().getPresentationContext(), + offset, offset, new DataRequestMonitor<List<Object>>(getExecutor(), rm) { + @Override + public void handleCompleted() { + final List<Object> data = getData(); if (data != null && data.size() != 0) { parentDelta.addNode(data.get(0), offset, IModelDelta.SELECT); - } - rm.done(); - } - }) - ); - } - - - /** - * Builds the delta in response to the stack frame limit preference changing. - * <p> - * Default behavior is to refresh the stack frames. - * - * @since 2.1 - */ - protected void buildDeltaForStackFrameLimitPreferenceChangedEvent(final VMDelta parentDelta, final RequestMonitor rm) { - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - rm.done(); - } - - private void buildDeltaForShowFullPathPreferenceChangedEvent(final VMDelta parentDelta, final RequestMonitor rm) { - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.STATE); - rm.done(); - } - - private String produceFrameElementName( String viewName , IFrameDMContext frame ) { - /* - * We are addressing Bugzilla 211490 which wants the Register View to keep the same expanded - * state for registers for stack frames within the same thread. Different threads could have - * different register sets ( e.g. one thread may have floating point & another may not ). But - * within a thread we are enforcing the assumption that the register sets will be the same. - * So we make a more convenient work flow by keeping the same expansion when selecting amount - * stack frames within the same thread. We accomplish this by only differentiating by adding - * the level for the Expression/Variables view. Otherwise we do not delineate based on which - * view and this captures the Register View in its filter. + } + rm.done(); + } + })); + } + + /** + * Builds the delta in response to the stack frame limit preference changing. + * <p> + * Default behavior is to refresh the stack frames. + * + * @since 2.1 + */ + protected void buildDeltaForStackFrameLimitPreferenceChangedEvent(final VMDelta parentDelta, + final RequestMonitor rm) { + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + rm.done(); + } + + private void buildDeltaForShowFullPathPreferenceChangedEvent(final VMDelta parentDelta, final RequestMonitor rm) { + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.STATE); + rm.done(); + } + + private String produceFrameElementName(String viewName, IFrameDMContext frame) { + /* + * We are addressing Bugzilla 211490 which wants the Register View to keep the same expanded + * state for registers for stack frames within the same thread. Different threads could have + * different register sets ( e.g. one thread may have floating point & another may not ). But + * within a thread we are enforcing the assumption that the register sets will be the same. + * So we make a more convenient work flow by keeping the same expansion when selecting amount + * stack frames within the same thread. We accomplish this by only differentiating by adding + * the level for the Expression/Variables view. Otherwise we do not delineate based on which + * view and this captures the Register View in its filter. */ - if ( viewName.startsWith(IDebugUIConstants.ID_VARIABLE_VIEW) || - viewName.startsWith(IDebugUIConstants.ID_EXPRESSION_VIEW) ) - { - return "Frame." + frame.getLevel() + "." + frame.getSessionId(); //$NON-NLS-1$ //$NON-NLS-2$ - } - else { - return "Frame" + frame.getSessionId(); //$NON-NLS-1$ - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#compareElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementCompareRequest[]) - */ - @Override + if (viewName.startsWith(IDebugUIConstants.ID_VARIABLE_VIEW) + || viewName.startsWith(IDebugUIConstants.ID_EXPRESSION_VIEW)) { + return "Frame." + frame.getLevel() + "." + frame.getSessionId(); //$NON-NLS-1$ //$NON-NLS-2$ + } else { + return "Frame" + frame.getSessionId(); //$NON-NLS-1$ + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#compareElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementCompareRequest[]) + */ + @Override public void compareElements(IElementCompareRequest[] requests) { - - for ( IElementCompareRequest request : requests ) { - - Object element = request.getElement(); - IMemento memento = request.getMemento(); - String mementoName = memento.getString("STACK_FRAME_MEMENTO_NAME"); //$NON-NLS-1$ - - if (mementoName != null) { - if (element instanceof IDMVMContext) { - - IDMContext dmc = ((IDMVMContext)element).getDMContext(); - - if ( dmc instanceof IFrameDMContext) { - - String elementName = produceFrameElementName( request.getPresentationContext().getId(), (IFrameDMContext) dmc ); - request.setEqual( elementName.equals( mementoName ) ); - } - } - } - request.done(); - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#encodeElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoRequest[]) - */ - @Override + + for (IElementCompareRequest request : requests) { + + Object element = request.getElement(); + IMemento memento = request.getMemento(); + String mementoName = memento.getString("STACK_FRAME_MEMENTO_NAME"); //$NON-NLS-1$ + + if (mementoName != null) { + if (element instanceof IDMVMContext) { + + IDMContext dmc = ((IDMVMContext) element).getDMContext(); + + if (dmc instanceof IFrameDMContext) { + + String elementName = produceFrameElementName(request.getPresentationContext().getId(), + (IFrameDMContext) dmc); + request.setEqual(elementName.equals(mementoName)); + } + } + } + request.done(); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#encodeElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoRequest[]) + */ + @Override public void encodeElements(IElementMementoRequest[] requests) { - - for ( IElementMementoRequest request : requests ) { - - Object element = request.getElement(); - IMemento memento = request.getMemento(); - - if (element instanceof IDMVMContext) { - - IDMContext dmc = ((IDMVMContext)element).getDMContext(); - - if ( dmc instanceof IFrameDMContext) { - - String elementName = produceFrameElementName( request.getPresentationContext().getId(), (IFrameDMContext) dmc ); - memento.putString("STACK_FRAME_MEMENTO_NAME", elementName); //$NON-NLS-1$ - } - } - request.done(); - } - } + + for (IElementMementoRequest request : requests) { + + Object element = request.getElement(); + IMemento memento = request.getMemento(); + + if (element instanceof IDMVMContext) { + + IDMContext dmc = ((IDMVMContext) element).getDMContext(); + + if (dmc instanceof IFrameDMContext) { + + String elementName = produceFrameElementName(request.getPresentationContext().getId(), + (IFrameDMContext) dmc); + memento.putString("STACK_FRAME_MEMENTO_NAME", elementName); //$NON-NLS-1$ + } + } + request.done(); + } + } /** * Get the current active stack frame limit. If no limit is applicable {@link Integer.MAX_VALUE} is returned. - * + * * @return the current stack frame limit - * + * * @since 1.1 */ public int getStackFrameLimit(IExecutionDMContext execCtx) { if (fTemporaryLimits.containsKey(execCtx)) { return fTemporaryLimits.get(execCtx); } - Object stackDepthLimit= getVMProvider().getPresentationContext().getProperty(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT); - if (stackDepthLimit instanceof Integer) { - return (Integer)stackDepthLimit; - } + Object stackDepthLimit = getVMProvider().getPresentationContext() + .getProperty(IDsfDebugUIConstants.PREF_STACK_FRAME_LIMIT); + if (stackDepthLimit instanceof Integer) { + return (Integer) stackDepthLimit; + } return Integer.MAX_VALUE; } /** - * Resets the temporary stack frame limit for the given execution context. + * Resets the temporary stack frame limit for the given execution context. * The stack frame limit should be reset when the a thread is suspended. - * + * * @param execCtx - * + * * @since 2.1 */ - protected void resetStackFrameLimit(IExecutionDMContext execCtx) { - if (execCtx instanceof IContainerDMContext) { - for (Iterator<IExecutionDMContext> itr = fTemporaryLimits.keySet().iterator(); itr.hasNext();) { - IExecutionDMContext limitCtx = itr.next(); - if (limitCtx.equals(execCtx) || DMContexts.isAncestorOf(limitCtx, execCtx)) { - itr.remove(); - } - } - } else { - fTemporaryLimits.remove(execCtx); - } - } - + protected void resetStackFrameLimit(IExecutionDMContext execCtx) { + if (execCtx instanceof IContainerDMContext) { + for (Iterator<IExecutionDMContext> itr = fTemporaryLimits.keySet().iterator(); itr.hasNext();) { + IExecutionDMContext limitCtx = itr.next(); + if (limitCtx.equals(execCtx) || DMContexts.isAncestorOf(limitCtx, execCtx)) { + itr.remove(); + } + } + } else { + fTemporaryLimits.remove(execCtx); + } + } /** * Increment the stack frame limit by the default increment. * This implementation doubles the current limit. - * + * * @since 1.1 */ public void incrementStackFrameLimit(IExecutionDMContext execCtx) { - final int stackFrameLimit= getStackFrameLimit(execCtx); + final int stackFrameLimit = getStackFrameLimit(execCtx); if (stackFrameLimit < Integer.MAX_VALUE / 2) { fTemporaryLimits.put(execCtx, stackFrameLimit * 2); } else { - fTemporaryLimits.put(execCtx, Integer.MAX_VALUE); + fTemporaryLimits.put(execCtx, Integer.MAX_VALUE); } } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/StandardProcessVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/StandardProcessVMNode.java index fedc6094081..230c7252673 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/StandardProcessVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/StandardProcessVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -30,152 +30,150 @@ import org.eclipse.debug.internal.ui.viewers.provisional.ILabelRequestMonitor; import org.eclipse.jface.viewers.TreePath; /** - * Layout node for the standard platform debug model IProcess object. This - * node requires that an ILaunch object be found as an ancestor of this node. - * It does not implement the label provider functionality, so the default - * adapters should be used to retrieve the label. + * Layout node for the standard platform debug model IProcess object. This + * node requires that an ILaunch object be found as an ancestor of this node. + * It does not implement the label provider functionality, so the default + * adapters should be used to retrieve the label. */ @SuppressWarnings("restriction") public class StandardProcessVMNode extends AbstractVMNode { - - public StandardProcessVMNode(AbstractVMProvider provider) { - super(provider); - } - - @Override - public String toString() { - return "StandardProcessVMNode"; //$NON-NLS-1$ - } - - @Override - public void update(IChildrenUpdate[] updates) { - for (IChildrenUpdate update : updates) { - ILaunch launch = findLaunch(update.getElementPath()); - if (launch == null) { - // There is no launch in the parent of this node. This means that the - // layout is misconfigured. - assert false; - update.done(); - continue; - } - - /* - * Assume that the process objects are stored within the launch, and - * retrieve them on dispatch thread. - */ - IProcess[] processes = launch.getProcesses(); - for (int i = 0; i < processes.length; i++) { - update.setChild(processes[i], i); - } - update.done(); - } - } - - @Override - public void update(final IChildrenCountUpdate[] updates) { - for (IChildrenCountUpdate update : updates) { - if (!checkUpdate(update)) continue; - ILaunch launch = findLaunch(update.getElementPath()); - if (launch == null) { - assert false; - update.setChildCount(0); - update.done(); - return; - } - - update.setChildCount(launch.getProcesses().length); - update.done(); - } - } - - // @see org.eclipse.cdt.dsf.ui.viewmodel.IViewModelLayoutNode#hasElements(org.eclipse.cdt.dsf.ui.viewmodel.IVMContext, org.eclipse.cdt.dsf.concurrent.DataRequestMonitor) - @Override - public void update(IHasChildrenUpdate[] updates) { - for (IHasChildrenUpdate update : updates) { - ILaunch launch = findLaunch(update.getElementPath()); - if (launch == null) { - assert false; - update.setHasChilren(false); - update.done(); - return; - } - - update.setHasChilren(launch.getProcesses().length != 0); - update.done(); - } - } - - // @see org.eclipse.cdt.dsf.ui.viewmodel.IViewModelLayoutNode#retrieveLabel(org.eclipse.cdt.dsf.ui.viewmodel.IVMContext, org.eclipse.debug.internal.ui.viewers.provisional.ILabelRequestMonitor) - public void updateLabel(IVMContext vmc, ILabelRequestMonitor result, String[] columns) { - - /* - * The implementation of IAdapterFactory that uses this node should not - * register a label adapter for IProcess. This will cause the default - * label provider to be used instead, and this method should then never - * be called. - */ - assert false; - result.done(); - } - - /** - * Recursively searches the VMC for Launch VMC, and returns its ILaunch. - * Returns null if an ILaunch is not found. - */ - private ILaunch findLaunch(TreePath path) { - for (int i = path.getSegmentCount() - 1; i >= 0; i--) { - if (path.getSegment(i) instanceof ILaunch) { - return (ILaunch)path.getSegment(i); - } - } - return null; - } - - @Override - public int getDeltaFlags(Object e) { - int myFlags = 0; - if (e instanceof DebugEvent) { - DebugEvent de = (DebugEvent)e; - if ( de.getSource() instanceof IProcess && - (de.getKind() == DebugEvent.CHANGE || - de.getKind() == DebugEvent.CREATE || - de.getKind() == DebugEvent.TERMINATE) ) - { - myFlags = IModelDelta.STATE; - } - } - return myFlags; - } - - @Override - public void buildDelta(Object e, VMDelta parent, int nodeOffset, RequestMonitor requestMonitor) { - if (e instanceof DebugEvent && ((DebugEvent)e).getSource() instanceof IProcess) { - DebugEvent de = (DebugEvent)e; - if (de.getKind() == DebugEvent.CHANGE) { - handleChange(de, parent); - } else if (de.getKind() == DebugEvent.CREATE) { - handleCreate(de, parent); - } else if (de.getKind() == DebugEvent.TERMINATE) { - handleTerminate(de, parent); - } - /* - * No other node should need to process events related to process. - * Therefore, just invoke the request monitor without calling super.buildDelta(). - */ - } - requestMonitor.done(); - } - - protected void handleChange(DebugEvent event, ModelDelta parent) { - parent.addNode(event.getSource(), IModelDelta.STATE); - } - - protected void handleCreate(DebugEvent event, ModelDelta parent) { - parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); - } - - protected void handleTerminate(DebugEvent event, ModelDelta parent) { - handleChange(event, parent); - } + + public StandardProcessVMNode(AbstractVMProvider provider) { + super(provider); + } + + @Override + public String toString() { + return "StandardProcessVMNode"; //$NON-NLS-1$ + } + + @Override + public void update(IChildrenUpdate[] updates) { + for (IChildrenUpdate update : updates) { + ILaunch launch = findLaunch(update.getElementPath()); + if (launch == null) { + // There is no launch in the parent of this node. This means that the + // layout is misconfigured. + assert false; + update.done(); + continue; + } + + /* + * Assume that the process objects are stored within the launch, and + * retrieve them on dispatch thread. + */ + IProcess[] processes = launch.getProcesses(); + for (int i = 0; i < processes.length; i++) { + update.setChild(processes[i], i); + } + update.done(); + } + } + + @Override + public void update(final IChildrenCountUpdate[] updates) { + for (IChildrenCountUpdate update : updates) { + if (!checkUpdate(update)) + continue; + ILaunch launch = findLaunch(update.getElementPath()); + if (launch == null) { + assert false; + update.setChildCount(0); + update.done(); + return; + } + + update.setChildCount(launch.getProcesses().length); + update.done(); + } + } + + // @see org.eclipse.cdt.dsf.ui.viewmodel.IViewModelLayoutNode#hasElements(org.eclipse.cdt.dsf.ui.viewmodel.IVMContext, org.eclipse.cdt.dsf.concurrent.DataRequestMonitor) + @Override + public void update(IHasChildrenUpdate[] updates) { + for (IHasChildrenUpdate update : updates) { + ILaunch launch = findLaunch(update.getElementPath()); + if (launch == null) { + assert false; + update.setHasChilren(false); + update.done(); + return; + } + + update.setHasChilren(launch.getProcesses().length != 0); + update.done(); + } + } + + // @see org.eclipse.cdt.dsf.ui.viewmodel.IViewModelLayoutNode#retrieveLabel(org.eclipse.cdt.dsf.ui.viewmodel.IVMContext, org.eclipse.debug.internal.ui.viewers.provisional.ILabelRequestMonitor) + public void updateLabel(IVMContext vmc, ILabelRequestMonitor result, String[] columns) { + + /* + * The implementation of IAdapterFactory that uses this node should not + * register a label adapter for IProcess. This will cause the default + * label provider to be used instead, and this method should then never + * be called. + */ + assert false; + result.done(); + } + + /** + * Recursively searches the VMC for Launch VMC, and returns its ILaunch. + * Returns null if an ILaunch is not found. + */ + private ILaunch findLaunch(TreePath path) { + for (int i = path.getSegmentCount() - 1; i >= 0; i--) { + if (path.getSegment(i) instanceof ILaunch) { + return (ILaunch) path.getSegment(i); + } + } + return null; + } + + @Override + public int getDeltaFlags(Object e) { + int myFlags = 0; + if (e instanceof DebugEvent) { + DebugEvent de = (DebugEvent) e; + if (de.getSource() instanceof IProcess && (de.getKind() == DebugEvent.CHANGE + || de.getKind() == DebugEvent.CREATE || de.getKind() == DebugEvent.TERMINATE)) { + myFlags = IModelDelta.STATE; + } + } + return myFlags; + } + + @Override + public void buildDelta(Object e, VMDelta parent, int nodeOffset, RequestMonitor requestMonitor) { + if (e instanceof DebugEvent && ((DebugEvent) e).getSource() instanceof IProcess) { + DebugEvent de = (DebugEvent) e; + if (de.getKind() == DebugEvent.CHANGE) { + handleChange(de, parent); + } else if (de.getKind() == DebugEvent.CREATE) { + handleCreate(de, parent); + } else if (de.getKind() == DebugEvent.TERMINATE) { + handleTerminate(de, parent); + } + /* + * No other node should need to process events related to process. + * Therefore, just invoke the request monitor without calling super.buildDelta(). + */ + } + requestMonitor.done(); + } + + protected void handleChange(DebugEvent event, ModelDelta parent) { + parent.addNode(event.getSource(), IModelDelta.STATE); + } + + protected void handleCreate(DebugEvent event, ModelDelta parent) { + parent.setFlags(parent.getFlags() | IModelDelta.CONTENT); + } + + protected void handleTerminate(DebugEvent event, ModelDelta parent) { + handleChange(event, parent); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/StateChangedEvent.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/StateChangedEvent.java index 1e49f81d886..e7dd9e5b781 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/StateChangedEvent.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/StateChangedEvent.java @@ -18,7 +18,7 @@ import org.eclipse.cdt.dsf.datamodel.IDMContext; /** * A generic UI state changed event. - * + * * @since 2.2 */ public class StateChangedEvent extends AbstractDMEvent<IDMContext> { diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/actions/ExpandStackAction.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/actions/ExpandStackAction.java index a297d126510..d27f279c277 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/actions/ExpandStackAction.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/launch/actions/ExpandStackAction.java @@ -40,36 +40,36 @@ public class ExpandStackAction extends AbstractVMProviderActionDelegate implemen public void run(IAction action) { Object element = getViewerInput(); if (element instanceof IncompleteStackVMContext) { - IncompleteStackVMContext incStackVmc = ((IncompleteStackVMContext) element); + IncompleteStackVMContext incStackVmc = ((IncompleteStackVMContext) element); IVMNode node = incStackVmc.getVMNode(); if (incStackVmc.getVMNode() instanceof StackFramesVMNode) { - final IExecutionDMContext exeCtx= incStackVmc.getExecutionDMContext(); + final IExecutionDMContext exeCtx = incStackVmc.getExecutionDMContext(); ((StackFramesVMNode) node).incrementStackFrameLimit(exeCtx); final ExpandStackEvent event = new ExpandStackEvent(exeCtx); final AbstractLaunchVMProvider vmProvider = (AbstractLaunchVMProvider) getVMProvider(); vmProvider.getExecutor().execute(new DsfRunnable() { - @Override + @Override public void run() { - vmProvider.handleEvent(event); - } + vmProvider.handleEvent(event); + } }); } } } - @Override - public void init(IViewPart view) { - super.init(view); + @Override + public void init(IViewPart view) { + super.init(view); updateEnablement(); - } - - @Override - public void debugContextChanged(DebugContextEvent event) { - super.debugContextChanged(event); + } + + @Override + public void debugContextChanged(DebugContextEvent event) { + super.debugContextChanged(event); updateEnablement(); - } + } - @Override + @Override public void selectionChanged(IAction action, ISelection selection) { super.selectionChanged(action, selection); updateEnablement(); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/MessagesForModulesVM.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/MessagesForModulesVM.java index 258859c0044..135f437f656 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/MessagesForModulesVM.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/MessagesForModulesVM.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,13 +20,13 @@ import org.eclipse.osgi.util.NLS; * @noinstantiate This class is not intended to be instantiated by clients. */ public class MessagesForModulesVM extends NLS { - public static String ModulesVMNode_No_columns__text_format; + public static String ModulesVMNode_No_columns__text_format; - static { - // initialize resource bundle - NLS.initializeMessages(MessagesForModulesVM.class.getName(), MessagesForModulesVM.class); - } + static { + // initialize resource bundle + NLS.initializeMessages(MessagesForModulesVM.class.getName(), MessagesForModulesVM.class); + } - private MessagesForModulesVM() { - } + private MessagesForModulesVM() { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/ModulesVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/ModulesVMNode.java index caa6c539ddd..bcbff3d2307 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/ModulesVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/ModulesVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Ericsson AB - Modules view for DSF implementation @@ -52,180 +52,180 @@ import org.eclipse.jface.resource.JFaceResources; /** * @since 1.0 - */ -public class ModulesVMNode extends AbstractDMVMNode - implements IElementLabelProvider, IElementPropertiesProvider -{ - /** - * Marker type for the modules VM context. It allows action enablement - * expressions to check for module context type. - */ - public class ModuleVMContext extends DMVMContext { - protected ModuleVMContext(IDMContext dmc) { - super(dmc); - } - } - - /** - * @since 2.0 - */ - public static final String PROP_IS_LOADED = "is_loaded"; //$NON-NLS-1$ - - - /** - * The label provider delegate. This VM node will delegate label updates to this provider - * which can be created by sub-classes. - * - * @since 2.0 - */ - private IElementLabelProvider fLabelProvider; - - /** - * Creates the label provider delegate. This VM node will delegate label - * updates to this provider which can be created by sub-classes. - * - * @return Returns the label provider for this node. - * - * @since 2.0 - */ - protected IElementLabelProvider createLabelProvider() { - PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); - - provider.setColumnInfo( - PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText(MessagesForModulesVM.ModulesVMNode_No_columns__text_format, new String[] { PROP_NAME }), - new DsfUILabelImage(IDsfDebugUIConstants.IMG_OBJS_SHARED_LIBRARY_SYMBOLS_LOADED) { - { setPropertyNames(new String[] { PROP_IS_LOADED }); } - - @Override - public boolean checkProperty(String propertyName, IStatus status, Map<String,Object> properties) { - if (PROP_IS_LOADED.equals(propertyName)) { - return Boolean.TRUE.equals( properties.get(propertyName) ); - } - return super.checkProperty(propertyName, status, properties); - }; - }, - new DsfUILabelImage(IDsfDebugUIConstants.IMG_OBJS_SHARED_LIBRARY_SYMBOLS_UNLOADED), - new StaleDataLabelBackground(), - new LabelFont(JFaceResources.getFontDescriptor(IDebugUIConstants.PREF_VARIABLE_TEXT_FONT).getFontData()[0]) - })); - - return provider; - } - - public ModulesVMNode(AbstractDMVMProvider provider, DsfSession session) { - super(provider, session, IModuleDMContext.class); - - fLabelProvider = createLabelProvider(); - } - - @Override - public String toString() { - return "ModulesVMNode(" + getSession().getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - } - - @Override - protected void updateElementsInSessionThread(final IChildrenUpdate update) { - IModules modulesService = getServicesTracker().getService(IModules.class); - final ISymbolDMContext symDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), ISymbolDMContext.class) ; - - if (modulesService == null || symDmc == null) { - handleFailedUpdate(update); - return; - } - - modulesService.getModules( - symDmc, - new ViewerDataRequestMonitor<IModuleDMContext[]>(getSession().getExecutor(), update) { - @Override - public void handleCompleted() { - if (!isSuccess()) { - update.done(); - return; - } - fillUpdateWithVMCs(update, getData()); - update.done(); - }}); - } - - @Override - protected IDMVMContext createVMContext(IDMContext dmc) { - return new ModuleVMContext(dmc); - } - - /* - * @since 2.0 - */ - @Override - public void update(final IPropertiesUpdate[] updates) { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - updatePropertiesInSessionThread(updates); - }}); - } catch (RejectedExecutionException e) { - for (IPropertiesUpdate update : updates) { - handleFailedUpdate(update); - } - } - } - - @Override - public void update(final ILabelUpdate[] updates) { - fLabelProvider.update(updates); - } - - /** - * @since 2.0 - */ - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { - IModules modulesService = getServicesTracker().getService(IModules.class); - for (final IPropertiesUpdate update : updates) { - final IModuleDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IModuleDMContext.class); - // If either update or service are not valid, fail the update and exit. - if ( modulesService == null || dmc == null ) { - handleFailedUpdate(update); - return; - } - - modulesService.getModuleData( - dmc, - new ViewerDataRequestMonitor<IModuleDMData>(getSession().getExecutor(), update) { - @Override - protected void handleSuccess() { - fillModuleDataProperties(update, getData()); - update.done(); - } - }); - } - } - - /** - * @since 2.0 - */ - protected void fillModuleDataProperties(IPropertiesUpdate update, IModuleDMData data) { - update.setProperty(PROP_NAME, data.getName()); - update.setProperty(PROP_IS_LOADED, data.isSymbolsLoaded()); - } - - @Override - public int getDeltaFlags(Object e) { - if (e instanceof IRunControl.ISuspendedDMEvent) { - return IModelDelta.CONTENT; - } - return IModelDelta.NO_CHANGE; - } - - @Override - public void buildDelta(Object e, VMDelta parentDelta, int nodeOffset, RequestMonitor rm) { - if (e instanceof IRunControl.ISuspendedDMEvent) { - // Create a delta that indicates all groups have changed - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } - - rm.done(); - } + */ +public class ModulesVMNode extends AbstractDMVMNode implements IElementLabelProvider, IElementPropertiesProvider { + /** + * Marker type for the modules VM context. It allows action enablement + * expressions to check for module context type. + */ + public class ModuleVMContext extends DMVMContext { + protected ModuleVMContext(IDMContext dmc) { + super(dmc); + } + } + + /** + * @since 2.0 + */ + public static final String PROP_IS_LOADED = "is_loaded"; //$NON-NLS-1$ + + /** + * The label provider delegate. This VM node will delegate label updates to this provider + * which can be created by sub-classes. + * + * @since 2.0 + */ + private IElementLabelProvider fLabelProvider; + + /** + * Creates the label provider delegate. This VM node will delegate label + * updates to this provider which can be created by sub-classes. + * + * @return Returns the label provider for this node. + * + * @since 2.0 + */ + protected IElementLabelProvider createLabelProvider() { + PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); + + provider.setColumnInfo(PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, + new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForModulesVM.ModulesVMNode_No_columns__text_format, + new String[] { PROP_NAME }), + new DsfUILabelImage(IDsfDebugUIConstants.IMG_OBJS_SHARED_LIBRARY_SYMBOLS_LOADED) { + { + setPropertyNames(new String[] { PROP_IS_LOADED }); + } + + @Override + public boolean checkProperty(String propertyName, IStatus status, + Map<String, Object> properties) { + if (PROP_IS_LOADED.equals(propertyName)) { + return Boolean.TRUE.equals(properties.get(propertyName)); + } + return super.checkProperty(propertyName, status, properties); + }; + }, new DsfUILabelImage(IDsfDebugUIConstants.IMG_OBJS_SHARED_LIBRARY_SYMBOLS_UNLOADED), + new StaleDataLabelBackground(), new LabelFont(JFaceResources + .getFontDescriptor(IDebugUIConstants.PREF_VARIABLE_TEXT_FONT).getFontData()[0]) })); + + return provider; + } + + public ModulesVMNode(AbstractDMVMProvider provider, DsfSession session) { + super(provider, session, IModuleDMContext.class); + + fLabelProvider = createLabelProvider(); + } + + @Override + public String toString() { + return "ModulesVMNode(" + getSession().getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } + + @Override + protected void updateElementsInSessionThread(final IChildrenUpdate update) { + IModules modulesService = getServicesTracker().getService(IModules.class); + final ISymbolDMContext symDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + ISymbolDMContext.class); + + if (modulesService == null || symDmc == null) { + handleFailedUpdate(update); + return; + } + + modulesService.getModules(symDmc, + new ViewerDataRequestMonitor<IModuleDMContext[]>(getSession().getExecutor(), update) { + @Override + public void handleCompleted() { + if (!isSuccess()) { + update.done(); + return; + } + fillUpdateWithVMCs(update, getData()); + update.done(); + } + }); + } + + @Override + protected IDMVMContext createVMContext(IDMContext dmc) { + return new ModuleVMContext(dmc); + } + + /* + * @since 2.0 + */ + @Override + public void update(final IPropertiesUpdate[] updates) { + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + updatePropertiesInSessionThread(updates); + } + }); + } catch (RejectedExecutionException e) { + for (IPropertiesUpdate update : updates) { + handleFailedUpdate(update); + } + } + } + + @Override + public void update(final ILabelUpdate[] updates) { + fLabelProvider.update(updates); + } + + /** + * @since 2.0 + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { + IModules modulesService = getServicesTracker().getService(IModules.class); + for (final IPropertiesUpdate update : updates) { + final IModuleDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IModuleDMContext.class); + // If either update or service are not valid, fail the update and exit. + if (modulesService == null || dmc == null) { + handleFailedUpdate(update); + return; + } + + modulesService.getModuleData(dmc, + new ViewerDataRequestMonitor<IModuleDMData>(getSession().getExecutor(), update) { + @Override + protected void handleSuccess() { + fillModuleDataProperties(update, getData()); + update.done(); + } + }); + } + } + + /** + * @since 2.0 + */ + protected void fillModuleDataProperties(IPropertiesUpdate update, IModuleDMData data) { + update.setProperty(PROP_NAME, data.getName()); + update.setProperty(PROP_IS_LOADED, data.isSymbolsLoaded()); + } + + @Override + public int getDeltaFlags(Object e) { + if (e instanceof IRunControl.ISuspendedDMEvent) { + return IModelDelta.CONTENT; + } + return IModelDelta.NO_CHANGE; + } + + @Override + public void buildDelta(Object e, VMDelta parentDelta, int nodeOffset, RequestMonitor rm) { + if (e instanceof IRunControl.ISuspendedDMEvent) { + // Create a delta that indicates all groups have changed + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } + + rm.done(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/ModulesVMProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/ModulesVMProvider.java index 47a57d3ad16..423dc6edbfa 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/ModulesVMProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/ModulesVMProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Ericsson AB - Modules view for DSF implementation @@ -33,46 +33,47 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationCont * @since 1.0 */ public class ModulesVMProvider extends AbstractDMVMProvider { - /* - * Current default for register formatting. - */ - public ModulesVMProvider(AbstractVMAdapter adapter, IPresentationContext context, DsfSession session) { - super(adapter, context, session); - - /* - * Create the top level node to deal with the root selection. - */ - IRootVMNode rootNode = new RootDMVMNode(this); - - /* - * Create the Group nodes next. They represent the first level shown in the view. - */ - IVMNode modulesNode = new ModulesVMNode(this, getSession()); - addChildNodes(rootNode, new IVMNode[] { modulesNode }); - - /* - * Now set this schema set as the layout set. - */ - setRootNode(rootNode); - } - - @Override - public void refresh() { - super.refresh(); - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + /* + * Current default for register formatting. + */ + public ModulesVMProvider(AbstractVMAdapter adapter, IPresentationContext context, DsfSession session) { + super(adapter, context, session); + + /* + * Create the top level node to deal with the root selection. + */ + IRootVMNode rootNode = new RootDMVMNode(this); + + /* + * Create the Group nodes next. They represent the first level shown in the view. + */ + IVMNode modulesNode = new ModulesVMNode(this, getSession()); + addChildNodes(rootNode, new IVMNode[] { modulesNode }); + + /* + * Now set this schema set as the layout set. + */ + setRootNode(rootNode); + } + + @Override + public void refresh() { + super.refresh(); + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), getSession().getId()); - IModules modulesService = tracker.getService(IModules.class); - if (modulesService instanceof ICachingService) { - ((ICachingService)modulesService).flushCache(null); - } - tracker.dispose(); - } - }); - } catch (RejectedExecutionException e) { - // Session disposed, ignore. - } - } + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + getSession().getId()); + IModules modulesService = tracker.getService(IModules.class); + if (modulesService instanceof ICachingService) { + ((ICachingService) modulesService).flushCache(null); + } + tracker.dispose(); + } + }); + } catch (RejectedExecutionException e) { + // Session disposed, ignore. + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModuleDetailPane.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModuleDetailPane.java index 847d7375c73..b06cffb5522 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModuleDetailPane.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModuleDetailPane.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation * QNX Software Systems - Mikhail Khodjaiants - Registers View (Bug 53640) @@ -16,7 +16,6 @@ *******************************************************************************/ package org.eclipse.cdt.dsf.debug.ui.viewmodel.modules.detail; - import java.util.concurrent.ExecutionException; import org.eclipse.cdt.debug.ui.ICDebugUIConstants; @@ -73,472 +72,487 @@ import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.progress.WorkbenchJob; import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds; - /** - * + * */ public class ModuleDetailPane extends ModulesAbstractDetailPane implements IAdaptable, IPropertyChangeListener { - /** - * These are the IDs for the actions in the context menu - */ - protected static final String DETAIL_COPY_ACTION = ActionFactory.COPY.getId() + ".SourceDetailPane"; //$NON-NLS-1$ - protected static final String DETAIL_SELECT_ALL_ACTION = IDebugView.SELECT_ALL_ACTION + ".SourceDetailPane"; //$NON-NLS-1$ - - /** - * The ID, name and description of this pane are stored in constants so that the class - * does not have to be instantiated to access them. - */ - public static final String ID = "ModuleDetailPane"; //$NON-NLS-1$ - public static final String NAME = "Module Viewer"; //$NON-NLS-1$ - public static final String DESCRIPTION = "A detail pane that is based on a source viewer. Displays as text and has actions for assigning values, content assist and text modifications."; //$NON-NLS-1$ - - - /** - * The source viewer in which the computed string detail - * of selected modules will be displayed. - */ - private SourceViewer fSourceViewer; - @Override - public Control createControl(Composite parent) { - createSourceViewer(parent); - - if (isInView()){ - createViewSpecificComponents(); - createActions(); - DsfUIPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); - JFaceResources.getFontRegistry().addListener(this); - } - return fSourceViewer.getControl(); + /** + * These are the IDs for the actions in the context menu + */ + protected static final String DETAIL_COPY_ACTION = ActionFactory.COPY.getId() + ".SourceDetailPane"; //$NON-NLS-1$ + protected static final String DETAIL_SELECT_ALL_ACTION = IDebugView.SELECT_ALL_ACTION + ".SourceDetailPane"; //$NON-NLS-1$ + + /** + * The ID, name and description of this pane are stored in constants so that the class + * does not have to be instantiated to access them. + */ + public static final String ID = "ModuleDetailPane"; //$NON-NLS-1$ + public static final String NAME = "Module Viewer"; //$NON-NLS-1$ + public static final String DESCRIPTION = "A detail pane that is based on a source viewer. Displays as text and has actions for assigning values, content assist and text modifications."; //$NON-NLS-1$ + + /** + * The source viewer in which the computed string detail + * of selected modules will be displayed. + */ + private SourceViewer fSourceViewer; + + @Override + public Control createControl(Composite parent) { + createSourceViewer(parent); + + if (isInView()) { + createViewSpecificComponents(); + createActions(); + DsfUIPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); + JFaceResources.getFontRegistry().addListener(this); + } + return fSourceViewer.getControl(); } - - private DetailJob fDetailJob = null; - @Override + + private DetailJob fDetailJob = null; + + @Override public void display(IStructuredSelection selection) { - if (selection == null){ - clearSourceViewer(); - return; - } - - if (isInView()){ - fSourceViewer.setEditable(true); - } - - if (selection.isEmpty()){ - clearSourceViewer(); - return; - } - - synchronized (this) { - if (fDetailJob != null) { - fDetailJob.cancel(); - } - fDetailJob = new DetailJob(selection.getFirstElement()); - fDetailJob.schedule(); - } - + if (selection == null) { + clearSourceViewer(); + return; + } + + if (isInView()) { + fSourceViewer.setEditable(true); + } + + if (selection.isEmpty()) { + clearSourceViewer(); + return; + } + + synchronized (this) { + if (fDetailJob != null) { + fDetailJob.cancel(); + } + fDetailJob = new DetailJob(selection.getFirstElement()); + fDetailJob.schedule(); + } + + } + + /** + * Clears the source viewer, removes all text. + */ + protected void clearSourceViewer() { + if (fDetailJob != null) { + fDetailJob.cancel(); + } + fDetailDocument.set(""); //$NON-NLS-1$ + fSourceViewer.setEditable(false); } - - /** - * Clears the source viewer, removes all text. - */ - protected void clearSourceViewer(){ - if (fDetailJob != null) { - fDetailJob.cancel(); - } - fDetailDocument.set(""); //$NON-NLS-1$ - fSourceViewer.setEditable(false); - } - + @Override public void dispose() { super.dispose(); - if (fDetailJob != null) fDetailJob.cancel(); - if (fSourceViewer != null && fSourceViewer.getControl() != null) fSourceViewer.getControl().dispose(); - - if (isInView()){ - DsfUIPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); - JFaceResources.getFontRegistry().removeListener(this); - } - + if (fDetailJob != null) + fDetailJob.cancel(); + if (fSourceViewer != null && fSourceViewer.getControl() != null) + fSourceViewer.getControl().dispose(); + + if (isInView()) { + DsfUIPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); + JFaceResources.getFontRegistry().removeListener(this); + } + } - @Override + + @Override public String getDescription() { - return DESCRIPTION; + return DESCRIPTION; } - @Override + + @Override public String getID() { - return ID; + return ID; } - @Override + + @Override public String getName() { - return NAME; + return NAME; } - - @Override + + @Override public boolean setFocus() { - if (fSourceViewer != null){ - fSourceViewer.getTextWidget().setFocus(); - return true; - } - return false; + if (fSourceViewer != null) { + fSourceViewer.getTextWidget().setFocus(); + return true; + } + return false; } - - @SuppressWarnings("unchecked") + + @SuppressWarnings("unchecked") @Override public <T> T getAdapter(Class<T> adapter) { - if (ITextViewer.class.equals(adapter)) { - return (T)fSourceViewer; - } - return null; + if (ITextViewer.class.equals(adapter)) { + return (T) fSourceViewer; + } + return null; } - - @Override + + @Override public void propertyChange(PropertyChangeEvent event) { - String propertyName= event.getProperty(); - if (propertyName.equals(IDebugUIConstants.PREF_DETAIL_PANE_FONT)) { - fSourceViewer.getTextWidget().setFont(JFaceResources.getFont(IDebugUIConstants.PREF_DETAIL_PANE_FONT)); - } + String propertyName = event.getProperty(); + if (propertyName.equals(IDebugUIConstants.PREF_DETAIL_PANE_FONT)) { + fSourceViewer.getTextWidget().setFont(JFaceResources.getFont(IDebugUIConstants.PREF_DETAIL_PANE_FONT)); + } + } + + /** + * Creates the source viewer in the given parent composite + * + * @param parent Parent composite to create the source viewer in + */ + private void createSourceViewer(Composite parent) { + + // Create & configure a SourceViewer + fSourceViewer = new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL); + fSourceViewer.setDocument(getDetailDocument()); + fSourceViewer.getTextWidget().setFont(JFaceResources.getFont(IDebugUIConstants.PREF_DETAIL_PANE_FONT)); + fSourceViewer.getTextWidget().setWordWrap(DsfUIPlugin.getDefault().getPreferenceStore() + .getBoolean(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP)); + fSourceViewer.setEditable(false); + PlatformUI.getWorkbench().getHelpSystem().setHelp(fSourceViewer.getTextWidget(), + IDsfDebugHelpContextIds.DETAIL_PANE); + Control control = fSourceViewer.getControl(); + GridData gd = new GridData(GridData.FILL_BOTH); + control.setLayoutData(gd); } - - - /** - * Creates the source viewer in the given parent composite - * - * @param parent Parent composite to create the source viewer in - */ - private void createSourceViewer(Composite parent) { - - // Create & configure a SourceViewer - fSourceViewer = new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL); - fSourceViewer.setDocument(getDetailDocument()); - fSourceViewer.getTextWidget().setFont(JFaceResources.getFont(IDebugUIConstants.PREF_DETAIL_PANE_FONT)); - fSourceViewer.getTextWidget().setWordWrap(DsfUIPlugin.getDefault().getPreferenceStore().getBoolean(IInternalDsfDebugUIConstants.PREF_DETAIL_PANE_WORD_WRAP)); - fSourceViewer.setEditable(false); - PlatformUI.getWorkbench().getHelpSystem().setHelp(fSourceViewer.getTextWidget(), IDsfDebugHelpContextIds.DETAIL_PANE); - Control control = fSourceViewer.getControl(); - GridData gd = new GridData(GridData.FILL_BOTH); - control.setLayoutData(gd); - } - - /** - * Variables used to create the detailed information for a selection - */ - private IDocument fDetailDocument; - - /** - * Lazily instantiate and return a Document for the detail pane text viewer. - */ - protected IDocument getDetailDocument() { - if (fDetailDocument == null) { - fDetailDocument = new Document(); - } - return fDetailDocument; - } - - /** - * Creates listeners and other components that should only be added to the - * source viewer when this detail pane is inside a view. - */ - private void createViewSpecificComponents(){ - - // Add a document listener so actions get updated when the document changes - getDetailDocument().addDocumentListener(new IDocumentListener() { - @Override - public void documentAboutToBeChanged(DocumentEvent event) {} - @Override - public void documentChanged(DocumentEvent event) { - updateSelectionDependentActions(); - } - }); - - // Add the selection listener so selection dependent actions get updated. - fSourceViewer.getSelectionProvider().addSelectionChangedListener(new ISelectionChangedListener() { - @Override - public void selectionChanged(SelectionChangedEvent event) { - updateSelectionDependentActions(); - } - }); - - // Add a focus listener to update actions when details area gains focus - fSourceViewer.getControl().addFocusListener(new FocusAdapter() { - @Override + + /** + * Variables used to create the detailed information for a selection + */ + private IDocument fDetailDocument; + + /** + * Lazily instantiate and return a Document for the detail pane text viewer. + */ + protected IDocument getDetailDocument() { + if (fDetailDocument == null) { + fDetailDocument = new Document(); + } + return fDetailDocument; + } + + /** + * Creates listeners and other components that should only be added to the + * source viewer when this detail pane is inside a view. + */ + private void createViewSpecificComponents() { + + // Add a document listener so actions get updated when the document changes + getDetailDocument().addDocumentListener(new IDocumentListener() { + @Override + public void documentAboutToBeChanged(DocumentEvent event) { + } + + @Override + public void documentChanged(DocumentEvent event) { + updateSelectionDependentActions(); + } + }); + + // Add the selection listener so selection dependent actions get updated. + fSourceViewer.getSelectionProvider().addSelectionChangedListener(new ISelectionChangedListener() { + @Override + public void selectionChanged(SelectionChangedEvent event) { + updateSelectionDependentActions(); + } + }); + + // Add a focus listener to update actions when details area gains focus + fSourceViewer.getControl().addFocusListener(new FocusAdapter() { + @Override public void focusGained(FocusEvent e) { - - getViewSite().setSelectionProvider(fSourceViewer.getSelectionProvider()); - - setGlobalAction(IDebugView.SELECT_ALL_ACTION, getAction(DETAIL_SELECT_ALL_ACTION)); - setGlobalAction(IDebugView.COPY_ACTION, getAction(DETAIL_COPY_ACTION)); - - getViewSite().getActionBars().updateActionBars(); - } - - @Override + + getViewSite().setSelectionProvider(fSourceViewer.getSelectionProvider()); + + setGlobalAction(IDebugView.SELECT_ALL_ACTION, getAction(DETAIL_SELECT_ALL_ACTION)); + setGlobalAction(IDebugView.COPY_ACTION, getAction(DETAIL_COPY_ACTION)); + + getViewSite().getActionBars().updateActionBars(); + } + + @Override public void focusLost(FocusEvent e) { - - getViewSite().setSelectionProvider(null); - - setGlobalAction(IDebugView.SELECT_ALL_ACTION, null); - setGlobalAction(IDebugView.COPY_ACTION, null); - getViewSite().getActionBars().updateActionBars(); - - } - }); - - // Add a context menu to the detail area - createDetailContextMenu(fSourceViewer.getTextWidget()); - } - - /** - * Create the context menu particular to the detail pane. Note that anyone - * wishing to contribute an action to this menu must use - * <code>ICDebugUIConstants.MODULES_VIEW_DETAIL_ID</code> as the - * <code>targetID</code> in the extension XML. - */ - protected void createDetailContextMenu(Control menuControl) { - MenuManager menuMgr= new MenuManager(); - menuMgr.setRemoveAllWhenShown(true); - menuMgr.addMenuListener(new IMenuListener() { - @Override - public void menuAboutToShow(IMenuManager mgr) { - fillDetailContextMenu(mgr); - } - }); - Menu menu= menuMgr.createContextMenu(menuControl); - menuControl.setMenu(menu); - - getViewSite().registerContextMenu(ICDebugUIConstants.MODULES_VIEW_DETAIL_ID, menuMgr, fSourceViewer.getSelectionProvider()); - - } - /** - * Adds items to the detail pane's context menu including any extension defined - * actions. - * - * @param menu The menu to add the item to. - */ - protected void fillDetailContextMenu(IMenuManager menu) { - - menu.add(new Separator(ICDebugUIConstants.MODULES_GROUP)); - menu.add(new Separator()); - menu.add(getAction(DETAIL_COPY_ACTION)); - menu.add(getAction(DETAIL_SELECT_ALL_ACTION)); - menu.add(new Separator()); - menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); - - } - /** - * Creates the actions to add to the context menu - */ - private void createActions() { - TextViewerAction textAction= new TextViewerAction(fSourceViewer, ITextOperationTarget.SELECT_ALL); - textAction.configureAction(MessagesForDetailPane.DetailPane_Select_All, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ - textAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.SELECT_ALL); - PlatformUI.getWorkbench().getHelpSystem().setHelp(textAction, IDsfDebugHelpContextIds.DETAIL_PANE_SELECT_ALL_ACTION); - setAction(DETAIL_SELECT_ALL_ACTION, textAction); - - textAction= new TextViewerAction(fSourceViewer, ITextOperationTarget.COPY); - textAction.configureAction(MessagesForDetailPane.DetailPane_Copy, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ - textAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY); - PlatformUI.getWorkbench().getHelpSystem().setHelp(textAction, IDsfDebugHelpContextIds.DETAIL_PANE_COPY_ACTION); - setAction(DETAIL_COPY_ACTION, textAction); - - setSelectionDependantAction(DETAIL_COPY_ACTION); - - updateSelectionDependentActions(); - } - - - /** - * Job to compute the details for a selection - */ - class DetailJob extends Job { - - private Object fElement; - // whether a result was collected - private IProgressMonitor fMonitor; - - public DetailJob(Object element) { - super("compute module details"); //$NON-NLS-1$ - setSystem(true); - fElement = element; - } - - /* (non-Javadoc) - * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) - */ - @Override + + getViewSite().setSelectionProvider(null); + + setGlobalAction(IDebugView.SELECT_ALL_ACTION, null); + setGlobalAction(IDebugView.COPY_ACTION, null); + getViewSite().getActionBars().updateActionBars(); + + } + }); + + // Add a context menu to the detail area + createDetailContextMenu(fSourceViewer.getTextWidget()); + } + + /** + * Create the context menu particular to the detail pane. Note that anyone + * wishing to contribute an action to this menu must use + * <code>ICDebugUIConstants.MODULES_VIEW_DETAIL_ID</code> as the + * <code>targetID</code> in the extension XML. + */ + protected void createDetailContextMenu(Control menuControl) { + MenuManager menuMgr = new MenuManager(); + menuMgr.setRemoveAllWhenShown(true); + menuMgr.addMenuListener(new IMenuListener() { + @Override + public void menuAboutToShow(IMenuManager mgr) { + fillDetailContextMenu(mgr); + } + }); + Menu menu = menuMgr.createContextMenu(menuControl); + menuControl.setMenu(menu); + + getViewSite().registerContextMenu(ICDebugUIConstants.MODULES_VIEW_DETAIL_ID, menuMgr, + fSourceViewer.getSelectionProvider()); + + } + + /** + * Adds items to the detail pane's context menu including any extension defined + * actions. + * + * @param menu The menu to add the item to. + */ + protected void fillDetailContextMenu(IMenuManager menu) { + + menu.add(new Separator(ICDebugUIConstants.MODULES_GROUP)); + menu.add(new Separator()); + menu.add(getAction(DETAIL_COPY_ACTION)); + menu.add(getAction(DETAIL_SELECT_ALL_ACTION)); + menu.add(new Separator()); + menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); + + } + + /** + * Creates the actions to add to the context menu + */ + private void createActions() { + TextViewerAction textAction = new TextViewerAction(fSourceViewer, ITextOperationTarget.SELECT_ALL); + textAction.configureAction(MessagesForDetailPane.DetailPane_Select_All, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ + textAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.SELECT_ALL); + PlatformUI.getWorkbench().getHelpSystem().setHelp(textAction, + IDsfDebugHelpContextIds.DETAIL_PANE_SELECT_ALL_ACTION); + setAction(DETAIL_SELECT_ALL_ACTION, textAction); + + textAction = new TextViewerAction(fSourceViewer, ITextOperationTarget.COPY); + textAction.configureAction(MessagesForDetailPane.DetailPane_Copy, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ + textAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY); + PlatformUI.getWorkbench().getHelpSystem().setHelp(textAction, IDsfDebugHelpContextIds.DETAIL_PANE_COPY_ACTION); + setAction(DETAIL_COPY_ACTION, textAction); + + setSelectionDependantAction(DETAIL_COPY_ACTION); + + updateSelectionDependentActions(); + } + + /** + * Job to compute the details for a selection + */ + class DetailJob extends Job { + + private Object fElement; + // whether a result was collected + private IProgressMonitor fMonitor; + + public DetailJob(Object element) { + super("compute module details"); //$NON-NLS-1$ + setSystem(true); + fElement = element; + } + + /* (non-Javadoc) + * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) + */ + @Override protected IStatus run(IProgressMonitor monitor) { - fMonitor = monitor; - /* - * Make sure this is an element we want to deal with. - */ - IModuleDMContext dmc = null; - if (fElement instanceof IDMVMContext) { - IDMContext vmcdmc = ((IDMVMContext)fElement).getDMContext(); - dmc = DMContexts.getAncestorOfType(vmcdmc, IModuleDMContext.class); - } - - if (dmc == null) return Status.OK_STATUS; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) return Status.OK_STATUS; - - /* - * Create the query to write the value to the service. Note: no need to - * guard against RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - GetModuleDetailsQuery query = new GetModuleDetailsQuery(dmc); - session.getExecutor().execute(query); - - /* - * Now we have the data, go and get it. Since the call is completed now - * the ".get()" will not suspend it will immediately return with the - * data. - */ - try { - detailComputed(getModuleDetail((IModuleDMData) query.get())); - } catch (InterruptedException e) { - assert false; - return Status.OK_STATUS; - } catch (ExecutionException e) { - return Status.OK_STATUS; - } - return Status.OK_STATUS; - } - - /** - * Set the module details in the detail pane view - * @param result - */ + fMonitor = monitor; + /* + * Make sure this is an element we want to deal with. + */ + IModuleDMContext dmc = null; + if (fElement instanceof IDMVMContext) { + IDMContext vmcdmc = ((IDMVMContext) fElement).getDMContext(); + dmc = DMContexts.getAncestorOfType(vmcdmc, IModuleDMContext.class); + } + + if (dmc == null) + return Status.OK_STATUS; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return Status.OK_STATUS; + + /* + * Create the query to write the value to the service. Note: no need to + * guard against RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + GetModuleDetailsQuery query = new GetModuleDetailsQuery(dmc); + session.getExecutor().execute(query); + + /* + * Now we have the data, go and get it. Since the call is completed now + * the ".get()" will not suspend it will immediately return with the + * data. + */ + try { + detailComputed(getModuleDetail((IModuleDMData) query.get())); + } catch (InterruptedException e) { + assert false; + return Status.OK_STATUS; + } catch (ExecutionException e) { + return Status.OK_STATUS; + } + return Status.OK_STATUS; + } + + /** + * Set the module details in the detail pane view + * @param result + */ private void detailComputed(final String result) { - if (!fMonitor.isCanceled()) { - WorkbenchJob setDetail = new WorkbenchJob("set details") { //$NON-NLS-1$ - @Override + if (!fMonitor.isCanceled()) { + WorkbenchJob setDetail = new WorkbenchJob("set details") { //$NON-NLS-1$ + @Override public IStatus runInUIThread(IProgressMonitor monitor) { - if (!fMonitor.isCanceled()) { - getDetailDocument().set(result); - } - return Status.OK_STATUS; - } - }; - setDetail.setSystem(true); - setDetail.schedule(); - } - } - - } - - /** - * To get the details of the given module selected in Modules View - * @param module - * @return - */ - private String getModuleDetail( IModuleDMData module ) { - StringBuilder sb = new StringBuilder(); - - // Type - String type = null; -// switch( module.getType() ) { -// case ICModule.EXECUTABLE: -// type = ModulesMessages.getString( "ModulesView.Executable" ); //$NON-NLS-1$ -// break; -// case ICModule.SHARED_LIBRARY: -// type = ModulesMessages.getString( "ModulesView.SharedLibrary" ); //$NON-NLS-1$ -// break; -// } - type = ModulesMessages.getString( "ModulesView.SharedLibrary" ); //$NON-NLS-1$ - if ( type != null ) { - sb.append( ModulesMessages.getString( "ModulesView.Type" ) ); //$NON-NLS-1$ - sb.append( type ); - sb.append( '\n' ); - } - - // Symbols flag - sb.append( ModulesMessages.getString( "ModulesView.Symbols" ) ); //$NON-NLS-1$ - sb.append( ( module.isSymbolsLoaded()) ? ModulesMessages.getString( "ModulesView.Loaded" ) : ModulesMessages.getString( "ModulesView.NotLoaded" ) ); //$NON-NLS-1$ //$NON-NLS-2$ - sb.append( '\n' ); - - // Symbols file - sb.append( ModulesMessages.getString( "ModulesView.SymbolsFile" ) ); //$NON-NLS-1$ - sb.append( module.getFile()); - sb.append( '\n' ); - - // Base address - String baseAddress = module.getBaseAddress(); - sb.append( ModulesMessages.getString( "ModulesView.BaseAddress" ) ); //$NON-NLS-1$ - sb.append( baseAddress ); - sb.append( '\n' ); - - // Size - long size = module.getSize(); - if ( size > 0 ) { - sb.append( ModulesMessages.getString( "ModulesView.Size" ) ); //$NON-NLS-1$ - sb.append( size ); - sb.append( '\n' ); - } - - return sb.toString(); - } - - - public class GetModuleDetailsQuery extends Query<Object> { - - private IModuleDMContext fDmc; - - public GetModuleDetailsQuery(IModuleDMContext dmc) { - super(); - fDmc = dmc; - } - - @Override - protected void execute(final DataRequestMonitor<Object> rm) { - /* - * We're in another dispatch, so we must guard against executor - * shutdown again. - */ - final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); - if (session == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Debug session already shut down.", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - /* - * Guard against a disposed service - */ - DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fDmc.getSessionId()); - IModules service = tracker.getService(IModules.class); - tracker.dispose(); - if (service == null) { - rm .setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Service unavailable", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - service.getModuleData(fDmc, new DataRequestMonitor<IModuleDMData>( session.getExecutor(), rm) { - @Override - protected void handleCompleted() { - /* - * We're in another dispatch, so we must guard against executor shutdown again. - */ - if (!DsfSession.isSessionActive(session.getId())) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Debug session already shut down.", null)); //$NON-NLS-1$ - rm.done(); - return; - } - super.handleCompleted(); - } - - @Override - protected void handleSuccess() { - /* - * All good set return value. - */ - rm.setData(getData()); - rm.done(); - } - }); - } - } -} + if (!fMonitor.isCanceled()) { + getDetailDocument().set(result); + } + return Status.OK_STATUS; + } + }; + setDetail.setSystem(true); + setDetail.schedule(); + } + } + + } + + /** + * To get the details of the given module selected in Modules View + * @param module + * @return + */ + private String getModuleDetail(IModuleDMData module) { + StringBuilder sb = new StringBuilder(); + + // Type + String type = null; + // switch( module.getType() ) { + // case ICModule.EXECUTABLE: + // type = ModulesMessages.getString( "ModulesView.Executable" ); //$NON-NLS-1$ + // break; + // case ICModule.SHARED_LIBRARY: + // type = ModulesMessages.getString( "ModulesView.SharedLibrary" ); //$NON-NLS-1$ + // break; + // } + type = ModulesMessages.getString("ModulesView.SharedLibrary"); //$NON-NLS-1$ + if (type != null) { + sb.append(ModulesMessages.getString("ModulesView.Type")); //$NON-NLS-1$ + sb.append(type); + sb.append('\n'); + } + + // Symbols flag + sb.append(ModulesMessages.getString("ModulesView.Symbols")); //$NON-NLS-1$ + sb.append((module.isSymbolsLoaded()) ? ModulesMessages.getString("ModulesView.Loaded") //$NON-NLS-1$ + : ModulesMessages.getString("ModulesView.NotLoaded")); //$NON-NLS-1$ + sb.append('\n'); + + // Symbols file + sb.append(ModulesMessages.getString("ModulesView.SymbolsFile")); //$NON-NLS-1$ + sb.append(module.getFile()); + sb.append('\n'); + + // Base address + String baseAddress = module.getBaseAddress(); + sb.append(ModulesMessages.getString("ModulesView.BaseAddress")); //$NON-NLS-1$ + sb.append(baseAddress); + sb.append('\n'); + // Size + long size = module.getSize(); + if (size > 0) { + sb.append(ModulesMessages.getString("ModulesView.Size")); //$NON-NLS-1$ + sb.append(size); + sb.append('\n'); + } + + return sb.toString(); + } + + public class GetModuleDetailsQuery extends Query<Object> { + + private IModuleDMContext fDmc; + + public GetModuleDetailsQuery(IModuleDMContext dmc) { + super(); + fDmc = dmc; + } + + @Override + protected void execute(final DataRequestMonitor<Object> rm) { + /* + * We're in another dispatch, so we must guard against executor + * shutdown again. + */ + final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); + if (session == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Debug session already shut down.", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + /* + * Guard against a disposed service + */ + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fDmc.getSessionId()); + IModules service = tracker.getService(IModules.class); + tracker.dispose(); + if (service == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Service unavailable", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + service.getModuleData(fDmc, new DataRequestMonitor<IModuleDMData>(session.getExecutor(), rm) { + @Override + protected void handleCompleted() { + /* + * We're in another dispatch, so we must guard against executor shutdown again. + */ + if (!DsfSession.isSessionActive(session.getId())) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Debug session already shut down.", null)); //$NON-NLS-1$ + rm.done(); + return; + } + super.handleCompleted(); + } + + @Override + protected void handleSuccess() { + /* + * All good set return value. + */ + rm.setData(getData()); + rm.done(); + } + }); + } + } +} diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModuleDetailPaneFactory.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModuleDetailPaneFactory.java index af09d48db17..7e119eb80a3 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModuleDetailPaneFactory.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModuleDetailPaneFactory.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Ericsson AB - Modules view for DSF implementation *******************************************************************************/ @@ -22,6 +22,7 @@ import org.eclipse.jface.viewers.IStructuredSelection; public class ModuleDetailPaneFactory implements IDetailPaneFactory { public static final String MODULE_DETAIL_PANE_ID = ModuleDetailPane.ID; + @Override public IDetailPane createDetailPane(String paneID) { return new ModuleDetailPane(); @@ -34,7 +35,7 @@ public class ModuleDetailPaneFactory implements IDetailPaneFactory { @Override public String getDetailPaneDescription(String paneID) { - if (paneID.equals(ModuleDetailPane.ID)){ + if (paneID.equals(ModuleDetailPane.ID)) { return ModuleDetailPane.DESCRIPTION; } return null; @@ -42,7 +43,7 @@ public class ModuleDetailPaneFactory implements IDetailPaneFactory { @Override public String getDetailPaneName(String paneID) { - if (paneID.equals(ModuleDetailPane.ID)){ + if (paneID.equals(ModuleDetailPane.ID)) { return ModuleDetailPane.NAME; } return null; diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModulesAbstractDetailPane.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModulesAbstractDetailPane.java index 54bb6e85079..79ac995dad9 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModulesAbstractDetailPane.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModulesAbstractDetailPane.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation * Wind River Systems - adopted to use with Modules view @@ -32,22 +32,22 @@ import org.eclipse.ui.texteditor.IUpdate; public abstract class ModulesAbstractDetailPane implements IDetailPane { /** - * The <code>IWorkbenchPartSite</code> that the details area (and the + * The <code>IWorkbenchPartSite</code> that the details area (and the * variables view) belongs to. */ private IWorkbenchPartSite fWorkbenchPartSite; - + /** * Map of actions. Keys are strings, values * are <code>IAction</code>. */ - private Map<String,IAction> fActionMap = new HashMap<String,IAction>(); - + private Map<String, IAction> fActionMap = new HashMap<String, IAction>(); + /** * Collection to track actions that should be updated when selection occurs. */ private List<String> fSelectionActions = new ArrayList<String>(); - + /* (non-Javadoc) * @see org.eclipse.debug.ui.IDetailPane#init(org.eclipse.ui.IWorkbenchPartSite) */ @@ -56,7 +56,7 @@ public abstract class ModulesAbstractDetailPane implements IDetailPane { fWorkbenchPartSite = workbench; } - + /* (non-Javadoc) * @see org.eclipse.debug.ui.IDetailPane#dispose() */ @@ -68,7 +68,7 @@ public abstract class ModulesAbstractDetailPane implements IDetailPane { /** * Adds an action to the Map storing actions. Removes it if action is null. - * + * * @param actionID The ID of the action, used as the key in the Map * @param action The action associated with the ID */ @@ -79,76 +79,77 @@ public abstract class ModulesAbstractDetailPane implements IDetailPane { fActionMap.put(actionID, action); } } - + /** * Adds the given action to the global action handler for the ViewSite. * A call to <code>updateActionBars()</code> must be called after changes * to propagate changes through the workbench. - * + * * @param actionID The ID of the action * @param action The action to be set globally */ - protected void setGlobalAction(String actionID, IAction action){ + protected void setGlobalAction(String actionID, IAction action) { getViewSite().getActionBars().setGlobalActionHandler(actionID, action); } - + /** * Adds the given action to the list of actions that will be updated when - * <code>updateSelectionDependentActions()</code> is called. If the string + * <code>updateSelectionDependentActions()</code> is called. If the string * is null it will not be added to the list. - * + * * @param actionID The ID of the action which should be updated */ - protected void setSelectionDependantAction(String actionID){ - if (actionID != null) fSelectionActions.add(actionID); + protected void setSelectionDependantAction(String actionID) { + if (actionID != null) + fSelectionActions.add(actionID); } - + /** * Gets the action out of the map, casts it to an <code>IAction</code> - * + * * @param actionID The ID of the action to find * @return The action associated with the ID or null if none is found. */ protected IAction getAction(String actionID) { return fActionMap.get(actionID); } - + /** * Calls the update method of the action with the given action ID. * The action must exist in the action map and must be an instance of * </code>IUpdate</code> - * + * * @param actionId The ID of the action to update */ protected void updateAction(String actionId) { - IAction action= getAction(actionId); + IAction action = getAction(actionId); if (action instanceof IUpdate) { ((IUpdate) action).update(); } } - + /** - * Iterates through the list of selection dependent actions and + * Iterates through the list of selection dependent actions and * updates them. Use <code>setSelectionDependentAction(String actionID)</code> - * to add an action to the list. The action must have been added to the known + * to add an action to the list. The action must have been added to the known * actions map by calling <code>setAction(String actionID, IAction action)</code> * before it can be updated by this method. */ protected void updateSelectionDependentActions() { - Iterator<String> iterator= fSelectionActions.iterator(); + Iterator<String> iterator = fSelectionActions.iterator(); while (iterator.hasNext()) { - updateAction(iterator.next()); + updateAction(iterator.next()); } } - + /** * Gets the view site for this view. May be null if this detail pane * is not part of a view. - * + * * @return The site for this view or <code>null</code> */ - protected IViewSite getViewSite(){ - if (fWorkbenchPartSite == null){ + protected IViewSite getViewSite() { + if (fWorkbenchPartSite == null) { return null; } else { return (IViewSite) fWorkbenchPartSite.getPart().getSite(); @@ -158,19 +159,19 @@ public abstract class ModulesAbstractDetailPane implements IDetailPane { /** * Gets the workbench part site for this view. May be null if this detail pane * is not part of a view. - * + * * @return The workbench part site or <code>null</code> */ protected IWorkbenchPartSite getWorkbenchPartSite() { return fWorkbenchPartSite; } - + /** * Returns whether this detail pane is being displayed in a view with a workbench part site. - * + * * @return whether this detail pane is being displayed in a view with a workbench part site. */ - protected boolean isInView(){ + protected boolean isInView() { return fWorkbenchPartSite != null; } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModulesMessages.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModulesMessages.java index 05662eb18b4..a5809a87019 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModulesMessages.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/modules/detail/ModulesMessages.java @@ -24,16 +24,15 @@ public class ModulesMessages { private static final String BUNDLE_NAME = "org.eclipse.cdt.dsf.debug.ui.viewmodel.modules.detail.ModulesMessages";//$NON-NLS-1$ - private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME ); + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); private ModulesMessages() { } - public static String getString( String key ) { + public static String getString(String key) { try { - return RESOURCE_BUNDLE.getString( key ); - } - catch( MissingResourceException e ) { + return RESOURCE_BUNDLE.getString(key); + } catch (MissingResourceException e) { return '!' + key + '!'; } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/AbstractElementVMProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/AbstractElementVMProvider.java index dae3f2cf735..fddd4c7c0f8 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/AbstractElementVMProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/AbstractElementVMProvider.java @@ -28,11 +28,10 @@ import org.eclipse.jface.viewers.TreePath; * Extending classes can override {@link #supportFormat(IVMContext)} to return false * if they do not want to support individual element formatting. */ -abstract public class AbstractElementVMProvider extends AbstractDMVMProvider implements IElementFormatProvider -{ +abstract public class AbstractElementVMProvider extends AbstractDMVMProvider implements IElementFormatProvider { private final IElementFormatProvider fElementFormatProvider; - - public AbstractElementVMProvider(AbstractVMAdapter adapter, IPresentationContext context, DsfSession session) { + + public AbstractElementVMProvider(AbstractVMAdapter adapter, IPresentationContext context, DsfSession session) { super(adapter, context, session); fElementFormatProvider = createElementNumberFormatProvider(this, getSession()); } @@ -40,10 +39,11 @@ abstract public class AbstractElementVMProvider extends AbstractDMVMProvider imp @Override public void dispose() { if (fElementFormatProvider instanceof ElementNumberFormatProvider) { - ((ElementNumberFormatProvider)fElementFormatProvider).dispose(); + ((ElementNumberFormatProvider) fElementFormatProvider).dispose(); } super.dispose(); } + protected IElementFormatProvider createElementNumberFormatProvider(IVMProvider provider, DsfSession session) { return new ElementNumberFormatProvider(provider, session); } @@ -55,12 +55,13 @@ abstract public class AbstractElementVMProvider extends AbstractDMVMProvider imp @Override public void getActiveFormat(IPresentationContext context, IVMNode node, Object viewerInput, TreePath elementPath, - DataRequestMonitor<String> rm) { + DataRequestMonitor<String> rm) { fElementFormatProvider.getActiveFormat(context, node, viewerInput, elementPath, rm); } @Override - public void setActiveFormat(IPresentationContext context, IVMNode[] node, Object viewerInput, TreePath[] elementPaths, String format) { + public void setActiveFormat(IPresentationContext context, IVMNode[] node, Object viewerInput, + TreePath[] elementPaths, String format) { fElementFormatProvider.setActiveFormat(context, node, viewerInput, elementPaths, format); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/ElementNumberFormatProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/ElementNumberFormatProvider.java index 4f7531eb7aa..c85bb231b68 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/ElementNumberFormatProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/ElementNumberFormatProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -51,59 +51,58 @@ import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; /** - * Default implementation of the {@link IElementFormatProvider}. It can be - * used within any {@link IVMProvider} to store and persist number-formats + * Default implementation of the {@link IElementFormatProvider}. It can be + * used within any {@link IVMProvider} to store and persist number-formats * selected by user for different elements. - * + * * @since 2.5 */ -public class ElementNumberFormatProvider implements IElementFormatProvider -{ +public class ElementNumberFormatProvider implements IElementFormatProvider { private static final String ELEMENT_FORMAT_PERSISTABLE_PROPERTY = "org.eclipse.cdt.dsf.ui.elementFormatPersistable"; //$NON-NLS-1$ private static final String FILTER_PROVIDER_ID = ElementNumberFormatProvider.class.getName() + ".eventFilter"; //$NON-NLS-1$ - private final IVMProvider fVMProvider; - private final DsfSession fSession; - private final Dictionary<String, String> fFilterProperties = new Hashtable<>(); - - public ElementNumberFormatProvider(IVMProvider vmProvider, DsfSession session) { - fVMProvider = vmProvider; - fSession = session; - initialize(); + private final IVMProvider fVMProvider; + private final DsfSession fSession; + private final Dictionary<String, String> fFilterProperties = new Hashtable<>(); + + public ElementNumberFormatProvider(IVMProvider vmProvider, DsfSession session) { + fVMProvider = vmProvider; + fSession = session; + initialize(); } - protected void initialize() { - IPresentationContext presentationCtx = getVMProvider().getPresentationContext(); - - IWorkbenchPart part = presentationCtx.getPart(); - String provider; - if (part != null) { - // Use an id that is unique to the instance of the view - // Note that although each view, including cloned ones, has its own presentation context, - // the presentation context id returned by getPresentationContext().getId() is the - // same for cloned views even though the presentation context itself is different. - // So we cannot use getPresentationContext().getId() as an unique id. - // Using the title of the view is also problematic as that title can - // be modified by a pin action (bug 511057) - // To get a fixed unique id for each cloned view we can use the name of the part - if (part instanceof IWorkbenchPart2) { - provider = ((IWorkbenchPart2)part).getPartName(); - } else { - provider = part.getTitle(); - } - } else { - // In some cases, we are not dealing with a part, e.g., the hover. - // In this case, use the presentation context id directly. - // Note that the hover will probably not provide per-element formating, - // but some extenders may choose to do so. - provider = getVMProvider().getPresentationContext().getId(); - } - - // Create the filter properties targeted at our provider, to be used when sending events - fFilterProperties.put(FILTER_PROVIDER_ID, provider); - - // Properly formatted OSGI filter string aimed at our provider - String filterStr = "(&(" + FILTER_PROVIDER_ID + "=" + provider + "))"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + protected void initialize() { + IPresentationContext presentationCtx = getVMProvider().getPresentationContext(); + + IWorkbenchPart part = presentationCtx.getPart(); + String provider; + if (part != null) { + // Use an id that is unique to the instance of the view + // Note that although each view, including cloned ones, has its own presentation context, + // the presentation context id returned by getPresentationContext().getId() is the + // same for cloned views even though the presentation context itself is different. + // So we cannot use getPresentationContext().getId() as an unique id. + // Using the title of the view is also problematic as that title can + // be modified by a pin action (bug 511057) + // To get a fixed unique id for each cloned view we can use the name of the part + if (part instanceof IWorkbenchPart2) { + provider = ((IWorkbenchPart2) part).getPartName(); + } else { + provider = part.getTitle(); + } + } else { + // In some cases, we are not dealing with a part, e.g., the hover. + // In this case, use the presentation context id directly. + // Note that the hover will probably not provide per-element formating, + // but some extenders may choose to do so. + provider = getVMProvider().getPresentationContext().getId(); + } + + // Create the filter properties targeted at our provider, to be used when sending events + fFilterProperties.put(FILTER_PROVIDER_ID, provider); + + // Properly formatted OSGI filter string aimed at our provider + String filterStr = "(&(" + FILTER_PROVIDER_ID + "=" + provider + "))"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ try { final Filter filter = DsfUIPlugin.getBundleContext().createFilter(filterStr); @@ -119,9 +118,9 @@ public class ElementNumberFormatProvider implements IElementFormatProvider assert false : e.getMessage(); } catch (RejectedExecutionException e) { } - } + } - public void dispose() { + public void dispose() { try { fSession.getExecutor().execute(new DsfRunnable() { @Override @@ -130,125 +129,122 @@ public class ElementNumberFormatProvider implements IElementFormatProvider } }); } catch (RejectedExecutionException e) { - } - } - - @DsfServiceEventHandler - public final void eventDispatched(ElementFormatEvent event) { + } + } + + @DsfServiceEventHandler + public final void eventDispatched(ElementFormatEvent event) { if (getVMProvider() instanceof AbstractVMProvider) { - ((AbstractVMProvider)getVMProvider()).handleEvent(event); + ((AbstractVMProvider) getVMProvider()).handleEvent(event); } } - - private IVMProvider getVMProvider() { - return fVMProvider; - } - - @Override - public void getActiveFormat(IPresentationContext context, IVMNode node, Object viewerInput, final TreePath elementPath, - final DataRequestMonitor<String> rm) - { - getElementKey( - viewerInput, elementPath, - new ImmediateDataRequestMonitor<String>(rm) { - @Override - protected void handleSuccess() { - SimpleMapPersistable<String> persistable = getPersistable(); - rm.done(persistable.getValue(getData())); - } - }); - } - - @Override + + private IVMProvider getVMProvider() { + return fVMProvider; + } + + @Override + public void getActiveFormat(IPresentationContext context, IVMNode node, Object viewerInput, + final TreePath elementPath, final DataRequestMonitor<String> rm) { + getElementKey(viewerInput, elementPath, new ImmediateDataRequestMonitor<String>(rm) { + @Override + protected void handleSuccess() { + SimpleMapPersistable<String> persistable = getPersistable(); + rm.done(persistable.getValue(getData())); + } + }); + } + + @Override public void setActiveFormat(IPresentationContext context, IVMNode[] node, Object viewerInput, - TreePath[] elementPaths, final String format) - { - final HashSet<Object> elementsToRefresh = new HashSet<>(); - final CountingRequestMonitor crm = new ImmediateCountingRequestMonitor() { - @Override - protected void handleCompleted() { - if (!elementsToRefresh.isEmpty()) { - // Send the event to all DSF sessions as they share the same view and the - // change of format will affect them as well. This is because they key - // we use from this implementation of getElementKey() is not specific to - // a session (and should not be if we want to have proper persistence). - for (DsfSession session : DsfSession.getActiveSessions()) { - // Use the filterProperties to specify that this event only impacts the current view. - session.dispatchEvent(new ElementFormatEvent(elementsToRefresh, 1), fFilterProperties); - } - } - } - }; - for (final TreePath path : elementPaths) { - getElementKey( - viewerInput, path, - new ImmediateDataRequestMonitor<String>(crm) { - @Override - protected void handleSuccess() { - SimpleMapPersistable<String> persistable = getPersistable(); - persistable.setValue(getData(), format); - elementsToRefresh.add(path.getLastSegment()); - crm.done(); - } - }); - } - crm.setDoneCount(elementPaths.length); - } - - @Override + TreePath[] elementPaths, final String format) { + final HashSet<Object> elementsToRefresh = new HashSet<>(); + final CountingRequestMonitor crm = new ImmediateCountingRequestMonitor() { + @Override + protected void handleCompleted() { + if (!elementsToRefresh.isEmpty()) { + // Send the event to all DSF sessions as they share the same view and the + // change of format will affect them as well. This is because they key + // we use from this implementation of getElementKey() is not specific to + // a session (and should not be if we want to have proper persistence). + for (DsfSession session : DsfSession.getActiveSessions()) { + // Use the filterProperties to specify that this event only impacts the current view. + session.dispatchEvent(new ElementFormatEvent(elementsToRefresh, 1), fFilterProperties); + } + } + } + }; + for (final TreePath path : elementPaths) { + getElementKey(viewerInput, path, new ImmediateDataRequestMonitor<String>(crm) { + @Override + protected void handleSuccess() { + SimpleMapPersistable<String> persistable = getPersistable(); + persistable.setValue(getData(), format); + elementsToRefresh.add(path.getLastSegment()); + crm.done(); + } + }); + } + crm.setDoneCount(elementPaths.length); + } + + @Override public boolean supportFormat(IVMContext context) { - if (context instanceof IDMVMContext) { - // The expressions view supports expression groups, which have no value, - // so we should not support formatting for expression groups. - if (((IDMVMContext)context).getDMContext() instanceof IExpressionGroupDMContext) { - return false; - } - } - return context instanceof IFormattedValueVMContext; - } - - // We do not make the element key session-specific or else when we start a new session for the same - // program, the format we chose will not be persisted. Instead, make the format change valid for - // any session, even if other sessions run a different program. The idea is that a user usually - // names her variables similarly so the chosen format should apply properly anyway. - protected void getElementKey(Object viewerInput, TreePath elementPath, final DataRequestMonitor<String> rm) { - Object element = elementPath.getLastSegment(); - if (element instanceof IDMVMContext) { - final IDMContext dmc = ((IDMVMContext)element).getDMContext(); + if (context instanceof IDMVMContext) { + // The expressions view supports expression groups, which have no value, + // so we should not support formatting for expression groups. + if (((IDMVMContext) context).getDMContext() instanceof IExpressionGroupDMContext) { + return false; + } + } + return context instanceof IFormattedValueVMContext; + } + + // We do not make the element key session-specific or else when we start a new session for the same + // program, the format we chose will not be persisted. Instead, make the format change valid for + // any session, even if other sessions run a different program. The idea is that a user usually + // names her variables similarly so the chosen format should apply properly anyway. + protected void getElementKey(Object viewerInput, TreePath elementPath, final DataRequestMonitor<String> rm) { + Object element = elementPath.getLastSegment(); + if (element instanceof IDMVMContext) { + final IDMContext dmc = ((IDMVMContext) element).getDMContext(); if (dmc instanceof IExpressionDMContext) { - rm.done(((IExpressionDMContext)dmc).getExpression()); + rm.done(((IExpressionDMContext) dmc).getExpression()); return; } else if (dmc instanceof IRegisterDMContext) { - fSession.getExecutor().execute(new DsfRunnable() { + fSession.getExecutor().execute(new DsfRunnable() { @Override public void run() { - DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), fSession.getId()); + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + fSession.getId()); IRegisters regService = tracker.getService(IRegisters.class); tracker.dispose(); - - regService.getRegisterData((IRegisterDMContext)dmc, new ImmediateDataRequestMonitor<IRegisterDMData>(rm) { - @Override - protected void handleSuccess() { - rm.done(getData().getName()); - } - }); + + regService.getRegisterData((IRegisterDMContext) dmc, + new ImmediateDataRequestMonitor<IRegisterDMData>(rm) { + @Override + protected void handleSuccess() { + rm.done(getData().getName()); + } + }); } }); return; } } - rm.done(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, "Cannot calculate peristable key for element: " + element, null)); //$NON-NLS-1$ - } + rm.done(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, + "Cannot calculate peristable key for element: " + element, null)); //$NON-NLS-1$ + } - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") protected SimpleMapPersistable<String> getPersistable() { - Object p = getVMProvider().getPresentationContext().getProperty(ELEMENT_FORMAT_PERSISTABLE_PROPERTY); - if (p instanceof SimpleMapPersistable) { - return (SimpleMapPersistable<String>)p; - } else { - SimpleMapPersistable<String> persistable = new SimpleMapPersistable<>(String.class); - getVMProvider().getPresentationContext().setProperty(ELEMENT_FORMAT_PERSISTABLE_PROPERTY, persistable); - return persistable; - } - } + Object p = getVMProvider().getPresentationContext().getProperty(ELEMENT_FORMAT_PERSISTABLE_PROPERTY); + if (p instanceof SimpleMapPersistable) { + return (SimpleMapPersistable<String>) p; + } else { + SimpleMapPersistable<String> persistable = new SimpleMapPersistable<>(String.class); + getVMProvider().getPresentationContext().setProperty(ELEMENT_FORMAT_PERSISTABLE_PROPERTY, persistable); + return persistable; + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/ElementNumberFormatsContribution.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/ElementNumberFormatsContribution.java index 0c4740c71ce..42a81e2ec53 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/ElementNumberFormatsContribution.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/ElementNumberFormatsContribution.java @@ -45,7 +45,7 @@ import org.eclipse.swt.widgets.MenuItem; /** * Dynamic menu contribution that shows available number formats in the current * selection of the view. - * + * * @since 2.2 */ public class ElementNumberFormatsContribution extends NumberFormatsContribution { @@ -60,8 +60,8 @@ public class ElementNumberFormatsContribution extends NumberFormatsContribution SelectFormatAction(IElementFormatProvider provider, IPresentationContext context, IVMNode[] nodes, Object viewerInput, TreePath[] elementPaths, String formatId) { - super(formatId == null ? MessagesForNumberFormat.ElementNumberFormatContribution_RestoreToPreference_label : - FormattedValueVMUtil.getFormatLabel(formatId), + super(formatId == null ? MessagesForNumberFormat.ElementNumberFormatContribution_RestoreToPreference_label + : FormattedValueVMUtil.getFormatLabel(formatId), formatId == null ? AS_PUSH_BUTTON : AS_RADIO_BUTTON); fProvider = provider; fContext = context; @@ -83,21 +83,19 @@ public class ElementNumberFormatsContribution extends NumberFormatsContribution } } - protected static IContributionItem[] NO_ITEMS = new IContributionItem[] { - new ContributionItem() { - @Override - public void fill(Menu menu, int index) { - MenuItem item = new MenuItem(menu, SWT.NONE); - item.setEnabled(false); - item.setText(MessagesForNumberFormat.NumberFormatContribution_EmptyFormatsList_label); - } - - @Override - public boolean isEnabled() { - return false; - } + protected static IContributionItem[] NO_ITEMS = new IContributionItem[] { new ContributionItem() { + @Override + public void fill(Menu menu, int index) { + MenuItem item = new MenuItem(menu, SWT.NONE); + item.setEnabled(false); + item.setText(MessagesForNumberFormat.NumberFormatContribution_EmptyFormatsList_label); } - }; + + @Override + public boolean isEnabled() { + return false; + } + } }; @Override protected IContributionItem[] getContributionItems() { @@ -105,13 +103,13 @@ public class ElementNumberFormatsContribution extends NumberFormatsContribution if (selection == null || selection.isEmpty() || selection instanceof ITreeSelection == false) { return NO_ITEMS; } - + IVMProvider provider = VMHandlerUtils.getVMProviderForSelection(selection); if (provider instanceof IElementFormatProvider == false) { return NO_ITEMS; } - - IPresentationContext context = provider.getPresentationContext(); + + IPresentationContext context = provider.getPresentationContext(); Object viewerInput = VMHandlerUtils.getViewerInput(context); TreePath[] elementPaths = ((ITreeSelection) selection).getPaths(); List<String> availableFormats = getAvailableFormats(provider, viewerInput, elementPaths); @@ -122,20 +120,20 @@ public class ElementNumberFormatsContribution extends NumberFormatsContribution IVMNode[] nodes = new IVMNode[elementPaths.length]; final List<SelectFormatAction> actions = new ArrayList<SelectFormatAction>(availableFormats.size()); for (String formatId : availableFormats) { - actions.add(new SelectFormatAction((IElementFormatProvider) provider, - context, nodes, viewerInput, elementPaths, formatId)); + actions.add(new SelectFormatAction((IElementFormatProvider) provider, context, nodes, viewerInput, + elementPaths, formatId)); } final String[] elementActiveFormats = new String[elementPaths.length]; - CountingRequestMonitor crm = new CountingRequestMonitor(SimpleDisplayExecutor.getSimpleDisplayExecutor(Display.getDefault()), null) { + CountingRequestMonitor crm = new CountingRequestMonitor( + SimpleDisplayExecutor.getSimpleDisplayExecutor(Display.getDefault()), null) { @Override protected void handleCompleted() { String activeFormat = null; for (int i = 0; i < elementActiveFormats.length; i++) { if (i == 0) { activeFormat = elementActiveFormats[i]; - } else if (activeFormat != null - && activeFormat.equals(elementActiveFormats[i]) == false) { + } else if (activeFormat != null && activeFormat.equals(elementActiveFormats[i]) == false) { activeFormat = null; break; } @@ -160,12 +158,12 @@ public class ElementNumberFormatsContribution extends NumberFormatsContribution final int index = i; ((IElementFormatProvider) provider).getActiveFormat(context, nodes[i], viewerInput, elementPaths[i], new DataRequestMonitor<String>(ImmediateExecutor.getInstance(), crm) { - @Override - protected void handleSuccess() { - elementActiveFormats[index] = this.getData(); - super.handleSuccess(); - } - }); + @Override + protected void handleSuccess() { + elementActiveFormats[index] = this.getData(); + super.handleSuccess(); + } + }); } crm.setDoneCount(elementPaths.length); int count = actions.size(); @@ -182,7 +180,7 @@ public class ElementNumberFormatsContribution extends NumberFormatsContribution */ private List<String> getAvailableFormats(IVMProvider provider, Object viewerInput, TreePath[] paths) { if (provider instanceof ICachingVMProviderExtension2) { - ICachingVMProviderExtension2 cachingProvider = (ICachingVMProviderExtension2)provider; + ICachingVMProviderExtension2 cachingProvider = (ICachingVMProviderExtension2) provider; String[] formats = null; for (TreePath path : paths) { @@ -190,7 +188,8 @@ public class ElementNumberFormatsContribution extends NumberFormatsContribution if (node != null) { ICacheEntry cacheEntry = cachingProvider.getCacheEntry(node, viewerInput, path); if (cacheEntry != null && cacheEntry.getProperties() != null) { - String[] entryFormats = (String[]) cacheEntry.getProperties().get(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS); + String[] entryFormats = (String[]) cacheEntry.getProperties() + .get(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS); if (entryFormats == null) { // At least one element has no formats. Use the default ones. return FORMATS; diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/FormattedValueLabelText.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/FormattedValueLabelText.java index fc26d0af2d1..97ae7b4aeb8 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/FormattedValueLabelText.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/FormattedValueLabelText.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -24,74 +24,74 @@ import com.ibm.icu.text.MessageFormat; /** * Label attribute that fills in the formatted value text using the active * number format for the view. - * + * * @since 2.0 */ public class FormattedValueLabelText extends LabelText { - private final String fPropertyPrefix; - private final String PROP_ACTIVE_FORMAT; - private final String PROP_ACTIVE_FORMAT_VALUE; - - public FormattedValueLabelText() { - this(MessagesForNumberFormat.FormattedValueLabelText__text_format, new String[0], ""); //$NON-NLS-1$ - } + private final String fPropertyPrefix; + private final String PROP_ACTIVE_FORMAT; + private final String PROP_ACTIVE_FORMAT_VALUE; + + public FormattedValueLabelText() { + this(MessagesForNumberFormat.FormattedValueLabelText__text_format, new String[0], ""); //$NON-NLS-1$ + } + + public FormattedValueLabelText(String popertyPrefix) { + this(MessagesForNumberFormat.FormattedValueLabelText__text_format, new String[0], popertyPrefix); + } + + public FormattedValueLabelText(String formatPattern, String[] propertyNames) { + this(formatPattern, propertyNames, ""); //$NON-NLS-1$ + } - public FormattedValueLabelText(String popertyPrefix) { - this(MessagesForNumberFormat.FormattedValueLabelText__text_format, new String[0], popertyPrefix); - } + public FormattedValueLabelText(String formatPattern, String[] propertyNames, String propertyPrefix) { + super(formatPattern, addActiveFormatPropertyNames(propertyNames, propertyPrefix)); + fPropertyPrefix = propertyPrefix; + PROP_ACTIVE_FORMAT = (fPropertyPrefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT).intern(); + PROP_ACTIVE_FORMAT_VALUE = (fPropertyPrefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE) + .intern(); + } - public FormattedValueLabelText(String formatPattern, String[] propertyNames) { - this(formatPattern, propertyNames, ""); //$NON-NLS-1$ - } + private static String[] addActiveFormatPropertyNames(String[] propertyNames, String prefix) { + String[] newPropertyNames = new String[propertyNames.length + 4]; + System.arraycopy(propertyNames, 0, newPropertyNames, 0, propertyNames.length); + newPropertyNames[propertyNames.length + + 0] = (prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE).intern(); + newPropertyNames[propertyNames.length + 1] = (prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT) + .intern(); + newPropertyNames[propertyNames.length + 2] = (prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS) + .intern(); + newPropertyNames[propertyNames.length + 3] = IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE; + return newPropertyNames; + } - public FormattedValueLabelText(String formatPattern, String[] propertyNames, String propertyPrefix) { - super(formatPattern, addActiveFormatPropertyNames(propertyNames, propertyPrefix)); - fPropertyPrefix = propertyPrefix; - PROP_ACTIVE_FORMAT = (fPropertyPrefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT).intern(); - PROP_ACTIVE_FORMAT_VALUE = (fPropertyPrefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE).intern(); - } + @Override + protected Object getPropertyValue(String propertyName, IStatus status, Map<String, Object> properties) { + // If the format is not the same as the preferred format, include it in the value string. + if (PROP_ACTIVE_FORMAT_VALUE.equals(propertyName)) { + Object activeFormat = properties.get(PROP_ACTIVE_FORMAT); + Object preferredFormat = properties.get(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE); + Object value = properties.get(PROP_ACTIVE_FORMAT_VALUE); + if (value != null && activeFormat != null && !activeFormat.equals(preferredFormat)) { + return MessageFormat.format(MessagesForNumberFormat.FormattedValueLabelText__Value__text_format, + new Object[] { value, FormattedValueVMUtil.getFormatLabel((String) activeFormat) }); + } + } + return properties.get(propertyName); + } - private static String[] addActiveFormatPropertyNames(String[] propertyNames, String prefix) { - String[] newPropertyNames = new String[propertyNames.length + 4]; - System.arraycopy(propertyNames, 0, newPropertyNames, 0, propertyNames.length); - newPropertyNames[propertyNames.length + 0] = (prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE).intern(); - newPropertyNames[propertyNames.length + 1] = (prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT).intern(); - newPropertyNames[propertyNames.length + 2] = (prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS).intern(); - newPropertyNames[propertyNames.length + 3] = IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE; - return newPropertyNames; - } - - @Override - protected Object getPropertyValue(String propertyName, IStatus status, Map<String, Object> properties) { - // If the format is not the same as the preferred format, include it in the value string. - if ( PROP_ACTIVE_FORMAT_VALUE.equals(propertyName) ) { - Object activeFormat = properties.get(PROP_ACTIVE_FORMAT); - Object preferredFormat = properties.get(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE); - Object value = properties.get(PROP_ACTIVE_FORMAT_VALUE); - if (value != null && activeFormat != null && !activeFormat.equals(preferredFormat)) { - return MessageFormat.format( - MessagesForNumberFormat.FormattedValueLabelText__Value__text_format, - new Object[] { - value, - FormattedValueVMUtil.getFormatLabel((String)activeFormat) }); - } - } - return properties.get(propertyName); - } - - @Override - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - for (String property : getPropertyNames()) { - if ( PROP_ACTIVE_FORMAT.equals(property) || - IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE.equals(property) ) - { - continue; - } - if (properties.get(property) == null) { - return false; - } - } - return true; - } + @Override + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + for (String property : getPropertyNames()) { + if (PROP_ACTIVE_FORMAT.equals(property) + || IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE.equals(property)) { + continue; + } + if (properties.get(property) == null) { + return false; + } + } + return true; + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/FormattedValueRetriever.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/FormattedValueRetriever.java index 002aa1982a4..7e65f654caa 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/FormattedValueRetriever.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/FormattedValueRetriever.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Winnie Lai (Texas Instruments) - Individual Element Number Format (Bug 202556) @@ -56,653 +56,664 @@ import org.osgi.framework.InvalidSyntaxException; import org.osgi.util.tracker.ServiceTracker; /** - * A helper class for View Model Node implementations that support elements - * to be formatted using different number formats. This object can be + * A helper class for View Model Node implementations that support elements + * to be formatted using different number formats. This object can be * instantiated by a VM node to retrieve formatted values from a given service - * using given DMC type. + * using given DMC type. * <p> * Note: This class is a replacement for the {@link FormattedValueVMUtil#updateFormattedValues(IPropertiesUpdate[], IFormattedValues, Class, RequestMonitor)} * static method. This new implementation retrieves cached values if they are - * available in the VM Cache. + * available in the VM Cache. * </p> - * + * * @see FormattedValueVMUtil * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues - * + * * @since 2.0 */ public class FormattedValueRetriever { - private final IVMNode fNode; - private final ICachingVMProviderExtension2 fCache; - private final IElementFormatProvider fElementFormatProvider; - private final ServiceTracker fServiceTracker; - private final Class<? extends IFormattedDataDMContext> fDmcType; - private final String fPropertyPrefix; - - private final String PROP_AVAILABLE_FORMATS; - private final String PROP_ACTIVE_FORMAT; - private final String PROP_ACTIVE_FORMAT_VALUE; - private final String PROP_BASE; - - public FormattedValueRetriever(IVMNode node, DsfSession session, Class<?> serviceClass, Class<? extends IFormattedDataDMContext> dmcType) { - this(node, createFilter(session, serviceClass), dmcType, null); - } - - public FormattedValueRetriever(IVMNode node, DsfSession session, Class<?> serviceClass, Class<? extends IFormattedDataDMContext> dmcType, String propertyPrefix) { - this(node, createFilter(session, serviceClass), dmcType, propertyPrefix); - } - - public FormattedValueRetriever(IVMNode node, Filter filter, Class<? extends IFormattedDataDMContext> dmcType, String propertyPrefix) { - fNode = node; - fCache = (ICachingVMProviderExtension2)node.getVMProvider(); - IVMProvider vmprovider = fNode.getVMProvider(); - fElementFormatProvider = vmprovider instanceof IElementFormatProvider ? (IElementFormatProvider) vmprovider : null; - fServiceTracker = new ServiceTracker(DsfUIPlugin.getBundleContext(), filter, null); - fServiceTracker.open(); - fDmcType = dmcType; - if (propertyPrefix == null) { - propertyPrefix = ""; //$NON-NLS-1$ - } - fPropertyPrefix = propertyPrefix; - PROP_AVAILABLE_FORMATS = (fPropertyPrefix + IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS).intern(); - PROP_ACTIVE_FORMAT = (fPropertyPrefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT).intern(); - PROP_ACTIVE_FORMAT_VALUE = (fPropertyPrefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE).intern(); - PROP_BASE = (fPropertyPrefix + IDebugVMConstants.PROP_FORMATTED_VALUE_BASE).intern(); - } - - /** - * Creates an OSGI service filter for the given service type in a given - * DSF session. - */ - private static Filter createFilter(DsfSession session, Class<?> serviceClass) { - try { - return DsfUIPlugin.getBundleContext().createFilter( DsfServices.createServiceFilter(serviceClass, session.getId()) ); - } catch (InvalidSyntaxException e) { - throw new RuntimeException("Unable to create service filter for " + serviceClass, e); //$NON-NLS-1$ - } - } - - public void dispose() { - fServiceTracker.close(); - } - - /** - * This method fills in the formatted value properties in the given array - * of property update objects using data retrieved from the given - * formatted values service. - * <p> - * Note: The node parameter must return a <code>ICachingVMProviderExtension2</code> - * through its {@link IVMNode#getVMProvider()} method. - * - * @param node This method also takes an <code>IVMNode</code> parameter - * which allows for retrieving the format value data from the View Model - * cache. If the needed value property is cached already, the cached - * value will be used otherwise the properties will be retrieved from the - * service. - * - * @param updates The array of updates to fill in information to. This - * update is used to retrieve the data model context and to write the - * properties into. Implementation will not directly mark these updates - * complete, but contribute towards that end by marking [monitor] complete. - * - * @param service The service to be used to retrieve the values from. - * - * @param dmcType The class type of the data model context. Some updates - * can contain multiple formatted data data model contexts, and this - * method assures that there is no ambiguity in which context should be - * used. - * - * @param rm Request monitor used to signal completion of work - * - * @since 2.2 - */ - @ConfinedToDsfExecutor("node.getExecutor()") - public void update(final IPropertiesUpdate updates[], final RequestMonitor rm) - { - retrieveElementActiveFormat(updates, new DataRequestMonitor<Map<IPropertiesUpdate, String>>(ImmediateExecutor.getInstance(), rm) { - @Override - protected void handleCompleted() { - final Map<IPropertiesUpdate, String> elementFormatMap = getData(); - final Map<IPropertiesUpdate, String[]> cachedAvailableFormatsMap = calcCachedAvailableFormatsMap(updates); - if ((cachedAvailableFormatsMap != null && cachedAvailableFormatsMap.size() == updates.length)) { - // All updates were satisfied by the cache. - doUpdateWithAvailableFormats(updates, cachedAvailableFormatsMap, elementFormatMap, rm); - } else { - final IFormattedValues service = (IFormattedValues)fServiceTracker.getService(); - if (service == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "Service not available " + fServiceTracker, null)); //$NON-NLS-1$ - rm.done(); - return; - } - try { - service.getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - retrieveAvailableFormats( - calcOutstandingAvailableFormatsUpdates(updates, cachedAvailableFormatsMap), - new DataRequestMonitor<Map<IPropertiesUpdate, String[]>>(fNode.getVMProvider().getExecutor(), rm) { - @Override - protected void handleSuccess() { - Map<IPropertiesUpdate, String[]> availableFormatsMap; - if (cachedAvailableFormatsMap != null) { - availableFormatsMap = cachedAvailableFormatsMap; - availableFormatsMap.putAll(getData()); - } else { - availableFormatsMap = getData(); - } - // Retrieve the formatted values now that we have the available formats (where needed). - // Note that we are passing off responsibility of our parent monitor - doUpdateWithAvailableFormats(updates, availableFormatsMap, elementFormatMap, rm); - } - }); - } - }); - } catch (RejectedExecutionException e) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "Service executor shut down " + service.getExecutor(), e)); //$NON-NLS-1$ - rm.done(); - } - } - } - }); - } - - private void retrieveElementActiveFormat(final IPropertiesUpdate updates[], final DataRequestMonitor<Map<IPropertiesUpdate, String>> rm) { - if (fElementFormatProvider == null) { - rm.setData(new HashMap<IPropertiesUpdate, String>(0)); - rm.done(); - return; - } - Map<IPropertiesUpdate, String> cachedMap = null; - HashSet<IPropertiesUpdate> outstanding = null; - for (IPropertiesUpdate update : updates) { - if (isElementFormatPropertyNeeded(update) == false) { - continue; - } - String active = null; - ICacheEntry cacheEntry = fCache.getCacheEntry(fNode, update.getViewerInput(), update.getElementPath()); - if (cacheEntry != null && cacheEntry.getProperties() != null) { - active = (String) cacheEntry.getProperties().get(PROP_ACTIVE_FORMAT); - } - if (active != null) { - if (cachedMap == null) { - cachedMap = new HashMap<IPropertiesUpdate, String>(updates.length * 4/3); - } - cachedMap.put(update, active); - } else { - if (outstanding == null) { - outstanding = new HashSet<IPropertiesUpdate>(updates.length * 4/3); - } - outstanding.add(update); - } - } - if (outstanding == null || outstanding.size() == 0) { - rm.setData(cachedMap == null ? new HashMap<IPropertiesUpdate, String>(0) : cachedMap); - rm.done(); - return; - } - if (cachedMap == null) { - cachedMap = new HashMap<IPropertiesUpdate, String>(updates.length * 4/3); - } - final Map<IPropertiesUpdate, String> elementFormatMap = Collections.synchronizedMap(cachedMap); - rm.setData(elementFormatMap); - final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), rm); - int count = 0; - for (final IPropertiesUpdate update : outstanding) { - fElementFormatProvider.getActiveFormat(update.getPresentationContext(), fNode, update.getViewerInput(), update.getElementPath(), - new ViewerDataRequestMonitor<String>(ImmediateExecutor.getInstance(), update) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - String active = this.getData(); - if (update.getProperties().contains(PROP_ACTIVE_FORMAT)) { - update.setProperty(PROP_ACTIVE_FORMAT, active); - } - elementFormatMap.put(update, active); - } - countingRm.done(); - } - }); - count++; - } - countingRm.setDoneCount(count); - - } - - /** - * Retrieves the <code>PROP_FORMATTED_VALUE_AVAILABLE_FORMATS</code> - * property for each update and returns it in a map. The returned - * map may be <code>null</code> if no cache data is available. - * - * @since 2.2 - */ - private Map<IPropertiesUpdate, String[]> calcCachedAvailableFormatsMap(IPropertiesUpdate updates[]) { - Map<IPropertiesUpdate, String[]> cachedAvailableFormatsMap = null; // delay creating map till needed - for (IPropertiesUpdate update : updates) { - ICacheEntry cacheEntry = fCache.getCacheEntry(fNode, update.getViewerInput(), update.getElementPath()); - if (cacheEntry != null && cacheEntry.getProperties() != null) { - String[] availableFormats = (String[]) - cacheEntry.getProperties().get(PROP_AVAILABLE_FORMATS); - // Add the cached entry to the cached map even if its null. This will help keep track - // of whether we need to call the service for data. - if (availableFormats != null || !isAvailableFormatsPropertyNeeded(update)) { - if (cachedAvailableFormatsMap == null) { - cachedAvailableFormatsMap = new HashMap<IPropertiesUpdate, String[]>(updates.length * 4/3); - } - cachedAvailableFormatsMap.put(update, availableFormats); - continue; - } - } - } - return cachedAvailableFormatsMap; - } - - /** - * Generates a list of updates which still need the - * <code>PROP_FORMATTED_VALUE_AVAILABLE_FORMATS</code> property. - * - * @since 2.2 - */ - private List<IPropertiesUpdate> calcOutstandingAvailableFormatsUpdates(IPropertiesUpdate[] updates, Map<IPropertiesUpdate, String[]> cachedAvailableFormatsMap) { - if (cachedAvailableFormatsMap != null) { - List<IPropertiesUpdate> outstandingUpdates = new ArrayList<IPropertiesUpdate>(updates.length - cachedAvailableFormatsMap.size()); - for (IPropertiesUpdate update : updates) { - if (!cachedAvailableFormatsMap.containsKey(update)) { - outstandingUpdates.add(update); - } - } - return outstandingUpdates; - } else { - return Arrays.asList(updates); - } - } - - /** - * Method to retrieve available formats for each update's element (if - * needed). The result is returned in a map and in the - * update object (if requested). - * <p> - * Note that we use a synchronized map because it's updated by a request - * monitor with an ImmediateExecutor. - * - * @since 2.2 - */ - @ConfinedToDsfExecutor("service.getExecutor()") - private void retrieveAvailableFormats( - final List<IPropertiesUpdate> updates, - final DataRequestMonitor<Map<IPropertiesUpdate, String[]>> rm) - { - IFormattedValues service = (IFormattedValues)fServiceTracker.getService(); - assert service.getExecutor().isInExecutorThread(); - - final Map<IPropertiesUpdate, String[]> availableFormats = Collections.synchronizedMap(new HashMap<IPropertiesUpdate, String[]>(updates.size() * 4/3)); - rm.setData(availableFormats); - final CountingRequestMonitor countingRm = new CountingRequestMonitor(service.getExecutor(), rm); - int count = 0; - - for (final IPropertiesUpdate update : updates) { - - if (!isAvailableFormatsPropertyNeeded(update)) { - continue; - } - - IFormattedDataDMContext dmc = getFormattedDataDMContext(update); - if (dmc == null) { - continue; - } - - service.getAvailableFormats( - dmc, - new ViewerDataRequestMonitor<String[]>(ImmediateExecutor.getInstance(), update) { - /** - * Note we don't mark the update object done, and we - * avoid calling our base implementation so that it - * doesn't either. The completion of this request is - * just a step in servicing the update. - */ - @Override - protected void handleCompleted() { - if (isSuccess()) { - // Set the result (available formats) into the update object if it was requested - if (update.getProperties().contains(PROP_AVAILABLE_FORMATS)) { - update.setProperty(PROP_AVAILABLE_FORMATS, getData()); - } - - if (getData().length != 0) { - // also add it to the map; we'll need to access it when querying the element's value. - availableFormats.put(update, getData()); - } else { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "No number formats available for " + update.getElement(), null)); //$NON-NLS-1$ - } - } else { - update.setStatus(getStatus()); - } - countingRm.done(); - } - }); - count++; - } - countingRm.setDoneCount(count); - - } - - /** - * This method continues retrieving formatted value properties. It is - * called once the available formats are calculated for each requested - * update. - * - * @param availableFormatsMap Prior to calling this method, the caller - * queries (where necessary) the formats supported by the element in each - * update, and it puts that information in this map. If an entry in - * [updates] does not appear in this map, it means that its view-model - * element doesn't support any formats (very unlikely), or that the - * available formats aren't necessary to service the properties specified - * in the update - * - * @since 2.2 - */ - @ConfinedToDsfExecutor("fNode.getExecutor()") - private void doUpdateWithAvailableFormats( - IPropertiesUpdate updates[], - final Map<IPropertiesUpdate, String[]> availableFormatsMap, - final Map<IPropertiesUpdate, String> elementFormatMap, - final RequestMonitor rm) - { - final List<IPropertiesUpdate> outstandingUpdates = new ArrayList<IPropertiesUpdate>(updates.length); - final Map<IPropertiesUpdate, List<String>> requestedFormatsMap = new HashMap<IPropertiesUpdate, List<String>>(updates.length * 4 / 3); - final Map<IPropertiesUpdate, String> activeFormatsMap = new HashMap<IPropertiesUpdate, String>(updates.length * 4 / 3); - - for (final IPropertiesUpdate update : updates) { - String preferredFormat = FormattedValueVMUtil.getPreferredFormat(update.getPresentationContext()); - if (update.getProperties().contains(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE)) { - update.setProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, preferredFormat); - } - - final String activeFormat = calcActiveFormat(update, preferredFormat, availableFormatsMap, elementFormatMap); - - if (update.getProperties().contains(PROP_ACTIVE_FORMAT)) { - assert activeFormat != null : "Our caller should have provided the available formats if this property was specified; given available formats, an 'active' nomination is guaranteed."; //$NON-NLS-1$ - update.setProperty(PROP_ACTIVE_FORMAT, activeFormat); - } - List<String> requestedFormats = calcRequestedFormats(update, activeFormat, availableFormatsMap.get(update)); - - ICacheEntry cacheEntry = fCache.getCacheEntry(fNode, update.getViewerInput(), update.getElementPath()); - if (cacheEntry != null && cacheEntry.getProperties() != null) { - IVMUpdatePolicyExtension updatePolicy = getVMUpdatePolicyExtension(); - Iterator<String> itr = requestedFormats.iterator(); - while (itr.hasNext()) { - String format = itr.next(); - String formatProperty = FormattedValueVMUtil.getPropertyForFormatId(format, fPropertyPrefix); - Object value = cacheEntry.getProperties().get(formatProperty); - if (value != null || !canUpdateProperty(cacheEntry, updatePolicy, formatProperty)) { - itr.remove(); - setUpdateFormatProperty(update, activeFormat, format, value); - } - } - } - - if (!requestedFormats.isEmpty()) { - outstandingUpdates.add(update); - requestedFormatsMap.put(update, requestedFormats); - activeFormatsMap.put(update, activeFormat); - } - } - final IFormattedValues service = (IFormattedValues)fServiceTracker.getService(); - if (service == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "Service not available " + fServiceTracker, null)); //$NON-NLS-1$ - rm.done(); - return; - } - try { - service.getExecutor().execute(new DsfRunnable() { - @Override + private final IVMNode fNode; + private final ICachingVMProviderExtension2 fCache; + private final IElementFormatProvider fElementFormatProvider; + private final ServiceTracker fServiceTracker; + private final Class<? extends IFormattedDataDMContext> fDmcType; + private final String fPropertyPrefix; + + private final String PROP_AVAILABLE_FORMATS; + private final String PROP_ACTIVE_FORMAT; + private final String PROP_ACTIVE_FORMAT_VALUE; + private final String PROP_BASE; + + public FormattedValueRetriever(IVMNode node, DsfSession session, Class<?> serviceClass, + Class<? extends IFormattedDataDMContext> dmcType) { + this(node, createFilter(session, serviceClass), dmcType, null); + } + + public FormattedValueRetriever(IVMNode node, DsfSession session, Class<?> serviceClass, + Class<? extends IFormattedDataDMContext> dmcType, String propertyPrefix) { + this(node, createFilter(session, serviceClass), dmcType, propertyPrefix); + } + + public FormattedValueRetriever(IVMNode node, Filter filter, Class<? extends IFormattedDataDMContext> dmcType, + String propertyPrefix) { + fNode = node; + fCache = (ICachingVMProviderExtension2) node.getVMProvider(); + IVMProvider vmprovider = fNode.getVMProvider(); + fElementFormatProvider = vmprovider instanceof IElementFormatProvider ? (IElementFormatProvider) vmprovider + : null; + fServiceTracker = new ServiceTracker(DsfUIPlugin.getBundleContext(), filter, null); + fServiceTracker.open(); + fDmcType = dmcType; + if (propertyPrefix == null) { + propertyPrefix = ""; //$NON-NLS-1$ + } + fPropertyPrefix = propertyPrefix; + PROP_AVAILABLE_FORMATS = (fPropertyPrefix + IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS).intern(); + PROP_ACTIVE_FORMAT = (fPropertyPrefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT).intern(); + PROP_ACTIVE_FORMAT_VALUE = (fPropertyPrefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE) + .intern(); + PROP_BASE = (fPropertyPrefix + IDebugVMConstants.PROP_FORMATTED_VALUE_BASE).intern(); + } + + /** + * Creates an OSGI service filter for the given service type in a given + * DSF session. + */ + private static Filter createFilter(DsfSession session, Class<?> serviceClass) { + try { + return DsfUIPlugin.getBundleContext() + .createFilter(DsfServices.createServiceFilter(serviceClass, session.getId())); + } catch (InvalidSyntaxException e) { + throw new RuntimeException("Unable to create service filter for " + serviceClass, e); //$NON-NLS-1$ + } + } + + public void dispose() { + fServiceTracker.close(); + } + + /** + * This method fills in the formatted value properties in the given array + * of property update objects using data retrieved from the given + * formatted values service. + * <p> + * Note: The node parameter must return a <code>ICachingVMProviderExtension2</code> + * through its {@link IVMNode#getVMProvider()} method. + * + * @param node This method also takes an <code>IVMNode</code> parameter + * which allows for retrieving the format value data from the View Model + * cache. If the needed value property is cached already, the cached + * value will be used otherwise the properties will be retrieved from the + * service. + * + * @param updates The array of updates to fill in information to. This + * update is used to retrieve the data model context and to write the + * properties into. Implementation will not directly mark these updates + * complete, but contribute towards that end by marking [monitor] complete. + * + * @param service The service to be used to retrieve the values from. + * + * @param dmcType The class type of the data model context. Some updates + * can contain multiple formatted data data model contexts, and this + * method assures that there is no ambiguity in which context should be + * used. + * + * @param rm Request monitor used to signal completion of work + * + * @since 2.2 + */ + @ConfinedToDsfExecutor("node.getExecutor()") + public void update(final IPropertiesUpdate updates[], final RequestMonitor rm) { + retrieveElementActiveFormat(updates, + new DataRequestMonitor<Map<IPropertiesUpdate, String>>(ImmediateExecutor.getInstance(), rm) { + @Override + protected void handleCompleted() { + final Map<IPropertiesUpdate, String> elementFormatMap = getData(); + final Map<IPropertiesUpdate, String[]> cachedAvailableFormatsMap = calcCachedAvailableFormatsMap( + updates); + if ((cachedAvailableFormatsMap != null && cachedAvailableFormatsMap.size() == updates.length)) { + // All updates were satisfied by the cache. + doUpdateWithAvailableFormats(updates, cachedAvailableFormatsMap, elementFormatMap, rm); + } else { + final IFormattedValues service = (IFormattedValues) fServiceTracker.getService(); + if (service == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.REQUEST_FAILED, "Service not available " + fServiceTracker, //$NON-NLS-1$ + null)); + rm.done(); + return; + } + try { + service.getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + retrieveAvailableFormats( + calcOutstandingAvailableFormatsUpdates(updates, + cachedAvailableFormatsMap), + new DataRequestMonitor<Map<IPropertiesUpdate, String[]>>( + fNode.getVMProvider().getExecutor(), rm) { + @Override + protected void handleSuccess() { + Map<IPropertiesUpdate, String[]> availableFormatsMap; + if (cachedAvailableFormatsMap != null) { + availableFormatsMap = cachedAvailableFormatsMap; + availableFormatsMap.putAll(getData()); + } else { + availableFormatsMap = getData(); + } + // Retrieve the formatted values now that we have the available formats (where needed). + // Note that we are passing off responsibility of our parent monitor + doUpdateWithAvailableFormats(updates, availableFormatsMap, + elementFormatMap, rm); + } + }); + } + }); + } catch (RejectedExecutionException e) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.REQUEST_FAILED, + "Service executor shut down " + service.getExecutor(), e)); //$NON-NLS-1$ + rm.done(); + } + } + } + }); + } + + private void retrieveElementActiveFormat(final IPropertiesUpdate updates[], + final DataRequestMonitor<Map<IPropertiesUpdate, String>> rm) { + if (fElementFormatProvider == null) { + rm.setData(new HashMap<IPropertiesUpdate, String>(0)); + rm.done(); + return; + } + Map<IPropertiesUpdate, String> cachedMap = null; + HashSet<IPropertiesUpdate> outstanding = null; + for (IPropertiesUpdate update : updates) { + if (isElementFormatPropertyNeeded(update) == false) { + continue; + } + String active = null; + ICacheEntry cacheEntry = fCache.getCacheEntry(fNode, update.getViewerInput(), update.getElementPath()); + if (cacheEntry != null && cacheEntry.getProperties() != null) { + active = (String) cacheEntry.getProperties().get(PROP_ACTIVE_FORMAT); + } + if (active != null) { + if (cachedMap == null) { + cachedMap = new HashMap<IPropertiesUpdate, String>(updates.length * 4 / 3); + } + cachedMap.put(update, active); + } else { + if (outstanding == null) { + outstanding = new HashSet<IPropertiesUpdate>(updates.length * 4 / 3); + } + outstanding.add(update); + } + } + if (outstanding == null || outstanding.size() == 0) { + rm.setData(cachedMap == null ? new HashMap<IPropertiesUpdate, String>(0) : cachedMap); + rm.done(); + return; + } + if (cachedMap == null) { + cachedMap = new HashMap<IPropertiesUpdate, String>(updates.length * 4 / 3); + } + final Map<IPropertiesUpdate, String> elementFormatMap = Collections.synchronizedMap(cachedMap); + rm.setData(elementFormatMap); + final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), rm); + int count = 0; + for (final IPropertiesUpdate update : outstanding) { + fElementFormatProvider.getActiveFormat(update.getPresentationContext(), fNode, update.getViewerInput(), + update.getElementPath(), + new ViewerDataRequestMonitor<String>(ImmediateExecutor.getInstance(), update) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + String active = this.getData(); + if (update.getProperties().contains(PROP_ACTIVE_FORMAT)) { + update.setProperty(PROP_ACTIVE_FORMAT, active); + } + elementFormatMap.put(update, active); + } + countingRm.done(); + } + }); + count++; + } + countingRm.setDoneCount(count); + + } + + /** + * Retrieves the <code>PROP_FORMATTED_VALUE_AVAILABLE_FORMATS</code> + * property for each update and returns it in a map. The returned + * map may be <code>null</code> if no cache data is available. + * + * @since 2.2 + */ + private Map<IPropertiesUpdate, String[]> calcCachedAvailableFormatsMap(IPropertiesUpdate updates[]) { + Map<IPropertiesUpdate, String[]> cachedAvailableFormatsMap = null; // delay creating map till needed + for (IPropertiesUpdate update : updates) { + ICacheEntry cacheEntry = fCache.getCacheEntry(fNode, update.getViewerInput(), update.getElementPath()); + if (cacheEntry != null && cacheEntry.getProperties() != null) { + String[] availableFormats = (String[]) cacheEntry.getProperties().get(PROP_AVAILABLE_FORMATS); + // Add the cached entry to the cached map even if its null. This will help keep track + // of whether we need to call the service for data. + if (availableFormats != null || !isAvailableFormatsPropertyNeeded(update)) { + if (cachedAvailableFormatsMap == null) { + cachedAvailableFormatsMap = new HashMap<IPropertiesUpdate, String[]>(updates.length * 4 / 3); + } + cachedAvailableFormatsMap.put(update, availableFormats); + continue; + } + } + } + return cachedAvailableFormatsMap; + } + + /** + * Generates a list of updates which still need the + * <code>PROP_FORMATTED_VALUE_AVAILABLE_FORMATS</code> property. + * + * @since 2.2 + */ + private List<IPropertiesUpdate> calcOutstandingAvailableFormatsUpdates(IPropertiesUpdate[] updates, + Map<IPropertiesUpdate, String[]> cachedAvailableFormatsMap) { + if (cachedAvailableFormatsMap != null) { + List<IPropertiesUpdate> outstandingUpdates = new ArrayList<IPropertiesUpdate>( + updates.length - cachedAvailableFormatsMap.size()); + for (IPropertiesUpdate update : updates) { + if (!cachedAvailableFormatsMap.containsKey(update)) { + outstandingUpdates.add(update); + } + } + return outstandingUpdates; + } else { + return Arrays.asList(updates); + } + } + + /** + * Method to retrieve available formats for each update's element (if + * needed). The result is returned in a map and in the + * update object (if requested). + * <p> + * Note that we use a synchronized map because it's updated by a request + * monitor with an ImmediateExecutor. + * + * @since 2.2 + */ + @ConfinedToDsfExecutor("service.getExecutor()") + private void retrieveAvailableFormats(final List<IPropertiesUpdate> updates, + final DataRequestMonitor<Map<IPropertiesUpdate, String[]>> rm) { + IFormattedValues service = (IFormattedValues) fServiceTracker.getService(); + assert service.getExecutor().isInExecutorThread(); + + final Map<IPropertiesUpdate, String[]> availableFormats = Collections + .synchronizedMap(new HashMap<IPropertiesUpdate, String[]>(updates.size() * 4 / 3)); + rm.setData(availableFormats); + final CountingRequestMonitor countingRm = new CountingRequestMonitor(service.getExecutor(), rm); + int count = 0; + + for (final IPropertiesUpdate update : updates) { + + if (!isAvailableFormatsPropertyNeeded(update)) { + continue; + } + + IFormattedDataDMContext dmc = getFormattedDataDMContext(update); + if (dmc == null) { + continue; + } + + service.getAvailableFormats(dmc, + new ViewerDataRequestMonitor<String[]>(ImmediateExecutor.getInstance(), update) { + /** + * Note we don't mark the update object done, and we + * avoid calling our base implementation so that it + * doesn't either. The completion of this request is + * just a step in servicing the update. + */ + @Override + protected void handleCompleted() { + if (isSuccess()) { + // Set the result (available formats) into the update object if it was requested + if (update.getProperties().contains(PROP_AVAILABLE_FORMATS)) { + update.setProperty(PROP_AVAILABLE_FORMATS, getData()); + } + + if (getData().length != 0) { + // also add it to the map; we'll need to access it when querying the element's value. + availableFormats.put(update, getData()); + } else { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.REQUEST_FAILED, + "No number formats available for " + update.getElement(), null)); //$NON-NLS-1$ + } + } else { + update.setStatus(getStatus()); + } + countingRm.done(); + } + }); + count++; + } + countingRm.setDoneCount(count); + + } + + /** + * This method continues retrieving formatted value properties. It is + * called once the available formats are calculated for each requested + * update. + * + * @param availableFormatsMap Prior to calling this method, the caller + * queries (where necessary) the formats supported by the element in each + * update, and it puts that information in this map. If an entry in + * [updates] does not appear in this map, it means that its view-model + * element doesn't support any formats (very unlikely), or that the + * available formats aren't necessary to service the properties specified + * in the update + * + * @since 2.2 + */ + @ConfinedToDsfExecutor("fNode.getExecutor()") + private void doUpdateWithAvailableFormats(IPropertiesUpdate updates[], + final Map<IPropertiesUpdate, String[]> availableFormatsMap, + final Map<IPropertiesUpdate, String> elementFormatMap, final RequestMonitor rm) { + final List<IPropertiesUpdate> outstandingUpdates = new ArrayList<IPropertiesUpdate>(updates.length); + final Map<IPropertiesUpdate, List<String>> requestedFormatsMap = new HashMap<IPropertiesUpdate, List<String>>( + updates.length * 4 / 3); + final Map<IPropertiesUpdate, String> activeFormatsMap = new HashMap<IPropertiesUpdate, String>( + updates.length * 4 / 3); + + for (final IPropertiesUpdate update : updates) { + String preferredFormat = FormattedValueVMUtil.getPreferredFormat(update.getPresentationContext()); + if (update.getProperties().contains(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE)) { + update.setProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, preferredFormat); + } + + final String activeFormat = calcActiveFormat(update, preferredFormat, availableFormatsMap, + elementFormatMap); + + if (update.getProperties().contains(PROP_ACTIVE_FORMAT)) { + assert activeFormat != null : "Our caller should have provided the available formats if this property was specified; given available formats, an 'active' nomination is guaranteed."; //$NON-NLS-1$ + update.setProperty(PROP_ACTIVE_FORMAT, activeFormat); + } + List<String> requestedFormats = calcRequestedFormats(update, activeFormat, availableFormatsMap.get(update)); + + ICacheEntry cacheEntry = fCache.getCacheEntry(fNode, update.getViewerInput(), update.getElementPath()); + if (cacheEntry != null && cacheEntry.getProperties() != null) { + IVMUpdatePolicyExtension updatePolicy = getVMUpdatePolicyExtension(); + Iterator<String> itr = requestedFormats.iterator(); + while (itr.hasNext()) { + String format = itr.next(); + String formatProperty = FormattedValueVMUtil.getPropertyForFormatId(format, fPropertyPrefix); + Object value = cacheEntry.getProperties().get(formatProperty); + if (value != null || !canUpdateProperty(cacheEntry, updatePolicy, formatProperty)) { + itr.remove(); + setUpdateFormatProperty(update, activeFormat, format, value); + } + } + } + + if (!requestedFormats.isEmpty()) { + outstandingUpdates.add(update); + requestedFormatsMap.put(update, requestedFormats); + activeFormatsMap.put(update, activeFormat); + } + } + final IFormattedValues service = (IFormattedValues) fServiceTracker.getService(); + if (service == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, + "Service not available " + fServiceTracker, null)); //$NON-NLS-1$ + rm.done(); + return; + } + try { + service.getExecutor().execute(new DsfRunnable() { + @Override public void run() { - doUpdateWithRequestedFormats(outstandingUpdates, requestedFormatsMap, activeFormatsMap, rm); - } - }); - } catch (RejectedExecutionException e) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "Service executor shut down " + service.getExecutor(), e)); //$NON-NLS-1$ - rm.done(); - } - } - - private IVMUpdatePolicyExtension getVMUpdatePolicyExtension() { - if( fCache.getActiveUpdatePolicy() instanceof IVMUpdatePolicyExtension) { - return (IVMUpdatePolicyExtension)fCache.getActiveUpdatePolicy(); - } - return null; - } - - private static boolean canUpdateProperty(ICacheEntry entry, IVMUpdatePolicyExtension updatePolicy, String property) { - return !entry.isDirty() || (updatePolicy != null && updatePolicy.canUpdateDirtyProperty(entry, property)); - } - - /** - * Retrieves the specified formatted values from the service. - * - * @param requestedFormatsMap Map containing the formats to be retrieved - * and filled in for each given update. - * @param activeFormatsMap Map containing the active format for each given - * update. The active format value needs to be set in the update using the - * special property <code>PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE</code>. - * - * @since 2.2 - */ - @ConfinedToDsfExecutor("service.getExecutor()") - private void doUpdateWithRequestedFormats( - List<IPropertiesUpdate> updates, - final Map<IPropertiesUpdate, List<String>> requestedFormatsMap, - final Map<IPropertiesUpdate, String> activeFormatsMap, - final RequestMonitor monitor) - { - IFormattedValues service = (IFormattedValues)fServiceTracker.getService(); - assert service.getExecutor().isInExecutorThread(); - - // Use a single counting RM for all the requested formats for each update. - final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), monitor); - int count = 0; - - for (final IPropertiesUpdate update : updates) { - IFormattedDataDMContext dmc = getFormattedDataDMContext(update); - if (dmc == null) { - continue; - } - - List<String> requestedFormats = requestedFormatsMap.get(update); - for (String requestedFormat : requestedFormats) { - final FormattedValueDMContext formattedValueDmc = service.getFormattedValueContext(dmc, requestedFormat); - service.getFormattedExpressionValue( - formattedValueDmc, - // Here also use the ViewerDataRequestMonitor in order to propagate the update's cancel request. - // However, when operation is complete, call the counting RM's done(). - // Use an immediate executor to avoid the possibility of a rejected execution exception. - new ViewerDataRequestMonitor<FormattedValueDMData>(ImmediateExecutor.getInstance(), update) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - setUpdateFormatProperty( - update, - activeFormatsMap.get(update), - formattedValueDmc.getFormatID(), - getData().getFormattedValue()); - } else { - update.setStatus(getStatus()); - } - // Note: we must not call the update's done method, instead call counting RM done. - countingRm.done(); - - }; - }); - count++; - } - } - countingRm.setDoneCount(count); - } - - /** - * Determine the 'active' value format. It is the view preference if - * and only if the element supports it. Otherwise it is the first - * format supported by the element. - * <p> - * Note: If the availableFormatsMap doesn't contain the available formats - * for the given update, it means the update doesn't request any properties - * which requires the active format to be calculated. - * - * @param update Properties update to calculate the active format for. - * @param availableFormatsMap The map of available formats. - * @param elementFormatMap The map of element active format. - * @return The active format, or null if active format not requested in - * update. - */ - private String calcActiveFormat(IPropertiesUpdate update, String preferredFormat, Map<IPropertiesUpdate, String[]> availableFormatsMap, - Map<IPropertiesUpdate, String> elementFormatMap) { - String[] availableFormats = availableFormatsMap.get(update); - if (availableFormats != null && availableFormats.length != 0) { - String elementFormat = elementFormatMap.get(update); - if (elementFormat != null && isFormatAvailable(elementFormat, availableFormats)) { - return elementFormat; - } - if (isFormatAvailable(preferredFormat, availableFormats)) { - return preferredFormat; - } else { - return availableFormats[0]; - } - } - return null; // null means we don't need to know what the active format is - } - - /** - * Returns <code>true</code> if the given availableFormats array contains - * the given format. - */ - private boolean isFormatAvailable(String format, String[] availableFormats) { - for (String availableFormat : availableFormats) { - if (availableFormat.equals(format)) { - return true; - } - } - return false; - } - - /** - * Service the properties that ask for the value in a specific - * format. If the update request contains the property - * PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, and the active format - * has not been explicitly requested, then we need an additional - * iteration to provide it. - */ - private List<String> calcRequestedFormats(IPropertiesUpdate update, String activeFormat, String[] availableFormats) { - List<String> requestedFormats = new ArrayList<String>(10); - - boolean activeFormatValueHandled = false; // have we come across a specific format request that is the active format? - - for (Iterator<String> itr = update.getProperties().iterator(); itr.hasNext() || (activeFormat != null && !activeFormatValueHandled);) { - String nextFormat; - if (itr.hasNext()) { - String propertyName = itr.next(); - if (propertyName.startsWith(PROP_BASE)) { - nextFormat = FormattedValueVMUtil.getFormatFromProperty(propertyName, fPropertyPrefix); - if (nextFormat.equals(activeFormat)) { - activeFormatValueHandled = true; - } - // if we know the supported formats (we may not), then no-op if this format is unsupported - if (availableFormats != null && !isFormatAvailable(nextFormat, availableFormats)) { - continue; - } - } - else { - continue; - } - } else { - // the additional iteration to handle the active format - nextFormat = activeFormat; - activeFormatValueHandled = true; - } - requestedFormats.add(nextFormat); - } - return requestedFormats; - } - - /** - * Writes the given formatted property value into the update. It also - * writes the active format property if needed. - * <p> - * If the given property value is null, this method writes an error status - * instead. - */ - private void setUpdateFormatProperty(IPropertiesUpdate update, String activeFormat, String format, Object value) { - String formatProperty = FormattedValueVMUtil.getPropertyForFormatId(format, fPropertyPrefix); - if (value != null) { - update.setProperty(formatProperty, value); - if (update.getProperties().contains(PROP_ACTIVE_FORMAT_VALUE) && - format.equals(activeFormat)) - { - update.setProperty(PROP_ACTIVE_FORMAT_VALUE, value); - } - } else { - IStatus staleDataStatus = DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_STATE, "Cache contains stale data. Refresh view.", null );//$NON-NLS-1$ - if (update.getProperties().contains(PROP_ACTIVE_FORMAT_VALUE) && - format.equals(activeFormat)) - { - PropertiesUpdateStatus.getPropertiesStatus(update).setStatus( - new String[] { PROP_ACTIVE_FORMAT_VALUE, formatProperty }, - staleDataStatus); - } else { - PropertiesUpdateStatus.getPropertiesStatus(update).setStatus(formatProperty, staleDataStatus); - } - } - } - - /** - * For each update, query the formats available for the update's - * element...but only if necessary. The available formats are necessary - * only if the update explicitly requests that information, or if the - * update is asking what the active format is or is asking for the value - * of the element in that format. The reason we need them in the last - * two cases is that we can't establish the 'active' format for an - * element without knowing its available formats. See - * updateFormattedValuesWithAvailableFormats(), as that's where we make - * that determination. - * @param update - * @return - */ - private boolean isAvailableFormatsPropertyNeeded(IPropertiesUpdate update) { - return update.getProperties().contains(PROP_AVAILABLE_FORMATS) || - update.getProperties().contains(PROP_ACTIVE_FORMAT) || - update.getProperties().contains(PROP_ACTIVE_FORMAT_VALUE); - } - - /** - * For each update, query the active format for the update's - * element...but only if necessary. It is necessary only if the - * update is asking what the active format is or is asking for the value - * of the element in that format. - * @param update - * @return true if needed - */ - private boolean isElementFormatPropertyNeeded(IPropertiesUpdate update) { - if (fElementFormatProvider == null) - return false; - return update.getProperties().contains(PROP_ACTIVE_FORMAT) || - update.getProperties().contains(PROP_ACTIVE_FORMAT_VALUE); - } - - /** - * Extracts the formatted data DMC from the update. If update doesn't - * contain DMC-based elemtn, it writes an error to the update and returns - * <code>null</code>. - */ - private IFormattedDataDMContext getFormattedDataDMContext(IPropertiesUpdate update) - { - IFormattedDataDMContext dmc = null; - if (update.getElement() instanceof IDMVMContext) { - dmc = DMContexts.getAncestorOfType(((IDMVMContext)update.getElement()).getDMContext(), fDmcType); - } - - if (dmc == null) { - update.setStatus(DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_HANDLE, "Update element did not contain a valid context: " + fDmcType, null)); //$NON-NLS-1$ - } - return dmc; - } + doUpdateWithRequestedFormats(outstandingUpdates, requestedFormatsMap, activeFormatsMap, rm); + } + }); + } catch (RejectedExecutionException e) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, + "Service executor shut down " + service.getExecutor(), e)); //$NON-NLS-1$ + rm.done(); + } + } + + private IVMUpdatePolicyExtension getVMUpdatePolicyExtension() { + if (fCache.getActiveUpdatePolicy() instanceof IVMUpdatePolicyExtension) { + return (IVMUpdatePolicyExtension) fCache.getActiveUpdatePolicy(); + } + return null; + } + + private static boolean canUpdateProperty(ICacheEntry entry, IVMUpdatePolicyExtension updatePolicy, + String property) { + return !entry.isDirty() || (updatePolicy != null && updatePolicy.canUpdateDirtyProperty(entry, property)); + } + + /** + * Retrieves the specified formatted values from the service. + * + * @param requestedFormatsMap Map containing the formats to be retrieved + * and filled in for each given update. + * @param activeFormatsMap Map containing the active format for each given + * update. The active format value needs to be set in the update using the + * special property <code>PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE</code>. + * + * @since 2.2 + */ + @ConfinedToDsfExecutor("service.getExecutor()") + private void doUpdateWithRequestedFormats(List<IPropertiesUpdate> updates, + final Map<IPropertiesUpdate, List<String>> requestedFormatsMap, + final Map<IPropertiesUpdate, String> activeFormatsMap, final RequestMonitor monitor) { + IFormattedValues service = (IFormattedValues) fServiceTracker.getService(); + assert service.getExecutor().isInExecutorThread(); + + // Use a single counting RM for all the requested formats for each update. + final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), monitor); + int count = 0; + + for (final IPropertiesUpdate update : updates) { + IFormattedDataDMContext dmc = getFormattedDataDMContext(update); + if (dmc == null) { + continue; + } + + List<String> requestedFormats = requestedFormatsMap.get(update); + for (String requestedFormat : requestedFormats) { + final FormattedValueDMContext formattedValueDmc = service.getFormattedValueContext(dmc, + requestedFormat); + service.getFormattedExpressionValue(formattedValueDmc, + // Here also use the ViewerDataRequestMonitor in order to propagate the update's cancel request. + // However, when operation is complete, call the counting RM's done(). + // Use an immediate executor to avoid the possibility of a rejected execution exception. + new ViewerDataRequestMonitor<FormattedValueDMData>(ImmediateExecutor.getInstance(), update) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + setUpdateFormatProperty(update, activeFormatsMap.get(update), + formattedValueDmc.getFormatID(), getData().getFormattedValue()); + } else { + update.setStatus(getStatus()); + } + // Note: we must not call the update's done method, instead call counting RM done. + countingRm.done(); + + }; + }); + count++; + } + } + countingRm.setDoneCount(count); + } + + /** + * Determine the 'active' value format. It is the view preference if + * and only if the element supports it. Otherwise it is the first + * format supported by the element. + * <p> + * Note: If the availableFormatsMap doesn't contain the available formats + * for the given update, it means the update doesn't request any properties + * which requires the active format to be calculated. + * + * @param update Properties update to calculate the active format for. + * @param availableFormatsMap The map of available formats. + * @param elementFormatMap The map of element active format. + * @return The active format, or null if active format not requested in + * update. + */ + private String calcActiveFormat(IPropertiesUpdate update, String preferredFormat, + Map<IPropertiesUpdate, String[]> availableFormatsMap, Map<IPropertiesUpdate, String> elementFormatMap) { + String[] availableFormats = availableFormatsMap.get(update); + if (availableFormats != null && availableFormats.length != 0) { + String elementFormat = elementFormatMap.get(update); + if (elementFormat != null && isFormatAvailable(elementFormat, availableFormats)) { + return elementFormat; + } + if (isFormatAvailable(preferredFormat, availableFormats)) { + return preferredFormat; + } else { + return availableFormats[0]; + } + } + return null; // null means we don't need to know what the active format is + } + + /** + * Returns <code>true</code> if the given availableFormats array contains + * the given format. + */ + private boolean isFormatAvailable(String format, String[] availableFormats) { + for (String availableFormat : availableFormats) { + if (availableFormat.equals(format)) { + return true; + } + } + return false; + } + + /** + * Service the properties that ask for the value in a specific + * format. If the update request contains the property + * PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, and the active format + * has not been explicitly requested, then we need an additional + * iteration to provide it. + */ + private List<String> calcRequestedFormats(IPropertiesUpdate update, String activeFormat, + String[] availableFormats) { + List<String> requestedFormats = new ArrayList<String>(10); + + boolean activeFormatValueHandled = false; // have we come across a specific format request that is the active format? + + for (Iterator<String> itr = update.getProperties().iterator(); itr.hasNext() + || (activeFormat != null && !activeFormatValueHandled);) { + String nextFormat; + if (itr.hasNext()) { + String propertyName = itr.next(); + if (propertyName.startsWith(PROP_BASE)) { + nextFormat = FormattedValueVMUtil.getFormatFromProperty(propertyName, fPropertyPrefix); + if (nextFormat.equals(activeFormat)) { + activeFormatValueHandled = true; + } + // if we know the supported formats (we may not), then no-op if this format is unsupported + if (availableFormats != null && !isFormatAvailable(nextFormat, availableFormats)) { + continue; + } + } else { + continue; + } + } else { + // the additional iteration to handle the active format + nextFormat = activeFormat; + activeFormatValueHandled = true; + } + requestedFormats.add(nextFormat); + } + return requestedFormats; + } + + /** + * Writes the given formatted property value into the update. It also + * writes the active format property if needed. + * <p> + * If the given property value is null, this method writes an error status + * instead. + */ + private void setUpdateFormatProperty(IPropertiesUpdate update, String activeFormat, String format, Object value) { + String formatProperty = FormattedValueVMUtil.getPropertyForFormatId(format, fPropertyPrefix); + if (value != null) { + update.setProperty(formatProperty, value); + if (update.getProperties().contains(PROP_ACTIVE_FORMAT_VALUE) && format.equals(activeFormat)) { + update.setProperty(PROP_ACTIVE_FORMAT_VALUE, value); + } + } else { + IStatus staleDataStatus = DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_STATE, + "Cache contains stale data. Refresh view.", null);//$NON-NLS-1$ + if (update.getProperties().contains(PROP_ACTIVE_FORMAT_VALUE) && format.equals(activeFormat)) { + PropertiesUpdateStatus.getPropertiesStatus(update) + .setStatus(new String[] { PROP_ACTIVE_FORMAT_VALUE, formatProperty }, staleDataStatus); + } else { + PropertiesUpdateStatus.getPropertiesStatus(update).setStatus(formatProperty, staleDataStatus); + } + } + } + + /** + * For each update, query the formats available for the update's + * element...but only if necessary. The available formats are necessary + * only if the update explicitly requests that information, or if the + * update is asking what the active format is or is asking for the value + * of the element in that format. The reason we need them in the last + * two cases is that we can't establish the 'active' format for an + * element without knowing its available formats. See + * updateFormattedValuesWithAvailableFormats(), as that's where we make + * that determination. + * @param update + * @return + */ + private boolean isAvailableFormatsPropertyNeeded(IPropertiesUpdate update) { + return update.getProperties().contains(PROP_AVAILABLE_FORMATS) + || update.getProperties().contains(PROP_ACTIVE_FORMAT) + || update.getProperties().contains(PROP_ACTIVE_FORMAT_VALUE); + } + + /** + * For each update, query the active format for the update's + * element...but only if necessary. It is necessary only if the + * update is asking what the active format is or is asking for the value + * of the element in that format. + * @param update + * @return true if needed + */ + private boolean isElementFormatPropertyNeeded(IPropertiesUpdate update) { + if (fElementFormatProvider == null) + return false; + return update.getProperties().contains(PROP_ACTIVE_FORMAT) + || update.getProperties().contains(PROP_ACTIVE_FORMAT_VALUE); + } + + /** + * Extracts the formatted data DMC from the update. If update doesn't + * contain DMC-based elemtn, it writes an error to the update and returns + * <code>null</code>. + */ + private IFormattedDataDMContext getFormattedDataDMContext(IPropertiesUpdate update) { + IFormattedDataDMContext dmc = null; + if (update.getElement() instanceof IDMVMContext) { + dmc = DMContexts.getAncestorOfType(((IDMVMContext) update.getElement()).getDMContext(), fDmcType); + } + + if (dmc == null) { + update.setStatus(DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_HANDLE, + "Update element did not contain a valid context: " + fDmcType, null)); //$NON-NLS-1$ + } + return dmc; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/FormattedValueVMUtil.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/FormattedValueVMUtil.java index d89c1e1d5ed..5b4c5cf3596 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/FormattedValueVMUtil.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/FormattedValueVMUtil.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -39,224 +39,222 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationCont import com.ibm.icu.text.MessageFormat; /** - * A helper class for View Model Node implementations that support elements - * to be formatted using different number formats. The various static methods in + * A helper class for View Model Node implementations that support elements + * to be formatted using different number formats. The various static methods in * this class handle populating the properties of an IPropertiesUpdate using data * retrieved from a DSF service implementing {@link IFormattedValues} interface. - * + * * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider * @see org.eclipse.cdt.dsf.debug.service.IFormattedValues - * + * * @since 2.0 */ public class FormattedValueVMUtil { - /** - * Cache to avoid creating many duplicate strings of formats and properties. - */ - private static Map<String, Map<String, String>> fFormatProperties = - Collections.synchronizedMap(new TreeMap<String, Map<String, String>>()); - - /** - * Common map of user-readable labels for format IDs. - */ - private static Map<String, String> fFormatLabels = new HashMap<String, String>(8); - - static { - setFormatLabel(IFormattedValues.NATURAL_FORMAT, MessagesForNumberFormat.FormattedValueVMUtil_Natural_format__label); - setFormatLabel(IFormattedValues.HEX_FORMAT, MessagesForNumberFormat.FormattedValueVMUtil_Hex_format__label); - setFormatLabel(IFormattedValues.DECIMAL_FORMAT, MessagesForNumberFormat.FormattedValueVMUtil_Decimal_format__label); - setFormatLabel(IFormattedValues.OCTAL_FORMAT, MessagesForNumberFormat.FormattedValueVMUtil_Octal_format__label); - setFormatLabel(IFormattedValues.BINARY_FORMAT, MessagesForNumberFormat.FormattedValueVMUtil_Binary_format__label); - setFormatLabel(IFormattedValues.STRING_FORMAT, MessagesForNumberFormat.FormattedValueVMUtil_String_format__label); - } - - /** - * Adds a user-readable label for a given format ID. If a given view model has a custom format ID, it can - * add its label to the map of format IDs using this method. - * - * @param formatId Format ID to set the label for. - * @param label User-readable label for a format. - */ - public static void setFormatLabel(String formatId, String label) { - fFormatLabels.put(formatId, label); - } - - /** - * Returns a user readable label for a given format ID. - */ - public static String getFormatLabel(String formatId) { - String label = fFormatLabels.get(formatId); - if (label != null) { - return label; - } else { - return MessageFormat.format( - MessagesForNumberFormat.FormattedValueVMUtil_Other_format__format_text, new Object[] { formatId }); - } - } - - /** - * Returns an element property representing an element value in a given format. - - * @deprecated Replaced by {@link #getPropertyForFormatId(String, String)} - */ - @Deprecated + /** + * Cache to avoid creating many duplicate strings of formats and properties. + */ + private static Map<String, Map<String, String>> fFormatProperties = Collections + .synchronizedMap(new TreeMap<String, Map<String, String>>()); + + /** + * Common map of user-readable labels for format IDs. + */ + private static Map<String, String> fFormatLabels = new HashMap<String, String>(8); + + static { + setFormatLabel(IFormattedValues.NATURAL_FORMAT, + MessagesForNumberFormat.FormattedValueVMUtil_Natural_format__label); + setFormatLabel(IFormattedValues.HEX_FORMAT, MessagesForNumberFormat.FormattedValueVMUtil_Hex_format__label); + setFormatLabel(IFormattedValues.DECIMAL_FORMAT, + MessagesForNumberFormat.FormattedValueVMUtil_Decimal_format__label); + setFormatLabel(IFormattedValues.OCTAL_FORMAT, MessagesForNumberFormat.FormattedValueVMUtil_Octal_format__label); + setFormatLabel(IFormattedValues.BINARY_FORMAT, + MessagesForNumberFormat.FormattedValueVMUtil_Binary_format__label); + setFormatLabel(IFormattedValues.STRING_FORMAT, + MessagesForNumberFormat.FormattedValueVMUtil_String_format__label); + } + + /** + * Adds a user-readable label for a given format ID. If a given view model has a custom format ID, it can + * add its label to the map of format IDs using this method. + * + * @param formatId Format ID to set the label for. + * @param label User-readable label for a format. + */ + public static void setFormatLabel(String formatId, String label) { + fFormatLabels.put(formatId, label); + } + + /** + * Returns a user readable label for a given format ID. + */ + public static String getFormatLabel(String formatId) { + String label = fFormatLabels.get(formatId); + if (label != null) { + return label; + } else { + return MessageFormat.format(MessagesForNumberFormat.FormattedValueVMUtil_Other_format__format_text, + new Object[] { formatId }); + } + } + + /** + * Returns an element property representing an element value in a given format. + + * @deprecated Replaced by {@link #getPropertyForFormatId(String, String)} + */ + @Deprecated public static String getPropertyForFormatId(String formatId) { - return getPropertyForFormatId(formatId, ""); //$NON-NLS-1$ - } - - /** - * Returns an element property representing an element value in a given format. - * - * @param Format ID to create the property for. - * @param prefix The prefix for the property that is used to distinguish - * it from other number format values in a given property map. May be - * <code>null</code> or an empty string if no prefix is used. - * @return The generated property name. - * - * @since 2.2 - */ - public static String getPropertyForFormatId(String formatId, String prefix) { - if (formatId == null) { - return null; - } - if (prefix == null) { - prefix = ""; //$NON-NLS-1$ - } - synchronized(fFormatProperties) { - Map<String, String> formatsMap = getFormatsMap(prefix); - String property = formatsMap.get(formatId); - if (property == null) { - property = (prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_BASE + "." + formatId).intern(); //$NON-NLS-1$ - formatsMap.put(formatId, property); - } - return property; - } - } - - private static Map<String, String> getFormatsMap(String prefix) { - synchronized(fFormatProperties) { - Map<String, String> prefixMap = fFormatProperties.get(prefix); - if (prefixMap == null) { - prefixMap = new TreeMap<String, String>(); - fFormatProperties.put(prefix, prefixMap); - } - return prefixMap; - } - } - - /** - * Returns a format ID based on the element property representing a - * formatted element value. - * - * @deprecated Replaced by {@link #getFormatFromProperty(String, String)} - */ - @Deprecated + return getPropertyForFormatId(formatId, ""); //$NON-NLS-1$ + } + + /** + * Returns an element property representing an element value in a given format. + * + * @param Format ID to create the property for. + * @param prefix The prefix for the property that is used to distinguish + * it from other number format values in a given property map. May be + * <code>null</code> or an empty string if no prefix is used. + * @return The generated property name. + * + * @since 2.2 + */ + public static String getPropertyForFormatId(String formatId, String prefix) { + if (formatId == null) { + return null; + } + if (prefix == null) { + prefix = ""; //$NON-NLS-1$ + } + synchronized (fFormatProperties) { + Map<String, String> formatsMap = getFormatsMap(prefix); + String property = formatsMap.get(formatId); + if (property == null) { + property = (prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_BASE + "." + formatId).intern(); //$NON-NLS-1$ + formatsMap.put(formatId, property); + } + return property; + } + } + + private static Map<String, String> getFormatsMap(String prefix) { + synchronized (fFormatProperties) { + Map<String, String> prefixMap = fFormatProperties.get(prefix); + if (prefixMap == null) { + prefixMap = new TreeMap<String, String>(); + fFormatProperties.put(prefix, prefixMap); + } + return prefixMap; + } + } + + /** + * Returns a format ID based on the element property representing a + * formatted element value. + * + * @deprecated Replaced by {@link #getFormatFromProperty(String, String)} + */ + @Deprecated public static String getFormatFromProperty(String property) { - return getFormatFromProperty(property, ""); //$NON-NLS-1$ - } - - /** - * Returns a format ID based on the element property representing a - * formatted element value. This method has an additional prefix parameter - * which is used when multiple number formats are stored in a single - * property map. - * - * @param property The property to extract the format from. - * @param prefix The prefix for the property that is used to distinguish - * it from other number format values in a given property map. May be - * <code>null</code> or an empty string if no prefix is used. - * @return The format ID. - * - * @throws IllegalArgumentException if the property is not a formatted value - * property. - * - * @since 2.2 - */ - public static String getFormatFromProperty(String property, String prefix) { - if (prefix == null) { - prefix = ""; //$NON-NLS-1$ - } - - synchronized(fFormatProperties) { - Map<String, String> formatsMap = getFormatsMap(prefix); - for (Map.Entry<String, String> entry : formatsMap.entrySet()) { - if (entry.getValue().equals(property)) { - return entry.getKey(); - } - } - if ( !property.startsWith(prefix) || - !property.startsWith(IDebugVMConstants.PROP_FORMATTED_VALUE_BASE, prefix.length()) ) - { - throw new IllegalArgumentException("Property " + property + " is not a valid formatted value format property."); //$NON-NLS-1$//$NON-NLS-2$ - } - String formatId = property.substring( - prefix.length() + IDebugVMConstants.PROP_FORMATTED_VALUE_BASE.length() + 1).intern(); - formatsMap.put(formatId, property); - return formatId; - } - } - - - /** - * Returns the user-selected number format that is saved in the given - * presentation context. - */ - public static String getPreferredFormat(IPresentationContext context) { - Object prop = context.getProperty( IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE ); - if ( prop != null ) { - return (String) prop; - } - return IFormattedValues.NATURAL_FORMAT; - } - - - /** - * This method fills in the formatted value properties in the given array - * of property update objects using data retrieved from the given - * formatted values service. - * - * @param updates The array of updates to fill in information to. This - * update is used to retrieve the data model context and to write the - * properties into. Implementation will not directly mark these updates - * complete, but contribute towards that end by marking [monitor] complete. - * @param service The service to be used to retrieve the values from. - * @param dmcType The class type of the data model context. Some updates - * can contain multiple formatted data data model contexts, and this - * method assures that there is no ambiguity in which context should be - * used. - * @param monitor Request monitor used to signal completion of work - * - * @deprecated This method has been replaced by the {@link FormattedValueRetriever} - * utility. - */ - @Deprecated + return getFormatFromProperty(property, ""); //$NON-NLS-1$ + } + + /** + * Returns a format ID based on the element property representing a + * formatted element value. This method has an additional prefix parameter + * which is used when multiple number formats are stored in a single + * property map. + * + * @param property The property to extract the format from. + * @param prefix The prefix for the property that is used to distinguish + * it from other number format values in a given property map. May be + * <code>null</code> or an empty string if no prefix is used. + * @return The format ID. + * + * @throws IllegalArgumentException if the property is not a formatted value + * property. + * + * @since 2.2 + */ + public static String getFormatFromProperty(String property, String prefix) { + if (prefix == null) { + prefix = ""; //$NON-NLS-1$ + } + + synchronized (fFormatProperties) { + Map<String, String> formatsMap = getFormatsMap(prefix); + for (Map.Entry<String, String> entry : formatsMap.entrySet()) { + if (entry.getValue().equals(property)) { + return entry.getKey(); + } + } + if (!property.startsWith(prefix) + || !property.startsWith(IDebugVMConstants.PROP_FORMATTED_VALUE_BASE, prefix.length())) { + throw new IllegalArgumentException( + "Property " + property + " is not a valid formatted value format property."); //$NON-NLS-1$//$NON-NLS-2$ + } + String formatId = property + .substring(prefix.length() + IDebugVMConstants.PROP_FORMATTED_VALUE_BASE.length() + 1).intern(); + formatsMap.put(formatId, property); + return formatId; + } + } + + /** + * Returns the user-selected number format that is saved in the given + * presentation context. + */ + public static String getPreferredFormat(IPresentationContext context) { + Object prop = context.getProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE); + if (prop != null) { + return (String) prop; + } + return IFormattedValues.NATURAL_FORMAT; + } + + /** + * This method fills in the formatted value properties in the given array + * of property update objects using data retrieved from the given + * formatted values service. + * + * @param updates The array of updates to fill in information to. This + * update is used to retrieve the data model context and to write the + * properties into. Implementation will not directly mark these updates + * complete, but contribute towards that end by marking [monitor] complete. + * @param service The service to be used to retrieve the values from. + * @param dmcType The class type of the data model context. Some updates + * can contain multiple formatted data data model contexts, and this + * method assures that there is no ambiguity in which context should be + * used. + * @param monitor Request monitor used to signal completion of work + * + * @deprecated This method has been replaced by the {@link FormattedValueRetriever} + * utility. + */ + @Deprecated @ConfinedToDsfExecutor("service.getExecutor()") - public static void updateFormattedValues( - final IPropertiesUpdate updates[], - final IFormattedValues service, - final Class<? extends IFormattedDataDMContext> dmcType, - final RequestMonitor monitor) - { + public static void updateFormattedValues(final IPropertiesUpdate updates[], final IFormattedValues service, + final Class<? extends IFormattedDataDMContext> dmcType, final RequestMonitor monitor) { // First retrieve the available formats for each update's element (if // needed). Store the result in a map (for internal use) and in the // update object (if requested). After that's done, call another method // to retrieve the formatted values. Note that we use a synchronized map // because it's updated by a request monitor with an ImmediateExecutor. - final Map<IPropertiesUpdate, String[]> availableFormats = Collections.synchronizedMap(new HashMap<IPropertiesUpdate, String[]>(updates.length * 4/3)); - final CountingRequestMonitor countingRm = new CountingRequestMonitor( - service.getExecutor(), monitor) { - @Override - protected void handleCompleted() { - // Retrieve the formatted values now that we have the available formats (where needed). - // Note that we are passing off responsibility of our parent monitor - updateFormattedValuesWithAvailableFormats(updates, service, dmcType, availableFormats, monitor); - - // Note: we must not call the update's done method - } - }; - int count = 0; - + final Map<IPropertiesUpdate, String[]> availableFormats = Collections + .synchronizedMap(new HashMap<IPropertiesUpdate, String[]>(updates.length * 4 / 3)); + final CountingRequestMonitor countingRm = new CountingRequestMonitor(service.getExecutor(), monitor) { + @Override + protected void handleCompleted() { + // Retrieve the formatted values now that we have the available formats (where needed). + // Note that we are passing off responsibility of our parent monitor + updateFormattedValuesWithAvailableFormats(updates, service, dmcType, availableFormats, monitor); + + // Note: we must not call the update's done method + } + }; + int count = 0; + // For each update, query the formats available for the update's // element...but only if necessary. The available formats are necessary // only if the update explicitly requests that information, or if the @@ -266,52 +264,53 @@ public class FormattedValueVMUtil { // element without knowing its available formats. See // updateFormattedValuesWithAvailableFormats(), as that's where we make // that determination. - for (final IPropertiesUpdate update : updates) { - if ((!update.getProperties().contains(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS) && - !update.getProperties().contains(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT) && - !update.getProperties().contains(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE))) - { - continue; - } - - IFormattedDataDMContext dmc = null; - if (update.getElement() instanceof IDMVMContext) { - dmc = DMContexts.getAncestorOfType(((IDMVMContext)update.getElement()).getDMContext(), dmcType); - } - - if (dmc == null) { - update.setStatus(DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_HANDLE, "Update element did not contain a valid context: " + dmcType, null)); //$NON-NLS-1$ - continue; - } - - service.getAvailableFormats( - dmc, - new ViewerDataRequestMonitor<String[]>(ImmediateExecutor.getInstance(), update) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - // Set the result (available formats) into the update object if it was requested - if (update.getProperties().contains(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS)) { - update.setProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS, getData()); - } - - // also add it to the map; we'll need to access it when querying the element's value. - availableFormats.put(update, getData()); - } else { - update.setStatus(getStatus()); - } - countingRm.done(); - - // Note we don't mark the update object done, and we - // avoid calling our base implementation so that it - // doesn't either. The completion of this request is - // just a step in servicing the update. - } - }); - count++; - } - countingRm.setDoneCount(count); - } + for (final IPropertiesUpdate update : updates) { + if ((!update.getProperties().contains(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS) + && !update.getProperties().contains(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT) + && !update.getProperties().contains(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE))) { + continue; + } + + IFormattedDataDMContext dmc = null; + if (update.getElement() instanceof IDMVMContext) { + dmc = DMContexts.getAncestorOfType(((IDMVMContext) update.getElement()).getDMContext(), dmcType); + } + + if (dmc == null) { + update.setStatus(DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_HANDLE, + "Update element did not contain a valid context: " + dmcType, null)); //$NON-NLS-1$ + continue; + } + + service.getAvailableFormats(dmc, + new ViewerDataRequestMonitor<String[]>(ImmediateExecutor.getInstance(), update) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + // Set the result (available formats) into the update object if it was requested + if (update.getProperties() + .contains(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS)) { + update.setProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS, + getData()); + } + + // also add it to the map; we'll need to access it when querying the element's value. + availableFormats.put(update, getData()); + } else { + update.setStatus(getStatus()); + } + countingRm.done(); + + // Note we don't mark the update object done, and we + // avoid calling our base implementation so that it + // doesn't either. The completion of this request is + // just a step in servicing the update. + } + }); + count++; + } + countingRm.setDoneCount(count); + } /** * @param updates @@ -329,125 +328,118 @@ public class FormattedValueVMUtil { * @param monitor * Request monitor used to signal completion of work */ - @ConfinedToDsfExecutor("service.getExecutor()") - private static void updateFormattedValuesWithAvailableFormats( - IPropertiesUpdate updates[], - IFormattedValues service, - Class<? extends IFormattedDataDMContext> dmcType, - Map<IPropertiesUpdate, String[]> availableFormatsMap, - final RequestMonitor monitor) - { - // Use a single counting RM for all the requested formats for each update. - final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), monitor); - int count = 0; - - for (final IPropertiesUpdate update : updates) { - IFormattedDataDMContext dmc = null; - if (update.getElement() instanceof IDMVMContext) { - dmc = DMContexts.getAncestorOfType(((IDMVMContext)update.getElement()).getDMContext(), dmcType); - } - if (dmc == null) { - // The error status should already be set by the calling method. - continue; - } - + @ConfinedToDsfExecutor("service.getExecutor()") + private static void updateFormattedValuesWithAvailableFormats(IPropertiesUpdate updates[], IFormattedValues service, + Class<? extends IFormattedDataDMContext> dmcType, Map<IPropertiesUpdate, String[]> availableFormatsMap, + final RequestMonitor monitor) { + // Use a single counting RM for all the requested formats for each update. + final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), monitor); + int count = 0; + + for (final IPropertiesUpdate update : updates) { + IFormattedDataDMContext dmc = null; + if (update.getElement() instanceof IDMVMContext) { + dmc = DMContexts.getAncestorOfType(((IDMVMContext) update.getElement()).getDMContext(), dmcType); + } + if (dmc == null) { + // The error status should already be set by the calling method. + continue; + } + // Determine the 'active' value format. It is the view preference if // and only if the element supports it. Otherwise it is the first // format supported by the element. If our caller didn't provide the // available formats for an update (element), then it means the // update doesn't contain any properties that requires us to // determine the active format. - String[] availableFormats = availableFormatsMap.get(update); - String _activeFormat = null; - if (availableFormats != null && availableFormats.length != 0) { - _activeFormat = getPreferredFormat(update.getPresentationContext()); - update.setProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, _activeFormat); - if (!isFormatAvailable(_activeFormat, availableFormats)) { - _activeFormat = availableFormats[0]; - } - } - final String activeFormat = _activeFormat; // null means we don't need to know what the active format is - - if (update.getProperties().contains(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT)) { - assert activeFormat != null : "Our caller should have provided the available formats if this property was specified; given available formats, an 'active' nomination is guaranteed."; //$NON-NLS-1$ - update.setProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, activeFormat); - } - + String[] availableFormats = availableFormatsMap.get(update); + String _activeFormat = null; + if (availableFormats != null && availableFormats.length != 0) { + _activeFormat = getPreferredFormat(update.getPresentationContext()); + update.setProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, _activeFormat); + if (!isFormatAvailable(_activeFormat, availableFormats)) { + _activeFormat = availableFormats[0]; + } + } + final String activeFormat = _activeFormat; // null means we don't need to know what the active format is + + if (update.getProperties().contains(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT)) { + assert activeFormat != null : "Our caller should have provided the available formats if this property was specified; given available formats, an 'active' nomination is guaranteed."; //$NON-NLS-1$ + update.setProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, activeFormat); + } + // Service the properties that ask for the value in a specific // format. If the update request contains the property // PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, and the active format // has not been explicitly requested, then we need an additional - // iteration to provide it. - boolean activeFormatValueRequested = false; // does the update object ask for PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE? - boolean activeFormatValueHandled = false; // have we come across a specific format request that is the active format? - if (update.getProperties().contains(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE)) { - assert activeFormat != null : "Our caller should have provided the available formats if this property was specified; given available formats, an 'active' nomination is guaranteed."; //$NON-NLS-1$ - activeFormatValueRequested = true; // we may end up making an additional run - } - - for (Iterator<String> itr = update.getProperties().iterator(); itr.hasNext() || (activeFormatValueRequested && !activeFormatValueHandled);) { - String nextFormat; - if (itr.hasNext()) { - String propertyName = itr.next(); - if (propertyName.startsWith(IDebugVMConstants.PROP_FORMATTED_VALUE_BASE)) { - nextFormat = FormattedValueVMUtil.getFormatFromProperty(propertyName); - if (nextFormat.equals(activeFormat)) { - activeFormatValueHandled = true; - } - // if we know the supported formats (we may not), then no-op if this format is unsupported - if (availableFormats != null && !isFormatAvailable(nextFormat, availableFormats)) { - continue; - } - } - else { - continue; - } - } else { - // the additional iteration to handle the active format - nextFormat = activeFormat; - activeFormatValueHandled = true; - } - - final boolean _activeFormatValueRequested = activeFormatValueRequested; - final FormattedValueDMContext formattedValueDmc = service.getFormattedValueContext(dmc, nextFormat); - service.getFormattedExpressionValue( - formattedValueDmc, - // Here also use the ViewerDataRequestMonitor in order to propagate the update's cancel request. - // Use an immediate executor to avoid the possibility of a rejected execution exception. - new ViewerDataRequestMonitor<FormattedValueDMData>(ImmediateExecutor.getInstance(), update) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - String format = formattedValueDmc.getFormatID(); - update.setProperty( - FormattedValueVMUtil.getPropertyForFormatId(format), - getData().getFormattedValue()); - if (_activeFormatValueRequested && format.equals(activeFormat)) { - update.setProperty( - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - getData().getFormattedValue()); - } - } else { - update.setStatus(getStatus()); - } - countingRm.done(); - - // Note: we must not call the update's done method - }; - }); - count++; - } - } - countingRm.setDoneCount(count); - } - - private static boolean isFormatAvailable(String format, String[] availableFormats) { - for (String availableFormat : availableFormats) { - if (availableFormat.equals(format)) { - return true; - } - } - return false; - } + // iteration to provide it. + boolean activeFormatValueRequested = false; // does the update object ask for PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE? + boolean activeFormatValueHandled = false; // have we come across a specific format request that is the active format? + if (update.getProperties().contains(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE)) { + assert activeFormat != null : "Our caller should have provided the available formats if this property was specified; given available formats, an 'active' nomination is guaranteed."; //$NON-NLS-1$ + activeFormatValueRequested = true; // we may end up making an additional run + } + + for (Iterator<String> itr = update.getProperties().iterator(); itr.hasNext() + || (activeFormatValueRequested && !activeFormatValueHandled);) { + String nextFormat; + if (itr.hasNext()) { + String propertyName = itr.next(); + if (propertyName.startsWith(IDebugVMConstants.PROP_FORMATTED_VALUE_BASE)) { + nextFormat = FormattedValueVMUtil.getFormatFromProperty(propertyName); + if (nextFormat.equals(activeFormat)) { + activeFormatValueHandled = true; + } + // if we know the supported formats (we may not), then no-op if this format is unsupported + if (availableFormats != null && !isFormatAvailable(nextFormat, availableFormats)) { + continue; + } + } else { + continue; + } + } else { + // the additional iteration to handle the active format + nextFormat = activeFormat; + activeFormatValueHandled = true; + } + + final boolean _activeFormatValueRequested = activeFormatValueRequested; + final FormattedValueDMContext formattedValueDmc = service.getFormattedValueContext(dmc, nextFormat); + service.getFormattedExpressionValue(formattedValueDmc, + // Here also use the ViewerDataRequestMonitor in order to propagate the update's cancel request. + // Use an immediate executor to avoid the possibility of a rejected execution exception. + new ViewerDataRequestMonitor<FormattedValueDMData>(ImmediateExecutor.getInstance(), update) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + String format = formattedValueDmc.getFormatID(); + update.setProperty(FormattedValueVMUtil.getPropertyForFormatId(format), + getData().getFormattedValue()); + if (_activeFormatValueRequested && format.equals(activeFormat)) { + update.setProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + getData().getFormattedValue()); + } + } else { + update.setStatus(getStatus()); + } + countingRm.done(); + + // Note: we must not call the update's done method + }; + }); + count++; + } + } + countingRm.setDoneCount(count); + } + + private static boolean isFormatAvailable(String format, String[] availableFormats) { + for (String availableFormat : availableFormats) { + if (availableFormat.equals(format)) { + return true; + } + } + return false; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/IElementFormatProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/IElementFormatProvider.java index 6712bbd4926..dc5a9a619e3 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/IElementFormatProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/IElementFormatProvider.java @@ -22,14 +22,13 @@ import org.eclipse.jface.viewers.TreePath; /** * Element format provider - an optional interface that provides individual element format * A view model provider (org.eclipse.cdt.dsf.ui.viewmodel.IVMProvider) can optionally implement this interface. - * If there is a requirement to persist individual format settings, this provider can + * If there is a requirement to persist individual format settings, this provider can * add an persistable (IPersistable) property to PresentationContext so that when presentation context - * is invoked to persist its properties, the individual format settings are persisted as well. - * + * is invoked to persist its properties, the individual format settings are persisted as well. + * * @since 2.2 */ -public interface IElementFormatProvider -{ +public interface IElementFormatProvider { /** * Get active format for a given element. * @param context presentation context @@ -43,28 +42,29 @@ public interface IElementFormatProvider * Note that if caller finds that the preference format is not available from service, * it will use the first available format from service. See FormattedValueRetriever. */ - public void getActiveFormat(IPresentationContext context, IVMNode node, Object viewerInput, TreePath elementPath, - DataRequestMonitor<String> rm); + public void getActiveFormat(IPresentationContext context, IVMNode node, Object viewerInput, TreePath elementPath, + DataRequestMonitor<String> rm); - /** - * Set active format for given elements. The caller will not fire any event to update view. - * The implementation of this method should fire proper events to refresh impacted elements. - * One way is to refresh the view through IVMCachingProvider.refresh but it will - * refresh other non-impacted elements. - * Another way that may be more optimal is to fire ElementFormatEvent that stores exactly the - * impacted elements. The view model can then handle the event more efficiently. - * @param context presentation context - * @param node view model nodes - * @param viewerInput viewer input - * @param elementPath element path of given elements - * @param format format - */ - public void setActiveFormat(IPresentationContext context, IVMNode[] node, Object viewerInput, TreePath[] elementPath, String format); + /** + * Set active format for given elements. The caller will not fire any event to update view. + * The implementation of this method should fire proper events to refresh impacted elements. + * One way is to refresh the view through IVMCachingProvider.refresh but it will + * refresh other non-impacted elements. + * Another way that may be more optimal is to fire ElementFormatEvent that stores exactly the + * impacted elements. The view model can then handle the event more efficiently. + * @param context presentation context + * @param node view model nodes + * @param viewerInput viewer input + * @param elementPath element path of given elements + * @param format format + */ + public void setActiveFormat(IPresentationContext context, IVMNode[] node, Object viewerInput, + TreePath[] elementPath, String format); - /** - * Test if this provider supports individual element format for a given context - * @param context given context - * @return true if this provider supports individual element format. - */ - public boolean supportFormat(IVMContext context); + /** + * Test if this provider supports individual element format for a given context + * @param context given context + * @return true if this provider supports individual element format. + */ + public boolean supportFormat(IVMContext context); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/IFormattedValueVMContext.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/IFormattedValueVMContext.java index 7b1dd37b89c..e1b9dd3bcb1 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/IFormattedValueVMContext.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/IFormattedValueVMContext.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/MessagesForNumberFormat.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/MessagesForNumberFormat.java index ffcdbcef776..f923a819a11 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/MessagesForNumberFormat.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/MessagesForNumberFormat.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems, Inc. - initial API and implementation *******************************************************************************/ @@ -20,25 +20,25 @@ import org.eclipse.osgi.util.NLS; * @noinstantiate This class is not intended to be instantiated by clients. */ public class MessagesForNumberFormat extends NLS { - public static String FormattedValueVMUtil_Natural_format__label; - public static String FormattedValueVMUtil_Decimal_format__label; - public static String FormattedValueVMUtil_Hex_format__label; - public static String FormattedValueVMUtil_Octal_format__label; - public static String FormattedValueVMUtil_Binary_format__label; - public static String FormattedValueVMUtil_String_format__label; - public static String FormattedValueVMUtil_Other_format__format_text; + public static String FormattedValueVMUtil_Natural_format__label; + public static String FormattedValueVMUtil_Decimal_format__label; + public static String FormattedValueVMUtil_Hex_format__label; + public static String FormattedValueVMUtil_Octal_format__label; + public static String FormattedValueVMUtil_Binary_format__label; + public static String FormattedValueVMUtil_String_format__label; + public static String FormattedValueVMUtil_Other_format__format_text; + + public static String NumberFormatContribution_EmptyFormatsList_label; + public static String ElementNumberFormatContribution_RestoreToPreference_label; - public static String NumberFormatContribution_EmptyFormatsList_label; - public static String ElementNumberFormatContribution_RestoreToPreference_label; - - public static String FormattedValueLabelText__Value__text_format; - public static String FormattedValueLabelText__text_format; + public static String FormattedValueLabelText__Value__text_format; + public static String FormattedValueLabelText__text_format; - static { - // initialize resource bundle - NLS.initializeMessages(MessagesForNumberFormat.class.getName(), MessagesForNumberFormat.class); - } + static { + // initialize resource bundle + NLS.initializeMessages(MessagesForNumberFormat.class.getName(), MessagesForNumberFormat.class); + } - private MessagesForNumberFormat() { - } + private MessagesForNumberFormat() { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/NumberFormatsContribution.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/NumberFormatsContribution.java index f7558199acc..fb195473b5b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/NumberFormatsContribution.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/NumberFormatsContribution.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Winnie Lai (Texas Instruments) - Individual Element Number Format (Bug 202556) @@ -35,95 +35,94 @@ import org.eclipse.ui.menus.IWorkbenchContribution; import org.eclipse.ui.services.IServiceLocator; /** - * Dynamic menu contribution that shows available number formats + * Dynamic menu contribution that shows available number formats * in the current view. - * + * * @since 1.1 */ public class NumberFormatsContribution extends CompoundContributionItem implements IWorkbenchContribution { - - protected static final List<String> FORMATS = new LinkedList<String>(); - static { - FORMATS.add(IFormattedValues.NATURAL_FORMAT); - FORMATS.add(IFormattedValues.HEX_FORMAT); - FORMATS.add(IFormattedValues.DECIMAL_FORMAT); - FORMATS.add(IFormattedValues.OCTAL_FORMAT); - FORMATS.add(IFormattedValues.BINARY_FORMAT); - FORMATS.add(IFormattedValues.STRING_FORMAT); - } - - private class SelectNumberFormatAction extends Action { - private final IPresentationContext fContext; - private final String fFormatId; - SelectNumberFormatAction(IPresentationContext context, String formatId) { - super(FormattedValueVMUtil.getFormatLabel(formatId), AS_RADIO_BUTTON); - fContext = context; - fFormatId = formatId; - } - - @Override - public void run() { - if (isChecked()) { - fContext.setProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, fFormatId); - } - } - } - - protected IServiceLocator fServiceLocator; - - private static IContributionItem[] NO_FORMAT_CONTRIBUTION_ITEMS = new IContributionItem[] { - new ContributionItem() { - @Override - public void fill(Menu menu, int index) { - MenuItem item = new MenuItem(menu, SWT.NONE); - item.setEnabled(false); - item.setText(MessagesForNumberFormat.NumberFormatContribution_EmptyFormatsList_label); + + protected static final List<String> FORMATS = new LinkedList<String>(); + static { + FORMATS.add(IFormattedValues.NATURAL_FORMAT); + FORMATS.add(IFormattedValues.HEX_FORMAT); + FORMATS.add(IFormattedValues.DECIMAL_FORMAT); + FORMATS.add(IFormattedValues.OCTAL_FORMAT); + FORMATS.add(IFormattedValues.BINARY_FORMAT); + FORMATS.add(IFormattedValues.STRING_FORMAT); + } + + private class SelectNumberFormatAction extends Action { + private final IPresentationContext fContext; + private final String fFormatId; + + SelectNumberFormatAction(IPresentationContext context, String formatId) { + super(FormattedValueVMUtil.getFormatLabel(formatId), AS_RADIO_BUTTON); + fContext = context; + fFormatId = formatId; + } + + @Override + public void run() { + if (isChecked()) { + fContext.setProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, fFormatId); } - - @Override - public boolean isEnabled() { - return false; + } + } + + protected IServiceLocator fServiceLocator; + + private static IContributionItem[] NO_FORMAT_CONTRIBUTION_ITEMS = new IContributionItem[] { new ContributionItem() { + @Override + public void fill(Menu menu, int index) { + MenuItem item = new MenuItem(menu, SWT.NONE); + item.setEnabled(false); + item.setText(MessagesForNumberFormat.NumberFormatContribution_EmptyFormatsList_label); + } + + @Override + public boolean isEnabled() { + return false; + } + } }; + + @Override + protected IContributionItem[] getContributionItems() { + IVMProvider provider = VMHandlerUtils.getActiveVMProvider(fServiceLocator); + + // If no part or selection, disable all. + if (provider == null) { + return NO_FORMAT_CONTRIBUTION_ITEMS; + } + + IPresentationContext context = provider.getPresentationContext(); + Object activeId = context.getProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE); + if (activeId == null) { + activeId = IFormattedValues.NATURAL_FORMAT; + } + + List<Action> actions = new ArrayList<Action>(FORMATS.size()); + for (String formatId : FORMATS) { + Action action = new SelectNumberFormatAction(context, formatId); + if (formatId.equals(activeId)) { + action.setChecked(true); } - } - }; - - @Override - protected IContributionItem[] getContributionItems() { - IVMProvider provider = VMHandlerUtils.getActiveVMProvider(fServiceLocator); - - // If no part or selection, disable all. - if (provider == null) { - return NO_FORMAT_CONTRIBUTION_ITEMS; - } - - IPresentationContext context = provider.getPresentationContext(); - Object activeId = context.getProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE); - if (activeId == null) { - activeId = IFormattedValues.NATURAL_FORMAT; - } - - List<Action> actions = new ArrayList<Action>(FORMATS.size()); - for (String formatId : FORMATS) { - Action action = new SelectNumberFormatAction(context, formatId); - if (formatId.equals(activeId)) { - action.setChecked(true); - } - actions.add(action); - } - - if ( actions.isEmpty() ) { - return NO_FORMAT_CONTRIBUTION_ITEMS; - } - - IContributionItem[] items = new IContributionItem[actions.size()]; - for (int i = 0; i < actions.size(); i++) { - items[i] = new ActionContributionItem(actions.get(i)); - } - return items; - } - - @Override + actions.add(action); + } + + if (actions.isEmpty()) { + return NO_FORMAT_CONTRIBUTION_ITEMS; + } + + IContributionItem[] items = new IContributionItem[actions.size()]; + for (int i = 0; i < actions.size(); i++) { + items[i] = new ActionContributionItem(actions.get(i)); + } + return items; + } + + @Override public void initialize(IServiceLocator serviceLocator) { - fServiceLocator = serviceLocator; - } + fServiceLocator = serviceLocator; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/NumberFormatsPropertyTester.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/NumberFormatsPropertyTester.java index 5b211e34a87..e557429c05a 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/NumberFormatsPropertyTester.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/NumberFormatsPropertyTester.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Winnie Lai (Texas Instruments) - Individual Element Number Format (Bug 202556) @@ -27,73 +27,74 @@ import org.eclipse.debug.ui.IDebugView; import org.eclipse.ui.IWorkbenchPart; /** - * Property tester for number format information available through the given - * object. The object being tested should be either an {@link IVMContext}, + * Property tester for number format information available through the given + * object. The object being tested should be either an {@link IVMContext}, * through which an instance of {@link IVMProvider} could be obtained. * Or it could be an {@link IWorkbenchPart}, which is tested to see if it - * is a debug view through which a caching VM provider can be obtained. + * is a debug view through which a caching VM provider can be obtained. * The view's presentation context is used to test the given property. * <p> * Three properties are supported: * <ul> - * <li> "areNumberFormatsSupported" - Checks whether number formats are + * <li> "areNumberFormatsSupported" - Checks whether number formats are * available at all given the receiver.</li> - * <li> "isNumberFormatAvailable" - Checks whether the number format ID in the + * <li> "isNumberFormatAvailable" - Checks whether the number format ID in the * expected value is available for the given receiver.</li> - * <li> "isNumberFormatActive" - Checks whether the number format ID in the expected + * <li> "isNumberFormatActive" - Checks whether the number format ID in the expected * value is the currently active number format for the given receiver.</li> * </ul> * </p> - * + * * @since 1.0 */ public class NumberFormatsPropertyTester extends PropertyTester { - private static final String SUPPORTED = "areNumberFormatsSupported"; //$NON-NLS-1$ - private static final String ELEMENT_FORMATS_SUPPORTED = "areElementNumberFormatsSupported"; //$NON-NLS-1$ - private static final String AVAILABLE = "isNumberFormatAvailable"; //$NON-NLS-1$ - private static final String ACTIVE = "isNumberFormatActive"; //$NON-NLS-1$ + private static final String SUPPORTED = "areNumberFormatsSupported"; //$NON-NLS-1$ + private static final String ELEMENT_FORMATS_SUPPORTED = "areElementNumberFormatsSupported"; //$NON-NLS-1$ + private static final String AVAILABLE = "isNumberFormatAvailable"; //$NON-NLS-1$ + private static final String ACTIVE = "isNumberFormatActive"; //$NON-NLS-1$ - private static final List<String> AVAILABLE_FORMATS = new ArrayList<String>(); - static { - AVAILABLE_FORMATS.add(IFormattedValues.NATURAL_FORMAT); - AVAILABLE_FORMATS.add(IFormattedValues.HEX_FORMAT); - AVAILABLE_FORMATS.add(IFormattedValues.DECIMAL_FORMAT); - AVAILABLE_FORMATS.add(IFormattedValues.OCTAL_FORMAT); - AVAILABLE_FORMATS.add(IFormattedValues.BINARY_FORMAT); - AVAILABLE_FORMATS.add(IFormattedValues.STRING_FORMAT); - }; - - @Override + private static final List<String> AVAILABLE_FORMATS = new ArrayList<String>(); + static { + AVAILABLE_FORMATS.add(IFormattedValues.NATURAL_FORMAT); + AVAILABLE_FORMATS.add(IFormattedValues.HEX_FORMAT); + AVAILABLE_FORMATS.add(IFormattedValues.DECIMAL_FORMAT); + AVAILABLE_FORMATS.add(IFormattedValues.OCTAL_FORMAT); + AVAILABLE_FORMATS.add(IFormattedValues.BINARY_FORMAT); + AVAILABLE_FORMATS.add(IFormattedValues.STRING_FORMAT); + }; + + @Override public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { - if (receiver instanceof IVMContext) { - IVMProvider provider = ((IVMContext)receiver).getVMNode().getVMProvider(); - if (provider != null) { - return testProvider(provider, property, expectedValue, (IVMContext) receiver); - } - } else if (receiver instanceof IDebugView) { - IVMProvider provider = VMHandlerUtils.getVMProviderForPart((IDebugView)receiver); - if (provider != null) { - return testProvider(provider, property, expectedValue, null); - } - } - return false; - } + if (receiver instanceof IVMContext) { + IVMProvider provider = ((IVMContext) receiver).getVMNode().getVMProvider(); + if (provider != null) { + return testProvider(provider, property, expectedValue, (IVMContext) receiver); + } + } else if (receiver instanceof IDebugView) { + IVMProvider provider = VMHandlerUtils.getVMProviderForPart((IDebugView) receiver); + if (provider != null) { + return testProvider(provider, property, expectedValue, null); + } + } + return false; + } + + private boolean testProvider(IVMProvider provider, String property, Object expectedValue, IVMContext vmctx) { + if (SUPPORTED.equals(property)) { + return true; + } else if (AVAILABLE.equals(property)) { + return AVAILABLE_FORMATS.contains(expectedValue); + } else if (ACTIVE.equals(property)) { + Object activeId = provider.getPresentationContext() + .getProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE); + return expectedValue != null && expectedValue.equals(activeId); + } else if (ELEMENT_FORMATS_SUPPORTED.equals(property)) { + if (provider instanceof IElementFormatProvider) { + return ((IElementFormatProvider) provider).supportFormat(vmctx); + } + } + return false; + } - private boolean testProvider(IVMProvider provider, String property, Object expectedValue, IVMContext vmctx) { - if (SUPPORTED.equals(property)) { - return true; - } else if (AVAILABLE.equals(property)) { - return AVAILABLE_FORMATS.contains(expectedValue); - } else if (ACTIVE.equals(property)) { - Object activeId = provider.getPresentationContext().getProperty(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE); - return expectedValue != null && expectedValue.equals(activeId); - } else if (ELEMENT_FORMATS_SUPPORTED.equals(property)) { - if (provider instanceof IElementFormatProvider) { - return ((IElementFormatProvider) provider).supportFormat(vmctx); - } - } - return false; - } - } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/RestoreNumberFormatPreferenceContribution.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/RestoreNumberFormatPreferenceContribution.java index 68157b12fcf..b933e8dfb25 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/RestoreNumberFormatPreferenceContribution.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/numberformat/RestoreNumberFormatPreferenceContribution.java @@ -30,7 +30,7 @@ import org.eclipse.jface.viewers.Viewer; /** * Dynamic menu contribution that restores the element number format in the current * selection of the view to view's preference. - * + * * We pull 'restore to preference' menu item out from ElementNumberFormatsContribution * so that clients can add extra contribution before or after it. See 371012. * @since 2.3 @@ -48,11 +48,11 @@ public class RestoreNumberFormatPreferenceContribution extends ElementNumberForm IVMNode[] nodes = new IVMNode[elementPaths.length]; Object viewerInput = null; if (context.getPart() instanceof AbstractDebugView) { - Viewer viewer = ((AbstractDebugView)context.getPart()).getViewer(); + Viewer viewer = ((AbstractDebugView) context.getPart()).getViewer(); if (viewer != null) { viewerInput = viewer.getInput(); } - } + } for (int i = 0; i < elementPaths.length; i++) { Object segment = elementPaths[i].getLastSegment(); if (segment instanceof IVMContext) { @@ -62,8 +62,8 @@ public class RestoreNumberFormatPreferenceContribution extends ElementNumberForm } } IContributionItem[] items = new IContributionItem[1]; - items[0] = new ActionContributionItem(new SelectFormatAction( - (IElementFormatProvider) provider, context, nodes, viewerInput, elementPaths, null)); + items[0] = new ActionContributionItem(new SelectFormatAction((IElementFormatProvider) provider, context, nodes, + viewerInput, elementPaths, null)); return items; } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/IRegisterVMConstants.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/IRegisterVMConstants.java index dd1bb24a083..0c424791f02 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/IRegisterVMConstants.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/IRegisterVMConstants.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -18,25 +18,25 @@ package org.eclipse.cdt.dsf.debug.ui.viewmodel.register; */ public interface IRegisterVMConstants { - public static final String PROP_DESCRIPTION = "description"; //$NON-NLS-1$ + public static final String PROP_DESCRIPTION = "description"; //$NON-NLS-1$ + + public static final String PROP_IS_FLOAT = "is_float"; //$NON-NLS-1$ + + public static final String PROP_IS_READABLE = "is_readable"; //$NON-NLS-1$ + + public static final String PROP_IS_READONCE = "is_readonce"; //$NON-NLS-1$ - public static final String PROP_IS_FLOAT = "is_float"; //$NON-NLS-1$ + public static final String PROP_IS_WRITEABLE = "is_writeable"; //$NON-NLS-1$ - public static final String PROP_IS_READABLE = "is_readable"; //$NON-NLS-1$ + public static final String PROP_IS_WRITEONCE = "is_writeonce"; //$NON-NLS-1$ - public static final String PROP_IS_READONCE = "is_readonce"; //$NON-NLS-1$ + public static final String PROP_HAS_SIDE_EFFECTS = "has_side_effects"; //$NON-NLS-1$ - public static final String PROP_IS_WRITEABLE = "is_writeable"; //$NON-NLS-1$ + public static final String PROP_IS_ZERO_BASED_NUMBERING = "is_zero_based_numbering"; //$NON-NLS-1$ - public static final String PROP_IS_WRITEONCE = "is_writeonce"; //$NON-NLS-1$ + public static final String PROP_IS_ZERO_BIT_LEFT_MOST = "is_zero_bit_left_most"; //$NON-NLS-1$ - public static final String PROP_HAS_SIDE_EFFECTS = "has_side_effects"; //$NON-NLS-1$ - - public static final String PROP_IS_ZERO_BASED_NUMBERING = "is_zero_based_numbering"; //$NON-NLS-1$ - - public static final String PROP_IS_ZERO_BIT_LEFT_MOST = "is_zero_bit_left_most"; //$NON-NLS-1$ - - public static final String PROP_CURRENT_MNEMONIC_LONG_NAME = "mnemonic_long_name"; //$NON-NLS-1$ + public static final String PROP_CURRENT_MNEMONIC_LONG_NAME = "mnemonic_long_name"; //$NON-NLS-1$ - public static final String PROP_CURRENT_MNEMONIC_SHORT_NAME = "mnemonic_short_name"; //$NON-NLS-1$ + public static final String PROP_CURRENT_MNEMONIC_SHORT_NAME = "mnemonic_short_name"; //$NON-NLS-1$ } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/MessagesForRegisterVM.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/MessagesForRegisterVM.java index df1ccdbfade..a03fa7e0954 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/MessagesForRegisterVM.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/MessagesForRegisterVM.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,41 +19,41 @@ import org.eclipse.osgi.util.NLS; * @noinstantiate This class is not intended to be instantiated by clients. */ public class MessagesForRegisterVM extends NLS { - public static String RegisterColumnPresentation_description; - public static String RegisterColumnPresentation_name; - public static String RegisterColumnPresentation_type; - public static String RegisterColumnPresentation_value; + public static String RegisterColumnPresentation_description; + public static String RegisterColumnPresentation_name; + public static String RegisterColumnPresentation_type; + public static String RegisterColumnPresentation_value; + + public static String RegisterGroupVMNode_Name_column__text_format; + public static String RegisterGroupVMNode_Description_column__text_format; + public static String RegisterGroupVMNode_Expression_column__text_format; + public static String RegisterGroupVMNode_No_columns__text_format; + public static String RegisterGroupVMNode_No_columns__Error__text_format; + + public static String RegisterVMNode_Description_column__text_format; + public static String RegisterVMNode_Name_column__text_format; + public static String RegisterVMNode_Expression_column__text_format; + public static String RegisterVMNode_Type_column__text_format; + public static String RegisterVMNode_No_columns__text_format; + public static String RegisterVMNode_No_columns__text_format_with_type; + public static String RegisterVMNode_No_columns__Error__text_format; - public static String RegisterGroupVMNode_Name_column__text_format; - public static String RegisterGroupVMNode_Description_column__text_format; - public static String RegisterGroupVMNode_Expression_column__text_format; - public static String RegisterGroupVMNode_No_columns__text_format; - public static String RegisterGroupVMNode_No_columns__Error__text_format; + public static String RegisterBitFieldVMNode_Name_column__text_format; + public static String RegisterBitFieldVMNode_Description_column__text_format; + public static String RegisterBitFieldVMNode_Type_column__text_format; + public static String RegisterBitFieldVMNode_Value_column__With_mnemonic__text_format; + public static String RegisterBitFieldVMNode_Expression_column__text_format; + public static String RegisterBitFieldVMNode_No_columns__text_format; + public static String RegisterBitFieldVMNode_No_columns__text_format_with_type; + public static String RegisterBitFieldVMNode_No_columns__With_mnemonic__text_format; + public static String RegisterBitFieldVMNode_No_columns__With_mnemonic__text_format_with_type; + public static String RegisterBitFieldVMNode_No_columns__Error__text_format; - public static String RegisterVMNode_Description_column__text_format; - public static String RegisterVMNode_Name_column__text_format; - public static String RegisterVMNode_Expression_column__text_format; - public static String RegisterVMNode_Type_column__text_format; - public static String RegisterVMNode_No_columns__text_format; - public static String RegisterVMNode_No_columns__text_format_with_type; - public static String RegisterVMNode_No_columns__Error__text_format; - - public static String RegisterBitFieldVMNode_Name_column__text_format; - public static String RegisterBitFieldVMNode_Description_column__text_format; - public static String RegisterBitFieldVMNode_Type_column__text_format; - public static String RegisterBitFieldVMNode_Value_column__With_mnemonic__text_format; - public static String RegisterBitFieldVMNode_Expression_column__text_format; - public static String RegisterBitFieldVMNode_No_columns__text_format; - public static String RegisterBitFieldVMNode_No_columns__text_format_with_type; - public static String RegisterBitFieldVMNode_No_columns__With_mnemonic__text_format; - public static String RegisterBitFieldVMNode_No_columns__With_mnemonic__text_format_with_type; - public static String RegisterBitFieldVMNode_No_columns__Error__text_format; - - static { - // initialize resource bundle - NLS.initializeMessages(MessagesForRegisterVM.class.getName(), MessagesForRegisterVM.class); - } + static { + // initialize resource bundle + NLS.initializeMessages(MessagesForRegisterVM.class.getName(), MessagesForRegisterVM.class); + } - private MessagesForRegisterVM() { - } + private MessagesForRegisterVM() { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterBitFieldCellModifier.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterBitFieldCellModifier.java index 4fc9d667655..f760c60a00a 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterBitFieldCellModifier.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterBitFieldCellModifier.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Winnie Lai (Texas Instruments) - Individual Element Number Format in editing (Bug 343021) @@ -28,165 +28,166 @@ import org.eclipse.cdt.dsf.ui.viewmodel.update.AbstractCachingVMProvider; import org.eclipse.cdt.dsf.ui.viewmodel.update.UserEditEvent; public class RegisterBitFieldCellModifier extends WatchExpressionCellModifier { - - public static enum BitFieldEditorStyle { NOTHING, BITFIELDCOMBO, BITFIELDTEXT } - - private AbstractCachingVMProvider fProvider; - private BitFieldEditorStyle fStyle; - private IBitFieldDMData fBitFieldData = null; - private Object fElement = null; - private SyncRegisterDataAccess fDataAccess = null; - protected String formatInEditing; - - /** - * @since 2.0 - */ - public RegisterBitFieldCellModifier(AbstractCachingVMProvider provider, - BitFieldEditorStyle style, SyncRegisterDataAccess access ) - { - fProvider = provider; - fStyle = style; - fDataAccess = access; - } - - /* - * Used to make sure we are dealing with a valid register. - */ - private IBitFieldDMContext getBitFieldDMC(Object element) { - if (element instanceof IDMVMContext) { - IDMContext dmc = ((IDMVMContext)element).getDMContext(); - return DMContexts.getAncestorOfType(dmc, IBitFieldDMContext.class); - } - return null; - } - - @Override - public boolean canModify(Object element, String property) { - - /* - * If we're in the column value, modify the register data. - * Otherwise, call the super-class to edit the watch expression. - */ - if ( IDebugVMConstants.COLUMN_ID__VALUE.equals(property) ) { - /* - * Make sure we are are dealing with a valid set of information. - */ - if ( getBitFieldDMC(element) == null ) return false; - - fElement = element; - - /* - * We need to read the register in order to get the attributes. - */ - fBitFieldData = fDataAccess.readBitField(element); - - if ( ( fBitFieldData != null ) && ( ! fBitFieldData.isWriteable() ) ) return false; - - return true ; - } else { - return super.canModify(element, property); - } - } - - @Override - public Object getValue(Object element, String property) { - /* - * If we're in the column value, modify the register data. - * Otherwise, call the super-class to edit the watch expression. - */ - if ( IDebugVMConstants.COLUMN_ID__VALUE.equals(property) ) { - /* - * Make sure we are working on the editable areas. - */ - if ( element != fElement ) return false; - - if ( fStyle == BitFieldEditorStyle.BITFIELDTEXT ) { - /* - * We let the Model provider supply the current format. - */ - String formatId = null; - - if ( element instanceof IVMContext) { - formatId = queryFormat((IVMContext) element); - } - else { - formatId = IFormattedValues.NATURAL_FORMAT; - } - formatInEditing = formatId; - String value = fDataAccess.getFormattedBitFieldValue(fElement, formatId); - - if ( value == null ) { value = "..."; } //$NON-NLS-1$ - - return value; - } - else { - /* - * This is a COMBO BOX. So we need to take the value of the bitfield and - * compare it to the associated mnemonic values to see which mnemonic is - * representing the current value. At this point the Bitfield Model data - * has already been established since the "canModify()" method is called - * first by the flexible hierarchy proxies. - */ - IMnemonic curMnemonic = fBitFieldData.getCurrentMnemonicValue(); - - int index = 0 ; - for ( IMnemonic mnemonic : fBitFieldData.getMnemonics() ) { - if ( mnemonic.equals( curMnemonic ) ) { - return index; - } - index ++; - } - - return null; - } - } else { - return super.getValue(element, property); - } - } - - @Override - public void modify(Object element, String property, Object value) { - /* - * If we're in the column value, modify the register data. - * Otherwise, call the super-class to edit the watch expression. - */ - if ( IDebugVMConstants.COLUMN_ID__VALUE.equals(property) ) { - if ( fStyle == BitFieldEditorStyle.BITFIELDTEXT ) { - if (value instanceof String) { - /* - * We let the Model provider supply the current format. - */ - String formatId = formatInEditing; - - if ( element instanceof IVMContext) { - if (formatId == null) { - formatId = queryFormat((IVMContext) element); - } - } - else { - formatId = IFormattedValues.NATURAL_FORMAT; - } - fDataAccess.writeBitField(element, (String) value, formatId); - fProvider.handleEvent(new UserEditEvent(element)); - } - } - else { - if (value instanceof Integer) { - /* - * Get the integer value corresponding to the selected entry. - */ - Integer val = (Integer) value; - - /* - * Write the bit field using the selected mnemonic. - */ - fDataAccess.writeBitField(element, fBitFieldData.getMnemonics()[val.intValue()]); - fProvider.handleEvent(new UserEditEvent(element)); - } - } - } else { - super.modify(element, property, value); - } - } -} + public static enum BitFieldEditorStyle { + NOTHING, BITFIELDCOMBO, BITFIELDTEXT + } + + private AbstractCachingVMProvider fProvider; + private BitFieldEditorStyle fStyle; + private IBitFieldDMData fBitFieldData = null; + private Object fElement = null; + private SyncRegisterDataAccess fDataAccess = null; + protected String formatInEditing; + + /** + * @since 2.0 + */ + public RegisterBitFieldCellModifier(AbstractCachingVMProvider provider, BitFieldEditorStyle style, + SyncRegisterDataAccess access) { + fProvider = provider; + fStyle = style; + fDataAccess = access; + } + + /* + * Used to make sure we are dealing with a valid register. + */ + private IBitFieldDMContext getBitFieldDMC(Object element) { + if (element instanceof IDMVMContext) { + IDMContext dmc = ((IDMVMContext) element).getDMContext(); + return DMContexts.getAncestorOfType(dmc, IBitFieldDMContext.class); + } + return null; + } + + @Override + public boolean canModify(Object element, String property) { + + /* + * If we're in the column value, modify the register data. + * Otherwise, call the super-class to edit the watch expression. + */ + if (IDebugVMConstants.COLUMN_ID__VALUE.equals(property)) { + /* + * Make sure we are are dealing with a valid set of information. + */ + if (getBitFieldDMC(element) == null) + return false; + + fElement = element; + + /* + * We need to read the register in order to get the attributes. + */ + fBitFieldData = fDataAccess.readBitField(element); + + if ((fBitFieldData != null) && (!fBitFieldData.isWriteable())) + return false; + + return true; + } else { + return super.canModify(element, property); + } + } + + @Override + public Object getValue(Object element, String property) { + /* + * If we're in the column value, modify the register data. + * Otherwise, call the super-class to edit the watch expression. + */ + if (IDebugVMConstants.COLUMN_ID__VALUE.equals(property)) { + /* + * Make sure we are working on the editable areas. + */ + if (element != fElement) + return false; + + if (fStyle == BitFieldEditorStyle.BITFIELDTEXT) { + /* + * We let the Model provider supply the current format. + */ + String formatId = null; + + if (element instanceof IVMContext) { + formatId = queryFormat((IVMContext) element); + } else { + formatId = IFormattedValues.NATURAL_FORMAT; + } + formatInEditing = formatId; + String value = fDataAccess.getFormattedBitFieldValue(fElement, formatId); + + if (value == null) { + value = "..."; //$NON-NLS-1$ + } + + return value; + } else { + /* + * This is a COMBO BOX. So we need to take the value of the bitfield and + * compare it to the associated mnemonic values to see which mnemonic is + * representing the current value. At this point the Bitfield Model data + * has already been established since the "canModify()" method is called + * first by the flexible hierarchy proxies. + */ + IMnemonic curMnemonic = fBitFieldData.getCurrentMnemonicValue(); + + int index = 0; + for (IMnemonic mnemonic : fBitFieldData.getMnemonics()) { + if (mnemonic.equals(curMnemonic)) { + return index; + } + index++; + } + + return null; + } + } else { + return super.getValue(element, property); + } + } + + @Override + public void modify(Object element, String property, Object value) { + /* + * If we're in the column value, modify the register data. + * Otherwise, call the super-class to edit the watch expression. + */ + if (IDebugVMConstants.COLUMN_ID__VALUE.equals(property)) { + if (fStyle == BitFieldEditorStyle.BITFIELDTEXT) { + if (value instanceof String) { + /* + * We let the Model provider supply the current format. + */ + String formatId = formatInEditing; + + if (element instanceof IVMContext) { + if (formatId == null) { + formatId = queryFormat((IVMContext) element); + } + } else { + formatId = IFormattedValues.NATURAL_FORMAT; + } + fDataAccess.writeBitField(element, (String) value, formatId); + fProvider.handleEvent(new UserEditEvent(element)); + } + } else { + if (value instanceof Integer) { + /* + * Get the integer value corresponding to the selected entry. + */ + Integer val = (Integer) value; + + /* + * Write the bit field using the selected mnemonic. + */ + fDataAccess.writeBitField(element, fBitFieldData.getMnemonics()[val.intValue()]); + fProvider.handleEvent(new UserEditEvent(element)); + } + } + } else { + super.modify(element, property, value); + } + } +} diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterBitFieldVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterBitFieldVMNode.java index 3fa93f80a55..426cc1ffd71 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterBitFieldVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterBitFieldVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Marc Khouzam (Ericsson) - Enable per-element formatting (Bug 439624) @@ -93,1031 +93,988 @@ import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.jface.viewers.TreePath; import org.eclipse.swt.widgets.Composite; -public class RegisterBitFieldVMNode extends AbstractExpressionVMNode - implements IElementEditor, IElementLabelProvider, IElementMementoProvider, IElementPropertiesProvider -{ +public class RegisterBitFieldVMNode extends AbstractExpressionVMNode + implements IElementEditor, IElementLabelProvider, IElementMementoProvider, IElementPropertiesProvider { + /** + * @since 2.0 + */ + private static final String PROP_BITFIELD_SHOW_TYPE_NAMES = "bitfield_show_type_names"; //$NON-NLS-1$ + + protected class BitFieldVMC extends DMVMContext implements IFormattedValueVMContext { + private IExpression fExpression; + + public BitFieldVMC(IDMContext dmc) { + super(dmc); + } + + public void setExpression(IExpression expression) { + fExpression = expression; + } + + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public Object getAdapter(Class adapter) { + if (fExpression != null && adapter.isAssignableFrom(fExpression.getClass())) { + return fExpression; + } else if (adapter.isAssignableFrom(IWatchExpressionFactoryAdapter2.class)) { + return getWatchExpressionFactory(); + } else { + return super.getAdapter(adapter); + } + } + + @Override + public boolean equals(Object other) { + if (other instanceof BitFieldVMC && super.equals(other)) { + BitFieldVMC otherBitField = (BitFieldVMC) other; + return (otherBitField.fExpression == null && fExpression == null) + || (otherBitField.fExpression != null && otherBitField.fExpression.equals(fExpression)); + } + return false; + } + + @Override + public int hashCode() { + return super.hashCode() + (fExpression != null ? fExpression.hashCode() : 0); + } + } + + protected class BitFieldExpressionFactory implements IWatchExpressionFactoryAdapter2 { + + @Override + public boolean canCreateWatchExpression(Object element) { + return element instanceof BitFieldVMC; + } + + /** + * Expected format: GRP( GroupName ).REG( RegisterName ).BFLD( BitFieldname ) + */ + @Override + public String createWatchExpression(Object element) throws CoreException { + IRegisterGroupDMData groupData = getSyncRegisterDataAccess().getRegisterGroupDMData(element); + IRegisterDMData registerData = getSyncRegisterDataAccess().getRegisterDMData(element); + IBitFieldDMData bitFieldData = getSyncRegisterDataAccess().getBitFieldDMData(element); + + if (groupData != null && registerData != null && bitFieldData != null) { + StringBuffer exprBuf = new StringBuffer(); + + exprBuf.append("GRP( "); //$NON-NLS-1$ + exprBuf.append(groupData.getName()); + exprBuf.append(" )"); //$NON-NLS-1$ + exprBuf.append(".REG( "); //$NON-NLS-1$ + exprBuf.append(registerData.getName()); + exprBuf.append(" )"); //$NON-NLS-1$ + exprBuf.append(".BFLD( "); //$NON-NLS-1$ + exprBuf.append(bitFieldData.getName()); + exprBuf.append(" )"); //$NON-NLS-1$ + + return exprBuf.toString(); + } + + return null; + } + } + + private SyncRegisterDataAccess fSyncRegisterDataAccess = null; + protected IWatchExpressionFactoryAdapter2 fBitFieldExpressionFactory = null; + + /** + * The label provider delegate. This VM node will delegate label updates to this provider + * which can be created by sub-classes. + * + * @since 2.0 + */ + private IElementLabelProvider fLabelProvider; + + /** + * Retriever for formatted values configured for this VM node. + * @since 2.2 + */ + private final FormattedValueRetriever fFormattedValueRetriever; + + public RegisterBitFieldVMNode(AbstractDMVMProvider provider, DsfSession session, SyncRegisterDataAccess access) { + super(provider, session, IBitFieldDMContext.class); + fSyncRegisterDataAccess = access; + fLabelProvider = createLabelProvider(); + fFormattedValueRetriever = new FormattedValueRetriever(this, session, IRegisters.class, + IBitFieldDMContext.class); + } + + @Override + public void dispose() { + super.dispose(); + fFormattedValueRetriever.dispose(); + } + + @Override + public String toString() { + return "RegisterBitFieldVMNode(" + getSession().getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } + + private Object[] constructTypeObjects(Map<String, Object> properties) { + int readAttr = 0; + if (Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_READABLE))) { + readAttr = 1; + } else if (Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_READONCE))) { + readAttr = 2; + } + + int writeAttr = 0; + if (Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_WRITEABLE))) { + writeAttr = 1; + } else if (Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_WRITEONCE))) { + writeAttr = 2; + } + + Object[] messageAttrs = new Object[] { readAttr, writeAttr }; + + return messageAttrs; + } + + /** + * Creates the label provider delegate. This VM node will delegate label + * updates to this provider which can be created by sub-classes. + * + * @return Returns the label provider for this node. + * + * @since 2.0 + */ + protected IElementLabelProvider createLabelProvider() { + PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); + + // The name column consists of the bit field name. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__NAME, + new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForRegisterVM.RegisterBitFieldVMNode_Name_column__text_format, + new String[] { PROP_NAME }), + new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER)), + new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // The description column contains a brief description of the bit field. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__DESCRIPTION, + new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForRegisterVM.RegisterBitFieldVMNode_Description_column__text_format, + new String[] { IRegisterVMConstants.PROP_DESCRIPTION }), + new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // In the type column add information about bit field read/write/fload flags. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__TYPE, + new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForRegisterVM.RegisterBitFieldVMNode_Type_column__text_format, + new String[] { IRegisterVMConstants.PROP_IS_READABLE, + IRegisterVMConstants.PROP_IS_READONCE, IRegisterVMConstants.PROP_IS_WRITEABLE, + IRegisterVMConstants.PROP_IS_WRITEONCE }) { + @Override + public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, + Map<String, Object> properties) { + Object[] messageAttrs = constructTypeObjects(properties); + try { + update.setLabel(getMessageFormat().format(messageAttrs, new StringBuffer(), null) + .toString(), columnIndex); + } catch (IllegalArgumentException e) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, 0, + "Failed formatting a message for column " + columnIndex + ", for update " //$NON-NLS-1$//$NON-NLS-2$ + + update, + e)); + } + } + }, new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // Value column shows the value in the active value format, followed by the active mnemonic if one is + // available. + // + // In case of error, show the error message in the value column (instead of the usual "...". This is needed + // for the expressions view, where an invalid expression entered by the user is a normal use case. + // + // For changed value high-lighting check the value in the active format. But if the format itself has changed, + // ignore the value change. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__VALUE, new LabelColumnInfo(new LabelAttribute[] { + new FormattedValueLabelText( + MessagesForRegisterVM.RegisterBitFieldVMNode_Value_column__With_mnemonic__text_format, + new String[] { IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + IRegisterVMConstants.PROP_CURRENT_MNEMONIC_LONG_NAME }), + new FormattedValueLabelText(), new ErrorLabelText(), new ErrorLabelForeground(), new LabelBackground( + DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()) { + { + setPropertyNames(new String[] { IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, + ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + Boolean activeFormatChanged = (Boolean) properties.get(ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); + Boolean activeChanged = (Boolean) properties.get(ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); + return Boolean.TRUE.equals(activeChanged) && !Boolean.TRUE.equals(activeFormatChanged); + } + }, new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // Expression column is visible only in the expressions view. It shows the expression string that the user + // entered. Expression column images are the same as for the name column. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__EXPRESSION, + new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForRegisterVM.RegisterBitFieldVMNode_Expression_column__text_format, + new String[] { PROP_ELEMENT_EXPRESSION }), + new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER)), + new StaleDataLabelForeground(), new VariableLabelFont(), })); + + provider.setColumnInfo(PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, + new LabelColumnInfo(new LabelAttribute[] { new FormattedValueLabelText( + MessagesForRegisterVM.RegisterBitFieldVMNode_No_columns__With_mnemonic__text_format, + new String[] { PROP_NAME, IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + IRegisterVMConstants.PROP_CURRENT_MNEMONIC_LONG_NAME }) { + @Override + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + Boolean showTypeNames = (Boolean) properties.get(PROP_BITFIELD_SHOW_TYPE_NAMES); + return showTypeNames != null && !showTypeNames.booleanValue() + && super.isEnabled(status, properties); + } + }, new FormattedValueLabelText( + MessagesForRegisterVM.RegisterBitFieldVMNode_No_columns__With_mnemonic__text_format_with_type, + new String[] { PROP_NAME, IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + IRegisterVMConstants.PROP_CURRENT_MNEMONIC_LONG_NAME, + IRegisterVMConstants.PROP_IS_READABLE, IRegisterVMConstants.PROP_IS_READONCE, + IRegisterVMConstants.PROP_IS_WRITEABLE, IRegisterVMConstants.PROP_IS_WRITEONCE, + PROP_BITFIELD_SHOW_TYPE_NAMES }) { + @Override + public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, + Map<String, Object> properties) { + Object[] messageAttrs = constructTypeObjects(properties); + Object[] combinedAttrs = new Object[messageAttrs.length + 3]; + combinedAttrs[0] = super.getPropertyValue(PROP_NAME, status, properties); + combinedAttrs[1] = super.getPropertyValue( + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, status, properties); + combinedAttrs[2] = super.getPropertyValue(IRegisterVMConstants.PROP_CURRENT_MNEMONIC_LONG_NAME, + status, properties); + for (int idx = 0; idx < messageAttrs.length; idx++) { + combinedAttrs[idx + 3] = messageAttrs[idx]; + } + + try { + update.setLabel( + getMessageFormat().format(combinedAttrs, new StringBuffer(), null).toString(), + columnIndex); + } catch (IllegalArgumentException e) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, 0, + "Failed formatting a message for column " + columnIndex + ", for update " + update, //$NON-NLS-1$//$NON-NLS-2$ + e)); + } + } + + @Override + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + Boolean showTypeNames = (Boolean) properties.get(PROP_BITFIELD_SHOW_TYPE_NAMES); + return showTypeNames != null && showTypeNames.booleanValue() + && super.isEnabled(status, properties); + } + }, new FormattedValueLabelText(MessagesForRegisterVM.RegisterBitFieldVMNode_No_columns__text_format, + new String[] { PROP_NAME, IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE }) { + @Override + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + Boolean showTypeNames = (Boolean) properties.get(PROP_BITFIELD_SHOW_TYPE_NAMES); + return showTypeNames != null && !showTypeNames.booleanValue() + && super.isEnabled(status, properties); + } + }, new FormattedValueLabelText( + MessagesForRegisterVM.RegisterBitFieldVMNode_No_columns__text_format_with_type, + new String[] { PROP_NAME, IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + IRegisterVMConstants.PROP_IS_READABLE, IRegisterVMConstants.PROP_IS_READONCE, + IRegisterVMConstants.PROP_IS_WRITEABLE, IRegisterVMConstants.PROP_IS_WRITEONCE, + PROP_BITFIELD_SHOW_TYPE_NAMES }) { + @Override + public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, + Map<String, Object> properties) { + Object[] messageAttrs = constructTypeObjects(properties); + Object[] combinedAttrs = new Object[messageAttrs.length + 2]; + combinedAttrs[0] = super.getPropertyValue(PROP_NAME, status, properties); + combinedAttrs[1] = super.getPropertyValue( + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, status, properties); + for (int idx = 0; idx < messageAttrs.length; idx++) { + combinedAttrs[idx + 2] = messageAttrs[idx]; + } + + try { + update.setLabel( + getMessageFormat().format(combinedAttrs, new StringBuffer(), null).toString(), + columnIndex); + } catch (IllegalArgumentException e) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, 0, + "Failed formatting a message for column " + columnIndex + ", for update " + update, //$NON-NLS-1$//$NON-NLS-2$ + e)); + } + } + + @Override + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + Boolean showTypeNames = (Boolean) properties.get(PROP_BITFIELD_SHOW_TYPE_NAMES); + return showTypeNames != null && showTypeNames.booleanValue() + && super.isEnabled(status, properties); + } + }, new ErrorLabelText(MessagesForRegisterVM.RegisterBitFieldVMNode_No_columns__Error__text_format, + new String[] { PROP_NAME }), + new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER)), + new LabelForeground(DebugUITools + .getPreferenceColor(IDebugUIConstants.PREF_CHANGED_DEBUG_ELEMENT_COLOR).getRGB()) { + { + setPropertyNames( + new String[] { IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, + ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + Boolean activeFormatChanged = (Boolean) properties + .get(ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); + Boolean activeChanged = (Boolean) properties + .get(ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); + return Boolean.TRUE.equals(activeChanged) && !Boolean.TRUE.equals(activeFormatChanged); + } + }, new StaleDataLabelBackground(), new VariableLabelFont(), })); + + return provider; + } + /** - * @since 2.0 - */ - private static final String PROP_BITFIELD_SHOW_TYPE_NAMES = "bitfield_show_type_names"; //$NON-NLS-1$ - - protected class BitFieldVMC extends DMVMContext - implements IFormattedValueVMContext - { - private IExpression fExpression; - public BitFieldVMC(IDMContext dmc) { - super(dmc); - } - - public void setExpression(IExpression expression) { - fExpression = expression; - } - - @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Object getAdapter(Class adapter) { - if (fExpression != null && adapter.isAssignableFrom(fExpression.getClass())) { - return fExpression; - } else if (adapter.isAssignableFrom(IWatchExpressionFactoryAdapter2.class)) { - return getWatchExpressionFactory(); - } else { - return super.getAdapter(adapter); - } - } - - @Override - public boolean equals(Object other) { - if (other instanceof BitFieldVMC && super.equals(other)) { - BitFieldVMC otherBitField = (BitFieldVMC)other; - return (otherBitField.fExpression == null && fExpression == null) || - (otherBitField.fExpression != null && otherBitField.fExpression.equals(fExpression)); - } - return false; - } - - @Override - public int hashCode() { - return super.hashCode() + (fExpression != null ? fExpression.hashCode() : 0); - } - } - - protected class BitFieldExpressionFactory implements IWatchExpressionFactoryAdapter2 { - - @Override - public boolean canCreateWatchExpression(Object element) { - return element instanceof BitFieldVMC; - } - - /** - * Expected format: GRP( GroupName ).REG( RegisterName ).BFLD( BitFieldname ) - */ - @Override - public String createWatchExpression(Object element) throws CoreException { - IRegisterGroupDMData groupData = getSyncRegisterDataAccess().getRegisterGroupDMData(element); - IRegisterDMData registerData = getSyncRegisterDataAccess().getRegisterDMData(element); - IBitFieldDMData bitFieldData = getSyncRegisterDataAccess().getBitFieldDMData(element); - - if (groupData != null && registerData != null && bitFieldData != null) { - StringBuffer exprBuf = new StringBuffer(); - - exprBuf.append("GRP( "); exprBuf.append(groupData.getName()); exprBuf.append(" )"); //$NON-NLS-1$ //$NON-NLS-2$ - exprBuf.append(".REG( "); exprBuf.append(registerData.getName()); exprBuf.append(" )"); //$NON-NLS-1$ //$NON-NLS-2$ - exprBuf.append(".BFLD( "); exprBuf.append(bitFieldData.getName()); exprBuf.append(" )"); //$NON-NLS-1$ //$NON-NLS-2$ - - return exprBuf.toString(); - } - - return null; - } - } - - private SyncRegisterDataAccess fSyncRegisterDataAccess = null; - protected IWatchExpressionFactoryAdapter2 fBitFieldExpressionFactory = null; - - /** - * The label provider delegate. This VM node will delegate label updates to this provider - * which can be created by sub-classes. - * - * @since 2.0 - */ - private IElementLabelProvider fLabelProvider; - - /** - * Retriever for formatted values configured for this VM node. - * @since 2.2 - */ - private final FormattedValueRetriever fFormattedValueRetriever; - - public RegisterBitFieldVMNode(AbstractDMVMProvider provider, DsfSession session, SyncRegisterDataAccess access) { - super(provider, session, IBitFieldDMContext.class); - fSyncRegisterDataAccess = access; - fLabelProvider = createLabelProvider(); - fFormattedValueRetriever = - new FormattedValueRetriever(this, session, IRegisters.class, IBitFieldDMContext.class); - } - - @Override - public void dispose() { - super.dispose(); - fFormattedValueRetriever.dispose(); - } - - @Override - public String toString() { - return "RegisterBitFieldVMNode(" + getSession().getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - } - - private Object[] constructTypeObjects( Map<String, Object> properties ) { - int readAttr = 0; - if ( Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_READABLE)) ) { - readAttr = 1; - } else if ( Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_READONCE)) ) { - readAttr = 2; - } - - int writeAttr = 0; - if ( Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_WRITEABLE)) ) { - writeAttr = 1; - } else if ( Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_WRITEONCE)) ) { - writeAttr = 2; - } - - Object[] messageAttrs = new Object[] { readAttr, writeAttr }; - - return messageAttrs; - } - - /** - * Creates the label provider delegate. This VM node will delegate label - * updates to this provider which can be created by sub-classes. - * - * @return Returns the label provider for this node. - * - * @since 2.0 - */ - protected IElementLabelProvider createLabelProvider() { - PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); - - // The name column consists of the bit field name. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__NAME, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForRegisterVM.RegisterBitFieldVMNode_Name_column__text_format, - new String[] { PROP_NAME }), - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER)), - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // The description column contains a brief description of the bit field. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__DESCRIPTION, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForRegisterVM.RegisterBitFieldVMNode_Description_column__text_format, - new String[] { IRegisterVMConstants.PROP_DESCRIPTION }), - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // In the type column add information about bit field read/write/fload flags. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__TYPE, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForRegisterVM.RegisterBitFieldVMNode_Type_column__text_format, - new String[] { - IRegisterVMConstants.PROP_IS_READABLE, - IRegisterVMConstants.PROP_IS_READONCE, - IRegisterVMConstants.PROP_IS_WRITEABLE, - IRegisterVMConstants.PROP_IS_WRITEONCE}) - { - @Override - public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { - Object[] messageAttrs = constructTypeObjects( properties ); - try { - update.setLabel(getMessageFormat().format( - messageAttrs, new StringBuffer(), null).toString(), columnIndex); - } catch (IllegalArgumentException e) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, 0, "Failed formatting a message for column " + columnIndex + ", for update " + update, e)); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - }, - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // Value column shows the value in the active value format, followed by the active mnemonic if one is - // available. - // - // In case of error, show the error message in the value column (instead of the usual "...". This is needed - // for the expressions view, where an invalid expression entered by the user is a normal use case. - // - // For changed value high-lighting check the value in the active format. But if the format itself has changed, - // ignore the value change. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__VALUE, - new LabelColumnInfo(new LabelAttribute[] { - new FormattedValueLabelText( - MessagesForRegisterVM.RegisterBitFieldVMNode_Value_column__With_mnemonic__text_format, - new String[] { - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - IRegisterVMConstants.PROP_CURRENT_MNEMONIC_LONG_NAME}), - new FormattedValueLabelText(), - new ErrorLabelText(), - new ErrorLabelForeground(), - new LabelBackground( - DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()) - { - { - setPropertyNames(new String[] { - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT}); - } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - Boolean activeFormatChanged = (Boolean)properties.get( - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); - Boolean activeChanged = (Boolean)properties.get( - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); - return Boolean.TRUE.equals(activeChanged) && !Boolean.TRUE.equals(activeFormatChanged); - } - }, - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // Expression column is visible only in the expressions view. It shows the expression string that the user - // entered. Expression column images are the same as for the name column. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__EXPRESSION, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForRegisterVM.RegisterBitFieldVMNode_Expression_column__text_format, - new String[] { PROP_ELEMENT_EXPRESSION }), - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER)), - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - provider.setColumnInfo( - PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, - new LabelColumnInfo(new LabelAttribute[] { - new FormattedValueLabelText( - MessagesForRegisterVM.RegisterBitFieldVMNode_No_columns__With_mnemonic__text_format, - new String[] { - PROP_NAME, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - IRegisterVMConstants.PROP_CURRENT_MNEMONIC_LONG_NAME}) - { - @Override - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - Boolean showTypeNames = (Boolean) properties.get(PROP_BITFIELD_SHOW_TYPE_NAMES); - return - showTypeNames != null && - !showTypeNames.booleanValue() && - super.isEnabled(status, properties); - } - }, - new FormattedValueLabelText( - MessagesForRegisterVM.RegisterBitFieldVMNode_No_columns__With_mnemonic__text_format_with_type, - new String[] { - PROP_NAME, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - IRegisterVMConstants.PROP_CURRENT_MNEMONIC_LONG_NAME, - IRegisterVMConstants.PROP_IS_READABLE, - IRegisterVMConstants.PROP_IS_READONCE, - IRegisterVMConstants.PROP_IS_WRITEABLE, - IRegisterVMConstants.PROP_IS_WRITEONCE, - PROP_BITFIELD_SHOW_TYPE_NAMES}) - { - @Override - public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { - Object[] messageAttrs = constructTypeObjects( properties ); - Object[] combinedAttrs = new Object[ messageAttrs.length + 3 ]; - combinedAttrs[0] = super.getPropertyValue(PROP_NAME, status, properties); - combinedAttrs[1] = super.getPropertyValue(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, status, properties); - combinedAttrs[2] = super.getPropertyValue(IRegisterVMConstants.PROP_CURRENT_MNEMONIC_LONG_NAME, status, properties); - for ( int idx = 0 ; idx < messageAttrs.length; idx ++ ) { - combinedAttrs[ idx + 3 ] = messageAttrs[ idx ]; - } - - try { - update.setLabel(getMessageFormat().format(combinedAttrs, new StringBuffer(), null).toString(), columnIndex); - } catch (IllegalArgumentException e) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, 0, "Failed formatting a message for column " + columnIndex + ", for update " + update, e)); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - @Override - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - Boolean showTypeNames = (Boolean) properties.get(PROP_BITFIELD_SHOW_TYPE_NAMES); - return - showTypeNames != null && - showTypeNames.booleanValue() && - super.isEnabled(status, properties); - } - }, - new FormattedValueLabelText( - MessagesForRegisterVM.RegisterBitFieldVMNode_No_columns__text_format, - new String[] { - PROP_NAME, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE}) - { - @Override - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - Boolean showTypeNames = (Boolean) properties.get(PROP_BITFIELD_SHOW_TYPE_NAMES); - return - showTypeNames != null && - !showTypeNames.booleanValue() && - super.isEnabled(status, properties); - } - }, - new FormattedValueLabelText( - MessagesForRegisterVM.RegisterBitFieldVMNode_No_columns__text_format_with_type, - new String[] { - PROP_NAME, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - IRegisterVMConstants.PROP_IS_READABLE, - IRegisterVMConstants.PROP_IS_READONCE, - IRegisterVMConstants.PROP_IS_WRITEABLE, - IRegisterVMConstants.PROP_IS_WRITEONCE, - PROP_BITFIELD_SHOW_TYPE_NAMES}) - { - @Override - public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { - Object[] messageAttrs = constructTypeObjects( properties ); - Object[] combinedAttrs = new Object[ messageAttrs.length + 2 ]; - combinedAttrs[0] = super.getPropertyValue(PROP_NAME, status, properties); - combinedAttrs[1] = super.getPropertyValue(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, status, properties); - for ( int idx = 0 ; idx < messageAttrs.length; idx ++ ) { - combinedAttrs[ idx + 2 ] = messageAttrs[ idx ]; - } - - try { - update.setLabel(getMessageFormat().format(combinedAttrs, new StringBuffer(), null).toString(), columnIndex); - } catch (IllegalArgumentException e) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, 0, "Failed formatting a message for column " + columnIndex + ", for update " + update, e)); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - @Override - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - Boolean showTypeNames = (Boolean) properties.get(PROP_BITFIELD_SHOW_TYPE_NAMES); - return - showTypeNames != null && - showTypeNames.booleanValue() && - super.isEnabled(status, properties); - } - }, - new ErrorLabelText( - MessagesForRegisterVM.RegisterBitFieldVMNode_No_columns__Error__text_format, - new String[] { PROP_NAME }), - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER)), - new LabelForeground( - DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_DEBUG_ELEMENT_COLOR).getRGB()) - { - { - setPropertyNames(new String[] { - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT}); - } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - Boolean activeFormatChanged = (Boolean)properties.get( - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); - Boolean activeChanged = (Boolean)properties.get( - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); - return Boolean.TRUE.equals(activeChanged) && !Boolean.TRUE.equals(activeFormatChanged); - } - }, - new StaleDataLabelBackground(), - new VariableLabelFont(), - })); - - return provider; - } - - /** - * @since 1.1 - */ - public SyncRegisterDataAccess getSyncRegisterDataAccess() { - return fSyncRegisterDataAccess; - } - - /** - * @since 1.1 - */ - public IWatchExpressionFactoryAdapter2 getWatchExpressionFactory() { - if ( fBitFieldExpressionFactory == null ) { - fBitFieldExpressionFactory = new BitFieldExpressionFactory(); - } - return fBitFieldExpressionFactory; - } - - @Override - public void update(final ILabelUpdate[] updates) { - fLabelProvider.update(updates); - } - - /** - * Update the variable view properties. The formatted values need to be - * updated in the VM executor thread while the rest of the properties is - * updated in the service session's executor thread. The implementation - * splits the handling of the updates to accomplish that. - * - * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) - * - * @since 2.0 - */ - @Override - public void update(final IPropertiesUpdate[] updates) { - final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), null) { - @Override - protected void handleCompleted() { - for (int i = 0; i < updates.length; i++) { - updates[i].done(); - } - }; - }; - int count = 0; - - fFormattedValueRetriever.update(updates, countingRm); - count++; - - final IPropertiesUpdate[] subUpdates = new IPropertiesUpdate[updates.length]; - for (int i = 0; i < updates.length; i++) { - final IPropertiesUpdate update = updates[i]; - subUpdates[i] = new VMDelegatingPropertiesUpdate(update, countingRm); - count++; - } - countingRm.setDoneCount(count); - - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - updatePropertiesInSessionThread(subUpdates); - }}); - } catch (RejectedExecutionException e) { - for (IPropertiesUpdate subUpdate : subUpdates) { - subUpdate.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "Session executor shut down " + getSession().getExecutor(), e)); //$NON-NLS-1$ - subUpdate.done(); - } - } - } - - - // - // @param return-value Boolean.TRUE --> Show Types ICON is selected/depressed - // @param return-value Boolean.FALSE --> Show Types ICON is not selected/depressed - // - private Boolean getShowTypeNamesState( IPresentationContext context ) { - Boolean attribute = (Boolean) context.getProperty(IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES); - - if (attribute != null) { - return attribute; - } - - return Boolean.FALSE; - } - - /** - * @since 2.0 - */ - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { - IRegisters service = getServicesTracker().getService(IRegisters.class, null); - - final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), null) { - @Override - protected void handleCompleted() { - for (final IPropertiesUpdate update : updates) { - update.done(); - } - }; - }; - int count = 0; - - for (final IPropertiesUpdate update : updates) { - IExpression expression = (IExpression)DebugPlugin.getAdapter(update.getElement(), IExpression.class); - if (expression != null) { - update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, expression.getExpressionText()); - } - - // Capture the current "Show Type Names" ICON state in case there are no columns. - if (update.getProperties().contains(PROP_BITFIELD_SHOW_TYPE_NAMES)) { - update.setProperty(PROP_BITFIELD_SHOW_TYPE_NAMES, getShowTypeNamesState(update.getPresentationContext())); - } - - IBitFieldDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IBitFieldDMContext.class); - if (dmc == null || service == null) { - handleFailedUpdate(update); - continue; - } - - service.getBitFieldData( - dmc, - // Use the ViewerDataRequestMonitor in order to propagate the update's cancel request. Use an immediate - // executor to avoid the possibility of a rejected execution exception. - new ViewerDataRequestMonitor<IBitFieldDMData>(getSession().getExecutor(), update) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - fillBitFieldDataProperties(update, getData()); - } else { - update.setStatus(getStatus()); - } - countingRm.done(); - } - }); - count++; - } - countingRm.setDoneCount(count); - } - - /** - * @since 2.0 - */ - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void fillBitFieldDataProperties(IPropertiesUpdate update, IBitFieldDMData data) { - update.setProperty(PROP_NAME, data.getName()); - update.setProperty(IRegisterVMConstants.PROP_DESCRIPTION, data.getDescription()); - update.setProperty(IRegisterVMConstants.PROP_IS_READABLE, data.isReadable()); - update.setProperty(IRegisterVMConstants.PROP_IS_READONCE, data.isReadOnce()); - update.setProperty(IRegisterVMConstants.PROP_IS_WRITEABLE, data.isWriteable()); - update.setProperty(IRegisterVMConstants.PROP_IS_WRITEONCE, data.isWriteOnce()); - update.setProperty(IRegisterVMConstants.PROP_HAS_SIDE_EFFECTS, data.hasSideEffects()); - update.setProperty(IRegisterVMConstants.PROP_IS_ZERO_BIT_LEFT_MOST, data.isZeroBitLeftMost()); - update.setProperty(IRegisterVMConstants.PROP_IS_ZERO_BASED_NUMBERING, data.isZeroBasedNumbering()); - IMnemonic mnemonic = data.getCurrentMnemonicValue(); - if (mnemonic != null) { - update.setProperty(IRegisterVMConstants.PROP_CURRENT_MNEMONIC_LONG_NAME, mnemonic.getLongName()); - update.setProperty(IRegisterVMConstants.PROP_CURRENT_MNEMONIC_SHORT_NAME, mnemonic.getShortName()); - } - - /* - * If this node has an expression then it has already been filled in by the higher - * level logic. If not then we need to supply something. In the previous version - * ( pre-property based ) we supplied the name. So we will do that here also. - */ - IExpression expression = (IExpression)DebugPlugin.getAdapter(update.getElement(), IExpression.class); - if (expression == null) { - update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, data.getName()); - } - } - - @Override - protected void updateElementsInSessionThread(final IChildrenUpdate update) { - final IRegisterDMContext regDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IRegisterDMContext.class); - - if (regDmc == null) { - handleFailedUpdate(update); - return; - } - - IRegisters regService = getServicesTracker().getService(IRegisters.class); - - if ( regService == null ) { - handleFailedUpdate(update); - return; - } - - - regService.getBitFields( - regDmc, - new ViewerDataRequestMonitor<IBitFieldDMContext[]>(getSession().getExecutor(), update) { - @Override - protected void handleFailure() { - handleFailedUpdate(update); - } - - @Override - protected void handleSuccess() { - fillUpdateWithVMCs(update, getData()); - update.done(); - } - }); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#createVMContext(org.eclipse.cdt.dsf.datamodel.IDMContext) - */ - @Override - protected IDMVMContext createVMContext(IDMContext dmc) { - return new BitFieldVMC(dmc); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.IVMNode#getDeltaFlags(java.lang.Object) - */ - @Override - public int getDeltaFlags(Object e) { - if ( e instanceof ISuspendedDMEvent || - e instanceof IMemoryChangedEvent || - e instanceof IRegisterChangedDMEvent || - (e instanceof PropertyChangeEvent && - ((PropertyChangeEvent)e).getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE) ) - { - return IModelDelta.CONTENT; - } - - if (e instanceof IBitFieldChangedDMEvent) { - return IModelDelta.STATE; - } - - return IModelDelta.NO_CHANGE; - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.IVMNode#buildDelta(java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, int, org.eclipse.cdt.dsf.concurrent.RequestMonitor) - */ - @Override - public void buildDelta(Object e, VMDelta parentDelta, int nodeOffset, RequestMonitor rm) { - // The following events can affect any bit field's values, - // refresh the contents of the parent element (i.e. all the registers). - if ( e instanceof ISuspendedDMEvent || - e instanceof IMemoryChangedEvent || - e instanceof IRegisterChangedDMEvent || - (e instanceof PropertyChangeEvent && - ((PropertyChangeEvent)e).getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE) ) - { - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } - - if (e instanceof IBitFieldChangedDMEvent) { - // Create a delta indicating that the value of bit field has changed. - parentDelta.addNode( createVMContext(((IBitFieldChangedDMEvent)e).getDMContext()), IModelDelta.STATE ); - } - - rm.done(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellEditor(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.String, java.lang.Object, org.eclipse.swt.widgets.Composite) - */ - @Override - public CellEditor getCellEditor(IPresentationContext context, String columnId, Object element, Composite parent) { - - if (IDebugVMConstants.COLUMN_ID__VALUE.equals(columnId)) { - /* - * In order to decide what kind of editor to present we need to know if there are - * mnemonics which can be used to represent the values. If there are then we will - * create a Combo editor for them. Otherwise we will just make a normal text cell - * editor. If there are bit groups then the modifier will check the size of the - * value being entered. - */ - IBitFieldDMData bitFieldData = getSyncRegisterDataAccess().readBitField(element); - - if ( bitFieldData != null && bitFieldData.isWriteable() ) { - - IMnemonic[] mnemonics = bitFieldData.getMnemonics(); - - if ( mnemonics != null && mnemonics.length != 0 ) { - - /* - * Create the list of readable dropdown selections. - */ - String[] StringValues = new String[ mnemonics.length ]; - - int idx = 0 ; - for ( IMnemonic mnemonic : mnemonics ) { - StringValues[ idx ++ ] = mnemonic.getLongName(); - } - - /* - * Not we are complex COMBO and return the right editor. - */ - return new ComboBoxCellEditor(parent, StringValues); - } - else { - /* - * Text editor even if we need to clamp the value entered. - */ - return new TextCellEditor(parent); - } - } - } else if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnId)) { - return new TextCellEditor(parent); - } - return null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellModifier(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.Object) - */ - @Override - public ICellModifier getCellModifier(IPresentationContext context, Object element) { - - /* - * In order to decide what kind of modifier to present we need to know if there - * are mnemonics which can be used to represent the values. - */ - IBitFieldDMData bitFieldData = getSyncRegisterDataAccess().readBitField(element); - - if ( bitFieldData != null && bitFieldData.isWriteable() ) { - - IMnemonic[] mnemonics = bitFieldData.getMnemonics(); - - if ( mnemonics != null && mnemonics.length != 0 ) { - /* - * Note we are complex COMBO and return the right editor. - */ - return new RegisterBitFieldCellModifier( - getDMVMProvider(), BitFieldEditorStyle.BITFIELDCOMBO, getSyncRegisterDataAccess() ); - } - else { - /* - * Text editor even if we need to clamp the value entered. - */ - return new RegisterBitFieldCellModifier( - getDMVMProvider(), BitFieldEditorStyle.BITFIELDTEXT, getSyncRegisterDataAccess() ); - } - } - else { - return null; - } - } - - /** - * Expected format: GRP( GroupName ).REG( RegisterName ).BFLD( BitFieldname ) - */ - - @Override - public boolean canParseExpression(IExpression expression) { - return parseExpressionForBitFieldName(expression.getExpressionText()) != null; - } - - private String parseExpressionForBitFieldName(String expression) { - - if (expression.startsWith("GRP(")) { //$NON-NLS-1$ - - /* - * Get the group portion. - */ - int startIdx = "GRP(".length(); //$NON-NLS-1$ - int endIdx = expression.indexOf(')', startIdx); - if ( startIdx == -1 || endIdx == -1 ) { - return null; - } - String remaining = expression.substring(endIdx+1); - if ( ! remaining.startsWith(".REG(") ) { //$NON-NLS-1$ - return null; - } - - /* - * Get the register portion. - */ - startIdx = ".REG(".length(); //$NON-NLS-1$ - endIdx = remaining.indexOf(')', startIdx); - if ( startIdx == -1 || endIdx == -1 ) { - return null; - } - remaining = remaining.substring(endIdx+1); - - /* - * Get the bit-field portion. - */ - if ( ! remaining.startsWith(".BFLD(") ) { //$NON-NLS-1$ - return null; - } - startIdx = ".BFLD(".length(); //$NON-NLS-1$ - endIdx = remaining.indexOf(')', startIdx); - if ( startIdx == -1 || endIdx == -1 ) { - return null; - } - String bitFieldName = remaining.substring(startIdx, endIdx); - - /* - * Make sure there is nothing following. If there is then this - * is not a properly formed expression and we do not claim it. - */ - remaining = remaining.substring( endIdx + 1); - - if ( remaining.length() != 0 ) { - return null; - } - - return bitFieldName.trim(); - } - - return null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.AbstractExpressionVMNode#testElementForExpression(java.lang.Object, org.eclipse.debug.core.model.IExpression, org.eclipse.cdt.dsf.concurrent.DataRequestMonitor) - */ - @Override - protected void testElementForExpression(Object element, IExpression expression, final DataRequestMonitor<Boolean> rm) { - if (!(element instanceof IDMVMContext)) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, "Invalid context", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - final IBitFieldDMContext dmc = DMContexts.getAncestorOfType(((IDMVMContext)element).getDMContext(), IBitFieldDMContext.class); - if (dmc == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, "Invalid context", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - final String bitFieldName = parseExpressionForBitFieldName(expression.getExpressionText()); - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + * @since 1.1 + */ + public SyncRegisterDataAccess getSyncRegisterDataAccess() { + return fSyncRegisterDataAccess; + } + + /** + * @since 1.1 + */ + public IWatchExpressionFactoryAdapter2 getWatchExpressionFactory() { + if (fBitFieldExpressionFactory == null) { + fBitFieldExpressionFactory = new BitFieldExpressionFactory(); + } + return fBitFieldExpressionFactory; + } + + @Override + public void update(final ILabelUpdate[] updates) { + fLabelProvider.update(updates); + } + + /** + * Update the variable view properties. The formatted values need to be + * updated in the VM executor thread while the rest of the properties is + * updated in the service session's executor thread. The implementation + * splits the handling of the updates to accomplish that. + * + * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) + * + * @since 2.0 + */ + @Override + public void update(final IPropertiesUpdate[] updates) { + final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), null) { + @Override + protected void handleCompleted() { + for (int i = 0; i < updates.length; i++) { + updates[i].done(); + } + }; + }; + int count = 0; + + fFormattedValueRetriever.update(updates, countingRm); + count++; + + final IPropertiesUpdate[] subUpdates = new IPropertiesUpdate[updates.length]; + for (int i = 0; i < updates.length; i++) { + final IPropertiesUpdate update = updates[i]; + subUpdates[i] = new VMDelegatingPropertiesUpdate(update, countingRm); + count++; + } + countingRm.setDoneCount(count); + + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - IRegisters registersService = getServicesTracker().getService(IRegisters.class); - if (registersService != null) { - registersService.getBitFieldData( - dmc, - new DataRequestMonitor<IBitFieldDMData>(ImmediateExecutor.getInstance(), rm) { - @Override - protected void handleSuccess() { - rm.setData( getData().getName().equals(bitFieldName) ); - rm.done(); - } - }); - } else { - rm.setStatus(new Status(IStatus.WARNING, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Register service not available", null)); //$NON-NLS-1$ - rm.done(); - } - } - }); - } catch (RejectedExecutionException e) { - rm.setStatus(new Status(IStatus.WARNING, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "DSF session shut down", null)); //$NON-NLS-1$ - rm.done(); - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.AbstractExpressionVMNode#associateExpression(java.lang.Object, org.eclipse.debug.core.model.IExpression) - */ - @Override - protected void associateExpression(Object element, IExpression expression) { - if (element instanceof BitFieldVMC) { - ((BitFieldVMC)element).setExpression(expression); - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#getDeltaFlagsForExpression(org.eclipse.debug.core.model.IExpression, java.lang.Object) - */ - @Override - public int getDeltaFlagsForExpression(IExpression expression, Object event) { - if (event instanceof ISuspendedDMEvent) { - return IModelDelta.CONTENT; - } - - if (event instanceof PropertyChangeEvent && - ((PropertyChangeEvent)event).getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE) { - return IModelDelta.CONTENT; - } - - if (event instanceof IMemoryChangedEvent) { - return IModelDelta.CONTENT; - } - - if (event instanceof ElementFormatEvent) { - int depth = ((ElementFormatEvent)event).getApplyDepth(); - if (depth == 0) return IModelDelta.NO_CHANGE; - if (depth == 1) return IModelDelta.STATE; - return IModelDelta.CONTENT; - } - - return IModelDelta.NO_CHANGE; - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#buildDeltaForExpression(org.eclipse.debug.core.model.IExpression, int, java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, org.eclipse.jface.viewers.TreePath, org.eclipse.cdt.dsf.concurrent.RequestMonitor) - */ - @Override - public void buildDeltaForExpression(final IExpression expression, final int elementIdx, final Object event, final VMDelta parentDelta, final TreePath path, final RequestMonitor rm) - { - // Always refresh the contents of the view upon suspended event. - if (event instanceof ISuspendedDMEvent) { - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } - - rm.done(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#buildDeltaForExpressionElement(java.lang.Object, int, java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, org.eclipse.cdt.dsf.concurrent.RequestMonitor) - */ - @Override - public void buildDeltaForExpressionElement(Object element, int elementIdx, Object event, VMDelta parentDelta, final RequestMonitor rm) - { - // The following events can affect register values, refresh the state - // of the expression. - if ( event instanceof IRegisterChangedDMEvent || - event instanceof IMemoryChangedEvent || - (event instanceof PropertyChangeEvent && - ((PropertyChangeEvent)event).getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE) ) - { - parentDelta.addNode(element, IModelDelta.STATE); - } - else if (event instanceof ElementFormatEvent) - { - int depth = ((ElementFormatEvent)event).getApplyDepth(); - if (depth != 0) { - int deltaType = IModelDelta.CONTENT; - if (depth == 1) deltaType = IModelDelta.STATE; - - Set<Object> elements = ((ElementFormatEvent)event).getElements(); - for (Object elem : elements) { - parentDelta.addNode(elem, deltaType); - } - } - } - - rm.done(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#compareElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementCompareRequest[]) - */ - private final String MEMENTO_NAME = "BITFIELD_MEMENTO_NAME"; //$NON-NLS-1$ - - @Override - public void compareElements(IElementCompareRequest[] requests) { - for ( final IElementCompareRequest request : requests ) { - final String mementoName = request.getMemento().getString(MEMENTO_NAME); - - final IBitFieldDMContext regDmc = findDmcInPath(request.getViewerInput(), request.getElementPath(), IBitFieldDMContext.class); - if (regDmc == null || mementoName == null) { - request.done(); - continue; - } - - // Now go get the model data for the single register group found. - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - final IRegisters regService = getServicesTracker().getService(IRegisters.class); - if ( regService != null ) { - regService.getBitFieldData( - regDmc, - new DataRequestMonitor<IBitFieldDMData>(regService.getExecutor(), null) { - @Override - protected void handleCompleted() { - if ( getStatus().isOK() ) { - // Now make sure the register group is the one we want. - request.setEqual( mementoName.equals( "BitField." + getData().getName() ) ); //$NON-NLS-1$ - } - request.done(); - } - }); - } else { - request.done(); - } - } - }); - } catch (RejectedExecutionException e) { - request.done(); - } - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#encodeElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoRequest[]) - */ - @Override - public void encodeElements(IElementMementoRequest[] requests) { - for ( final IElementMementoRequest request : requests ) { - final IBitFieldDMContext regDmc = findDmcInPath(request.getViewerInput(), request.getElementPath(), IBitFieldDMContext.class); - if (regDmc == null) { - request.done(); - continue; - } - - // Now go get the model data for the single register group found. - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - final IRegisters regService = getServicesTracker().getService(IRegisters.class); - if ( regService != null ) { - regService.getBitFieldData( - regDmc, - new DataRequestMonitor<IBitFieldDMData>(regService.getExecutor(), null) { - @Override - protected void handleCompleted() { - if ( getStatus().isOK() ) { - // Now make sure the register group is the one we want. - request.getMemento().putString(MEMENTO_NAME, "BitField." + getData().getName()); //$NON-NLS-1$ - } - request.done(); - } - }); - } else { - request.done(); - } - } - }); - } catch (RejectedExecutionException e) { - request.done(); - } - } - } + updatePropertiesInSessionThread(subUpdates); + } + }); + } catch (RejectedExecutionException e) { + for (IPropertiesUpdate subUpdate : subUpdates) { + subUpdate.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, + "Session executor shut down " + getSession().getExecutor(), e)); //$NON-NLS-1$ + subUpdate.done(); + } + } + } + + // + // @param return-value Boolean.TRUE --> Show Types ICON is selected/depressed + // @param return-value Boolean.FALSE --> Show Types ICON is not selected/depressed + // + private Boolean getShowTypeNamesState(IPresentationContext context) { + Boolean attribute = (Boolean) context.getProperty(IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES); + + if (attribute != null) { + return attribute; + } + + return Boolean.FALSE; + } + + /** + * @since 2.0 + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { + IRegisters service = getServicesTracker().getService(IRegisters.class, null); + + final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), null) { + @Override + protected void handleCompleted() { + for (final IPropertiesUpdate update : updates) { + update.done(); + } + }; + }; + int count = 0; + + for (final IPropertiesUpdate update : updates) { + IExpression expression = (IExpression) DebugPlugin.getAdapter(update.getElement(), IExpression.class); + if (expression != null) { + update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, expression.getExpressionText()); + } + + // Capture the current "Show Type Names" ICON state in case there are no columns. + if (update.getProperties().contains(PROP_BITFIELD_SHOW_TYPE_NAMES)) { + update.setProperty(PROP_BITFIELD_SHOW_TYPE_NAMES, + getShowTypeNamesState(update.getPresentationContext())); + } + + IBitFieldDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IBitFieldDMContext.class); + if (dmc == null || service == null) { + handleFailedUpdate(update); + continue; + } + + service.getBitFieldData(dmc, + // Use the ViewerDataRequestMonitor in order to propagate the update's cancel request. Use an immediate + // executor to avoid the possibility of a rejected execution exception. + new ViewerDataRequestMonitor<IBitFieldDMData>(getSession().getExecutor(), update) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + fillBitFieldDataProperties(update, getData()); + } else { + update.setStatus(getStatus()); + } + countingRm.done(); + } + }); + count++; + } + countingRm.setDoneCount(count); + } + + /** + * @since 2.0 + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void fillBitFieldDataProperties(IPropertiesUpdate update, IBitFieldDMData data) { + update.setProperty(PROP_NAME, data.getName()); + update.setProperty(IRegisterVMConstants.PROP_DESCRIPTION, data.getDescription()); + update.setProperty(IRegisterVMConstants.PROP_IS_READABLE, data.isReadable()); + update.setProperty(IRegisterVMConstants.PROP_IS_READONCE, data.isReadOnce()); + update.setProperty(IRegisterVMConstants.PROP_IS_WRITEABLE, data.isWriteable()); + update.setProperty(IRegisterVMConstants.PROP_IS_WRITEONCE, data.isWriteOnce()); + update.setProperty(IRegisterVMConstants.PROP_HAS_SIDE_EFFECTS, data.hasSideEffects()); + update.setProperty(IRegisterVMConstants.PROP_IS_ZERO_BIT_LEFT_MOST, data.isZeroBitLeftMost()); + update.setProperty(IRegisterVMConstants.PROP_IS_ZERO_BASED_NUMBERING, data.isZeroBasedNumbering()); + IMnemonic mnemonic = data.getCurrentMnemonicValue(); + if (mnemonic != null) { + update.setProperty(IRegisterVMConstants.PROP_CURRENT_MNEMONIC_LONG_NAME, mnemonic.getLongName()); + update.setProperty(IRegisterVMConstants.PROP_CURRENT_MNEMONIC_SHORT_NAME, mnemonic.getShortName()); + } + + /* + * If this node has an expression then it has already been filled in by the higher + * level logic. If not then we need to supply something. In the previous version + * ( pre-property based ) we supplied the name. So we will do that here also. + */ + IExpression expression = (IExpression) DebugPlugin.getAdapter(update.getElement(), IExpression.class); + if (expression == null) { + update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, data.getName()); + } + } + + @Override + protected void updateElementsInSessionThread(final IChildrenUpdate update) { + final IRegisterDMContext regDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IRegisterDMContext.class); + + if (regDmc == null) { + handleFailedUpdate(update); + return; + } + + IRegisters regService = getServicesTracker().getService(IRegisters.class); + + if (regService == null) { + handleFailedUpdate(update); + return; + } + + regService.getBitFields(regDmc, + new ViewerDataRequestMonitor<IBitFieldDMContext[]>(getSession().getExecutor(), update) { + @Override + protected void handleFailure() { + handleFailedUpdate(update); + } + + @Override + protected void handleSuccess() { + fillUpdateWithVMCs(update, getData()); + update.done(); + } + }); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#createVMContext(org.eclipse.cdt.dsf.datamodel.IDMContext) + */ + @Override + protected IDMVMContext createVMContext(IDMContext dmc) { + return new BitFieldVMC(dmc); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.IVMNode#getDeltaFlags(java.lang.Object) + */ + @Override + public int getDeltaFlags(Object e) { + if (e instanceof ISuspendedDMEvent || e instanceof IMemoryChangedEvent || e instanceof IRegisterChangedDMEvent + || (e instanceof PropertyChangeEvent && ((PropertyChangeEvent) e) + .getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE)) { + return IModelDelta.CONTENT; + } + + if (e instanceof IBitFieldChangedDMEvent) { + return IModelDelta.STATE; + } + + return IModelDelta.NO_CHANGE; + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.IVMNode#buildDelta(java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, int, org.eclipse.cdt.dsf.concurrent.RequestMonitor) + */ + @Override + public void buildDelta(Object e, VMDelta parentDelta, int nodeOffset, RequestMonitor rm) { + // The following events can affect any bit field's values, + // refresh the contents of the parent element (i.e. all the registers). + if (e instanceof ISuspendedDMEvent || e instanceof IMemoryChangedEvent || e instanceof IRegisterChangedDMEvent + || (e instanceof PropertyChangeEvent && ((PropertyChangeEvent) e) + .getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE)) { + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } + + if (e instanceof IBitFieldChangedDMEvent) { + // Create a delta indicating that the value of bit field has changed. + parentDelta.addNode(createVMContext(((IBitFieldChangedDMEvent) e).getDMContext()), IModelDelta.STATE); + } + + rm.done(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellEditor(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.String, java.lang.Object, org.eclipse.swt.widgets.Composite) + */ + @Override + public CellEditor getCellEditor(IPresentationContext context, String columnId, Object element, Composite parent) { + + if (IDebugVMConstants.COLUMN_ID__VALUE.equals(columnId)) { + /* + * In order to decide what kind of editor to present we need to know if there are + * mnemonics which can be used to represent the values. If there are then we will + * create a Combo editor for them. Otherwise we will just make a normal text cell + * editor. If there are bit groups then the modifier will check the size of the + * value being entered. + */ + IBitFieldDMData bitFieldData = getSyncRegisterDataAccess().readBitField(element); + + if (bitFieldData != null && bitFieldData.isWriteable()) { + + IMnemonic[] mnemonics = bitFieldData.getMnemonics(); + + if (mnemonics != null && mnemonics.length != 0) { + + /* + * Create the list of readable dropdown selections. + */ + String[] StringValues = new String[mnemonics.length]; + + int idx = 0; + for (IMnemonic mnemonic : mnemonics) { + StringValues[idx++] = mnemonic.getLongName(); + } + + /* + * Not we are complex COMBO and return the right editor. + */ + return new ComboBoxCellEditor(parent, StringValues); + } else { + /* + * Text editor even if we need to clamp the value entered. + */ + return new TextCellEditor(parent); + } + } + } else if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnId)) { + return new TextCellEditor(parent); + } + return null; + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellModifier(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.Object) + */ + @Override + public ICellModifier getCellModifier(IPresentationContext context, Object element) { + + /* + * In order to decide what kind of modifier to present we need to know if there + * are mnemonics which can be used to represent the values. + */ + IBitFieldDMData bitFieldData = getSyncRegisterDataAccess().readBitField(element); + + if (bitFieldData != null && bitFieldData.isWriteable()) { + + IMnemonic[] mnemonics = bitFieldData.getMnemonics(); + + if (mnemonics != null && mnemonics.length != 0) { + /* + * Note we are complex COMBO and return the right editor. + */ + return new RegisterBitFieldCellModifier(getDMVMProvider(), BitFieldEditorStyle.BITFIELDCOMBO, + getSyncRegisterDataAccess()); + } else { + /* + * Text editor even if we need to clamp the value entered. + */ + return new RegisterBitFieldCellModifier(getDMVMProvider(), BitFieldEditorStyle.BITFIELDTEXT, + getSyncRegisterDataAccess()); + } + } else { + return null; + } + } + + /** + * Expected format: GRP( GroupName ).REG( RegisterName ).BFLD( BitFieldname ) + */ + + @Override + public boolean canParseExpression(IExpression expression) { + return parseExpressionForBitFieldName(expression.getExpressionText()) != null; + } + + private String parseExpressionForBitFieldName(String expression) { + + if (expression.startsWith("GRP(")) { //$NON-NLS-1$ + + /* + * Get the group portion. + */ + int startIdx = "GRP(".length(); //$NON-NLS-1$ + int endIdx = expression.indexOf(')', startIdx); + if (startIdx == -1 || endIdx == -1) { + return null; + } + String remaining = expression.substring(endIdx + 1); + if (!remaining.startsWith(".REG(")) { //$NON-NLS-1$ + return null; + } + + /* + * Get the register portion. + */ + startIdx = ".REG(".length(); //$NON-NLS-1$ + endIdx = remaining.indexOf(')', startIdx); + if (startIdx == -1 || endIdx == -1) { + return null; + } + remaining = remaining.substring(endIdx + 1); + + /* + * Get the bit-field portion. + */ + if (!remaining.startsWith(".BFLD(")) { //$NON-NLS-1$ + return null; + } + startIdx = ".BFLD(".length(); //$NON-NLS-1$ + endIdx = remaining.indexOf(')', startIdx); + if (startIdx == -1 || endIdx == -1) { + return null; + } + String bitFieldName = remaining.substring(startIdx, endIdx); + + /* + * Make sure there is nothing following. If there is then this + * is not a properly formed expression and we do not claim it. + */ + remaining = remaining.substring(endIdx + 1); + + if (remaining.length() != 0) { + return null; + } + + return bitFieldName.trim(); + } + + return null; + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.AbstractExpressionVMNode#testElementForExpression(java.lang.Object, org.eclipse.debug.core.model.IExpression, org.eclipse.cdt.dsf.concurrent.DataRequestMonitor) + */ + @Override + protected void testElementForExpression(Object element, IExpression expression, + final DataRequestMonitor<Boolean> rm) { + if (!(element instanceof IDMVMContext)) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, + "Invalid context", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + final IBitFieldDMContext dmc = DMContexts.getAncestorOfType(((IDMVMContext) element).getDMContext(), + IBitFieldDMContext.class); + if (dmc == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, + "Invalid context", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + final String bitFieldName = parseExpressionForBitFieldName(expression.getExpressionText()); + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + IRegisters registersService = getServicesTracker().getService(IRegisters.class); + if (registersService != null) { + registersService.getBitFieldData(dmc, + new DataRequestMonitor<IBitFieldDMData>(ImmediateExecutor.getInstance(), rm) { + @Override + protected void handleSuccess() { + rm.setData(getData().getName().equals(bitFieldName)); + rm.done(); + } + }); + } else { + rm.setStatus(new Status(IStatus.WARNING, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.INVALID_STATE, "Register service not available", null)); //$NON-NLS-1$ + rm.done(); + } + } + }); + } catch (RejectedExecutionException e) { + rm.setStatus(new Status(IStatus.WARNING, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "DSF session shut down", null)); //$NON-NLS-1$ + rm.done(); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.AbstractExpressionVMNode#associateExpression(java.lang.Object, org.eclipse.debug.core.model.IExpression) + */ + @Override + protected void associateExpression(Object element, IExpression expression) { + if (element instanceof BitFieldVMC) { + ((BitFieldVMC) element).setExpression(expression); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#getDeltaFlagsForExpression(org.eclipse.debug.core.model.IExpression, java.lang.Object) + */ + @Override + public int getDeltaFlagsForExpression(IExpression expression, Object event) { + if (event instanceof ISuspendedDMEvent) { + return IModelDelta.CONTENT; + } + + if (event instanceof PropertyChangeEvent && ((PropertyChangeEvent) event) + .getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE) { + return IModelDelta.CONTENT; + } + + if (event instanceof IMemoryChangedEvent) { + return IModelDelta.CONTENT; + } + + if (event instanceof ElementFormatEvent) { + int depth = ((ElementFormatEvent) event).getApplyDepth(); + if (depth == 0) + return IModelDelta.NO_CHANGE; + if (depth == 1) + return IModelDelta.STATE; + return IModelDelta.CONTENT; + } + + return IModelDelta.NO_CHANGE; + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#buildDeltaForExpression(org.eclipse.debug.core.model.IExpression, int, java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, org.eclipse.jface.viewers.TreePath, org.eclipse.cdt.dsf.concurrent.RequestMonitor) + */ + @Override + public void buildDeltaForExpression(final IExpression expression, final int elementIdx, final Object event, + final VMDelta parentDelta, final TreePath path, final RequestMonitor rm) { + // Always refresh the contents of the view upon suspended event. + if (event instanceof ISuspendedDMEvent) { + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } + + rm.done(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#buildDeltaForExpressionElement(java.lang.Object, int, java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, org.eclipse.cdt.dsf.concurrent.RequestMonitor) + */ + @Override + public void buildDeltaForExpressionElement(Object element, int elementIdx, Object event, VMDelta parentDelta, + final RequestMonitor rm) { + // The following events can affect register values, refresh the state + // of the expression. + if (event instanceof IRegisterChangedDMEvent || event instanceof IMemoryChangedEvent + || (event instanceof PropertyChangeEvent && ((PropertyChangeEvent) event) + .getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE)) { + parentDelta.addNode(element, IModelDelta.STATE); + } else if (event instanceof ElementFormatEvent) { + int depth = ((ElementFormatEvent) event).getApplyDepth(); + if (depth != 0) { + int deltaType = IModelDelta.CONTENT; + if (depth == 1) + deltaType = IModelDelta.STATE; + + Set<Object> elements = ((ElementFormatEvent) event).getElements(); + for (Object elem : elements) { + parentDelta.addNode(elem, deltaType); + } + } + } + + rm.done(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#compareElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementCompareRequest[]) + */ + private final String MEMENTO_NAME = "BITFIELD_MEMENTO_NAME"; //$NON-NLS-1$ + + @Override + public void compareElements(IElementCompareRequest[] requests) { + for (final IElementCompareRequest request : requests) { + final String mementoName = request.getMemento().getString(MEMENTO_NAME); + + final IBitFieldDMContext regDmc = findDmcInPath(request.getViewerInput(), request.getElementPath(), + IBitFieldDMContext.class); + if (regDmc == null || mementoName == null) { + request.done(); + continue; + } + + // Now go get the model data for the single register group found. + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + final IRegisters regService = getServicesTracker().getService(IRegisters.class); + if (regService != null) { + regService.getBitFieldData(regDmc, + new DataRequestMonitor<IBitFieldDMData>(regService.getExecutor(), null) { + @Override + protected void handleCompleted() { + if (getStatus().isOK()) { + // Now make sure the register group is the one we want. + request.setEqual(mementoName.equals("BitField." + getData().getName())); //$NON-NLS-1$ + } + request.done(); + } + }); + } else { + request.done(); + } + } + }); + } catch (RejectedExecutionException e) { + request.done(); + } + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#encodeElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoRequest[]) + */ + @Override + public void encodeElements(IElementMementoRequest[] requests) { + for (final IElementMementoRequest request : requests) { + final IBitFieldDMContext regDmc = findDmcInPath(request.getViewerInput(), request.getElementPath(), + IBitFieldDMContext.class); + if (regDmc == null) { + request.done(); + continue; + } + + // Now go get the model data for the single register group found. + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + final IRegisters regService = getServicesTracker().getService(IRegisters.class); + if (regService != null) { + regService.getBitFieldData(regDmc, + new DataRequestMonitor<IBitFieldDMData>(regService.getExecutor(), null) { + @Override + protected void handleCompleted() { + if (getStatus().isOK()) { + // Now make sure the register group is the one we want. + request.getMemento().putString(MEMENTO_NAME, + "BitField." + getData().getName()); //$NON-NLS-1$ + } + request.done(); + } + }); + } else { + request.done(); + } + } + }); + } catch (RejectedExecutionException e) { + request.done(); + } + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterCellModifier.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterCellModifier.java index baece2ee808..9b2672c2053 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterCellModifier.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterCellModifier.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Winnie Lai (Texas Instruments) - Individual Element Number Format in editing (Bug 343021) @@ -27,118 +27,120 @@ import org.eclipse.cdt.dsf.ui.viewmodel.update.AbstractCachingVMProvider; import org.eclipse.cdt.dsf.ui.viewmodel.update.UserEditEvent; public class RegisterCellModifier extends WatchExpressionCellModifier { - - private AbstractCachingVMProvider fProvider; - private SyncRegisterDataAccess fDataAccess = null; - protected String formatInEditing; - - public RegisterCellModifier(AbstractCachingVMProvider provider, SyncRegisterDataAccess access) - { - fProvider = provider; - fDataAccess = access; - } - - public SyncRegisterDataAccess getRegisterDataAccess() { - return fDataAccess; - } - - /* - * Used to make sure we are dealing with a valid register. - */ - protected IRegisterDMContext getRegisterDMC(Object element) { - if (element instanceof IDMVMContext) { - IDMContext dmc = ((IDMVMContext)element).getDMContext(); - return DMContexts.getAncestorOfType(dmc, IRegisterDMContext.class); - } - return null; - } - - @Override - public boolean canModify(Object element, String property) { - - /* - * If we're in the column value, modify the register data. - * Otherwise, call the super-class to edit the watch expression. - */ - if (IDebugVMConstants.COLUMN_ID__VALUE.equals(property)) { - /* - * Make sure we are are dealing with a valid set of information. - */ - if ( getRegisterDMC(element) == null ) return false; - - /* - * We need to read the register in order to get the attributes. - */ - - IRegisterDMData regData = fDataAccess.readRegister(element); - - if ( ( regData != null ) && ( ! regData.isWriteable() ) ) return false; - - return true ; - } else { - return super.canModify(element, property); - } - } - - @Override - public Object getValue(Object element, String property) { - /* - * If we're in the column value, modify the register data. - * Otherwise, call the super-class to edit the watch expression. - */ - if ( IDebugVMConstants.COLUMN_ID__VALUE.equals(property) ) { - /* - * We let the Model provider supply the current format. - */ - String formatId = null; - - if ( element instanceof IVMContext) { - formatId = queryFormat((IVMContext) element); - } - else { - formatId = IFormattedValues.NATURAL_FORMAT; - } - formatInEditing = formatId; - String value = - - fDataAccess.getFormattedRegisterValue(element, formatId); - - if ( value == null ) { return "..."; } //$NON-NLS-1$ - else { return value; } - } else { - return super.getValue(element, property); - } - } - - @Override - public void modify(Object element, String property, Object value) { - /* - * If we're in the column value, modify the register data. - * Otherwise, call the super-class to edit the watch expression. - */ - - if ( IDebugVMConstants.COLUMN_ID__VALUE.equals(property) ) { - - if (value instanceof String) { - /* - * We let the Model provider supply the current format. - */ - String formatId = formatInEditing; - - if ( element instanceof IVMContext) { - if (formatId == null) { - formatId = queryFormat((IVMContext) element); - } - } - else { - formatId = IFormattedValues.NATURAL_FORMAT; - } - - fDataAccess.writeRegister(element, (String) value, formatId); - fProvider.handleEvent(new UserEditEvent(element)); - } - } else { - super.modify(element, property, value); - } - } + + private AbstractCachingVMProvider fProvider; + private SyncRegisterDataAccess fDataAccess = null; + protected String formatInEditing; + + public RegisterCellModifier(AbstractCachingVMProvider provider, SyncRegisterDataAccess access) { + fProvider = provider; + fDataAccess = access; + } + + public SyncRegisterDataAccess getRegisterDataAccess() { + return fDataAccess; + } + + /* + * Used to make sure we are dealing with a valid register. + */ + protected IRegisterDMContext getRegisterDMC(Object element) { + if (element instanceof IDMVMContext) { + IDMContext dmc = ((IDMVMContext) element).getDMContext(); + return DMContexts.getAncestorOfType(dmc, IRegisterDMContext.class); + } + return null; + } + + @Override + public boolean canModify(Object element, String property) { + + /* + * If we're in the column value, modify the register data. + * Otherwise, call the super-class to edit the watch expression. + */ + if (IDebugVMConstants.COLUMN_ID__VALUE.equals(property)) { + /* + * Make sure we are are dealing with a valid set of information. + */ + if (getRegisterDMC(element) == null) + return false; + + /* + * We need to read the register in order to get the attributes. + */ + + IRegisterDMData regData = fDataAccess.readRegister(element); + + if ((regData != null) && (!regData.isWriteable())) + return false; + + return true; + } else { + return super.canModify(element, property); + } + } + + @Override + public Object getValue(Object element, String property) { + /* + * If we're in the column value, modify the register data. + * Otherwise, call the super-class to edit the watch expression. + */ + if (IDebugVMConstants.COLUMN_ID__VALUE.equals(property)) { + /* + * We let the Model provider supply the current format. + */ + String formatId = null; + + if (element instanceof IVMContext) { + formatId = queryFormat((IVMContext) element); + } else { + formatId = IFormattedValues.NATURAL_FORMAT; + } + formatInEditing = formatId; + String value = + + fDataAccess.getFormattedRegisterValue(element, formatId); + + if (value == null) { + return "..."; //$NON-NLS-1$ + } else { + return value; + } + } else { + return super.getValue(element, property); + } + } + + @Override + public void modify(Object element, String property, Object value) { + /* + * If we're in the column value, modify the register data. + * Otherwise, call the super-class to edit the watch expression. + */ + + if (IDebugVMConstants.COLUMN_ID__VALUE.equals(property)) { + + if (value instanceof String) { + /* + * We let the Model provider supply the current format. + */ + String formatId = formatInEditing; + + if (element instanceof IVMContext) { + if (formatId == null) { + formatId = queryFormat((IVMContext) element); + } + } else { + formatId = IFormattedValues.NATURAL_FORMAT; + } + + fDataAccess.writeRegister(element, (String) value, formatId); + fProvider.handleEvent(new UserEditEvent(element)); + } + } else { + super.modify(element, property, value); + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterColumnPresentation.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterColumnPresentation.java index 1ce300b2a0e..8d96abf6482 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterColumnPresentation.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterColumnPresentation.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,64 +20,64 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationCont import org.eclipse.jface.resource.ImageDescriptor; /** - * + * */ public class RegisterColumnPresentation implements IColumnPresentation { - public static final String ID = DsfUIPlugin.PLUGIN_ID + ".REGISTERS_COLUMN_PRESENTATION_ID"; //$NON-NLS-1$ + public static final String ID = DsfUIPlugin.PLUGIN_ID + ".REGISTERS_COLUMN_PRESENTATION_ID"; //$NON-NLS-1$ - @Override + @Override public void init(IPresentationContext context) { - } - - @Override + } + + @Override public void dispose() { - } + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getAvailableColumns() - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getAvailableColumns() + @Override public String[] getAvailableColumns() { - return new String[] { IDebugVMConstants.COLUMN_ID__NAME, IDebugVMConstants.COLUMN_ID__TYPE, IDebugVMConstants.COLUMN_ID__VALUE, IDebugVMConstants.COLUMN_ID__DESCRIPTION, }; - } + return new String[] { IDebugVMConstants.COLUMN_ID__NAME, IDebugVMConstants.COLUMN_ID__TYPE, + IDebugVMConstants.COLUMN_ID__VALUE, IDebugVMConstants.COLUMN_ID__DESCRIPTION, }; + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getHeader(java.lang.String) - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getHeader(java.lang.String) + @Override public String getHeader(String id) { - if (IDebugVMConstants.COLUMN_ID__NAME.equals(id)) { - return MessagesForRegisterVM.RegisterColumnPresentation_name; - } else if (IDebugVMConstants.COLUMN_ID__TYPE.equals(id)) { - return MessagesForRegisterVM.RegisterColumnPresentation_type; - } else if (IDebugVMConstants.COLUMN_ID__VALUE.equals(id)) { - return MessagesForRegisterVM.RegisterColumnPresentation_value; - } else if (IDebugVMConstants.COLUMN_ID__DESCRIPTION.equals(id)) { - return MessagesForRegisterVM.RegisterColumnPresentation_description; - } - return null; - } + if (IDebugVMConstants.COLUMN_ID__NAME.equals(id)) { + return MessagesForRegisterVM.RegisterColumnPresentation_name; + } else if (IDebugVMConstants.COLUMN_ID__TYPE.equals(id)) { + return MessagesForRegisterVM.RegisterColumnPresentation_type; + } else if (IDebugVMConstants.COLUMN_ID__VALUE.equals(id)) { + return MessagesForRegisterVM.RegisterColumnPresentation_value; + } else if (IDebugVMConstants.COLUMN_ID__DESCRIPTION.equals(id)) { + return MessagesForRegisterVM.RegisterColumnPresentation_description; + } + return null; + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getId() - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getId() + @Override public String getId() { - return ID; - } - - @Override - public ImageDescriptor getImageDescriptor(String id) { - return null; - } + return ID; + } + @Override + public ImageDescriptor getImageDescriptor(String id) { + return null; + } - - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getInitialColumns() - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getInitialColumns() + @Override public String[] getInitialColumns() { - return new String[] { IDebugVMConstants.COLUMN_ID__NAME, IDebugVMConstants.COLUMN_ID__VALUE, IDebugVMConstants.COLUMN_ID__DESCRIPTION }; - } - - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#isOptional() - @Override + return new String[] { IDebugVMConstants.COLUMN_ID__NAME, IDebugVMConstants.COLUMN_ID__VALUE, + IDebugVMConstants.COLUMN_ID__DESCRIPTION }; + } + + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#isOptional() + @Override public boolean isOptional() { - return true; - } + return true; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterGroupVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterGroupVMNode.java index 15250015cf1..ae0dc79c73e 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterGroupVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterGroupVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -72,560 +72,545 @@ import org.eclipse.jface.viewers.TreePath; import org.eclipse.swt.widgets.Composite; public class RegisterGroupVMNode extends AbstractExpressionVMNode - implements IElementEditor, IElementLabelProvider, IElementMementoProvider, IElementPropertiesProvider -{ - /** - * @since 2.0 - */ - private static final String PROP_REGISTER_GROUP_DESCRIPTION = "register_group_description"; //$NON-NLS-1$ - - protected class RegisterGroupVMC extends DMVMContext - { - private IExpression fExpression; - public RegisterGroupVMC(IDMContext dmc) { - super(dmc); - } - - public void setExpression(IExpression expression) { - fExpression = expression; - } - - @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Object getAdapter(Class adapter) { - if (fExpression != null && adapter.isAssignableFrom(fExpression.getClass())) { - return fExpression; - } else if (adapter.isAssignableFrom(IWatchExpressionFactoryAdapter2.class)) { - return getWatchExpressionFactory(); - } else { - return super.getAdapter(adapter); - } - } - - @Override - public boolean equals(Object other) { - if (other instanceof RegisterGroupVMC && super.equals(other)) { - RegisterGroupVMC otherGroup = (RegisterGroupVMC)other; - return (otherGroup.fExpression == null && fExpression == null) || - (otherGroup.fExpression != null && otherGroup.fExpression.equals(fExpression)); - } - return false; - } - - @Override - public int hashCode() { - return super.hashCode() + (fExpression != null ? fExpression.hashCode() : 0); - } - } - - protected class RegisterGroupExpressionFactory implements IWatchExpressionFactoryAdapter2 { - - @Override - public boolean canCreateWatchExpression(Object element) { - return element instanceof RegisterGroupVMC; - } - - /** - * Expected format: Group(GroupName) - */ - @Override - public String createWatchExpression(Object element) throws CoreException { - IRegisterGroupDMData groupData = getSyncRegisterDataAccess().getRegisterGroupDMData(element); - if (groupData != null) { - StringBuilder exprBuf = new StringBuilder(); - exprBuf.append("GRP( "); //$NON-NLS-1$ - exprBuf.append(groupData.getName()); - exprBuf.append(" )"); //$NON-NLS-1$ - return exprBuf.toString(); - } - - return null; - } - } - - final private SyncRegisterDataAccess fSyncRegisterDataAccess; - private IWatchExpressionFactoryAdapter2 fRegisterGroupExpressionFactory = null; - private WatchExpressionCellModifier fWatchExpressionCellModifier = new WatchExpressionCellModifier(); - - /** - * The label provider delegate. This VM node will delegate label updates to this provider - * which can be created by sub-classes. - * - * @since 2.0 - */ - private IElementLabelProvider fLabelProvider; - - public RegisterGroupVMNode(AbstractDMVMProvider provider, DsfSession session, SyncRegisterDataAccess syncDataAccess) { - super(provider, session, IRegisterGroupDMContext.class); - fLabelProvider = createLabelProvider(); - fSyncRegisterDataAccess = syncDataAccess; - } - - @Override - public String toString() { - return "RegisterGroupVMNode(" + getSession().getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - } - - public SyncRegisterDataAccess getSyncRegisterDataAccess() { - return fSyncRegisterDataAccess; - } - - /** - * @since 1.1 - */ - public IWatchExpressionFactoryAdapter2 getWatchExpressionFactory() { - if ( fRegisterGroupExpressionFactory == null ) { - fRegisterGroupExpressionFactory = new RegisterGroupExpressionFactory(); - } - return fRegisterGroupExpressionFactory; - } - - @Override - protected void updateElementsInSessionThread(final IChildrenUpdate update) { - - IRegisters regService = getServicesTracker().getService(IRegisters.class); - - if ( regService == null ) { - handleFailedUpdate(update); - return; - } - - regService.getRegisterGroups( - createCompositeDMVMContext(update), - new ViewerDataRequestMonitor<IRegisterGroupDMContext[]>(getSession().getExecutor(), update) { - @Override - public void handleCompleted() { - if (!isSuccess()) { - update.done(); - return; - } - fillUpdateWithVMCs(update, getData()); - update.done(); - }}); - } - - @Override - protected IDMVMContext createVMContext(IDMContext dmc) { - return new RegisterGroupVMC(dmc); - } - - /** - * Creates the label provider delegate. This VM node will delegate label - * updates to this provider which can be created by sub-classes. - * - * @return Returns the label provider for this node. - * - * @since 2.0 - */ - protected IElementLabelProvider createLabelProvider() { - PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); - - // The name column consists of the group name. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__NAME, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForRegisterVM.RegisterGroupVMNode_Name_column__text_format, - new String[] { PROP_NAME }), - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER_GROUP)), - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // The description column contains a brief description of the register group. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__DESCRIPTION, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText(MessagesForRegisterVM.RegisterGroupVMNode_Description_column__text_format, - new String[] { PROP_REGISTER_GROUP_DESCRIPTION }), - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // Expression column is visible only in the expressions view. It shows the expression string that the user - // entered. Expression column images are the same as for the name column. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__EXPRESSION, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForRegisterVM.RegisterGroupVMNode_Expression_column__text_format, - new String[] { PROP_ELEMENT_EXPRESSION }), - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER_GROUP)), - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - provider.setColumnInfo( - PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText(MessagesForRegisterVM.RegisterGroupVMNode_No_columns__text_format, - new String[] { PROP_NAME, PROP_REGISTER_GROUP_DESCRIPTION}), - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER_GROUP)), - new StaleDataLabelBackground(), - new VariableLabelFont(), - })); - - return provider; - } - - @Override - public void update(final ILabelUpdate[] updates) { - fLabelProvider.update(updates); - } - - /** - * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) - * - * @since 2.0 - */ - @Override - public void update(final IPropertiesUpdate[] updates) { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - updatePropertiesInSessionThread(updates); - }}); - } catch (RejectedExecutionException e) { - for (IPropertiesUpdate update : updates) { - handleFailedUpdate(update); - } - } - } - - /** - * @since 2.0 - */ - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void updatePropertiesInSessionThread(IPropertiesUpdate[] updates) { - IRegisters service = getServicesTracker().getService(IRegisters.class, null); - - for (final IPropertiesUpdate update : updates) { - IExpression expression = (IExpression)DebugPlugin.getAdapter(update.getElement(), IExpression.class); - if (expression != null) { - update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, expression.getExpressionText()); - } - - IRegisterGroupDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IRegisterGroupDMContext.class); - IRegisters regService = getServicesTracker().getService(IRegisters.class); - - if ( dmc == null || regService == null) { - handleFailedUpdate(update); - return; - } - - service.getRegisterGroupData( - dmc, - new ViewerDataRequestMonitor<IRegisterGroupDMData>(getSession().getExecutor(), update) { - @Override - protected void handleSuccess() { - fillRegisterGroupDataProperties(update, getData()); - update.done(); - } - }); - } - } - - /** - * @since 2.0 - */ - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void fillRegisterGroupDataProperties(IPropertiesUpdate update, IRegisterGroupDMData data) { - update.setProperty(PROP_NAME, data.getName()); - update.setProperty(PROP_REGISTER_GROUP_DESCRIPTION, data.getDescription()); - - /* - * If this node has an expression then it has already been filled in by the higher - * level logic. If not then we need to supply something. In the previous version - * ( pre-property based ) we supplied the name. So we will do that here also. - */ - IExpression expression = (IExpression)DebugPlugin.getAdapter(update.getElement(), IExpression.class); - if (expression == null) { - update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, data.getName()); - } - } - - @Override - public int getDeltaFlags(Object e) { - if (e instanceof ISuspendedDMEvent) { - return IModelDelta.CONTENT; - } - else if (e instanceof IGroupsChangedDMEvent) { - return IModelDelta.CONTENT; - } - else if (e instanceof IGroupChangedDMEvent) { - return IModelDelta.STATE; - } - return IModelDelta.NO_CHANGE; - } - - @Override - public void buildDelta(Object e, VMDelta parentDelta, int nodeOffset, RequestMonitor rm) { - // Although the register groups themselves are not affected by the - // suspended event, typically all the registers are. Add a CONTENT changed - // flag to the parent to repaint all the groups and their registers. - if (e instanceof ISuspendedDMEvent) { - // Create a delta that indicates all groups have changed - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } - else if (e instanceof IGroupsChangedDMEvent) { - // Create a delta that indicates all groups have changed - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } - else if (e instanceof IGroupChangedDMEvent) { - // Create a delta that indicates that specific group changed - parentDelta.addNode( createVMContext(((IGroupChangedDMEvent)e).getDMContext()), IModelDelta.STATE ); - } - rm.done(); - } - - @Override - public boolean canParseExpression(IExpression expression) { - return parseExpressionForGroupName(expression.getExpressionText()) != null; - } - - /** - * Expected format: Group(GroupName) - */ - private String parseExpressionForGroupName(String expression) { - if (expression.startsWith("GRP(")) { //$NON-NLS-1$ - /* - * Extract the group name. - */ - int startIdx = "GRP(".length(); //$NON-NLS-1$ - int endIdx = expression.indexOf(')', startIdx); - if ( startIdx == -1 || endIdx == -1 ) { - return null; - } - String groupName = expression.substring(startIdx, endIdx); - return groupName.trim(); - } - - return null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#getDeltaFlagsForExpression(org.eclipse.debug.core.model.IExpression, java.lang.Object) - */ - @Override - public int getDeltaFlagsForExpression(IExpression expression, Object event) { - - if (event instanceof ISuspendedDMEvent || - event instanceof IGroupsChangedDMEvent) - { - return IModelDelta.CONTENT; - } - - if (event instanceof IGroupChangedDMEvent) { - return IModelDelta.STATE; - } - - return IModelDelta.NO_CHANGE; - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#buildDeltaForExpression(org.eclipse.debug.core.model.IExpression, int, java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, org.eclipse.jface.viewers.TreePath, org.eclipse.cdt.dsf.concurrent.RequestMonitor) - */ - @Override - public void buildDeltaForExpression(IExpression expression, int elementIdx, Object event, VMDelta parentDelta, - TreePath path, RequestMonitor rm) - { - if (event instanceof ISuspendedDMEvent) { - // Mark the parent delta indicating that elements were added and/or removed. - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } - - // If the group definitions have changed, refresh the whole expressions - // view contents since previously invalid expressions may now evaluate - // to valid groups - if (event instanceof IGroupsChangedDMEvent) { - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } - - - rm.done(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#buildDeltaForExpressionElement(java.lang.Object, int, java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, org.eclipse.cdt.dsf.concurrent.RequestMonitor) - */ - @Override - public void buildDeltaForExpressionElement(Object element, int elementIdx, Object event, VMDelta parentDelta, final RequestMonitor rm) - { - if (event instanceof IGroupChangedDMEvent) { - parentDelta.addNode(element, IModelDelta.STATE); - } - rm.done(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.AbstractExpressionVMNode#testElementForExpression(java.lang.Object, org.eclipse.debug.core.model.IExpression, org.eclipse.cdt.dsf.concurrent.DataRequestMonitor) - */ - @Override - protected void testElementForExpression(Object element, IExpression expression, final DataRequestMonitor<Boolean> rm) { - if (!(element instanceof IDMVMContext)) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, "Invalid context", null)); //$NON-NLS-1$ - rm.done(); - return; - } - final IRegisterGroupDMContext dmc = DMContexts.getAncestorOfType(((IDMVMContext)element).getDMContext(), IRegisterGroupDMContext.class); - if (dmc == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, "Invalid context", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - final String groupName = parseExpressionForGroupName(expression.getExpressionText()); - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - IRegisters registersService = getServicesTracker().getService(IRegisters.class); - if (registersService != null) { - registersService.getRegisterGroupData( - dmc, - new DataRequestMonitor<IRegisterGroupDMData>(ImmediateExecutor.getInstance(), rm) { - @Override - protected void handleSuccess() { - rm.setData( getData().getName().equals(groupName) ); - rm.done(); - } - }); - } else { - rm.setStatus(new Status(IStatus.WARNING, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Register service not available", null)); //$NON-NLS-1$ - rm.done(); - } - } - }); - } catch (RejectedExecutionException e) { - rm.setStatus(new Status(IStatus.WARNING, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "DSF session shut down", null)); //$NON-NLS-1$ - rm.done(); - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.AbstractExpressionVMNode#associateExpression(java.lang.Object, org.eclipse.debug.core.model.IExpression) - */ - @Override - protected void associateExpression(Object element, IExpression expression) { - if (element instanceof RegisterGroupVMC) { - ((RegisterGroupVMC)element).setExpression(expression); - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellEditor(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.String, java.lang.Object, org.eclipse.swt.widgets.Composite) - */ - @Override - public CellEditor getCellEditor(IPresentationContext context, String columnId, Object element, Composite parent) { - if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnId)) { - return new TextCellEditor(parent); - } - return null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellModifier(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.Object) - */ - @Override - public ICellModifier getCellModifier(IPresentationContext context, Object element) { - return fWatchExpressionCellModifier; - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#compareElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementCompareRequest[]) - */ - private final String MEMENTO_NAME = "GROUP_MEMENTO_NAME"; //$NON-NLS-1$ - - @Override - public void compareElements(IElementCompareRequest[] requests) { - for (final IElementCompareRequest request : requests ) { - final IRegisterGroupDMContext regDmc = findDmcInPath(request.getViewerInput(), request.getElementPath(), IRegisterGroupDMContext.class); - final String mementoName = request.getMemento().getString(MEMENTO_NAME); - - if (regDmc == null || mementoName == null) { - request.done(); - continue; - } - - // Now go get the model data for the single register group found. - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - final IRegisters regService = getServicesTracker().getService(IRegisters.class); - if ( regService != null ) { - regService.getRegisterGroupData( - regDmc, - new DataRequestMonitor<IRegisterGroupDMData>(regService.getExecutor(), null) { - @Override - protected void handleCompleted() { - if ( getStatus().isOK() ) { - // Now make sure the register group is the one we want. - request.setEqual( mementoName.equals( "Group." + getData().getName()) ); //$NON-NLS-1$ - } - request.done(); - } - }); - } else { - request.done(); - } - } - }); - } catch (RejectedExecutionException e) { - request.done(); - } - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#encodeElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoRequest[]) - */ - @Override - public void encodeElements(IElementMementoRequest[] requests) { - for ( final IElementMementoRequest request : requests ) { - final IRegisterGroupDMContext regDmc = findDmcInPath(request.getViewerInput(), request.getElementPath(), IRegisterGroupDMContext.class); - if (regDmc == null) { - request.done(); - continue; - } - - // Now go get the model data for the single register group found. - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - final IRegisters regService = getServicesTracker().getService(IRegisters.class); - if ( regService != null ) { - regService.getRegisterGroupData( - regDmc, - new DataRequestMonitor<IRegisterGroupDMData>(regService.getExecutor(), null) { - @Override - protected void handleCompleted() { - if ( getStatus().isOK() ) { - // Now make sure the register group is the one we want. - request.getMemento().putString(MEMENTO_NAME, "Group." + getData().getName()); //$NON-NLS-1$ - } - request.done(); - } - }); - } else { - request.done(); - } - } - }); - } catch (RejectedExecutionException e) { - request.done(); - } - } - } + implements IElementEditor, IElementLabelProvider, IElementMementoProvider, IElementPropertiesProvider { + /** + * @since 2.0 + */ + private static final String PROP_REGISTER_GROUP_DESCRIPTION = "register_group_description"; //$NON-NLS-1$ + + protected class RegisterGroupVMC extends DMVMContext { + private IExpression fExpression; + + public RegisterGroupVMC(IDMContext dmc) { + super(dmc); + } + + public void setExpression(IExpression expression) { + fExpression = expression; + } + + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public Object getAdapter(Class adapter) { + if (fExpression != null && adapter.isAssignableFrom(fExpression.getClass())) { + return fExpression; + } else if (adapter.isAssignableFrom(IWatchExpressionFactoryAdapter2.class)) { + return getWatchExpressionFactory(); + } else { + return super.getAdapter(adapter); + } + } + + @Override + public boolean equals(Object other) { + if (other instanceof RegisterGroupVMC && super.equals(other)) { + RegisterGroupVMC otherGroup = (RegisterGroupVMC) other; + return (otherGroup.fExpression == null && fExpression == null) + || (otherGroup.fExpression != null && otherGroup.fExpression.equals(fExpression)); + } + return false; + } + + @Override + public int hashCode() { + return super.hashCode() + (fExpression != null ? fExpression.hashCode() : 0); + } + } + + protected class RegisterGroupExpressionFactory implements IWatchExpressionFactoryAdapter2 { + + @Override + public boolean canCreateWatchExpression(Object element) { + return element instanceof RegisterGroupVMC; + } + + /** + * Expected format: Group(GroupName) + */ + @Override + public String createWatchExpression(Object element) throws CoreException { + IRegisterGroupDMData groupData = getSyncRegisterDataAccess().getRegisterGroupDMData(element); + if (groupData != null) { + StringBuilder exprBuf = new StringBuilder(); + exprBuf.append("GRP( "); //$NON-NLS-1$ + exprBuf.append(groupData.getName()); + exprBuf.append(" )"); //$NON-NLS-1$ + return exprBuf.toString(); + } + + return null; + } + } + + final private SyncRegisterDataAccess fSyncRegisterDataAccess; + private IWatchExpressionFactoryAdapter2 fRegisterGroupExpressionFactory = null; + private WatchExpressionCellModifier fWatchExpressionCellModifier = new WatchExpressionCellModifier(); + + /** + * The label provider delegate. This VM node will delegate label updates to this provider + * which can be created by sub-classes. + * + * @since 2.0 + */ + private IElementLabelProvider fLabelProvider; + + public RegisterGroupVMNode(AbstractDMVMProvider provider, DsfSession session, + SyncRegisterDataAccess syncDataAccess) { + super(provider, session, IRegisterGroupDMContext.class); + fLabelProvider = createLabelProvider(); + fSyncRegisterDataAccess = syncDataAccess; + } + + @Override + public String toString() { + return "RegisterGroupVMNode(" + getSession().getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } + + public SyncRegisterDataAccess getSyncRegisterDataAccess() { + return fSyncRegisterDataAccess; + } + + /** + * @since 1.1 + */ + public IWatchExpressionFactoryAdapter2 getWatchExpressionFactory() { + if (fRegisterGroupExpressionFactory == null) { + fRegisterGroupExpressionFactory = new RegisterGroupExpressionFactory(); + } + return fRegisterGroupExpressionFactory; + } + + @Override + protected void updateElementsInSessionThread(final IChildrenUpdate update) { + + IRegisters regService = getServicesTracker().getService(IRegisters.class); + + if (regService == null) { + handleFailedUpdate(update); + return; + } + + regService.getRegisterGroups(createCompositeDMVMContext(update), + new ViewerDataRequestMonitor<IRegisterGroupDMContext[]>(getSession().getExecutor(), update) { + @Override + public void handleCompleted() { + if (!isSuccess()) { + update.done(); + return; + } + fillUpdateWithVMCs(update, getData()); + update.done(); + } + }); + } + + @Override + protected IDMVMContext createVMContext(IDMContext dmc) { + return new RegisterGroupVMC(dmc); + } + + /** + * Creates the label provider delegate. This VM node will delegate label + * updates to this provider which can be created by sub-classes. + * + * @return Returns the label provider for this node. + * + * @since 2.0 + */ + protected IElementLabelProvider createLabelProvider() { + PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); + + // The name column consists of the group name. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__NAME, + new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForRegisterVM.RegisterGroupVMNode_Name_column__text_format, + new String[] { PROP_NAME }), + new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER_GROUP)), + new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // The description column contains a brief description of the register group. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__DESCRIPTION, + new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForRegisterVM.RegisterGroupVMNode_Description_column__text_format, + new String[] { PROP_REGISTER_GROUP_DESCRIPTION }), + new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // Expression column is visible only in the expressions view. It shows the expression string that the user + // entered. Expression column images are the same as for the name column. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__EXPRESSION, + new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForRegisterVM.RegisterGroupVMNode_Expression_column__text_format, + new String[] { PROP_ELEMENT_EXPRESSION }), + new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER_GROUP)), + new StaleDataLabelForeground(), new VariableLabelFont(), })); + + provider.setColumnInfo(PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, + new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForRegisterVM.RegisterGroupVMNode_No_columns__text_format, + new String[] { PROP_NAME, PROP_REGISTER_GROUP_DESCRIPTION }), + new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER_GROUP)), + new StaleDataLabelBackground(), new VariableLabelFont(), })); + + return provider; + } + + @Override + public void update(final ILabelUpdate[] updates) { + fLabelProvider.update(updates); + } + + /** + * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) + * + * @since 2.0 + */ + @Override + public void update(final IPropertiesUpdate[] updates) { + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + updatePropertiesInSessionThread(updates); + } + }); + } catch (RejectedExecutionException e) { + for (IPropertiesUpdate update : updates) { + handleFailedUpdate(update); + } + } + } + + /** + * @since 2.0 + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void updatePropertiesInSessionThread(IPropertiesUpdate[] updates) { + IRegisters service = getServicesTracker().getService(IRegisters.class, null); + + for (final IPropertiesUpdate update : updates) { + IExpression expression = (IExpression) DebugPlugin.getAdapter(update.getElement(), IExpression.class); + if (expression != null) { + update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, expression.getExpressionText()); + } + + IRegisterGroupDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IRegisterGroupDMContext.class); + IRegisters regService = getServicesTracker().getService(IRegisters.class); + + if (dmc == null || regService == null) { + handleFailedUpdate(update); + return; + } + + service.getRegisterGroupData(dmc, + new ViewerDataRequestMonitor<IRegisterGroupDMData>(getSession().getExecutor(), update) { + @Override + protected void handleSuccess() { + fillRegisterGroupDataProperties(update, getData()); + update.done(); + } + }); + } + } + + /** + * @since 2.0 + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void fillRegisterGroupDataProperties(IPropertiesUpdate update, IRegisterGroupDMData data) { + update.setProperty(PROP_NAME, data.getName()); + update.setProperty(PROP_REGISTER_GROUP_DESCRIPTION, data.getDescription()); + + /* + * If this node has an expression then it has already been filled in by the higher + * level logic. If not then we need to supply something. In the previous version + * ( pre-property based ) we supplied the name. So we will do that here also. + */ + IExpression expression = (IExpression) DebugPlugin.getAdapter(update.getElement(), IExpression.class); + if (expression == null) { + update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, data.getName()); + } + } + + @Override + public int getDeltaFlags(Object e) { + if (e instanceof ISuspendedDMEvent) { + return IModelDelta.CONTENT; + } else if (e instanceof IGroupsChangedDMEvent) { + return IModelDelta.CONTENT; + } else if (e instanceof IGroupChangedDMEvent) { + return IModelDelta.STATE; + } + return IModelDelta.NO_CHANGE; + } + + @Override + public void buildDelta(Object e, VMDelta parentDelta, int nodeOffset, RequestMonitor rm) { + // Although the register groups themselves are not affected by the + // suspended event, typically all the registers are. Add a CONTENT changed + // flag to the parent to repaint all the groups and their registers. + if (e instanceof ISuspendedDMEvent) { + // Create a delta that indicates all groups have changed + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } else if (e instanceof IGroupsChangedDMEvent) { + // Create a delta that indicates all groups have changed + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } else if (e instanceof IGroupChangedDMEvent) { + // Create a delta that indicates that specific group changed + parentDelta.addNode(createVMContext(((IGroupChangedDMEvent) e).getDMContext()), IModelDelta.STATE); + } + rm.done(); + } + + @Override + public boolean canParseExpression(IExpression expression) { + return parseExpressionForGroupName(expression.getExpressionText()) != null; + } + + /** + * Expected format: Group(GroupName) + */ + private String parseExpressionForGroupName(String expression) { + if (expression.startsWith("GRP(")) { //$NON-NLS-1$ + /* + * Extract the group name. + */ + int startIdx = "GRP(".length(); //$NON-NLS-1$ + int endIdx = expression.indexOf(')', startIdx); + if (startIdx == -1 || endIdx == -1) { + return null; + } + String groupName = expression.substring(startIdx, endIdx); + return groupName.trim(); + } + + return null; + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#getDeltaFlagsForExpression(org.eclipse.debug.core.model.IExpression, java.lang.Object) + */ + @Override + public int getDeltaFlagsForExpression(IExpression expression, Object event) { + + if (event instanceof ISuspendedDMEvent || event instanceof IGroupsChangedDMEvent) { + return IModelDelta.CONTENT; + } + + if (event instanceof IGroupChangedDMEvent) { + return IModelDelta.STATE; + } + + return IModelDelta.NO_CHANGE; + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#buildDeltaForExpression(org.eclipse.debug.core.model.IExpression, int, java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, org.eclipse.jface.viewers.TreePath, org.eclipse.cdt.dsf.concurrent.RequestMonitor) + */ + @Override + public void buildDeltaForExpression(IExpression expression, int elementIdx, Object event, VMDelta parentDelta, + TreePath path, RequestMonitor rm) { + if (event instanceof ISuspendedDMEvent) { + // Mark the parent delta indicating that elements were added and/or removed. + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } + + // If the group definitions have changed, refresh the whole expressions + // view contents since previously invalid expressions may now evaluate + // to valid groups + if (event instanceof IGroupsChangedDMEvent) { + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } + + rm.done(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#buildDeltaForExpressionElement(java.lang.Object, int, java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, org.eclipse.cdt.dsf.concurrent.RequestMonitor) + */ + @Override + public void buildDeltaForExpressionElement(Object element, int elementIdx, Object event, VMDelta parentDelta, + final RequestMonitor rm) { + if (event instanceof IGroupChangedDMEvent) { + parentDelta.addNode(element, IModelDelta.STATE); + } + rm.done(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.AbstractExpressionVMNode#testElementForExpression(java.lang.Object, org.eclipse.debug.core.model.IExpression, org.eclipse.cdt.dsf.concurrent.DataRequestMonitor) + */ + @Override + protected void testElementForExpression(Object element, IExpression expression, + final DataRequestMonitor<Boolean> rm) { + if (!(element instanceof IDMVMContext)) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, + "Invalid context", null)); //$NON-NLS-1$ + rm.done(); + return; + } + final IRegisterGroupDMContext dmc = DMContexts.getAncestorOfType(((IDMVMContext) element).getDMContext(), + IRegisterGroupDMContext.class); + if (dmc == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, + "Invalid context", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + final String groupName = parseExpressionForGroupName(expression.getExpressionText()); + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + IRegisters registersService = getServicesTracker().getService(IRegisters.class); + if (registersService != null) { + registersService.getRegisterGroupData(dmc, + new DataRequestMonitor<IRegisterGroupDMData>(ImmediateExecutor.getInstance(), rm) { + @Override + protected void handleSuccess() { + rm.setData(getData().getName().equals(groupName)); + rm.done(); + } + }); + } else { + rm.setStatus(new Status(IStatus.WARNING, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.INVALID_STATE, "Register service not available", null)); //$NON-NLS-1$ + rm.done(); + } + } + }); + } catch (RejectedExecutionException e) { + rm.setStatus(new Status(IStatus.WARNING, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "DSF session shut down", null)); //$NON-NLS-1$ + rm.done(); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.AbstractExpressionVMNode#associateExpression(java.lang.Object, org.eclipse.debug.core.model.IExpression) + */ + @Override + protected void associateExpression(Object element, IExpression expression) { + if (element instanceof RegisterGroupVMC) { + ((RegisterGroupVMC) element).setExpression(expression); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellEditor(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.String, java.lang.Object, org.eclipse.swt.widgets.Composite) + */ + @Override + public CellEditor getCellEditor(IPresentationContext context, String columnId, Object element, Composite parent) { + if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnId)) { + return new TextCellEditor(parent); + } + return null; + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellModifier(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.Object) + */ + @Override + public ICellModifier getCellModifier(IPresentationContext context, Object element) { + return fWatchExpressionCellModifier; + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#compareElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementCompareRequest[]) + */ + private final String MEMENTO_NAME = "GROUP_MEMENTO_NAME"; //$NON-NLS-1$ + + @Override + public void compareElements(IElementCompareRequest[] requests) { + for (final IElementCompareRequest request : requests) { + final IRegisterGroupDMContext regDmc = findDmcInPath(request.getViewerInput(), request.getElementPath(), + IRegisterGroupDMContext.class); + final String mementoName = request.getMemento().getString(MEMENTO_NAME); + + if (regDmc == null || mementoName == null) { + request.done(); + continue; + } + + // Now go get the model data for the single register group found. + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + final IRegisters regService = getServicesTracker().getService(IRegisters.class); + if (regService != null) { + regService.getRegisterGroupData(regDmc, + new DataRequestMonitor<IRegisterGroupDMData>(regService.getExecutor(), null) { + @Override + protected void handleCompleted() { + if (getStatus().isOK()) { + // Now make sure the register group is the one we want. + request.setEqual(mementoName.equals("Group." + getData().getName())); //$NON-NLS-1$ + } + request.done(); + } + }); + } else { + request.done(); + } + } + }); + } catch (RejectedExecutionException e) { + request.done(); + } + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#encodeElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoRequest[]) + */ + @Override + public void encodeElements(IElementMementoRequest[] requests) { + for (final IElementMementoRequest request : requests) { + final IRegisterGroupDMContext regDmc = findDmcInPath(request.getViewerInput(), request.getElementPath(), + IRegisterGroupDMContext.class); + if (regDmc == null) { + request.done(); + continue; + } + + // Now go get the model data for the single register group found. + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + final IRegisters regService = getServicesTracker().getService(IRegisters.class); + if (regService != null) { + regService.getRegisterGroupData(regDmc, + new DataRequestMonitor<IRegisterGroupDMData>(regService.getExecutor(), null) { + @Override + protected void handleCompleted() { + if (getStatus().isOK()) { + // Now make sure the register group is the one we want. + request.getMemento().putString(MEMENTO_NAME, + "Group." + getData().getName()); //$NON-NLS-1$ + } + request.done(); + } + }); + } else { + request.done(); + } + } + }); + } catch (RejectedExecutionException e) { + request.done(); + } + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterRootDMVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterRootDMVMNode.java index 1c733d12c2c..5f25bb2022d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterRootDMVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterRootDMVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,36 +20,40 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoPr import org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoRequest; /* - * We are extending the ROOT VM node for the register view so we can - * provide Memento providers for the root node. In the Register VM - * Provider we are returning a pseudo VMContext selection when the - * original input is a child of an execution context we return a selection - * which represents an Execution Context instead. This ensures that the - * Register View does not collapse and redraw when going from frame to frame - * when stepping or just when selecting within the view. + * We are extending the ROOT VM node for the register view so we can + * provide Memento providers for the root node. In the Register VM + * Provider we are returning a pseudo VMContext selection when the + * original input is a child of an execution context we return a selection + * which represents an Execution Context instead. This ensures that the + * Register View does not collapse and redraw when going from frame to frame + * when stepping or just when selecting within the view. */ public class RegisterRootDMVMNode extends RootDMVMNode implements IElementMementoProvider { - + public RegisterRootDMVMNode(AbstractVMProvider provider) { - super(provider); - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#compareElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementCompareRequest[]) - */ - @Override + super(provider); + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#compareElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementCompareRequest[]) + */ + @Override public void compareElements(IElementCompareRequest[] requests) { - for ( IElementMementoRequest request : requests ) { request.done(); } - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#encodeElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoRequest[]) - */ - @Override + for (IElementMementoRequest request : requests) { + request.done(); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#encodeElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoRequest[]) + */ + @Override public void encodeElements(IElementMementoRequest[] requests) { - - for ( IElementMementoRequest request : requests ) { request.done(); } - } + + for (IElementMementoRequest request : requests) { + request.done(); + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterVMNode.java index 0d0193eeab1..cfc91588032 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Alvaro Sanchez-Leon (Ericsson) - Make Registers View specific to a frame (Bug 323552) @@ -94,954 +94,918 @@ import org.eclipse.swt.widgets.Composite; /** * @since 1.0 */ -public class RegisterVMNode extends AbstractExpressionVMNode - implements IElementEditor, IElementLabelProvider, IElementMementoProvider, IElementPropertiesProvider -{ +public class RegisterVMNode extends AbstractExpressionVMNode + implements IElementEditor, IElementLabelProvider, IElementMementoProvider, IElementPropertiesProvider { + /** + * @since 2.0 + */ + private static final String PROP_REGISTER_SHOW_TYPE_NAMES = "register_show_type_names"; //$NON-NLS-1$ + + protected class RegisterVMC extends DMVMContext implements IFormattedValueVMContext { + private IExpression fExpression; + + public RegisterVMC(IDMContext dmc) { + super(dmc); + } + + public void setExpression(IExpression expression) { + fExpression = expression; + } + + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public Object getAdapter(Class adapter) { + if (fExpression != null && adapter.isAssignableFrom(fExpression.getClass())) { + return fExpression; + } else if (adapter.isAssignableFrom(IWatchExpressionFactoryAdapter2.class)) { + return getWatchExpressionFactory(); + } else { + return super.getAdapter(adapter); + } + } + + @Override + public boolean equals(Object other) { + if (other instanceof RegisterVMC && super.equals(other)) { + RegisterVMC otherReg = (RegisterVMC) other; + return (otherReg.fExpression == null && fExpression == null) + || (otherReg.fExpression != null && otherReg.fExpression.equals(fExpression)); + } + return false; + } + + @Override + public int hashCode() { + return super.hashCode() + (fExpression != null ? fExpression.hashCode() : 0); + } + } + + protected class RegisterExpressionFactory implements IWatchExpressionFactoryAdapter2 { + + @Override + public boolean canCreateWatchExpression(Object element) { + return element instanceof RegisterVMC; + } + + /** + * Expected format: GRP( GroupName ).REG( RegisterName ) + */ + @Override + public String createWatchExpression(Object element) throws CoreException { + IRegisterGroupDMData groupData = getSyncRegisterDataAccess().getRegisterGroupDMData(element); + IRegisterDMData registerData = getSyncRegisterDataAccess().getRegisterDMData(element); + + if (groupData != null && registerData != null) { + StringBuffer exprBuf = new StringBuffer(); + + exprBuf.append("GRP( "); //$NON-NLS-1$ + exprBuf.append(groupData.getName()); + exprBuf.append(" )"); //$NON-NLS-1$ + exprBuf.append(".REG( "); //$NON-NLS-1$ + exprBuf.append(registerData.getName()); + exprBuf.append(" )"); //$NON-NLS-1$ + + return exprBuf.toString(); + } + + return null; + } + } + + private IWatchExpressionFactoryAdapter2 fRegisterExpressionFactory = null; + final private SyncRegisterDataAccess fSyncRegisterDataAccess; + + /** + * The label provider delegate. This VM node will delegate label updates to this provider + * which can be created by sub-classes. + * + * @since 2.0 + */ + private IElementLabelProvider fLabelProvider; + + /** + * Retriever for formatted values configured for this VM node. + * @since 2.2 + */ + private final FormattedValueRetriever fFormattedValueRetriever; + + public RegisterVMNode(AbstractDMVMProvider provider, DsfSession session, SyncRegisterDataAccess syncDataAccess) { + super(provider, session, IRegisterDMContext.class); + fSyncRegisterDataAccess = syncDataAccess; + fLabelProvider = createLabelProvider(); + fFormattedValueRetriever = new FormattedValueRetriever(this, session, IRegisters.class, + IRegisterDMContext.class); + } + + private Object[] constructTypeObjects(Map<String, Object> properties) { + int type = 0; + if (Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_FLOAT))) { + type = 1; + } + + int readAttr = 0; + if (Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_READABLE))) { + readAttr = 1; + } else if (Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_READONCE))) { + readAttr = 2; + } + + int writeAttr = 0; + if (Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_WRITEABLE))) { + writeAttr = 1; + } else if (Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_WRITEONCE))) { + writeAttr = 2; + } + Object[] messageAttrs = new Object[] { type, readAttr, writeAttr }; + return messageAttrs; + } + /** - * @since 2.0 - */ - private static final String PROP_REGISTER_SHOW_TYPE_NAMES = "register_show_type_names"; //$NON-NLS-1$ - - protected class RegisterVMC extends DMVMContext - implements IFormattedValueVMContext - { - private IExpression fExpression; - public RegisterVMC(IDMContext dmc) { - super(dmc); - } - - public void setExpression(IExpression expression) { - fExpression = expression; - } - - @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Object getAdapter(Class adapter) { - if (fExpression != null && adapter.isAssignableFrom(fExpression.getClass())) { - return fExpression; - } else if (adapter.isAssignableFrom(IWatchExpressionFactoryAdapter2.class)) { - return getWatchExpressionFactory(); - } else { - return super.getAdapter(adapter); - } - } - - @Override - public boolean equals(Object other) { - if (other instanceof RegisterVMC && super.equals(other)) { - RegisterVMC otherReg = (RegisterVMC)other; - return (otherReg.fExpression == null && fExpression == null) || - (otherReg.fExpression != null && otherReg.fExpression.equals(fExpression)); - } - return false; - } - - @Override - public int hashCode() { - return super.hashCode() + (fExpression != null ? fExpression.hashCode() : 0); - } - } - - protected class RegisterExpressionFactory implements IWatchExpressionFactoryAdapter2 { - - @Override - public boolean canCreateWatchExpression(Object element) { - return element instanceof RegisterVMC; - } - - /** - * Expected format: GRP( GroupName ).REG( RegisterName ) - */ - @Override - public String createWatchExpression(Object element) throws CoreException { - IRegisterGroupDMData groupData = getSyncRegisterDataAccess().getRegisterGroupDMData(element); - IRegisterDMData registerData = getSyncRegisterDataAccess().getRegisterDMData(element); - - if (groupData != null && registerData != null) { - StringBuffer exprBuf = new StringBuffer(); - - exprBuf.append("GRP( "); exprBuf.append(groupData.getName()); exprBuf.append(" )"); //$NON-NLS-1$ //$NON-NLS-2$ - exprBuf.append(".REG( "); exprBuf.append(registerData.getName()); exprBuf.append(" )"); //$NON-NLS-1$ //$NON-NLS-2$ - - return exprBuf.toString(); - } - - return null; - } - } - - private IWatchExpressionFactoryAdapter2 fRegisterExpressionFactory = null; - final private SyncRegisterDataAccess fSyncRegisterDataAccess; - - /** - * The label provider delegate. This VM node will delegate label updates to this provider - * which can be created by sub-classes. - * - * @since 2.0 - */ - private IElementLabelProvider fLabelProvider; - - /** - * Retriever for formatted values configured for this VM node. - * @since 2.2 - */ - private final FormattedValueRetriever fFormattedValueRetriever; - - public RegisterVMNode(AbstractDMVMProvider provider, DsfSession session, SyncRegisterDataAccess syncDataAccess) { - super(provider, session, IRegisterDMContext.class); - fSyncRegisterDataAccess = syncDataAccess; - fLabelProvider = createLabelProvider(); - fFormattedValueRetriever = - new FormattedValueRetriever(this, session, IRegisters.class, IRegisterDMContext.class); - } - - private Object[] constructTypeObjects( Map<String, Object> properties ) { - int type = 0; - if ( Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_FLOAT)) ) { - type = 1; - } - - int readAttr = 0; - if ( Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_READABLE)) ) { - readAttr = 1; - } else if ( Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_READONCE)) ) { - readAttr = 2; - } - - int writeAttr = 0; - if ( Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_WRITEABLE)) ) { - writeAttr = 1; - } else if ( Boolean.TRUE.equals(properties.get(IRegisterVMConstants.PROP_IS_WRITEONCE)) ) { - writeAttr = 2; - } - Object[] messageAttrs = new Object[] { type, readAttr, writeAttr }; - return messageAttrs; - } - - /** - * Creates the label provider delegate. This VM node will delegate label - * updates to this provider which can be created by sub-classes. - * - * @return Returns the label provider for this node. - * - * @since 2.0 - */ - private LabelBackground columnIdValueBackground; - private IPropertyChangeListener fPreferenceChangeListener; - - @Override - public void dispose() { - - if ( fPreferenceChangeListener != null ) { - DebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferenceChangeListener); - } - - super.dispose(); - - fFormattedValueRetriever.dispose(); - } - - protected IElementLabelProvider createLabelProvider() { - /* - * Create background which is responsive to the preference color changes. - */ - columnIdValueBackground = new LabelBackground( - DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()) - { - { - setPropertyNames(new String[] { - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT}); - } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - Boolean activeFormatChanged = (Boolean)properties.get( - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); - Boolean activeChanged = (Boolean)properties.get( - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); - return Boolean.TRUE.equals(activeChanged) && !Boolean.TRUE.equals(activeFormatChanged); - } - }; - - if ( fPreferenceChangeListener != null ) { - DebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferenceChangeListener); - } - - fPreferenceChangeListener = new IPropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent event) { - if ( event.getProperty().equals(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND) ) { - columnIdValueBackground.setBackground(DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()); - } - } - }; - - DebugUITools.getPreferenceStore().addPropertyChangeListener(fPreferenceChangeListener); - - PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); - - // The name column consists of the register name. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__NAME, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForRegisterVM.RegisterVMNode_Name_column__text_format, - new String[] { PROP_NAME }), - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER)), - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // The description column contains a brief description of the register. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__DESCRIPTION, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForRegisterVM.RegisterVMNode_Description_column__text_format, - new String[] { IRegisterVMConstants.PROP_DESCRIPTION }), - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // In the type column add information about register read/write/fload flags. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__TYPE, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForRegisterVM.RegisterVMNode_Type_column__text_format, - new String[] { - IRegisterVMConstants.PROP_IS_FLOAT, - IRegisterVMConstants.PROP_IS_READABLE, - IRegisterVMConstants.PROP_IS_READONCE, - IRegisterVMConstants.PROP_IS_WRITEABLE, - IRegisterVMConstants.PROP_IS_WRITEONCE - }) - { - @Override - public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { - Object[] messageAttrs = constructTypeObjects( properties ); - try { - update.setLabel(getMessageFormat().format(messageAttrs, new StringBuffer(), null).toString(), columnIndex); - } catch (IllegalArgumentException e) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, 0, "Failed formatting a message for column " + columnIndex + ", for update " + update, e)); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - }, - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // Value column shows the value in the active value format. - // - // In case of error, show the error message in the value column (instead of the usual "...". This is needed - // for the expressions view, where an invalid expression entered by the user is a normal use case. - // - // For changed value high-lighting check the value in the active format. But if the format itself has changed, - // ignore the value change. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__VALUE, - new LabelColumnInfo(new LabelAttribute[] { - new FormattedValueLabelText(), - new ErrorLabelText(), - new ErrorLabelForeground(), - columnIdValueBackground, - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // Expression column is visible only in the expressions view. It shows the expression string that the user - // entered. Expression column images are the same as for the name column. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__EXPRESSION, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForRegisterVM.RegisterVMNode_Expression_column__text_format, - new String[] { PROP_ELEMENT_EXPRESSION }), - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER)), - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - provider.setColumnInfo( - PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, - new LabelColumnInfo(new LabelAttribute[] { - new FormattedValueLabelText( - MessagesForRegisterVM.RegisterVMNode_No_columns__text_format, - new String[] { PROP_NAME, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE}) - { + * Creates the label provider delegate. This VM node will delegate label + * updates to this provider which can be created by sub-classes. + * + * @return Returns the label provider for this node. + * + * @since 2.0 + */ + private LabelBackground columnIdValueBackground; + private IPropertyChangeListener fPreferenceChangeListener; + + @Override + public void dispose() { + + if (fPreferenceChangeListener != null) { + DebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferenceChangeListener); + } + + super.dispose(); + + fFormattedValueRetriever.dispose(); + } + + protected IElementLabelProvider createLabelProvider() { + /* + * Create background which is responsive to the preference color changes. + */ + columnIdValueBackground = new LabelBackground( + DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()) { + { + setPropertyNames(new String[] { IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + Boolean activeFormatChanged = (Boolean) properties.get(ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); + Boolean activeChanged = (Boolean) properties.get(ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); + return Boolean.TRUE.equals(activeChanged) && !Boolean.TRUE.equals(activeFormatChanged); + } + }; + + if (fPreferenceChangeListener != null) { + DebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferenceChangeListener); + } + + fPreferenceChangeListener = new IPropertyChangeListener() { + @Override + public void propertyChange(PropertyChangeEvent event) { + if (event.getProperty().equals(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND)) { + columnIdValueBackground.setBackground( + DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()); + } + } + }; + + DebugUITools.getPreferenceStore().addPropertyChangeListener(fPreferenceChangeListener); + + PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); + + // The name column consists of the register name. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__NAME, + new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForRegisterVM.RegisterVMNode_Name_column__text_format, + new String[] { PROP_NAME }), + new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER)), + new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // The description column contains a brief description of the register. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__DESCRIPTION, + new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForRegisterVM.RegisterVMNode_Description_column__text_format, + new String[] { IRegisterVMConstants.PROP_DESCRIPTION }), + new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // In the type column add information about register read/write/fload flags. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__TYPE, + new LabelColumnInfo(new LabelAttribute[] { new LabelText( + MessagesForRegisterVM.RegisterVMNode_Type_column__text_format, + new String[] { IRegisterVMConstants.PROP_IS_FLOAT, IRegisterVMConstants.PROP_IS_READABLE, + IRegisterVMConstants.PROP_IS_READONCE, IRegisterVMConstants.PROP_IS_WRITEABLE, + IRegisterVMConstants.PROP_IS_WRITEONCE }) { + @Override + public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, + Map<String, Object> properties) { + Object[] messageAttrs = constructTypeObjects(properties); + try { + update.setLabel( + getMessageFormat().format(messageAttrs, new StringBuffer(), null).toString(), + columnIndex); + } catch (IllegalArgumentException e) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, 0, + "Failed formatting a message for column " + columnIndex + ", for update " + update, //$NON-NLS-1$//$NON-NLS-2$ + e)); + } + } + }, new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // Value column shows the value in the active value format. + // + // In case of error, show the error message in the value column (instead of the usual "...". This is needed + // for the expressions view, where an invalid expression entered by the user is a normal use case. + // + // For changed value high-lighting check the value in the active format. But if the format itself has changed, + // ignore the value change. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__VALUE, + new LabelColumnInfo(new LabelAttribute[] { new FormattedValueLabelText(), new ErrorLabelText(), + new ErrorLabelForeground(), columnIdValueBackground, new StaleDataLabelForeground(), + new VariableLabelFont(), })); + + // Expression column is visible only in the expressions view. It shows the expression string that the user + // entered. Expression column images are the same as for the name column. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__EXPRESSION, + new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForRegisterVM.RegisterVMNode_Expression_column__text_format, + new String[] { PROP_ELEMENT_EXPRESSION }), + new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER)), + new StaleDataLabelForeground(), new VariableLabelFont(), })); + + provider.setColumnInfo(PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, + new LabelColumnInfo(new LabelAttribute[] { new FormattedValueLabelText( + MessagesForRegisterVM.RegisterVMNode_No_columns__text_format, + new String[] { PROP_NAME, IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE }) { + @Override + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + Boolean showTypeNames = (Boolean) properties.get(PROP_REGISTER_SHOW_TYPE_NAMES); + return showTypeNames != null && !showTypeNames.booleanValue() + && super.isEnabled(status, properties); + } + }, new FormattedValueLabelText(MessagesForRegisterVM.RegisterVMNode_No_columns__text_format_with_type, + new String[] { PROP_NAME, IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + IRegisterVMConstants.PROP_IS_FLOAT, IRegisterVMConstants.PROP_IS_READABLE, + IRegisterVMConstants.PROP_IS_READONCE, IRegisterVMConstants.PROP_IS_WRITEABLE, + IRegisterVMConstants.PROP_IS_WRITEONCE, PROP_REGISTER_SHOW_TYPE_NAMES }) { @Override - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - Boolean showTypeNames = (Boolean) properties.get(PROP_REGISTER_SHOW_TYPE_NAMES); - return - showTypeNames != null && - !showTypeNames.booleanValue() && - super.isEnabled(status, properties); - } - }, - new FormattedValueLabelText( - MessagesForRegisterVM.RegisterVMNode_No_columns__text_format_with_type, - new String[] { PROP_NAME, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - IRegisterVMConstants.PROP_IS_FLOAT, - IRegisterVMConstants.PROP_IS_READABLE, - IRegisterVMConstants.PROP_IS_READONCE, - IRegisterVMConstants.PROP_IS_WRITEABLE, - IRegisterVMConstants.PROP_IS_WRITEONCE, - PROP_REGISTER_SHOW_TYPE_NAMES}) - { - @Override - public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { - Object[] messageAttrs = constructTypeObjects( properties ); - Object[] combinedAttrs = new Object[ messageAttrs.length + 2 ]; - combinedAttrs[0] = super.getPropertyValue(PROP_NAME, status, properties); - combinedAttrs[1] = super.getPropertyValue(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, status, properties); - for ( int idx = 0 ; idx < messageAttrs.length; idx ++ ) { - combinedAttrs[ idx + 2 ] = messageAttrs[ idx ]; - } - try { - update.setLabel(getMessageFormat().format(combinedAttrs, new StringBuffer(), null).toString(), columnIndex); - } catch (IllegalArgumentException e) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, 0, "Failed formatting a message for column " + columnIndex + ", for update " + update, e)); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - @Override - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - Boolean showTypeNames = (Boolean) properties.get(PROP_REGISTER_SHOW_TYPE_NAMES); - return - showTypeNames != null && - showTypeNames.booleanValue() && - super.isEnabled(status, properties); - } - }, - new ErrorLabelText( - MessagesForRegisterVM.RegisterVMNode_No_columns__Error__text_format, - new String[] { PROP_NAME }), - new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER)), - new LabelForeground( - DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_DEBUG_ELEMENT_COLOR).getRGB()) - { - { - setPropertyNames(new String[] { - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT}); - } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - Boolean activeFormatChanged = (Boolean)properties.get( - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); - Boolean activeChanged = (Boolean)properties.get( - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); - return Boolean.TRUE.equals(activeChanged) && !Boolean.TRUE.equals(activeFormatChanged); - } - }, - new StaleDataLabelBackground(), - new VariableLabelFont(), - })); - - return provider; - } - - @Override - public String toString() { - return "RegisterVMNode(" + getSession().getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - } - - protected SyncRegisterDataAccess getSyncRegisterDataAccess() { - return fSyncRegisterDataAccess; - } - - /** - * @since 1.1 - */ - public IWatchExpressionFactoryAdapter2 getWatchExpressionFactory() { - if ( fRegisterExpressionFactory == null ) { - fRegisterExpressionFactory = new RegisterExpressionFactory(); - } - return fRegisterExpressionFactory; - } - - @Override - public void update(final ILabelUpdate[] updates) { - fLabelProvider.update(updates); - } - - /** - * Update the variable view properties. The formatted values need to be - * updated in the VM executor thread while the rest of the properties is - * updated in the service session's executor thread. The implementation - * splits the handling of the updates to accomplish that. - * - * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) - * - * @since 2.0 - */ - @Override - public void update(final IPropertiesUpdate[] updates) { - final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), null) { - @Override - protected void handleCompleted() { - for (int i = 0; i < updates.length; i++) { - updates[i].done(); - } - }; - }; - int count = 0; - - fFormattedValueRetriever.update(updates, countingRm); - count++; - - final IPropertiesUpdate[] subUpdates = new IPropertiesUpdate[updates.length]; - for (int i = 0; i < updates.length; i++) { - final IPropertiesUpdate update = updates[i]; - subUpdates[i] = new VMDelegatingPropertiesUpdate(update, countingRm); - count++; - } - countingRm.setDoneCount(count); - - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - updatePropertiesInSessionThread(subUpdates); - }}); - } catch (RejectedExecutionException e) { - for (IPropertiesUpdate subUpdate : subUpdates) { - subUpdate.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "Session executor shut down " + getSession().getExecutor(), e)); //$NON-NLS-1$ - subUpdate.done(); - } - } - } - - // - // @param return-value Boolean.TRUE --> Show Types ICON is selected/depressed - // @param return-value Boolean.FALSE --> Show Types ICON is not selected/depressed - // - private Boolean getShowTypeNamesState( IPresentationContext context ) { - Boolean attribute = (Boolean) context.getProperty(IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES); - - if (attribute != null) { - return attribute; - } - - return Boolean.FALSE; - } - - /** - * @since 2.0 - */ - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { - IRegisters service = getServicesTracker().getService(IRegisters.class, null); + public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, + Map<String, Object> properties) { + Object[] messageAttrs = constructTypeObjects(properties); + Object[] combinedAttrs = new Object[messageAttrs.length + 2]; + combinedAttrs[0] = super.getPropertyValue(PROP_NAME, status, properties); + combinedAttrs[1] = super.getPropertyValue( + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, status, properties); + for (int idx = 0; idx < messageAttrs.length; idx++) { + combinedAttrs[idx + 2] = messageAttrs[idx]; + } + try { + update.setLabel( + getMessageFormat().format(combinedAttrs, new StringBuffer(), null).toString(), + columnIndex); + } catch (IllegalArgumentException e) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, 0, + "Failed formatting a message for column " + columnIndex + ", for update " + update, //$NON-NLS-1$//$NON-NLS-2$ + e)); + } + } + + @Override + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + Boolean showTypeNames = (Boolean) properties.get(PROP_REGISTER_SHOW_TYPE_NAMES); + return showTypeNames != null && showTypeNames.booleanValue() + && super.isEnabled(status, properties); + } + }, new ErrorLabelText(MessagesForRegisterVM.RegisterVMNode_No_columns__Error__text_format, + new String[] { PROP_NAME }), + new LabelImage(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_REGISTER)), + new LabelForeground(DebugUITools + .getPreferenceColor(IDebugUIConstants.PREF_CHANGED_DEBUG_ELEMENT_COLOR).getRGB()) { + { + setPropertyNames( + new String[] { IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, + ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + Boolean activeFormatChanged = (Boolean) properties + .get(ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); + Boolean activeChanged = (Boolean) properties + .get(ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); + return Boolean.TRUE.equals(activeChanged) && !Boolean.TRUE.equals(activeFormatChanged); + } + }, new StaleDataLabelBackground(), new VariableLabelFont(), })); + + return provider; + } + + @Override + public String toString() { + return "RegisterVMNode(" + getSession().getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } + + protected SyncRegisterDataAccess getSyncRegisterDataAccess() { + return fSyncRegisterDataAccess; + } + + /** + * @since 1.1 + */ + public IWatchExpressionFactoryAdapter2 getWatchExpressionFactory() { + if (fRegisterExpressionFactory == null) { + fRegisterExpressionFactory = new RegisterExpressionFactory(); + } + return fRegisterExpressionFactory; + } + + @Override + public void update(final ILabelUpdate[] updates) { + fLabelProvider.update(updates); + } + + /** + * Update the variable view properties. The formatted values need to be + * updated in the VM executor thread while the rest of the properties is + * updated in the service session's executor thread. The implementation + * splits the handling of the updates to accomplish that. + * + * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) + * + * @since 2.0 + */ + @Override + public void update(final IPropertiesUpdate[] updates) { + final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), null) { + @Override + protected void handleCompleted() { + for (int i = 0; i < updates.length; i++) { + updates[i].done(); + } + }; + }; + int count = 0; + + fFormattedValueRetriever.update(updates, countingRm); + count++; + + final IPropertiesUpdate[] subUpdates = new IPropertiesUpdate[updates.length]; + for (int i = 0; i < updates.length; i++) { + final IPropertiesUpdate update = updates[i]; + subUpdates[i] = new VMDelegatingPropertiesUpdate(update, countingRm); + count++; + } + countingRm.setDoneCount(count); + + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + updatePropertiesInSessionThread(subUpdates); + } + }); + } catch (RejectedExecutionException e) { + for (IPropertiesUpdate subUpdate : subUpdates) { + subUpdate.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, + "Session executor shut down " + getSession().getExecutor(), e)); //$NON-NLS-1$ + subUpdate.done(); + } + } + } + + // + // @param return-value Boolean.TRUE --> Show Types ICON is selected/depressed + // @param return-value Boolean.FALSE --> Show Types ICON is not selected/depressed + // + private Boolean getShowTypeNamesState(IPresentationContext context) { + Boolean attribute = (Boolean) context.getProperty(IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES); + + if (attribute != null) { + return attribute; + } + + return Boolean.FALSE; + } + + /** + * @since 2.0 + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { + IRegisters service = getServicesTracker().getService(IRegisters.class, null); // Create a counting request monitor to coordinate various activities // on the updated objects. Though the update objects will be given to // various ViewerDataRequestMonitors, such monitors must make sure to // not mark the update objects complete. That needs to be left to the // following monitor. - final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), null) { - @Override - protected void handleCompleted() { - for (final IPropertiesUpdate update : updates) { - update.done(); - } - }; - }; - int count = 0; - - for (final IPropertiesUpdate update : updates) { - IExpression expression = (IExpression)DebugPlugin.getAdapter(update.getElement(), IExpression.class); - if (expression != null) { - update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, expression.getExpressionText()); - } - - final IRegisterDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IRegisterDMContext.class); - if (dmc == null || service == null) { - handleFailedUpdate(update); - continue; - } - - // Capture the current "Show Type Names" ICON state in case there are no columns. - if (update.getProperties().contains(PROP_REGISTER_SHOW_TYPE_NAMES)) { - update.setProperty(PROP_REGISTER_SHOW_TYPE_NAMES, getShowTypeNamesState(update.getPresentationContext())); - } - - service.getRegisterData( - dmc, - // Use the ViewerDataRequestMonitor in order to propagate the update's cancel request. Use an immediate - // executor to avoid the possibility of a rejected execution exception. - new ViewerDataRequestMonitor<IRegisterDMData>(getSession().getExecutor(), update) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - fillRegisterDataProperties(update, getData()); - } else { - update.setStatus(getStatus()); - } - countingRm.done(); - - // Note: we must not call the update's done method - } - }); - count++; - } - countingRm.setDoneCount(count); - } - - /** - * @since 2.0 - */ - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void fillRegisterDataProperties(IPropertiesUpdate update, IRegisterDMData data) - { - update.setProperty(PROP_NAME, data.getName()); - update.setProperty(IRegisterVMConstants.PROP_DESCRIPTION, data.getDescription()); - update.setProperty(IRegisterVMConstants.PROP_IS_FLOAT, data.isFloat()); - update.setProperty(IRegisterVMConstants.PROP_IS_READABLE, data.isReadable()); - update.setProperty(IRegisterVMConstants.PROP_IS_READONCE, data.isReadOnce()); - update.setProperty(IRegisterVMConstants.PROP_IS_WRITEABLE, data.isWriteable()); - update.setProperty(IRegisterVMConstants.PROP_IS_WRITEONCE, data.isWriteOnce()); - - /* - * If this node has an expression then it has already been filled in by the higher - * level logic. If not then we need to supply something. In the previous version - * ( pre-property based ) we supplied the name. So we will do that here also. - */ - IExpression expression = (IExpression)DebugPlugin.getAdapter(update.getElement(), IExpression.class); - if (expression == null) { - update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, data.getName()); - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#update(org.eclipse.debug.internal.ui.viewers.model.provisional.IHasChildrenUpdate[]) - */ - @Override - public void update(IHasChildrenUpdate[] updates) { - // As an optimization, always indicate that register groups have - // children. - for (IHasChildrenUpdate update : updates) { - update.setHasChilren(true); - update.done(); - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#updateElementsInSessionThread(org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenUpdate) - */ - @Override - protected void updateElementsInSessionThread(final IChildrenUpdate update) { - - IRegisters regService = getServicesTracker().getService(IRegisters.class); - - if ( regService == null ) { - handleFailedUpdate(update); - return; - } - - regService.getRegisters( - createCompositeDMVMContext(update), - new ViewerDataRequestMonitor<IRegisterDMContext[]>(getSession().getExecutor(), update) { - @Override - public void handleCompleted() { - if (!isSuccess()) { - handleFailedUpdate(update); - return; - } - fillUpdateWithVMCs(update, getData()); - update.done(); - } - }); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#createVMContext(org.eclipse.cdt.dsf.datamodel.IDMContext) - */ - @Override - protected IDMVMContext createVMContext(IDMContext dmc) { - return new RegisterVMC(dmc); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.IVMNode#getDeltaFlags(java.lang.Object) - */ - @Override - public int getDeltaFlags(Object e) { - if ( e instanceof ISuspendedDMEvent || - e instanceof IResumedDMEvent || - e instanceof IMemoryChangedEvent || - e instanceof IRegistersChangedDMEvent || - (e instanceof PropertyChangeEvent && - (((PropertyChangeEvent)e).getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE || - ((PropertyChangeEvent)e).getProperty() == IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES)) ) - { - return IModelDelta.CONTENT; - } - - if (e instanceof IRegisterChangedDMEvent) { - return IModelDelta.STATE; - } - - if (e instanceof ElementFormatEvent) { - int depth = ((ElementFormatEvent)e).getApplyDepth(); - if (depth == 0) return IModelDelta.NO_CHANGE; - if (depth == 1) return IModelDelta.STATE; - return IModelDelta.CONTENT; - } - - return IModelDelta.NO_CHANGE; - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.IVMNode#buildDelta(java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, int, org.eclipse.cdt.dsf.concurrent.RequestMonitor) - */ - @Override - public void buildDelta(Object e, VMDelta parentDelta, int nodeOffset, RequestMonitor rm) { - // The following events can affect any register's values, - // refresh the contents of the parent element (i.e. all the registers). - if ( e instanceof ISuspendedDMEvent || - e instanceof IResumedDMEvent || - e instanceof IMemoryChangedEvent || - e instanceof IRegistersChangedDMEvent || - (e instanceof PropertyChangeEvent && - (((PropertyChangeEvent)e).getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE || - ((PropertyChangeEvent)e).getProperty() == IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES)) ) - { - // Create a delta that the whole register group has changed. - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } - - if (e instanceof IRegisterChangedDMEvent) { - parentDelta.addNode( createVMContext(((IRegisterChangedDMEvent)e).getDMContext()), IModelDelta.STATE ); - } - else if ( e instanceof ElementFormatEvent ) - { - int depth = ((ElementFormatEvent)e).getApplyDepth(); - if (depth != 0) { - int deltaType = IModelDelta.CONTENT; - if (depth == 1) deltaType = IModelDelta.STATE; - - Set<Object> elements = ((ElementFormatEvent)e).getElements(); - for (Object elem : elements) { - parentDelta.addNode(elem, deltaType); - } - } - } - - rm.done(); - } - - /** - * Expected format: GRP( GroupName ).REG( RegisterName ) - * or: $RegisterName - */ - @Override - public boolean canParseExpression(IExpression expression) { - return parseExpressionForRegisterName(expression.getExpressionText()) != null; - } - - private String parseExpressionForRegisterName(String expression) { - if (expression.startsWith("GRP(")) { //$NON-NLS-1$ - /* - * Get the group portion. - */ - int startIdx = "GRP(".length(); //$NON-NLS-1$ - int endIdx = expression.indexOf(')', startIdx); - if ( startIdx == -1 || endIdx == -1 ) { - return null; - } - String remaining = expression.substring(endIdx+1); - if ( ! remaining.startsWith(".REG(") ) { //$NON-NLS-1$ - return null; - } - - /* - * Get the register portion. - */ - startIdx = ".REG(".length(); //$NON-NLS-1$ - endIdx = remaining.indexOf(')', startIdx); - if ( startIdx == -1 || endIdx == -1 ) { - return null; - } - String regName = remaining.substring(startIdx,endIdx); - return regName.trim(); - } - else if ( expression.startsWith("$") ) { //$NON-NLS-1$ - /* - * At this point I am leaving this code here to represent the register case. To do this - * correctly would be to use the findRegister function and upgrade the register service - * to deal with registers that do not have a specified group parent context. I do not - * have the time for this right now. So by saying we do not handle this the Expression - * VM node will take it and pass it to the debug engine as a generic expression. Most - * debug engines ( GDB included ) have an inherent knowledge of the core registers as - * part of their expression evaluation and will respond with a flat value for the reg. - * This is not totally complete in that you should be able to express a register which - * has bit fields for example and the bit fields should be expandable in the expression - * view. With this method it will just appear to have a single value and no sub-fields. - * I will file a defect/enhancement for this to mark it. This comment will act as the - * place-holder for the future work. - */ - return null; - } - - return null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.AbstractExpressionVMNode#testElementForExpression(java.lang.Object, org.eclipse.debug.core.model.IExpression, org.eclipse.cdt.dsf.concurrent.DataRequestMonitor) - */ - @Override - protected void testElementForExpression(Object element, IExpression expression, final DataRequestMonitor<Boolean> rm) { - if (!(element instanceof IDMVMContext)) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, "Invalid context", null)); //$NON-NLS-1$ - rm.done(); - return; - } - final IRegisterDMContext dmc = DMContexts.getAncestorOfType(((IDMVMContext)element).getDMContext(), IRegisterDMContext.class); - if (dmc == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, "Invalid context", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - final String regName = parseExpressionForRegisterName(expression.getExpressionText()); - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - IRegisters registersService = getServicesTracker().getService(IRegisters.class); - if (registersService != null) { - registersService.getRegisterData( - dmc, - new DataRequestMonitor<IRegisterDMData>(ImmediateExecutor.getInstance(), rm) { - @Override - protected void handleSuccess() { - rm.setData( getData().getName().equals(regName) ); - rm.done(); - } - }); - } else { - rm.setStatus(new Status(IStatus.WARNING, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Register service not available", null)); //$NON-NLS-1$ - rm.done(); - } - } - }); - } catch (RejectedExecutionException e) { - rm.setStatus(new Status(IStatus.WARNING, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "DSF session shut down", null)); //$NON-NLS-1$ - rm.done(); - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.AbstractExpressionVMNode#associateExpression(java.lang.Object, org.eclipse.debug.core.model.IExpression) - */ - @Override - protected void associateExpression(Object element, IExpression expression) { - if (element instanceof RegisterVMC) { - ((RegisterVMC)element).setExpression(expression); - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#getDeltaFlagsForExpression(org.eclipse.debug.core.model.IExpression, java.lang.Object) - */ - @Override - public int getDeltaFlagsForExpression(IExpression expression, Object event) { - if ( event instanceof IRegisterChangedDMEvent || - event instanceof IMemoryChangedEvent || - (event instanceof PropertyChangeEvent && - (((PropertyChangeEvent)event).getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE || - ((PropertyChangeEvent)event).getProperty() == IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES)) ) - { - return IModelDelta.STATE; - } - - if (event instanceof IRegistersChangedDMEvent || - event instanceof ISuspendedDMEvent) - { - return IModelDelta.CONTENT; - } - - return IModelDelta.NO_CHANGE; - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#buildDeltaForExpression(org.eclipse.debug.core.model.IExpression, int, java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, org.eclipse.jface.viewers.TreePath, org.eclipse.cdt.dsf.concurrent.RequestMonitor) - */ - @Override - public void buildDeltaForExpression(IExpression expression, int elementIdx, Object event, VMDelta parentDelta, - TreePath path, RequestMonitor rm) - { - // If the register definition has changed, refresh all the - // expressions in the expression manager. This is because some - // expressions that were previously invalid, may now represent new - // registers. - if (event instanceof IRegistersChangedDMEvent) { - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } - - // Always refresh the contents of the view upon suspended event. - if (event instanceof ISuspendedDMEvent) { - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } - - rm.done(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#buildDeltaForExpressionElement(java.lang.Object, int, java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, org.eclipse.cdt.dsf.concurrent.RequestMonitor) - */ - @Override - public void buildDeltaForExpressionElement(Object element, int elementIdx, Object event, VMDelta parentDelta, final RequestMonitor rm) - { - // The following events can affect register values, refresh the state - // of the expression. - if ( event instanceof IRegisterChangedDMEvent || - event instanceof IMemoryChangedEvent || - (event instanceof PropertyChangeEvent && - ((PropertyChangeEvent)event).getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE) ) - { - parentDelta.addNode(element, IModelDelta.STATE); - } - - rm.done(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellEditor(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.String, java.lang.Object, org.eclipse.swt.widgets.Composite) - */ - @Override - public CellEditor getCellEditor(IPresentationContext context, String columnId, Object element, Composite parent) { - if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnId)) { - return new TextCellEditor(parent); - } - else if (IDebugVMConstants.COLUMN_ID__VALUE.equals(columnId)) { - /* - * See if the register is writable and if so we will created a - * cell editor for it. - */ - IRegisterDMData regData = getSyncRegisterDataAccess().readRegister(element); - - if ( regData != null && regData.isWriteable() ) { - return new TextCellEditor(parent); - } - } - return null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellModifier(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.Object) - */ - @Override - public ICellModifier getCellModifier(IPresentationContext context, Object element) { - return new RegisterCellModifier( getDMVMProvider(), getSyncRegisterDataAccess() ); - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#compareElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementCompareRequest[]) - */ - private final String MEMENTO_NAME = "REGISTER_MEMENTO_NAME"; //$NON-NLS-1$ - - @Override - public void compareElements(IElementCompareRequest[] requests) { - for ( final IElementCompareRequest request : requests ) { - final IRegisterDMContext regDmc = findDmcInPath(request.getViewerInput(), request.getElementPath(), IRegisterDMContext.class); - final String mementoName = request.getMemento().getString(MEMENTO_NAME); - if (regDmc == null || mementoName == null) { - request.done(); - continue; - } - - // Now go get the model data for the single register group found. - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - final IRegisters regService = getServicesTracker().getService(IRegisters.class); - if ( regService != null ) { - regService.getRegisterData( - regDmc, - new DataRequestMonitor<IRegisterDMData>(regService.getExecutor(), null) { - @Override - protected void handleCompleted() { - if ( getStatus().isOK() ) { - // Now make sure the register group is the one we want. - request.setEqual( mementoName.equals( "Register." + getData().getName() ) ); //$NON-NLS-1$ - } - request.done(); - } - }); - } else { - request.done(); - } - } - }); - } catch (RejectedExecutionException e) { - request.done(); - } - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#encodeElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoRequest[]) - */ - @Override - public void encodeElements(IElementMementoRequest[] requests) { - for ( final IElementMementoRequest request : requests ) { - final IRegisterDMContext regDmc = findDmcInPath(request.getViewerInput(), request.getElementPath(), IRegisterDMContext.class); - if (regDmc == null) { - request.done(); - continue; - } - - // Now go get the model data for the single register group found. - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override - public void run() { - final IRegisters regService = getServicesTracker().getService(IRegisters.class); - if ( regService != null ) { - regService.getRegisterData( - regDmc, - new DataRequestMonitor<IRegisterDMData>(regService.getExecutor(), null) { - @Override - protected void handleCompleted() { - if ( getStatus().isOK() ) { - // Now make sure the register group is the one we want. - request.getMemento().putString(MEMENTO_NAME, "Register." + getData().getName()); //$NON-NLS-1$ - } - request.done(); - } - }); - } else { - request.done(); - } - } - }); - } catch (RejectedExecutionException e) { - request.done(); - } - } - } + final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), null) { + @Override + protected void handleCompleted() { + for (final IPropertiesUpdate update : updates) { + update.done(); + } + }; + }; + int count = 0; + + for (final IPropertiesUpdate update : updates) { + IExpression expression = (IExpression) DebugPlugin.getAdapter(update.getElement(), IExpression.class); + if (expression != null) { + update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, expression.getExpressionText()); + } + + final IRegisterDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IRegisterDMContext.class); + if (dmc == null || service == null) { + handleFailedUpdate(update); + continue; + } + + // Capture the current "Show Type Names" ICON state in case there are no columns. + if (update.getProperties().contains(PROP_REGISTER_SHOW_TYPE_NAMES)) { + update.setProperty(PROP_REGISTER_SHOW_TYPE_NAMES, + getShowTypeNamesState(update.getPresentationContext())); + } + + service.getRegisterData(dmc, + // Use the ViewerDataRequestMonitor in order to propagate the update's cancel request. Use an immediate + // executor to avoid the possibility of a rejected execution exception. + new ViewerDataRequestMonitor<IRegisterDMData>(getSession().getExecutor(), update) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + fillRegisterDataProperties(update, getData()); + } else { + update.setStatus(getStatus()); + } + countingRm.done(); + + // Note: we must not call the update's done method + } + }); + count++; + } + countingRm.setDoneCount(count); + } + + /** + * @since 2.0 + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void fillRegisterDataProperties(IPropertiesUpdate update, IRegisterDMData data) { + update.setProperty(PROP_NAME, data.getName()); + update.setProperty(IRegisterVMConstants.PROP_DESCRIPTION, data.getDescription()); + update.setProperty(IRegisterVMConstants.PROP_IS_FLOAT, data.isFloat()); + update.setProperty(IRegisterVMConstants.PROP_IS_READABLE, data.isReadable()); + update.setProperty(IRegisterVMConstants.PROP_IS_READONCE, data.isReadOnce()); + update.setProperty(IRegisterVMConstants.PROP_IS_WRITEABLE, data.isWriteable()); + update.setProperty(IRegisterVMConstants.PROP_IS_WRITEONCE, data.isWriteOnce()); + + /* + * If this node has an expression then it has already been filled in by the higher + * level logic. If not then we need to supply something. In the previous version + * ( pre-property based ) we supplied the name. So we will do that here also. + */ + IExpression expression = (IExpression) DebugPlugin.getAdapter(update.getElement(), IExpression.class); + if (expression == null) { + update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, data.getName()); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#update(org.eclipse.debug.internal.ui.viewers.model.provisional.IHasChildrenUpdate[]) + */ + @Override + public void update(IHasChildrenUpdate[] updates) { + // As an optimization, always indicate that register groups have + // children. + for (IHasChildrenUpdate update : updates) { + update.setHasChilren(true); + update.done(); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#updateElementsInSessionThread(org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenUpdate) + */ + @Override + protected void updateElementsInSessionThread(final IChildrenUpdate update) { + + IRegisters regService = getServicesTracker().getService(IRegisters.class); + + if (regService == null) { + handleFailedUpdate(update); + return; + } + + regService.getRegisters(createCompositeDMVMContext(update), + new ViewerDataRequestMonitor<IRegisterDMContext[]>(getSession().getExecutor(), update) { + @Override + public void handleCompleted() { + if (!isSuccess()) { + handleFailedUpdate(update); + return; + } + fillUpdateWithVMCs(update, getData()); + update.done(); + } + }); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#createVMContext(org.eclipse.cdt.dsf.datamodel.IDMContext) + */ + @Override + protected IDMVMContext createVMContext(IDMContext dmc) { + return new RegisterVMC(dmc); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.IVMNode#getDeltaFlags(java.lang.Object) + */ + @Override + public int getDeltaFlags(Object e) { + if (e instanceof ISuspendedDMEvent || e instanceof IResumedDMEvent || e instanceof IMemoryChangedEvent + || e instanceof IRegistersChangedDMEvent + || (e instanceof PropertyChangeEvent && (((PropertyChangeEvent) e) + .getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE + || ((PropertyChangeEvent) e) + .getProperty() == IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES))) { + return IModelDelta.CONTENT; + } + + if (e instanceof IRegisterChangedDMEvent) { + return IModelDelta.STATE; + } + + if (e instanceof ElementFormatEvent) { + int depth = ((ElementFormatEvent) e).getApplyDepth(); + if (depth == 0) + return IModelDelta.NO_CHANGE; + if (depth == 1) + return IModelDelta.STATE; + return IModelDelta.CONTENT; + } + + return IModelDelta.NO_CHANGE; + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.IVMNode#buildDelta(java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, int, org.eclipse.cdt.dsf.concurrent.RequestMonitor) + */ + @Override + public void buildDelta(Object e, VMDelta parentDelta, int nodeOffset, RequestMonitor rm) { + // The following events can affect any register's values, + // refresh the contents of the parent element (i.e. all the registers). + if (e instanceof ISuspendedDMEvent || e instanceof IResumedDMEvent || e instanceof IMemoryChangedEvent + || e instanceof IRegistersChangedDMEvent + || (e instanceof PropertyChangeEvent && (((PropertyChangeEvent) e) + .getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE + || ((PropertyChangeEvent) e) + .getProperty() == IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES))) { + // Create a delta that the whole register group has changed. + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } + + if (e instanceof IRegisterChangedDMEvent) { + parentDelta.addNode(createVMContext(((IRegisterChangedDMEvent) e).getDMContext()), IModelDelta.STATE); + } else if (e instanceof ElementFormatEvent) { + int depth = ((ElementFormatEvent) e).getApplyDepth(); + if (depth != 0) { + int deltaType = IModelDelta.CONTENT; + if (depth == 1) + deltaType = IModelDelta.STATE; + + Set<Object> elements = ((ElementFormatEvent) e).getElements(); + for (Object elem : elements) { + parentDelta.addNode(elem, deltaType); + } + } + } + + rm.done(); + } + + /** + * Expected format: GRP( GroupName ).REG( RegisterName ) + * or: $RegisterName + */ + @Override + public boolean canParseExpression(IExpression expression) { + return parseExpressionForRegisterName(expression.getExpressionText()) != null; + } + + private String parseExpressionForRegisterName(String expression) { + if (expression.startsWith("GRP(")) { //$NON-NLS-1$ + /* + * Get the group portion. + */ + int startIdx = "GRP(".length(); //$NON-NLS-1$ + int endIdx = expression.indexOf(')', startIdx); + if (startIdx == -1 || endIdx == -1) { + return null; + } + String remaining = expression.substring(endIdx + 1); + if (!remaining.startsWith(".REG(")) { //$NON-NLS-1$ + return null; + } + + /* + * Get the register portion. + */ + startIdx = ".REG(".length(); //$NON-NLS-1$ + endIdx = remaining.indexOf(')', startIdx); + if (startIdx == -1 || endIdx == -1) { + return null; + } + String regName = remaining.substring(startIdx, endIdx); + return regName.trim(); + } else if (expression.startsWith("$")) { //$NON-NLS-1$ + /* + * At this point I am leaving this code here to represent the register case. To do this + * correctly would be to use the findRegister function and upgrade the register service + * to deal with registers that do not have a specified group parent context. I do not + * have the time for this right now. So by saying we do not handle this the Expression + * VM node will take it and pass it to the debug engine as a generic expression. Most + * debug engines ( GDB included ) have an inherent knowledge of the core registers as + * part of their expression evaluation and will respond with a flat value for the reg. + * This is not totally complete in that you should be able to express a register which + * has bit fields for example and the bit fields should be expandable in the expression + * view. With this method it will just appear to have a single value and no sub-fields. + * I will file a defect/enhancement for this to mark it. This comment will act as the + * place-holder for the future work. + */ + return null; + } + + return null; + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.AbstractExpressionVMNode#testElementForExpression(java.lang.Object, org.eclipse.debug.core.model.IExpression, org.eclipse.cdt.dsf.concurrent.DataRequestMonitor) + */ + @Override + protected void testElementForExpression(Object element, IExpression expression, + final DataRequestMonitor<Boolean> rm) { + if (!(element instanceof IDMVMContext)) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, + "Invalid context", null)); //$NON-NLS-1$ + rm.done(); + return; + } + final IRegisterDMContext dmc = DMContexts.getAncestorOfType(((IDMVMContext) element).getDMContext(), + IRegisterDMContext.class); + if (dmc == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_HANDLE, + "Invalid context", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + final String regName = parseExpressionForRegisterName(expression.getExpressionText()); + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + IRegisters registersService = getServicesTracker().getService(IRegisters.class); + if (registersService != null) { + registersService.getRegisterData(dmc, + new DataRequestMonitor<IRegisterDMData>(ImmediateExecutor.getInstance(), rm) { + @Override + protected void handleSuccess() { + rm.setData(getData().getName().equals(regName)); + rm.done(); + } + }); + } else { + rm.setStatus(new Status(IStatus.WARNING, DsfUIPlugin.PLUGIN_ID, + IDsfStatusConstants.INVALID_STATE, "Register service not available", null)); //$NON-NLS-1$ + rm.done(); + } + } + }); + } catch (RejectedExecutionException e) { + rm.setStatus(new Status(IStatus.WARNING, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "DSF session shut down", null)); //$NON-NLS-1$ + rm.done(); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.AbstractExpressionVMNode#associateExpression(java.lang.Object, org.eclipse.debug.core.model.IExpression) + */ + @Override + protected void associateExpression(Object element, IExpression expression) { + if (element instanceof RegisterVMC) { + ((RegisterVMC) element).setExpression(expression); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#getDeltaFlagsForExpression(org.eclipse.debug.core.model.IExpression, java.lang.Object) + */ + @Override + public int getDeltaFlagsForExpression(IExpression expression, Object event) { + if (event instanceof IRegisterChangedDMEvent || event instanceof IMemoryChangedEvent + || (event instanceof PropertyChangeEvent && (((PropertyChangeEvent) event) + .getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE + || ((PropertyChangeEvent) event) + .getProperty() == IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES))) { + return IModelDelta.STATE; + } + + if (event instanceof IRegistersChangedDMEvent || event instanceof ISuspendedDMEvent) { + return IModelDelta.CONTENT; + } + + return IModelDelta.NO_CHANGE; + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#buildDeltaForExpression(org.eclipse.debug.core.model.IExpression, int, java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, org.eclipse.jface.viewers.TreePath, org.eclipse.cdt.dsf.concurrent.RequestMonitor) + */ + @Override + public void buildDeltaForExpression(IExpression expression, int elementIdx, Object event, VMDelta parentDelta, + TreePath path, RequestMonitor rm) { + // If the register definition has changed, refresh all the + // expressions in the expression manager. This is because some + // expressions that were previously invalid, may now represent new + // registers. + if (event instanceof IRegistersChangedDMEvent) { + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } + + // Always refresh the contents of the view upon suspended event. + if (event instanceof ISuspendedDMEvent) { + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } + + rm.done(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.IExpressionVMNode#buildDeltaForExpressionElement(java.lang.Object, int, java.lang.Object, org.eclipse.cdt.dsf.ui.viewmodel.VMDelta, org.eclipse.cdt.dsf.concurrent.RequestMonitor) + */ + @Override + public void buildDeltaForExpressionElement(Object element, int elementIdx, Object event, VMDelta parentDelta, + final RequestMonitor rm) { + // The following events can affect register values, refresh the state + // of the expression. + if (event instanceof IRegisterChangedDMEvent || event instanceof IMemoryChangedEvent + || (event instanceof PropertyChangeEvent && ((PropertyChangeEvent) event) + .getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE)) { + parentDelta.addNode(element, IModelDelta.STATE); + } + + rm.done(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellEditor(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.String, java.lang.Object, org.eclipse.swt.widgets.Composite) + */ + @Override + public CellEditor getCellEditor(IPresentationContext context, String columnId, Object element, Composite parent) { + if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnId)) { + return new TextCellEditor(parent); + } else if (IDebugVMConstants.COLUMN_ID__VALUE.equals(columnId)) { + /* + * See if the register is writable and if so we will created a + * cell editor for it. + */ + IRegisterDMData regData = getSyncRegisterDataAccess().readRegister(element); + + if (regData != null && regData.isWriteable()) { + return new TextCellEditor(parent); + } + } + return null; + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor#getCellModifier(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.Object) + */ + @Override + public ICellModifier getCellModifier(IPresentationContext context, Object element) { + return new RegisterCellModifier(getDMVMProvider(), getSyncRegisterDataAccess()); + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#compareElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementCompareRequest[]) + */ + private final String MEMENTO_NAME = "REGISTER_MEMENTO_NAME"; //$NON-NLS-1$ + + @Override + public void compareElements(IElementCompareRequest[] requests) { + for (final IElementCompareRequest request : requests) { + final IRegisterDMContext regDmc = findDmcInPath(request.getViewerInput(), request.getElementPath(), + IRegisterDMContext.class); + final String mementoName = request.getMemento().getString(MEMENTO_NAME); + if (regDmc == null || mementoName == null) { + request.done(); + continue; + } + + // Now go get the model data for the single register group found. + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + final IRegisters regService = getServicesTracker().getService(IRegisters.class); + if (regService != null) { + regService.getRegisterData(regDmc, + new DataRequestMonitor<IRegisterDMData>(regService.getExecutor(), null) { + @Override + protected void handleCompleted() { + if (getStatus().isOK()) { + // Now make sure the register group is the one we want. + request.setEqual(mementoName.equals("Register." + getData().getName())); //$NON-NLS-1$ + } + request.done(); + } + }); + } else { + request.done(); + } + } + }); + } catch (RejectedExecutionException e) { + request.done(); + } + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoProvider#encodeElements(org.eclipse.debug.internal.ui.viewers.model.provisional.IElementMementoRequest[]) + */ + @Override + public void encodeElements(IElementMementoRequest[] requests) { + for (final IElementMementoRequest request : requests) { + final IRegisterDMContext regDmc = findDmcInPath(request.getViewerInput(), request.getElementPath(), + IRegisterDMContext.class); + if (regDmc == null) { + request.done(); + continue; + } + + // Now go get the model data for the single register group found. + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + final IRegisters regService = getServicesTracker().getService(IRegisters.class); + if (regService != null) { + regService.getRegisterData(regDmc, + new DataRequestMonitor<IRegisterDMData>(regService.getExecutor(), null) { + @Override + protected void handleCompleted() { + if (getStatus().isOK()) { + // Now make sure the register group is the one we want. + request.getMemento().putString(MEMENTO_NAME, + "Register." + getData().getName()); //$NON-NLS-1$ + } + request.done(); + } + }); + } else { + request.done(); + } + } + }); + } catch (RejectedExecutionException e) { + request.done(); + } + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterVMProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterVMProvider.java index 49c09d7b75a..68088de4785 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterVMProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/RegisterVMProvider.java @@ -7,12 +7,12 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Alvaro Sanchez-Leon (Ericsson) - Make Registers View specific to a frame (Bug 323552) - * Raphael Zulliger (Indel) - Allow derived classes of RegisterVMProvider - * to create alternative configuration (Bug + * Raphael Zulliger (Indel) - Allow derived classes of RegisterVMProvider + * to create alternative configuration (Bug * 431622) *******************************************************************************/ package org.eclipse.cdt.dsf.debug.ui.viewmodel.register; @@ -52,213 +52,214 @@ import org.eclipse.jface.util.PropertyChangeEvent; /** * Provides the VIEW MODEL for the DEBUG MODEL REGISTER view. */ -public class RegisterVMProvider extends AbstractElementVMProvider -{ - private IPropertyChangeListener fPreferencesListener = new IPropertyChangeListener() { - @Override +public class RegisterVMProvider extends AbstractElementVMProvider { + private IPropertyChangeListener fPreferencesListener = new IPropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent event) { - String property = event.getProperty(); + String property = event.getProperty(); if (property.equals(IDsfDebugUIConstants.PREF_WAIT_FOR_VIEW_UPDATE_AFTER_STEP_ENABLE)) { - IPreferenceStore store = DsfDebugUITools.getPreferenceStore(); - setDelayEventHandleForViewUpdate(store.getBoolean(property)); - } - } - }; - - private IPropertyChangeListener fPresentationContextListener = new IPropertyChangeListener() { - @Override + IPreferenceStore store = DsfDebugUITools.getPreferenceStore(); + setDelayEventHandleForViewUpdate(store.getBoolean(property)); + } + } + }; + + private IPropertyChangeListener fPresentationContextListener = new IPropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent event) { - handleEvent(event); - } - }; - - /* - * Current default for register formatting. - */ - public RegisterVMProvider(AbstractVMAdapter adapter, IPresentationContext context, DsfSession session) { - super(adapter, context, session); - - context.addPropertyChangeListener(fPresentationContextListener); - - IPreferenceStore store = DsfDebugUITools.getPreferenceStore(); - store.addPropertyChangeListener(fPreferencesListener); - setDelayEventHandleForViewUpdate(store.getBoolean(IDsfDebugUIConstants.PREF_WAIT_FOR_VIEW_UPDATE_AFTER_STEP_ENABLE)); - - configureLayout(); - } - - /** - * Configures the nodes of this provider. This method may be over-ridden by - * sub classes to create an alternate configuration in this provider. - */ - protected void configureLayout() { - - /* - * Create the register data access routines. - */ - SyncRegisterDataAccess regAccess = new SyncRegisterDataAccess(getSession()) ; - - /* - * Create the top level node to deal with the root selection. - */ - IRootVMNode rootNode = new RegisterRootDMVMNode(this); - - /* - * Create the Group nodes next. They represent the first level shown in the view. - */ - IVMNode registerGroupNode = new RegisterGroupVMNode(this, getSession(), regAccess); - addChildNodes(rootNode, new IVMNode[] { registerGroupNode }); - - /* - * Create the next level which is the registers themselves. - */ - IVMNode registerNode = new RegisterVMNode(this, getSession(), regAccess); - addChildNodes(registerGroupNode, new IVMNode[] { registerNode }); - - /* - * Create the next level which is the bitfield level. - */ - IVMNode bitFieldNode = new RegisterBitFieldVMNode(this, getSession(), regAccess); - addChildNodes(registerNode, new IVMNode[] { bitFieldNode }); - - /* - * Now set this schema set as the layout set. - */ - setRootNode(rootNode); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.update.AbstractCachingVMProvider#createUpdateModes() - */ - @Override - protected IVMUpdatePolicy[] createUpdateModes() { - return new IVMUpdatePolicy[] { new AutomaticUpdatePolicy(), new DebugManualUpdatePolicy(), new BreakpointHitUpdatePolicy() }; - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMProvider#dispose() - */ - @Override - public void dispose() { - DsfDebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferencesListener); - getPresentationContext().removePropertyChangeListener(fPresentationContextListener); - super.dispose(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.AbstractVMProvider#createColumnPresentation(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.Object) - */ - @Override - public IColumnPresentation createColumnPresentation(IPresentationContext context, Object element) { - return new RegisterColumnPresentation(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.AbstractVMProvider#getColumnPresentationId(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.Object) - */ - @Override - public String getColumnPresentationId(IPresentationContext context, Object element) { - return RegisterColumnPresentation.ID; - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.AbstractVMProvider#canSkipHandlingEvent(java.lang.Object, java.lang.Object) - */ - @Override - protected boolean canSkipHandlingEvent(Object newEvent, Object eventToSkip) { - /* - * To optimize the performance of the view when stepping rapidly, skip all - * other events when a suspended event is received, including older suspended - * events. - */ - return newEvent instanceof ISuspendedDMEvent; - } - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.AbstractVMProvider#update(org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerInputUpdate) - */ - @Override + handleEvent(event); + } + }; + + /* + * Current default for register formatting. + */ + public RegisterVMProvider(AbstractVMAdapter adapter, IPresentationContext context, DsfSession session) { + super(adapter, context, session); + + context.addPropertyChangeListener(fPresentationContextListener); + + IPreferenceStore store = DsfDebugUITools.getPreferenceStore(); + store.addPropertyChangeListener(fPreferencesListener); + setDelayEventHandleForViewUpdate( + store.getBoolean(IDsfDebugUIConstants.PREF_WAIT_FOR_VIEW_UPDATE_AFTER_STEP_ENABLE)); + + configureLayout(); + } + + /** + * Configures the nodes of this provider. This method may be over-ridden by + * sub classes to create an alternate configuration in this provider. + */ + protected void configureLayout() { + + /* + * Create the register data access routines. + */ + SyncRegisterDataAccess regAccess = new SyncRegisterDataAccess(getSession()); + + /* + * Create the top level node to deal with the root selection. + */ + IRootVMNode rootNode = new RegisterRootDMVMNode(this); + + /* + * Create the Group nodes next. They represent the first level shown in the view. + */ + IVMNode registerGroupNode = new RegisterGroupVMNode(this, getSession(), regAccess); + addChildNodes(rootNode, new IVMNode[] { registerGroupNode }); + + /* + * Create the next level which is the registers themselves. + */ + IVMNode registerNode = new RegisterVMNode(this, getSession(), regAccess); + addChildNodes(registerGroupNode, new IVMNode[] { registerNode }); + + /* + * Create the next level which is the bitfield level. + */ + IVMNode bitFieldNode = new RegisterBitFieldVMNode(this, getSession(), regAccess); + addChildNodes(registerNode, new IVMNode[] { bitFieldNode }); + + /* + * Now set this schema set as the layout set. + */ + setRootNode(rootNode); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.update.AbstractCachingVMProvider#createUpdateModes() + */ + @Override + protected IVMUpdatePolicy[] createUpdateModes() { + return new IVMUpdatePolicy[] { new AutomaticUpdatePolicy(), new DebugManualUpdatePolicy(), + new BreakpointHitUpdatePolicy() }; + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMProvider#dispose() + */ + @Override + public void dispose() { + DsfDebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferencesListener); + getPresentationContext().removePropertyChangeListener(fPresentationContextListener); + super.dispose(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.AbstractVMProvider#createColumnPresentation(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.Object) + */ + @Override + public IColumnPresentation createColumnPresentation(IPresentationContext context, Object element) { + return new RegisterColumnPresentation(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.AbstractVMProvider#getColumnPresentationId(org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext, java.lang.Object) + */ + @Override + public String getColumnPresentationId(IPresentationContext context, Object element) { + return RegisterColumnPresentation.ID; + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.AbstractVMProvider#canSkipHandlingEvent(java.lang.Object, java.lang.Object) + */ + @Override + protected boolean canSkipHandlingEvent(Object newEvent, Object eventToSkip) { + /* + * To optimize the performance of the view when stepping rapidly, skip all + * other events when a suspended event is received, including older suspended + * events. + */ + return newEvent instanceof ISuspendedDMEvent; + } + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.AbstractVMProvider#update(org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerInputUpdate) + */ + @Override public void update(IViewerInputUpdate update) { /* * Using the frame context as first alternative to display register values per stack frame * if not available e.g. user selected a thread, the execution context is used instead */ - Object element = update.getElement(); - if (element instanceof IDMVMContext) { - IDMContext ctx = ((IDMVMContext) element).getDMContext(); + Object element = update.getElement(); + if (element instanceof IDMVMContext) { + IDMContext ctx = ((IDMVMContext) element).getDMContext(); IDMContext selDmc = DMContexts.getAncestorOfType(ctx, IFrameDMContext.class); if (selDmc == null) { selDmc = DMContexts.getAncestorOfType(ctx, IExecutionDMContext.class); } - - if ( selDmc != null ) { - /* - * This tells the Flexible Hierarchy that element driving this view has not changed - * and there is no need to redraw the view. Since this is a somewhat fake VMContext - * we provide our Root Layout node as the representative VM node. - */ - update.setInputElement(new ViewInputElement(RegisterVMProvider.this.getRootVMNode(), selDmc)); - update.done(); - return; - } - } - - /* - * If we reach here, then we did not override the standard behavior. Invoke the - * super class and this will provide the default standard behavior. - */ - super.update(update); - } - - /* - * Provides a local implementation of the IDMVMContext. This allows us to return one - * of our own making, representing the DMContext we want to use as selection criteria. - */ - private class ViewInputElement extends AbstractVMContext implements IDMVMContext { + + if (selDmc != null) { + /* + * This tells the Flexible Hierarchy that element driving this view has not changed + * and there is no need to redraw the view. Since this is a somewhat fake VMContext + * we provide our Root Layout node as the representative VM node. + */ + update.setInputElement(new ViewInputElement(RegisterVMProvider.this.getRootVMNode(), selDmc)); + update.done(); + return; + } + } + + /* + * If we reach here, then we did not override the standard behavior. Invoke the + * super class and this will provide the default standard behavior. + */ + super.update(update); + } + + /* + * Provides a local implementation of the IDMVMContext. This allows us to return one + * of our own making, representing the DMContext we want to use as selection criteria. + */ + private class ViewInputElement extends AbstractVMContext implements IDMVMContext { final private IDMContext fDMContext; - - public ViewInputElement(IVMNode node, IDMContext dmc) { + + public ViewInputElement(IVMNode node, IDMContext dmc) { super(node); fDMContext = dmc; } - + @Override public IDMContext getDMContext() { return fDMContext; } /** - * The IAdaptable implementation. If the adapter is the DM context, - * return the context, otherwise delegate to IDMContext.getAdapter(). - */ - @SuppressWarnings("unchecked") + * The IAdaptable implementation. If the adapter is the DM context, + * return the context, otherwise delegate to IDMContext.getAdapter(). + */ + @SuppressWarnings("unchecked") @Override - public <T> T getAdapter(Class<T> adapter) { - T superAdapter = super.getAdapter(adapter); - if (superAdapter != null) { - return superAdapter; - } else { - // Delegate to the Data Model to find the context. - if (adapter.isInstance(fDMContext)) { - return (T)fDMContext; - } else { - return fDMContext.getAdapter(adapter); - } - } - } + public <T> T getAdapter(Class<T> adapter) { + T superAdapter = super.getAdapter(adapter); + if (superAdapter != null) { + return superAdapter; + } else { + // Delegate to the Data Model to find the context. + if (adapter.isInstance(fDMContext)) { + return (T) fDMContext; + } else { + return fDMContext.getAdapter(adapter); + } + } + } @Override public boolean equals(Object obj) { - - if ( obj instanceof ViewInputElement && ((ViewInputElement) obj).fDMContext.equals(fDMContext) ) { + + if (obj instanceof ViewInputElement && ((ViewInputElement) obj).fDMContext.equals(fDMContext)) { return true; } return false; @@ -269,24 +270,25 @@ public class RegisterVMProvider extends AbstractElementVMProvider return fDMContext.hashCode(); } } - - @Override - public void refresh() { - super.refresh(); - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + + @Override + public void refresh() { + super.refresh(); + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), getSession().getId()); - IRegisters registerService = tracker.getService(IRegisters.class); - if (registerService instanceof ICachingService) { - ((ICachingService)registerService).flushCache(null); - } - tracker.dispose(); - } - }); - } catch (RejectedExecutionException e) { - // Session disposed, ignore. - } - } + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + getSession().getId()); + IRegisters registerService = tracker.getService(IRegisters.class); + if (registerService instanceof ICachingService) { + ((ICachingService) registerService).flushCache(null); + } + tracker.dispose(); + } + }); + } catch (RejectedExecutionException e) { + // Session disposed, ignore. + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/SyncRegisterDataAccess.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/SyncRegisterDataAccess.java index 7ce4918a81e..b7a85d7b21d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/SyncRegisterDataAccess.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/register/SyncRegisterDataAccess.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -47,778 +47,767 @@ import org.osgi.util.tracker.ServiceTracker; @ThreadSafeAndProhibitedFromDsfExecutor("fSession#getExecutor") public class SyncRegisterDataAccess { - abstract public class RegistersServiceQuery<V, K extends IDMContext> extends Query<V> { - - final protected K fDmc; - - public RegistersServiceQuery(K dmc) { - fDmc = dmc; - } - - @Override - protected void execute(final DataRequestMonitor<V> rm) { - /* - * We're in another dispatch, so we must guard against executor - * shutdown again. - */ - final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); - if (session == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Debug session already shut down.", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - /* - * Guard against a disposed service - */ - IRegisters service = getService(); - if (service == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, - "Service unavailable", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - doExecute(service, rm); - } - - abstract protected void doExecute(IRegisters registersService, DataRequestMonitor<V> rm); - } - - - /** - * The session that this data access operates in. - */ - private final DsfSession fSession; - - /** - * Need to use the OSGi service tracker here (instead of DsfServiceTracker), - * because we're accessing it in non-dispatch thread. DsfServiceTracker is - * not thread-safe. - */ - @ThreadSafe - private ServiceTracker fServiceTracker; - - public SyncRegisterDataAccess(DsfSession session) { - fSession = session; - } - - @ThreadSafe - private synchronized IRegisters getService() { - - String serviceId = DsfServices.createServiceFilter(IRegisters.class, fSession.getId()); - if (fServiceTracker == null) { - try { - fServiceTracker = new ServiceTracker(DsfUIPlugin.getBundleContext(), DsfUIPlugin - .getBundleContext().createFilter(serviceId), null); - fServiceTracker.open(); - } catch (InvalidSyntaxException e) { - return null; - } - } - return (IRegisters) fServiceTracker.getService(); - } - - @ThreadSafe - public synchronized void dispose() { - if (fServiceTracker != null) { - fServiceTracker.close(); - } - } - - public class GetBitFieldValueQuery extends RegistersServiceQuery<IBitFieldDMData, IBitFieldDMContext> { - - public GetBitFieldValueQuery(IBitFieldDMContext dmc) { - super(dmc); - } - - @Override - protected void doExecute(IRegisters service, final DataRequestMonitor<IBitFieldDMData> rm) { - service.getBitFieldData( - fDmc, - new DataRequestMonitor<IBitFieldDMData>(ImmediateExecutor.getInstance(), rm) { - @Override - protected void handleSuccess() { - /* - * All good set return value. - */ - rm.setData(getData()); - rm.done(); - } - }); - } - } - - public IBitFieldDMContext getBitFieldDMC(Object element) { - if (element instanceof IDMVMContext) { - IDMContext dmc = ((IDMVMContext) element).getDMContext(); - return DMContexts.getAncestorOfType(dmc, IBitFieldDMContext.class); - } - return null; - } - - public IBitFieldDMData readBitField(Object element) { - /* - * Get the DMC and the session. If element is not an register DMC, or - * session is stale, then bail out. - */ - IBitFieldDMContext dmc = getBitFieldDMC(element); - if (dmc == null) - return null; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) - return null; - - /* - * Create the query to request the value from service. Note: no need to - * guard agains RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - GetBitFieldValueQuery query = new GetBitFieldValueQuery(dmc); - session.getExecutor().execute(query); - - /* - * Now we have the data, go and get it. Since the call is completed now - * the ".get()" will not suspend it will immediately return with the - * data. - */ - try { - return query.get(); - } catch (InterruptedException e) { - assert false; - return null; - } catch (ExecutionException e) { - return null; - } - } - - public class SetBitFieldValueQuery extends RegistersServiceQuery<Object, IBitFieldDMContext> { - - private String fValue; - private String fFormatId; - - public SetBitFieldValueQuery(IBitFieldDMContext dmc, String value, String formatId) { - super(dmc); - fValue = value; - fFormatId = formatId; - } - - @Override - protected void doExecute(IRegisters service, final DataRequestMonitor<Object> rm) { - // Write the bit field using a string/format style. - service.writeBitField( - fDmc, fValue, fFormatId, - new DataRequestMonitor<IBitFieldDMData>(ImmediateExecutor.getInstance(), rm) { - @Override - protected void handleSuccess() { - /* - * All good set return value. - */ - rm.setData(new Object()); - rm.done(); - } - }); - } - } - - public void writeBitField(Object element, String value, String formatId) { - - /* - * Get the DMC and the session. If element is not an register DMC, or - * session is stale, then bail out. - */ - IBitFieldDMContext dmc = getBitFieldDMC(element); - if (dmc == null) - return; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) - return; - - /* - * Create the query to write the value to the service. Note: no need to - * guard agains RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - SetBitFieldValueQuery query = new SetBitFieldValueQuery(dmc, value, formatId); - session.getExecutor().execute(query); - - /* - * Now we have the data, go and get it. Since the call is completed now - * the ".get()" will not suspend it will immediately return with the - * data. - */ - try { - /* - * Return value is irrelevant, any error would come through with an - * exception. - */ - query.get(); - } catch (InterruptedException e) { - assert false; - } catch (ExecutionException e) { - assert false; - /* - * View must be shutting down, no need to show erro dialog. - */ - } - } - - public class SetBitFieldValueMnemonicQuery extends RegistersServiceQuery<Object, IBitFieldDMContext> { - IMnemonic fMnemonic; - - public SetBitFieldValueMnemonicQuery(IBitFieldDMContext dmc, IMnemonic mnemonic) { - super(dmc); - fMnemonic = mnemonic; - } - - @Override - protected void doExecute(IRegisters service, final DataRequestMonitor<Object> rm) { - // Write the bit field using the mnemonic style. - service.writeBitField( - fDmc, fMnemonic, - new DataRequestMonitor<IBitFieldDMData>(ImmediateExecutor.getInstance(), rm) { - @Override - protected void handleSuccess() { - /* - * All good set return value. - */ - rm.setData(new Object()); - rm.done(); - } - }); - } - } - - public void writeBitField(Object element, IMnemonic mnemonic) { - - /* - * Get the DMC and the session. If element is not an register DMC, or - * session is stale, then bail out. - */ - IBitFieldDMContext dmc = getBitFieldDMC(element); - if (dmc == null) - return; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) - return; - - /* - * Create the query to write the value to the service. Note: no need to - * guard agains RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - SetBitFieldValueMnemonicQuery query = new SetBitFieldValueMnemonicQuery(dmc, mnemonic); - session.getExecutor().execute(query); - - /* - * Now we have the data, go and get it. Since the call is completed now - * the ".get()" will not suspend it will immediately return with the - * data. - */ - try { - /* - * Return value is irrelevant, any error would come through with an - * exception. - */ - query.get(); - } catch (InterruptedException e) { - assert false; - } catch (ExecutionException e) { - /* - * View must be shutting down, no need to show erro dialog. - */ - } - } - - public IRegisterGroupDMContext getRegisterGroupDMC(Object element) { - if (element instanceof IDMVMContext) { - IDMContext dmc = ((IDMVMContext) element).getDMContext(); - return DMContexts.getAncestorOfType(dmc, IRegisterGroupDMContext.class); - } - return null; - } - - public IRegisterDMContext getRegisterDMC(Object element) { - if (element instanceof IDMVMContext) { - IDMContext dmc = ((IDMVMContext) element).getDMContext(); - return DMContexts.getAncestorOfType(dmc, IRegisterDMContext.class); - } - return null; - } - - public IFormattedDataDMContext getFormattedDMC(Object element) { - if (element instanceof IDMVMContext) { - IDMContext dmc = ((IDMVMContext) element).getDMContext(); - IRegisterDMContext regdmc = DMContexts.getAncestorOfType(dmc, IRegisterDMContext.class); - return DMContexts.getAncestorOfType(regdmc, IFormattedDataDMContext.class); - } - return null; - } - - public class GetRegisterGroupValueQuery extends RegistersServiceQuery<IRegisterGroupDMData, IRegisterGroupDMContext> { - public GetRegisterGroupValueQuery(IRegisterGroupDMContext dmc) { - super(dmc); - } - - @Override - protected void doExecute(IRegisters service, final DataRequestMonitor<IRegisterGroupDMData> rm) { - service.getRegisterGroupData( - fDmc, - new DataRequestMonitor<IRegisterGroupDMData>(ImmediateExecutor.getInstance(), rm) { - @Override - protected void handleSuccess() { - /* - * All good set return value. - */ - rm.setData(getData()); - rm.done(); - } - }); - } - } - - public IRegisterGroupDMData readRegisterGroup(Object element) { - /* - * Get the DMC and the session. If element is not an register DMC, or - * session is stale, then bail out. - */ - IRegisterGroupDMContext dmc = getRegisterGroupDMC(element); - if (dmc == null) - return null; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) - return null; - - /* - * Create the query to request the value from service. Note: no need to - * guard agains RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - GetRegisterGroupValueQuery query = new GetRegisterGroupValueQuery(dmc); - session.getExecutor().execute(query); - - /* - * Now we have the data, go and get it. Since the call is completed now - * the ".get()" will not suspend it will immediately return with the - * data. - */ - try { - return query.get(); - } catch (InterruptedException e) { - assert false; - return null; - } catch (ExecutionException e) { - return null; - } - } - - public class GetRegisterValueQuery extends RegistersServiceQuery<IRegisterDMData, IRegisterDMContext> { - public GetRegisterValueQuery(IRegisterDMContext dmc) { - super(dmc); - } - - @Override - protected void doExecute(IRegisters service, final DataRequestMonitor<IRegisterDMData> rm) { - service.getRegisterData( - fDmc, - new DataRequestMonitor<IRegisterDMData>(ImmediateExecutor.getInstance(), rm) { - @Override - protected void handleSuccess() { - /* - * All good set return value. - */ - rm.setData(getData()); - rm.done(); - } - }); - } - } - - public IRegisterDMData readRegister(Object element) { - /* - * Get the DMC and the session. If element is not an register DMC, or - * session is stale, then bail out. - */ - IRegisterDMContext dmc = getRegisterDMC(element); - if (dmc == null) - return null; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) - return null; - - /* - * Create the query to request the value from service. Note: no need to - * guard agains RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - GetRegisterValueQuery query = new GetRegisterValueQuery(dmc); - session.getExecutor().execute(query); - - /* - * Now we have the data, go and get it. Since the call is completed now - * the ".get()" will not suspend it will immediately return with the - * data. - */ - try { - return query.get(); - } catch (InterruptedException e) { - assert false; - return null; - } catch (ExecutionException e) { - return null; - } - } - - public class SetRegisterValueQuery extends RegistersServiceQuery<Object, IRegisterDMContext> { - private String fValue; - - private String fFormatId; - - public SetRegisterValueQuery(IRegisterDMContext dmc, String value, String formatId) { - super(dmc); - fValue = value; - fFormatId = formatId; - } - - @Override - protected void doExecute(IRegisters service, final DataRequestMonitor<Object> rm) { - /* - * Write the bit field using a string/format style. - */ - service.writeRegister( - fDmc, fValue, fFormatId, - new DataRequestMonitor<IBitFieldDMData>(ImmediateExecutor.getInstance(), rm) { - @Override - protected void handleSuccess() { - /* - * All good set return value. - */ - rm.setData(new Object()); - rm.done(); - } - }); - } - } - - public void writeRegister(Object element, String value, String formatId) { - - /* - * Get the DMC and the session. If element is not an register DMC, or - * session is stale, then bail out. - */ - IRegisterDMContext dmc = getRegisterDMC(element); - if (dmc == null) - return; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) - return; - - /* - * Create the query to write the value to the service. Note: no need to - * guard agains RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - SetRegisterValueQuery query = new SetRegisterValueQuery(dmc, value, formatId); - session.getExecutor().execute(query); - - /* - * Now we have the data, go and get it. Since the call is completed now - * the ".get()" will not suspend it will immediately return with the - * data. - */ - try { - /* - * Return value is irrelevant, any error would come through with an - * exception. - */ - query.get(); - } catch (InterruptedException e) { - assert false; - } catch (ExecutionException e) { - /* - * View must be shutting down, no need to show erro dialog. - */ - } - } - - public class GetSupportFormatsValueQuery extends RegistersServiceQuery<String[], IFormattedDataDMContext> { - - public GetSupportFormatsValueQuery(IFormattedDataDMContext dmc) { - super(dmc); - } - - @Override - protected void doExecute(IRegisters service, final DataRequestMonitor<String[]> rm) { - service.getAvailableFormats(fDmc, rm); - } - } - - public String[] getSupportedFormats(Object element) { - - /* - * Get the DMC and the session. If element is not an register DMC, or - * session is stale, then bail out. - */ - IFormattedDataDMContext dmc = null; - if (element instanceof IDMVMContext) { - IDMContext vmcdmc = ((IDMVMContext) element).getDMContext(); - IRegisterDMContext regdmc = DMContexts.getAncestorOfType(vmcdmc, IRegisterDMContext.class); - dmc = DMContexts.getAncestorOfType(regdmc, IFormattedDataDMContext.class); - } - - if (dmc == null) - return null; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) - return null; - - /* - * Create the query to write the value to the service. Note: no need to - * guard agains RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - GetSupportFormatsValueQuery query = new GetSupportFormatsValueQuery(dmc); - session.getExecutor().execute(query); - - /* - * Now we have the data, go and get it. Since the call is completed now - * the ".get()" will not suspend it will immediately return with the - * data. - */ - try { - return query.get(); - } catch (InterruptedException e) { - assert false; - return null; - } catch (ExecutionException e) { - return null; - } - } - - public class GetFormattedValueValueQuery extends RegistersServiceQuery<String, IFormattedDataDMContext> { - - private String fFormatId; - - public GetFormattedValueValueQuery(IFormattedDataDMContext dmc, String formatId) { - super(dmc); - fFormatId = formatId; - } - - @Override - protected void doExecute(IRegisters service, final DataRequestMonitor<String> rm) { - /* - * Convert to the proper formatting DMC then go get the formatted - * value. - */ - - FormattedValueDMContext formDmc = service.getFormattedValueContext(fDmc, fFormatId); - - service.getFormattedExpressionValue( - formDmc, - new DataRequestMonitor<FormattedValueDMData>(ImmediateExecutor.getInstance(), rm) { - @Override - protected void handleSuccess() { - /* - * All good set return value. - */ - rm.setData(getData().getFormattedValue()); - rm.done(); - } - }); - } - } - - public String getFormattedRegisterValue(Object element, String formatId) { - - /* - * Get the DMC and the session. If element is not an register DMC, or - * session is stale, then bail out. - */ - IFormattedDataDMContext dmc = null; - if (element instanceof IDMVMContext) { - IDMContext vmcdmc = ((IDMVMContext) element).getDMContext(); - IRegisterDMContext regdmc = DMContexts.getAncestorOfType(vmcdmc, IRegisterDMContext.class); - dmc = DMContexts.getAncestorOfType(regdmc, IFormattedDataDMContext.class); - } - - if (dmc == null) - return null; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) - return null; - - /* - * Create the query to write the value to the service. Note: no need to - * guard agains RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - GetFormattedValueValueQuery query = new GetFormattedValueValueQuery(dmc, formatId); - session.getExecutor().execute(query); - - /* - * Now we have the data, go and get it. Since the call is completed now - * the ".get()" will not suspend it will immediately return with the - * data. - */ - try { - return query.get(); - } catch (InterruptedException e) { - assert false; - return null; - } catch (ExecutionException e) { - return null; - } - } - - public String getFormattedBitFieldValue(Object element, String formatId) { - - /* - * Get the DMC and the session. If element is not an register DMC, or - * session is stale, then bail out. - */ - IFormattedDataDMContext dmc = null; - if (element instanceof IDMVMContext) { - IDMContext vmcdmc = ((IDMVMContext) element).getDMContext(); - IBitFieldDMContext bitfielddmc = DMContexts.getAncestorOfType(vmcdmc, IBitFieldDMContext.class); - dmc = DMContexts.getAncestorOfType(bitfielddmc, IFormattedDataDMContext.class); - } - - if (dmc == null) - return null; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) - return null; - - /* - * Create the query to write the value to the service. Note: no need to - * guard agains RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - GetFormattedValueValueQuery query = new GetFormattedValueValueQuery(dmc, formatId); - session.getExecutor().execute(query); - - /* - * Now we have the data, go and get it. Since the call is completed now - * the ".get()" will not suspend it will immediately return with the - * data. - */ - try { - return query.get(); - } catch (InterruptedException e) { - assert false; - return null; - } catch (ExecutionException e) { - return null; - } - } - - public class GetRegisterGroupDataQuery extends RegistersServiceQuery<IRegisterGroupDMData, IRegisterGroupDMContext> { - - public GetRegisterGroupDataQuery(IRegisterGroupDMContext dmc) { - super(dmc); - } - - @Override - protected void doExecute(IRegisters service, final DataRequestMonitor<IRegisterGroupDMData> rm) { - service.getRegisterGroupData(fDmc, rm); - } - } - - public IRegisterGroupDMData getRegisterGroupDMData(Object element) { - IRegisterGroupDMContext dmc = null; - if (element instanceof IDMVMContext) { - dmc = DMContexts.getAncestorOfType( - ((IDMVMContext) element).getDMContext(), - IRegisterGroupDMContext.class); - } - - if (dmc != null) { - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - - if (session != null) { - GetRegisterGroupDataQuery query = new GetRegisterGroupDataQuery(dmc); - session.getExecutor().execute(query); - - try { - return query.get(); - } catch (InterruptedException e) { - } catch (ExecutionException e) { - } - } - } - return null; - } - - - public class GetRegisterDataQuery extends RegistersServiceQuery<IRegisterDMData, IRegisterDMContext> { - - public GetRegisterDataQuery(IRegisterDMContext dmc) { - super(dmc); - } - - @Override - protected void doExecute(IRegisters service, final DataRequestMonitor<IRegisterDMData> rm) { - service.getRegisterData(fDmc, rm); - } - } - - public IRegisterDMData getRegisterDMData(Object element) { - IRegisterDMContext dmc = null; - if (element instanceof IDMVMContext) { - dmc = DMContexts.getAncestorOfType( ((IDMVMContext) element).getDMContext(), IRegisterDMContext.class ); - } - - if (dmc != null) { - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - - if (session != null) { - GetRegisterDataQuery query = new GetRegisterDataQuery(dmc); - session.getExecutor().execute(query); - - try { - return query.get(); - } catch (InterruptedException e) { - } catch (ExecutionException e) { - } - } - } - return null; - } - - public class GetBitFieldQuery extends RegistersServiceQuery<IBitFieldDMData, IBitFieldDMContext> { - - public GetBitFieldQuery(IBitFieldDMContext dmc) { - super(dmc); - } - - @Override - protected void doExecute(IRegisters service, final DataRequestMonitor<IBitFieldDMData> rm) { - service.getBitFieldData(fDmc, rm); - } - } - - public IBitFieldDMData getBitFieldDMData(Object element) { - IBitFieldDMContext dmc = null; - if (element instanceof IDMVMContext) { - dmc = DMContexts.getAncestorOfType( ((IDMVMContext) element).getDMContext(), IBitFieldDMContext.class ); - } - - if (dmc != null) { - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - - if (session != null) { - GetBitFieldQuery query = new GetBitFieldQuery(dmc); - session.getExecutor().execute(query); - - try { - return query.get(); - } catch (InterruptedException e) { - } catch (ExecutionException e) { - } - } - } - return null; - } - + abstract public class RegistersServiceQuery<V, K extends IDMContext> extends Query<V> { + + final protected K fDmc; + + public RegistersServiceQuery(K dmc) { + fDmc = dmc; + } + + @Override + protected void execute(final DataRequestMonitor<V> rm) { + /* + * We're in another dispatch, so we must guard against executor + * shutdown again. + */ + final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); + if (session == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Debug session already shut down.", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + /* + * Guard against a disposed service + */ + IRegisters service = getService(); + if (service == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Service unavailable", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + doExecute(service, rm); + } + + abstract protected void doExecute(IRegisters registersService, DataRequestMonitor<V> rm); + } + + /** + * The session that this data access operates in. + */ + private final DsfSession fSession; + + /** + * Need to use the OSGi service tracker here (instead of DsfServiceTracker), + * because we're accessing it in non-dispatch thread. DsfServiceTracker is + * not thread-safe. + */ + @ThreadSafe + private ServiceTracker fServiceTracker; + + public SyncRegisterDataAccess(DsfSession session) { + fSession = session; + } + + @ThreadSafe + private synchronized IRegisters getService() { + + String serviceId = DsfServices.createServiceFilter(IRegisters.class, fSession.getId()); + if (fServiceTracker == null) { + try { + fServiceTracker = new ServiceTracker(DsfUIPlugin.getBundleContext(), + DsfUIPlugin.getBundleContext().createFilter(serviceId), null); + fServiceTracker.open(); + } catch (InvalidSyntaxException e) { + return null; + } + } + return (IRegisters) fServiceTracker.getService(); + } + + @ThreadSafe + public synchronized void dispose() { + if (fServiceTracker != null) { + fServiceTracker.close(); + } + } + + public class GetBitFieldValueQuery extends RegistersServiceQuery<IBitFieldDMData, IBitFieldDMContext> { + + public GetBitFieldValueQuery(IBitFieldDMContext dmc) { + super(dmc); + } + + @Override + protected void doExecute(IRegisters service, final DataRequestMonitor<IBitFieldDMData> rm) { + service.getBitFieldData(fDmc, new DataRequestMonitor<IBitFieldDMData>(ImmediateExecutor.getInstance(), rm) { + @Override + protected void handleSuccess() { + /* + * All good set return value. + */ + rm.setData(getData()); + rm.done(); + } + }); + } + } + + public IBitFieldDMContext getBitFieldDMC(Object element) { + if (element instanceof IDMVMContext) { + IDMContext dmc = ((IDMVMContext) element).getDMContext(); + return DMContexts.getAncestorOfType(dmc, IBitFieldDMContext.class); + } + return null; + } + + public IBitFieldDMData readBitField(Object element) { + /* + * Get the DMC and the session. If element is not an register DMC, or + * session is stale, then bail out. + */ + IBitFieldDMContext dmc = getBitFieldDMC(element); + if (dmc == null) + return null; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return null; + + /* + * Create the query to request the value from service. Note: no need to + * guard agains RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + GetBitFieldValueQuery query = new GetBitFieldValueQuery(dmc); + session.getExecutor().execute(query); + + /* + * Now we have the data, go and get it. Since the call is completed now + * the ".get()" will not suspend it will immediately return with the + * data. + */ + try { + return query.get(); + } catch (InterruptedException e) { + assert false; + return null; + } catch (ExecutionException e) { + return null; + } + } + + public class SetBitFieldValueQuery extends RegistersServiceQuery<Object, IBitFieldDMContext> { + + private String fValue; + private String fFormatId; + + public SetBitFieldValueQuery(IBitFieldDMContext dmc, String value, String formatId) { + super(dmc); + fValue = value; + fFormatId = formatId; + } + + @Override + protected void doExecute(IRegisters service, final DataRequestMonitor<Object> rm) { + // Write the bit field using a string/format style. + service.writeBitField(fDmc, fValue, fFormatId, + new DataRequestMonitor<IBitFieldDMData>(ImmediateExecutor.getInstance(), rm) { + @Override + protected void handleSuccess() { + /* + * All good set return value. + */ + rm.setData(new Object()); + rm.done(); + } + }); + } + } + + public void writeBitField(Object element, String value, String formatId) { + + /* + * Get the DMC and the session. If element is not an register DMC, or + * session is stale, then bail out. + */ + IBitFieldDMContext dmc = getBitFieldDMC(element); + if (dmc == null) + return; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return; + + /* + * Create the query to write the value to the service. Note: no need to + * guard agains RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + SetBitFieldValueQuery query = new SetBitFieldValueQuery(dmc, value, formatId); + session.getExecutor().execute(query); + + /* + * Now we have the data, go and get it. Since the call is completed now + * the ".get()" will not suspend it will immediately return with the + * data. + */ + try { + /* + * Return value is irrelevant, any error would come through with an + * exception. + */ + query.get(); + } catch (InterruptedException e) { + assert false; + } catch (ExecutionException e) { + assert false; + /* + * View must be shutting down, no need to show erro dialog. + */ + } + } + + public class SetBitFieldValueMnemonicQuery extends RegistersServiceQuery<Object, IBitFieldDMContext> { + IMnemonic fMnemonic; + + public SetBitFieldValueMnemonicQuery(IBitFieldDMContext dmc, IMnemonic mnemonic) { + super(dmc); + fMnemonic = mnemonic; + } + + @Override + protected void doExecute(IRegisters service, final DataRequestMonitor<Object> rm) { + // Write the bit field using the mnemonic style. + service.writeBitField(fDmc, fMnemonic, + new DataRequestMonitor<IBitFieldDMData>(ImmediateExecutor.getInstance(), rm) { + @Override + protected void handleSuccess() { + /* + * All good set return value. + */ + rm.setData(new Object()); + rm.done(); + } + }); + } + } + + public void writeBitField(Object element, IMnemonic mnemonic) { + + /* + * Get the DMC and the session. If element is not an register DMC, or + * session is stale, then bail out. + */ + IBitFieldDMContext dmc = getBitFieldDMC(element); + if (dmc == null) + return; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return; + + /* + * Create the query to write the value to the service. Note: no need to + * guard agains RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + SetBitFieldValueMnemonicQuery query = new SetBitFieldValueMnemonicQuery(dmc, mnemonic); + session.getExecutor().execute(query); + + /* + * Now we have the data, go and get it. Since the call is completed now + * the ".get()" will not suspend it will immediately return with the + * data. + */ + try { + /* + * Return value is irrelevant, any error would come through with an + * exception. + */ + query.get(); + } catch (InterruptedException e) { + assert false; + } catch (ExecutionException e) { + /* + * View must be shutting down, no need to show erro dialog. + */ + } + } + + public IRegisterGroupDMContext getRegisterGroupDMC(Object element) { + if (element instanceof IDMVMContext) { + IDMContext dmc = ((IDMVMContext) element).getDMContext(); + return DMContexts.getAncestorOfType(dmc, IRegisterGroupDMContext.class); + } + return null; + } + + public IRegisterDMContext getRegisterDMC(Object element) { + if (element instanceof IDMVMContext) { + IDMContext dmc = ((IDMVMContext) element).getDMContext(); + return DMContexts.getAncestorOfType(dmc, IRegisterDMContext.class); + } + return null; + } + + public IFormattedDataDMContext getFormattedDMC(Object element) { + if (element instanceof IDMVMContext) { + IDMContext dmc = ((IDMVMContext) element).getDMContext(); + IRegisterDMContext regdmc = DMContexts.getAncestorOfType(dmc, IRegisterDMContext.class); + return DMContexts.getAncestorOfType(regdmc, IFormattedDataDMContext.class); + } + return null; + } + + public class GetRegisterGroupValueQuery + extends RegistersServiceQuery<IRegisterGroupDMData, IRegisterGroupDMContext> { + public GetRegisterGroupValueQuery(IRegisterGroupDMContext dmc) { + super(dmc); + } + + @Override + protected void doExecute(IRegisters service, final DataRequestMonitor<IRegisterGroupDMData> rm) { + service.getRegisterGroupData(fDmc, + new DataRequestMonitor<IRegisterGroupDMData>(ImmediateExecutor.getInstance(), rm) { + @Override + protected void handleSuccess() { + /* + * All good set return value. + */ + rm.setData(getData()); + rm.done(); + } + }); + } + } + + public IRegisterGroupDMData readRegisterGroup(Object element) { + /* + * Get the DMC and the session. If element is not an register DMC, or + * session is stale, then bail out. + */ + IRegisterGroupDMContext dmc = getRegisterGroupDMC(element); + if (dmc == null) + return null; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return null; + + /* + * Create the query to request the value from service. Note: no need to + * guard agains RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + GetRegisterGroupValueQuery query = new GetRegisterGroupValueQuery(dmc); + session.getExecutor().execute(query); + + /* + * Now we have the data, go and get it. Since the call is completed now + * the ".get()" will not suspend it will immediately return with the + * data. + */ + try { + return query.get(); + } catch (InterruptedException e) { + assert false; + return null; + } catch (ExecutionException e) { + return null; + } + } + + public class GetRegisterValueQuery extends RegistersServiceQuery<IRegisterDMData, IRegisterDMContext> { + public GetRegisterValueQuery(IRegisterDMContext dmc) { + super(dmc); + } + + @Override + protected void doExecute(IRegisters service, final DataRequestMonitor<IRegisterDMData> rm) { + service.getRegisterData(fDmc, new DataRequestMonitor<IRegisterDMData>(ImmediateExecutor.getInstance(), rm) { + @Override + protected void handleSuccess() { + /* + * All good set return value. + */ + rm.setData(getData()); + rm.done(); + } + }); + } + } + + public IRegisterDMData readRegister(Object element) { + /* + * Get the DMC and the session. If element is not an register DMC, or + * session is stale, then bail out. + */ + IRegisterDMContext dmc = getRegisterDMC(element); + if (dmc == null) + return null; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return null; + + /* + * Create the query to request the value from service. Note: no need to + * guard agains RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + GetRegisterValueQuery query = new GetRegisterValueQuery(dmc); + session.getExecutor().execute(query); + + /* + * Now we have the data, go and get it. Since the call is completed now + * the ".get()" will not suspend it will immediately return with the + * data. + */ + try { + return query.get(); + } catch (InterruptedException e) { + assert false; + return null; + } catch (ExecutionException e) { + return null; + } + } + + public class SetRegisterValueQuery extends RegistersServiceQuery<Object, IRegisterDMContext> { + private String fValue; + + private String fFormatId; + + public SetRegisterValueQuery(IRegisterDMContext dmc, String value, String formatId) { + super(dmc); + fValue = value; + fFormatId = formatId; + } + + @Override + protected void doExecute(IRegisters service, final DataRequestMonitor<Object> rm) { + /* + * Write the bit field using a string/format style. + */ + service.writeRegister(fDmc, fValue, fFormatId, + new DataRequestMonitor<IBitFieldDMData>(ImmediateExecutor.getInstance(), rm) { + @Override + protected void handleSuccess() { + /* + * All good set return value. + */ + rm.setData(new Object()); + rm.done(); + } + }); + } + } + + public void writeRegister(Object element, String value, String formatId) { + + /* + * Get the DMC and the session. If element is not an register DMC, or + * session is stale, then bail out. + */ + IRegisterDMContext dmc = getRegisterDMC(element); + if (dmc == null) + return; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return; + + /* + * Create the query to write the value to the service. Note: no need to + * guard agains RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + SetRegisterValueQuery query = new SetRegisterValueQuery(dmc, value, formatId); + session.getExecutor().execute(query); + + /* + * Now we have the data, go and get it. Since the call is completed now + * the ".get()" will not suspend it will immediately return with the + * data. + */ + try { + /* + * Return value is irrelevant, any error would come through with an + * exception. + */ + query.get(); + } catch (InterruptedException e) { + assert false; + } catch (ExecutionException e) { + /* + * View must be shutting down, no need to show erro dialog. + */ + } + } + + public class GetSupportFormatsValueQuery extends RegistersServiceQuery<String[], IFormattedDataDMContext> { + + public GetSupportFormatsValueQuery(IFormattedDataDMContext dmc) { + super(dmc); + } + + @Override + protected void doExecute(IRegisters service, final DataRequestMonitor<String[]> rm) { + service.getAvailableFormats(fDmc, rm); + } + } + + public String[] getSupportedFormats(Object element) { + + /* + * Get the DMC and the session. If element is not an register DMC, or + * session is stale, then bail out. + */ + IFormattedDataDMContext dmc = null; + if (element instanceof IDMVMContext) { + IDMContext vmcdmc = ((IDMVMContext) element).getDMContext(); + IRegisterDMContext regdmc = DMContexts.getAncestorOfType(vmcdmc, IRegisterDMContext.class); + dmc = DMContexts.getAncestorOfType(regdmc, IFormattedDataDMContext.class); + } + + if (dmc == null) + return null; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return null; + + /* + * Create the query to write the value to the service. Note: no need to + * guard agains RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + GetSupportFormatsValueQuery query = new GetSupportFormatsValueQuery(dmc); + session.getExecutor().execute(query); + + /* + * Now we have the data, go and get it. Since the call is completed now + * the ".get()" will not suspend it will immediately return with the + * data. + */ + try { + return query.get(); + } catch (InterruptedException e) { + assert false; + return null; + } catch (ExecutionException e) { + return null; + } + } + + public class GetFormattedValueValueQuery extends RegistersServiceQuery<String, IFormattedDataDMContext> { + + private String fFormatId; + + public GetFormattedValueValueQuery(IFormattedDataDMContext dmc, String formatId) { + super(dmc); + fFormatId = formatId; + } + + @Override + protected void doExecute(IRegisters service, final DataRequestMonitor<String> rm) { + /* + * Convert to the proper formatting DMC then go get the formatted + * value. + */ + + FormattedValueDMContext formDmc = service.getFormattedValueContext(fDmc, fFormatId); + + service.getFormattedExpressionValue(formDmc, + new DataRequestMonitor<FormattedValueDMData>(ImmediateExecutor.getInstance(), rm) { + @Override + protected void handleSuccess() { + /* + * All good set return value. + */ + rm.setData(getData().getFormattedValue()); + rm.done(); + } + }); + } + } + + public String getFormattedRegisterValue(Object element, String formatId) { + + /* + * Get the DMC and the session. If element is not an register DMC, or + * session is stale, then bail out. + */ + IFormattedDataDMContext dmc = null; + if (element instanceof IDMVMContext) { + IDMContext vmcdmc = ((IDMVMContext) element).getDMContext(); + IRegisterDMContext regdmc = DMContexts.getAncestorOfType(vmcdmc, IRegisterDMContext.class); + dmc = DMContexts.getAncestorOfType(regdmc, IFormattedDataDMContext.class); + } + + if (dmc == null) + return null; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return null; + + /* + * Create the query to write the value to the service. Note: no need to + * guard agains RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + GetFormattedValueValueQuery query = new GetFormattedValueValueQuery(dmc, formatId); + session.getExecutor().execute(query); + + /* + * Now we have the data, go and get it. Since the call is completed now + * the ".get()" will not suspend it will immediately return with the + * data. + */ + try { + return query.get(); + } catch (InterruptedException e) { + assert false; + return null; + } catch (ExecutionException e) { + return null; + } + } + + public String getFormattedBitFieldValue(Object element, String formatId) { + + /* + * Get the DMC and the session. If element is not an register DMC, or + * session is stale, then bail out. + */ + IFormattedDataDMContext dmc = null; + if (element instanceof IDMVMContext) { + IDMContext vmcdmc = ((IDMVMContext) element).getDMContext(); + IBitFieldDMContext bitfielddmc = DMContexts.getAncestorOfType(vmcdmc, IBitFieldDMContext.class); + dmc = DMContexts.getAncestorOfType(bitfielddmc, IFormattedDataDMContext.class); + } + + if (dmc == null) + return null; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return null; + + /* + * Create the query to write the value to the service. Note: no need to + * guard agains RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + GetFormattedValueValueQuery query = new GetFormattedValueValueQuery(dmc, formatId); + session.getExecutor().execute(query); + + /* + * Now we have the data, go and get it. Since the call is completed now + * the ".get()" will not suspend it will immediately return with the + * data. + */ + try { + return query.get(); + } catch (InterruptedException e) { + assert false; + return null; + } catch (ExecutionException e) { + return null; + } + } + + public class GetRegisterGroupDataQuery + extends RegistersServiceQuery<IRegisterGroupDMData, IRegisterGroupDMContext> { + + public GetRegisterGroupDataQuery(IRegisterGroupDMContext dmc) { + super(dmc); + } + + @Override + protected void doExecute(IRegisters service, final DataRequestMonitor<IRegisterGroupDMData> rm) { + service.getRegisterGroupData(fDmc, rm); + } + } + + public IRegisterGroupDMData getRegisterGroupDMData(Object element) { + IRegisterGroupDMContext dmc = null; + if (element instanceof IDMVMContext) { + dmc = DMContexts.getAncestorOfType(((IDMVMContext) element).getDMContext(), IRegisterGroupDMContext.class); + } + + if (dmc != null) { + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + + if (session != null) { + GetRegisterGroupDataQuery query = new GetRegisterGroupDataQuery(dmc); + session.getExecutor().execute(query); + + try { + return query.get(); + } catch (InterruptedException e) { + } catch (ExecutionException e) { + } + } + } + return null; + } + + public class GetRegisterDataQuery extends RegistersServiceQuery<IRegisterDMData, IRegisterDMContext> { + + public GetRegisterDataQuery(IRegisterDMContext dmc) { + super(dmc); + } + + @Override + protected void doExecute(IRegisters service, final DataRequestMonitor<IRegisterDMData> rm) { + service.getRegisterData(fDmc, rm); + } + } + + public IRegisterDMData getRegisterDMData(Object element) { + IRegisterDMContext dmc = null; + if (element instanceof IDMVMContext) { + dmc = DMContexts.getAncestorOfType(((IDMVMContext) element).getDMContext(), IRegisterDMContext.class); + } + + if (dmc != null) { + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + + if (session != null) { + GetRegisterDataQuery query = new GetRegisterDataQuery(dmc); + session.getExecutor().execute(query); + + try { + return query.get(); + } catch (InterruptedException e) { + } catch (ExecutionException e) { + } + } + } + return null; + } + + public class GetBitFieldQuery extends RegistersServiceQuery<IBitFieldDMData, IBitFieldDMContext> { + + public GetBitFieldQuery(IBitFieldDMContext dmc) { + super(dmc); + } + + @Override + protected void doExecute(IRegisters service, final DataRequestMonitor<IBitFieldDMData> rm) { + service.getBitFieldData(fDmc, rm); + } + } + + public IBitFieldDMData getBitFieldDMData(Object element) { + IBitFieldDMContext dmc = null; + if (element instanceof IDMVMContext) { + dmc = DMContexts.getAncestorOfType(((IDMVMContext) element).getDMContext(), IBitFieldDMContext.class); + } + + if (dmc != null) { + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + + if (session != null) { + GetBitFieldQuery query = new GetBitFieldQuery(dmc); + session.getExecutor().execute(query); + + try { + return query.get(); + } catch (InterruptedException e) { + } catch (ExecutionException e) { + } + } + } + return null; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/BreakpointHitUpdatePolicy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/BreakpointHitUpdatePolicy.java index 2ae97dc6304..613d38031c5 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/BreakpointHitUpdatePolicy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/BreakpointHitUpdatePolicy.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -23,49 +23,49 @@ import org.eclipse.cdt.dsf.ui.viewmodel.update.IElementUpdateTester; * @since 1.0 */ public class BreakpointHitUpdatePolicy extends DebugManualUpdatePolicy { - - public static String BREAKPOINT_HIT_UPDATE_POLICY_ID = "org.eclipse.cdt.dsf.debug.ui.viewmodel.update.breakpointHitUpdatePolicy"; //$NON-NLS-1$ - - /** - * Creates a breakpoint hit update policy for debug views. - */ - public BreakpointHitUpdatePolicy() { - super(); - } - - /** - * Creates a breakpoint hit update policy for debug views for models that - * retrieve multiple formatted values for each view entry. The given - * prefixes distinguish the formatted values properties from each other. - * - * @see FormattedValueRetriever - * @see FormattedValueVMUtil#getPropertyForFormatId(String, String) - * - * @param prefixes Prefixes to use when flushing the active formatted value - * from VM cache. - */ - public BreakpointHitUpdatePolicy(String[] prefixes) { - super(prefixes); - } - @Override - public String getID() { - return BREAKPOINT_HIT_UPDATE_POLICY_ID; - } - - @Override - public String getName() { - return MessagesForVMUpdate.BreakpointHitUpdatePolicy_name; - } - - @Override - public IElementUpdateTester getElementUpdateTester(Object event) { - if(event instanceof ISuspendedDMEvent) { - ISuspendedDMEvent suspendedEvent = (ISuspendedDMEvent)event; - if(suspendedEvent.getReason().equals(StateChangeReason.BREAKPOINT)) { - return super.getElementUpdateTester(REFRESH_EVENT); - } - } - return super.getElementUpdateTester(event); - } + public static String BREAKPOINT_HIT_UPDATE_POLICY_ID = "org.eclipse.cdt.dsf.debug.ui.viewmodel.update.breakpointHitUpdatePolicy"; //$NON-NLS-1$ + + /** + * Creates a breakpoint hit update policy for debug views. + */ + public BreakpointHitUpdatePolicy() { + super(); + } + + /** + * Creates a breakpoint hit update policy for debug views for models that + * retrieve multiple formatted values for each view entry. The given + * prefixes distinguish the formatted values properties from each other. + * + * @see FormattedValueRetriever + * @see FormattedValueVMUtil#getPropertyForFormatId(String, String) + * + * @param prefixes Prefixes to use when flushing the active formatted value + * from VM cache. + */ + public BreakpointHitUpdatePolicy(String[] prefixes) { + super(prefixes); + } + + @Override + public String getID() { + return BREAKPOINT_HIT_UPDATE_POLICY_ID; + } + + @Override + public String getName() { + return MessagesForVMUpdate.BreakpointHitUpdatePolicy_name; + } + + @Override + public IElementUpdateTester getElementUpdateTester(Object event) { + if (event instanceof ISuspendedDMEvent) { + ISuspendedDMEvent suspendedEvent = (ISuspendedDMEvent) event; + if (suspendedEvent.getReason().equals(StateChangeReason.BREAKPOINT)) { + return super.getElementUpdateTester(REFRESH_EVENT); + } + } + return super.getElementUpdateTester(event); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/DebugManualUpdatePolicy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/DebugManualUpdatePolicy.java index 4447e07002b..0bfd5ee0832 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/DebugManualUpdatePolicy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/DebugManualUpdatePolicy.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Winnie Lai (Texas Instruments) - Individual Element Number Format (Bug 202556) @@ -30,116 +30,114 @@ import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.TreePath; /** - * Manual update policy with extensions specific for the debugger views. It - * properly handles the changes in active number format values in debug view. + * Manual update policy with extensions specific for the debugger views. It + * properly handles the changes in active number format values in debug view. * This requires clearing of cached properties related to the active format * preference, but not clearing the formatted value data retrieved from the - * service. - * + * service. + * * @since 2.1 */ -public class DebugManualUpdatePolicy extends ManualUpdatePolicy implements IVMUpdatePolicyExtension { - - private final Set<String> fActiveNumberFormatPropertiesWithPrefixes; - private final Set<String> fElementFormatPropertiesWithPrefixes; - - /** - * Creates a manual update policy for debug views. - */ - public DebugManualUpdatePolicy() { - this(new String[0]); - } - - /** - * Creates a manual update policy for debug views for models that retrieve - * multiple formatted values for each view entry. The given prefixes - * distinguish the formatted values properties from each other. - * - * @see FormattedValueRetriever - * @see FormattedValueVMUtil#getPropertyForFormatId(String, String) - * - * @param prefixes Prefixes to use when flushing the active formatted value - * from VM cache. - */ - public DebugManualUpdatePolicy(String[] prefixes) { - if (prefixes.length == 0) { - fActiveNumberFormatPropertiesWithPrefixes = ACTIVE_NUMBER_FORMAT_PROPERTIES; - fElementFormatPropertiesWithPrefixes = ELEMENT_FORMAT_PROPERTIES; - } else { - fActiveNumberFormatPropertiesWithPrefixes = new TreeSet<String>(ACTIVE_NUMBER_FORMAT_PROPERTIES); - fElementFormatPropertiesWithPrefixes = new TreeSet<String>(ELEMENT_FORMAT_PROPERTIES); - for (String prefix : prefixes) { - fActiveNumberFormatPropertiesWithPrefixes.add( - (prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT).intern()); - fActiveNumberFormatPropertiesWithPrefixes.add( - (prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE).intern()); - fElementFormatPropertiesWithPrefixes.add( - (prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT).intern()); - fElementFormatPropertiesWithPrefixes.add( - (prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE).intern()); - } - } - - } - - private static final Set<String> ACTIVE_NUMBER_FORMAT_PROPERTIES = new TreeSet<String>(); - static { - ACTIVE_NUMBER_FORMAT_PROPERTIES.add(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); - ACTIVE_NUMBER_FORMAT_PROPERTIES.add(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); - ACTIVE_NUMBER_FORMAT_PROPERTIES.add(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE); - } - - private static final Set<String> ELEMENT_FORMAT_PROPERTIES = new TreeSet<String>(); - static { - ELEMENT_FORMAT_PROPERTIES.add(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); - ELEMENT_FORMAT_PROPERTIES.add(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); - } - - /** - * This specialized element update tester flushes the active number format - * property of the elemetn under consideration. The partial property flush - * is performed only if the cache entry is not yet dirty. - */ - private IElementUpdateTester fNumberFormatPropertyEventUpdateTester = new IElementUpdateTesterExtension() { - - @Override +public class DebugManualUpdatePolicy extends ManualUpdatePolicy implements IVMUpdatePolicyExtension { + + private final Set<String> fActiveNumberFormatPropertiesWithPrefixes; + private final Set<String> fElementFormatPropertiesWithPrefixes; + + /** + * Creates a manual update policy for debug views. + */ + public DebugManualUpdatePolicy() { + this(new String[0]); + } + + /** + * Creates a manual update policy for debug views for models that retrieve + * multiple formatted values for each view entry. The given prefixes + * distinguish the formatted values properties from each other. + * + * @see FormattedValueRetriever + * @see FormattedValueVMUtil#getPropertyForFormatId(String, String) + * + * @param prefixes Prefixes to use when flushing the active formatted value + * from VM cache. + */ + public DebugManualUpdatePolicy(String[] prefixes) { + if (prefixes.length == 0) { + fActiveNumberFormatPropertiesWithPrefixes = ACTIVE_NUMBER_FORMAT_PROPERTIES; + fElementFormatPropertiesWithPrefixes = ELEMENT_FORMAT_PROPERTIES; + } else { + fActiveNumberFormatPropertiesWithPrefixes = new TreeSet<String>(ACTIVE_NUMBER_FORMAT_PROPERTIES); + fElementFormatPropertiesWithPrefixes = new TreeSet<String>(ELEMENT_FORMAT_PROPERTIES); + for (String prefix : prefixes) { + fActiveNumberFormatPropertiesWithPrefixes + .add((prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT).intern()); + fActiveNumberFormatPropertiesWithPrefixes + .add((prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE).intern()); + fElementFormatPropertiesWithPrefixes + .add((prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT).intern()); + fElementFormatPropertiesWithPrefixes + .add((prefix + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE).intern()); + } + } + + } + + private static final Set<String> ACTIVE_NUMBER_FORMAT_PROPERTIES = new TreeSet<String>(); + static { + ACTIVE_NUMBER_FORMAT_PROPERTIES.add(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); + ACTIVE_NUMBER_FORMAT_PROPERTIES.add(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); + ACTIVE_NUMBER_FORMAT_PROPERTIES.add(IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE); + } + + private static final Set<String> ELEMENT_FORMAT_PROPERTIES = new TreeSet<String>(); + static { + ELEMENT_FORMAT_PROPERTIES.add(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); + ELEMENT_FORMAT_PROPERTIES.add(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); + } + + /** + * This specialized element update tester flushes the active number format + * property of the elemetn under consideration. The partial property flush + * is performed only if the cache entry is not yet dirty. + */ + private IElementUpdateTester fNumberFormatPropertyEventUpdateTester = new IElementUpdateTesterExtension() { + + @Override public int getUpdateFlags(Object viewerInput, TreePath path) { - return FLUSH_PARTIAL_PROPERTIES; - } - - @Override + return FLUSH_PARTIAL_PROPERTIES; + } + + @Override public Collection<String> getPropertiesToFlush(Object viewerInput, TreePath path, boolean isDirty) { - return fActiveNumberFormatPropertiesWithPrefixes; - } - - @Override + return fActiveNumberFormatPropertiesWithPrefixes; + } + + @Override public boolean includes(IElementUpdateTester tester) { - // includes ElementFormatUpdateTester as well? - return tester.equals(this); - } - - @Override - public String toString() { - return "Manual (refresh = false) update tester for an event that did not originate from the data model"; //$NON-NLS-1$ - } - }; - - @Override - public IElementUpdateTester getElementUpdateTester(Object event) { - if ( event instanceof PropertyChangeEvent && - IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE.equals( ((PropertyChangeEvent)event).getProperty()) ) - { - return fNumberFormatPropertyEventUpdateTester; - } - if ( event instanceof ElementFormatEvent ) - { - return new ElementFormatUpdateTester(((ElementFormatEvent) event), fElementFormatPropertiesWithPrefixes); - } - return super.getElementUpdateTester(event); - } - - @Override + // includes ElementFormatUpdateTester as well? + return tester.equals(this); + } + + @Override + public String toString() { + return "Manual (refresh = false) update tester for an event that did not originate from the data model"; //$NON-NLS-1$ + } + }; + + @Override + public IElementUpdateTester getElementUpdateTester(Object event) { + if (event instanceof PropertyChangeEvent && IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE + .equals(((PropertyChangeEvent) event).getProperty())) { + return fNumberFormatPropertyEventUpdateTester; + } + if (event instanceof ElementFormatEvent) { + return new ElementFormatUpdateTester(((ElementFormatEvent) event), fElementFormatPropertiesWithPrefixes); + } + return super.getElementUpdateTester(event); + } + + @Override public boolean canUpdateDirtyProperty(ICacheEntry entry, String property) { - return fActiveNumberFormatPropertiesWithPrefixes.contains(property); - } + return fActiveNumberFormatPropertiesWithPrefixes.contains(property); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/ElementFormatEvent.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/ElementFormatEvent.java index 60da0faf845..2dcc913373a 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/ElementFormatEvent.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/ElementFormatEvent.java @@ -17,9 +17,9 @@ import java.util.Set; /** * An event that indicates the format of certain elements has changed. - * Even when a viewer is configured to be in a manual update mode, there is a need to + * Even when a viewer is configured to be in a manual update mode, there is a need to * update the labels/states of elements. - * + * * @since 2.2 */ public class ElementFormatEvent { @@ -44,7 +44,7 @@ public class ElementFormatEvent { /** * Get the elements for which the format has changed. - * + * * @return the elements */ public Set<Object> getElements() { @@ -54,7 +54,7 @@ public class ElementFormatEvent { /** * Get the depth to which the change of format applies, with respect to the * affected elements and their children. - * + * * @return the apply depth. */ public int getApplyDepth() { diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/ElementFormatUpdateTester.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/ElementFormatUpdateTester.java index 8ad36e77c68..7f1568f18f0 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/ElementFormatUpdateTester.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/ElementFormatUpdateTester.java @@ -25,7 +25,7 @@ import org.eclipse.jface.viewers.TreePath; * An update tester for element format event (ElementFormatEvent). This tester * flushes partial properties for elements that are affected by a change of * element format. - * + * * @since 2.2 */ public class ElementFormatUpdateTester implements IElementUpdateTesterExtension { @@ -64,8 +64,7 @@ public class ElementFormatUpdateTester implements IElementUpdateTesterExtension } @Override - public Collection<String> getPropertiesToFlush(Object viewerInput, - TreePath path, boolean isDirty) { + public Collection<String> getPropertiesToFlush(Object viewerInput, TreePath path, boolean isDirty) { return propertiesWithPrefixes; } @@ -75,8 +74,7 @@ public class ElementFormatUpdateTester implements IElementUpdateTesterExtension return true; } if (tester instanceof ElementFormatUpdateTester) { - return formatEvent.getElements().containsAll( - ((ElementFormatUpdateTester) tester).formatEvent.getElements()) + return formatEvent.getElements().containsAll(((ElementFormatUpdateTester) tester).formatEvent.getElements()) && propertiesWithPrefixes.containsAll(((ElementFormatUpdateTester) tester).propertiesWithPrefixes) && formatEvent.getApplyDepth() == ((ElementFormatUpdateTester) tester).formatEvent.getApplyDepth(); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/MessagesForVMUpdate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/MessagesForVMUpdate.java index 4ca2ff98407..0b3781aa9a1 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/MessagesForVMUpdate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/update/MessagesForVMUpdate.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,15 +19,15 @@ import org.eclipse.osgi.util.NLS; * @noinstantiate This class is not intended to be instantiated by clients. */ public class MessagesForVMUpdate extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.cdt.dsf.debug.ui.viewmodel.update.messages"; //$NON-NLS-1$ + private static final String BUNDLE_NAME = "org.eclipse.cdt.dsf.debug.ui.viewmodel.update.messages"; //$NON-NLS-1$ - public static String BreakpointHitUpdatePolicy_name; + public static String BreakpointHitUpdatePolicy_name; - static { - // initialize resource bundle - NLS.initializeMessages(BUNDLE_NAME, MessagesForVMUpdate.class); - } + static { + // initialize resource bundle + NLS.initializeMessages(BUNDLE_NAME, MessagesForVMUpdate.class); + } - private MessagesForVMUpdate() { - } + private MessagesForVMUpdate() { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/MessagesForVariablesVM.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/MessagesForVariablesVM.java index 1e9acd4e7e7..62d460a260f 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/MessagesForVariablesVM.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/MessagesForVariablesVM.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,34 +20,34 @@ import org.eclipse.osgi.util.NLS; * @noinstantiate This class is not intended to be instantiated by clients. */ public class MessagesForVariablesVM extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.cdt.dsf.debug.ui.viewmodel.variable.messages"; //$NON-NLS-1$ + private static final String BUNDLE_NAME = "org.eclipse.cdt.dsf.debug.ui.viewmodel.variable.messages"; //$NON-NLS-1$ - public static String VariableColumnPresentation_name; - public static String VariableColumnPresentation_type; - public static String VariableColumnPresentation_value; - public static String VariableColumnPresentation_location; + public static String VariableColumnPresentation_name; + public static String VariableColumnPresentation_type; + public static String VariableColumnPresentation_value; + public static String VariableColumnPresentation_location; - public static String VariableVMNode_CannotCastVariable; + public static String VariableVMNode_CannotCastVariable; public static String VariableVMNode_Location_column__Error__text_format; - public static String VariableVMNode_Location_column__text_format; - public static String VariableVMNode_Description_column__text_format; - public static String VariableVMNode_Expression_column__text_format; - public static String VariableVMNode_Name_column__text_format; - public static String VariableVMNode_NoColumns_column__Error__text_format; - public static String VariableVMNode_NoColumns_column__text_format; - public static String VariableVMNode_NoColumns_column__No_string__text_format_with_type; - public static String VariableVMNode_NoColumns_column__text_format_with_type; - public static String VariableVMNode_NoColumns_column__No_string__text_format; - public static String VariableVMNode_Type_column__Error__text_format; - public static String VariableVMNode_Type_column__text_format; - public static String VariableVMNode_Value_column__text_format; - - static { - // initialize resource bundle - NLS.initializeMessages(BUNDLE_NAME, MessagesForVariablesVM.class); - } - - private MessagesForVariablesVM() { - } + public static String VariableVMNode_Location_column__text_format; + public static String VariableVMNode_Description_column__text_format; + public static String VariableVMNode_Expression_column__text_format; + public static String VariableVMNode_Name_column__text_format; + public static String VariableVMNode_NoColumns_column__Error__text_format; + public static String VariableVMNode_NoColumns_column__text_format; + public static String VariableVMNode_NoColumns_column__No_string__text_format_with_type; + public static String VariableVMNode_NoColumns_column__text_format_with_type; + public static String VariableVMNode_NoColumns_column__No_string__text_format; + public static String VariableVMNode_Type_column__Error__text_format; + public static String VariableVMNode_Type_column__text_format; + public static String VariableVMNode_Value_column__text_format; + + static { + // initialize resource bundle + NLS.initializeMessages(BUNDLE_NAME, MessagesForVariablesVM.class); + } + + private MessagesForVariablesVM() { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/SyncVariableDataAccess.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/SyncVariableDataAccess.java index 32663cc79ca..81d3fbae37b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/SyncVariableDataAccess.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/SyncVariableDataAccess.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -40,521 +40,531 @@ import org.osgi.util.tracker.ServiceTracker; @ThreadSafeAndProhibitedFromDsfExecutor("fSession#getExecutor") public class SyncVariableDataAccess { - /** - * The session that this data access operates in. - */ - private final DsfSession fSession; - - /** - * Need to use the OSGi service tracker here (instead of DsfServiceTracker), - * because we're accessing it in non-dispatch thread. DsfServiceTracker is - * not thread-safe. - */ - @ThreadSafe - private ServiceTracker fServiceTracker; - - - public SyncVariableDataAccess(DsfSession session) { - fSession = session; - } - - @ThreadSafe - private synchronized IExpressions getService() { - - if (fServiceTracker == null) { - try { - fServiceTracker = new ServiceTracker( - DsfUIPlugin.getBundleContext(), - DsfUIPlugin.getBundleContext().createFilter(getServiceFilter()), null); - fServiceTracker.open(); - } catch (InvalidSyntaxException e) { - return null; - } - } - return (IExpressions) fServiceTracker.getService(); - } - - private String getServiceFilter() { - StringBuilder filter = new StringBuilder(); - filter.append("(&"); //$NON-NLS-1$ - filter.append("(OBJECTCLASS="); //$NON-NLS-1$ - filter.append(IExpressions.class.getName()); - filter.append(')'); - filter.append('('); - filter.append(IDsfService.PROP_SESSION_ID); - filter.append('='); - filter.append(fSession.getId()); - filter.append(')'); - filter.append(')'); - return filter.toString(); - } - - @ThreadSafe - public synchronized void dispose() { - if (fServiceTracker != null) { - fServiceTracker.close(); - } - } - - public IExpressionDMContext getVariableDMC(Object element) { - if (element instanceof IAdaptable) { - return ((IAdaptable) element).getAdapter(IExpressionDMContext.class); - } - return null; - } - - - public class GetVariableValueQuery extends Query<IExpressionDMData> { - - private IExpressionDMContext fDmc; - - public GetVariableValueQuery(IExpressionDMContext dmc) { - super(); - fDmc = dmc; - } - - @Override - protected void execute(final DataRequestMonitor<IExpressionDMData> rm) { - /* - * Guard against the session being disposed. If session is disposed - * it could mean that the executor is shut-down, which in turn could - * mean that we can't complete the RequestMonitor argument. in that - * case, cancel to notify waiting thread. - */ - final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); - if (session == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Debug session already shut down.", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - IExpressions service = getService(); - if (service == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Service not available", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - service.getExpressionData(fDmc, new DataRequestMonitor<IExpressionDMData>(session.getExecutor(), rm) { - @Override - protected void handleSuccess() { - /* - * All good set return value. - */ - rm.setData(getData()); - rm.done(); - } - }); - } - } - - public IExpressionDMContext getExpressionDMC(Object element) { - if (element instanceof IAdaptable) { - return ((IAdaptable) element).getAdapter(IExpressionDMContext.class); - } - return null; - } - - public IExpressionDMData readVariable(Object element) { - /* - * Get the DMC and the session. If element is not an expression DMC, or - * session is stale, then bail out. - */ - IExpressionDMContext dmc = getExpressionDMC(element); - if (dmc == null) return null; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) return null; - - /* - * Create the query to request the value from service. Note: no need to - * guard against RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - GetVariableValueQuery query = new GetVariableValueQuery(dmc); - session.getExecutor().execute(query); + /** + * The session that this data access operates in. + */ + private final DsfSession fSession; + + /** + * Need to use the OSGi service tracker here (instead of DsfServiceTracker), + * because we're accessing it in non-dispatch thread. DsfServiceTracker is + * not thread-safe. + */ + @ThreadSafe + private ServiceTracker fServiceTracker; + + public SyncVariableDataAccess(DsfSession session) { + fSession = session; + } + + @ThreadSafe + private synchronized IExpressions getService() { + + if (fServiceTracker == null) { + try { + fServiceTracker = new ServiceTracker(DsfUIPlugin.getBundleContext(), + DsfUIPlugin.getBundleContext().createFilter(getServiceFilter()), null); + fServiceTracker.open(); + } catch (InvalidSyntaxException e) { + return null; + } + } + return (IExpressions) fServiceTracker.getService(); + } + + private String getServiceFilter() { + StringBuilder filter = new StringBuilder(); + filter.append("(&"); //$NON-NLS-1$ + filter.append("(OBJECTCLASS="); //$NON-NLS-1$ + filter.append(IExpressions.class.getName()); + filter.append(')'); + filter.append('('); + filter.append(IDsfService.PROP_SESSION_ID); + filter.append('='); + filter.append(fSession.getId()); + filter.append(')'); + filter.append(')'); + return filter.toString(); + } + + @ThreadSafe + public synchronized void dispose() { + if (fServiceTracker != null) { + fServiceTracker.close(); + } + } + + public IExpressionDMContext getVariableDMC(Object element) { + if (element instanceof IAdaptable) { + return ((IAdaptable) element).getAdapter(IExpressionDMContext.class); + } + return null; + } + + public class GetVariableValueQuery extends Query<IExpressionDMData> { + + private IExpressionDMContext fDmc; + + public GetVariableValueQuery(IExpressionDMContext dmc) { + super(); + fDmc = dmc; + } + + @Override + protected void execute(final DataRequestMonitor<IExpressionDMData> rm) { + /* + * Guard against the session being disposed. If session is disposed + * it could mean that the executor is shut-down, which in turn could + * mean that we can't complete the RequestMonitor argument. in that + * case, cancel to notify waiting thread. + */ + final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); + if (session == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Debug session already shut down.", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + IExpressions service = getService(); + if (service == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Service not available", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + service.getExpressionData(fDmc, new DataRequestMonitor<IExpressionDMData>(session.getExecutor(), rm) { + @Override + protected void handleSuccess() { + /* + * All good set return value. + */ + rm.setData(getData()); + rm.done(); + } + }); + } + } + + public IExpressionDMContext getExpressionDMC(Object element) { + if (element instanceof IAdaptable) { + return ((IAdaptable) element).getAdapter(IExpressionDMContext.class); + } + return null; + } + + public IExpressionDMData readVariable(Object element) { + /* + * Get the DMC and the session. If element is not an expression DMC, or + * session is stale, then bail out. + */ + IExpressionDMContext dmc = getExpressionDMC(element); + if (dmc == null) + return null; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return null; + + /* + * Create the query to request the value from service. Note: no need to + * guard against RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + GetVariableValueQuery query = new GetVariableValueQuery(dmc); + session.getExecutor().execute(query); /* * This class is about synchronous access to the variable, so wait until * the query has completed on the DSF session thread and return the * result. */ - try { - return query.get(); - } catch (InterruptedException e) { - assert false; - return null; - } catch (ExecutionException e) { - return null; - } - } - - public class SetVariableValueQuery extends Query<Object> { - - private IExpressionDMContext fDmc; - private String fValue; - private String fFormatId; - - public SetVariableValueQuery(IExpressionDMContext dmc, String value, String formatId) { - super(); - fDmc = dmc; - fValue = value; - fFormatId = formatId; - } - - @Override - protected void execute(final DataRequestMonitor<Object> rm) { - /* - * We're in another dispatch, so we must guard against executor - * shutdown again. - */ - final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); - if (session == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Debug session already shut down.", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - /* - * Guard against a disposed service - */ - IExpressions service = getService(); - if (service == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Service unavailable", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - /* - * Write the expression value using a string/format style. - */ - service.writeExpression( - fDmc, - fValue, - fFormatId, - new DataRequestMonitor<IExpressionDMData>(session.getExecutor(), rm) { - @Override - protected void handleSuccess() { - /* - * All good set return value. - */ - rm.setData(new Object()); - rm.done(); - } - } - ); - } - } - - public void writeVariable(Object element, String value, String formatId) { - - /* - * Get the DMC and the session. If element is not an register DMC, or - * session is stale, then bail out. - */ - IExpressionDMContext dmc = getExpressionDMC(element); - if (dmc == null) return; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) return; - - /* - * Create the query to write the value to the service. Note: no need to - * guard against RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - SetVariableValueQuery query = new SetVariableValueQuery(dmc, value, formatId); - session.getExecutor().execute(query); + try { + return query.get(); + } catch (InterruptedException e) { + assert false; + return null; + } catch (ExecutionException e) { + return null; + } + } + + public class SetVariableValueQuery extends Query<Object> { + + private IExpressionDMContext fDmc; + private String fValue; + private String fFormatId; + + public SetVariableValueQuery(IExpressionDMContext dmc, String value, String formatId) { + super(); + fDmc = dmc; + fValue = value; + fFormatId = formatId; + } + + @Override + protected void execute(final DataRequestMonitor<Object> rm) { + /* + * We're in another dispatch, so we must guard against executor + * shutdown again. + */ + final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); + if (session == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Debug session already shut down.", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + /* + * Guard against a disposed service + */ + IExpressions service = getService(); + if (service == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Service unavailable", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + /* + * Write the expression value using a string/format style. + */ + service.writeExpression(fDmc, fValue, fFormatId, + new DataRequestMonitor<IExpressionDMData>(session.getExecutor(), rm) { + @Override + protected void handleSuccess() { + /* + * All good set return value. + */ + rm.setData(new Object()); + rm.done(); + } + }); + } + } + + public void writeVariable(Object element, String value, String formatId) { + + /* + * Get the DMC and the session. If element is not an register DMC, or + * session is stale, then bail out. + */ + IExpressionDMContext dmc = getExpressionDMC(element); + if (dmc == null) + return; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return; + + /* + * Create the query to write the value to the service. Note: no need to + * guard against RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + SetVariableValueQuery query = new SetVariableValueQuery(dmc, value, formatId); + session.getExecutor().execute(query); /* * This class is about synchronous access to the variable, so wait until - * the query has completed on the DSF session thread. + * the query has completed on the DSF session thread. + */ + try { + /* + * Return value is irrelevant, any error would come through with an + * exception. + */ + query.get(3000, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + assert false; + } catch (ExecutionException e) { + /* + * View must be shutting down, no need to show error dialog. + */ + } catch (TimeoutException e) { + assert false; + } + } + + public IFormattedDataDMContext getFormattedDMC(Object element) { + if (element instanceof IAdaptable) { + return ((IAdaptable) element).getAdapter(IFormattedDataDMContext.class); + } + return null; + } + + public class GetSupportFormatsValueQuery extends Query<Object> { + + IFormattedDataDMContext fDmc; + + public GetSupportFormatsValueQuery(IFormattedDataDMContext dmc) { + super(); + fDmc = dmc; + } + + @Override + protected void execute(final DataRequestMonitor<Object> rm) { + /* + * We're in another dispatch, so we must guard against executor + * shutdown again. + */ + final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); + if (session == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Debug session already shut down.", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + /* + * Guard against a disposed service + */ + IExpressions service = getService(); + if (service == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Service unavailable", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + /* + * Get the available formats from the service. + */ + service.getAvailableFormats(fDmc, new DataRequestMonitor<String[]>(session.getExecutor(), rm) { + @Override + protected void handleSuccess() { + /* + * All good set return value. + */ + rm.setData(getData()); + rm.done(); + } + }); + } + } + + public String[] getSupportedFormats(Object element) { + + /* + * Get the DMC and the session. If element is not an register DMC, or + * session is stale, then bail out. */ - try { - /* - * Return value is irrelevant, any error would come through with an - * exception. - */ - query.get(3000, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - assert false; - } catch (ExecutionException e) { - /* - * View must be shutting down, no need to show error dialog. - */ - } catch (TimeoutException e) { - assert false; - } - } - - public IFormattedDataDMContext getFormattedDMC(Object element) { - if (element instanceof IAdaptable) { - return ((IAdaptable) element).getAdapter(IFormattedDataDMContext.class); - } - return null; - } - - public class GetSupportFormatsValueQuery extends Query<Object> { - - IFormattedDataDMContext fDmc; - - public GetSupportFormatsValueQuery(IFormattedDataDMContext dmc) { - super(); - fDmc = dmc; - } - - @Override - protected void execute(final DataRequestMonitor<Object> rm) { - /* - * We're in another dispatch, so we must guard against executor - * shutdown again. - */ - final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); - if (session == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Debug session already shut down.", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - /* - * Guard against a disposed service - */ - IExpressions service = getService(); - if (service == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Service unavailable", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - /* - * Get the available formats from the service. - */ - service.getAvailableFormats( - fDmc, - new DataRequestMonitor<String[]>(session.getExecutor(), rm) { - @Override - protected void handleSuccess() { - /* - * All good set return value. - */ - rm.setData(getData()); - rm.done(); - } - } - ); - } - } - - public String[] getSupportedFormats(Object element) { - - /* - * Get the DMC and the session. If element is not an register DMC, or - * session is stale, then bail out. - */ - IFormattedDataDMContext dmc = getFormattedDMC(element); - if (dmc == null) return null; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) return null; - - /* - * Create the query to write the value to the service. Note: no need to - * guard against RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - GetSupportFormatsValueQuery query = new GetSupportFormatsValueQuery(dmc); - session.getExecutor().execute(query); - - /* - * Now we have the data, go and get it. Since the call is completed now - * the ".get()" will not suspend it will immediately return with the - * data. - */ - try { - return (String[]) query.get(); - } catch (InterruptedException e) { - assert false; - return null; - } catch (ExecutionException e) { - return null; - } - } - - public class GetFormattedValueValueQuery extends Query<Object> { - - private IFormattedDataDMContext fDmc; - private String fFormatId; - private boolean fEditable; - - public GetFormattedValueValueQuery(IFormattedDataDMContext dmc, String formatId) { - this(dmc, formatId, false); - } - - public GetFormattedValueValueQuery(IFormattedDataDMContext dmc, String formatId, boolean editable) { - super(); - fDmc = dmc; - fFormatId = formatId; - fEditable = editable; - } - - @Override - protected void execute(final DataRequestMonitor<Object> rm) { - /* - * We're in another dispatch, so we must guard against executor - * shutdown again. - */ - final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); - if (session == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Debug session already shut down.", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - /* - * Guard against a disposed service - */ - IExpressions service = getService(); - if (service == null) { - rm .setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Service unavailable", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - /* - * Convert to the proper formatting DMC then go get the formatted value. - */ - - FormattedValueDMContext formDmc = service.getFormattedValueContext(fDmc, fFormatId); - - service.getFormattedExpressionValue(formDmc, new DataRequestMonitor<FormattedValueDMData>(session.getExecutor(), rm) { - @Override - protected void handleSuccess() { - rm.setData(fEditable ? getData().getEditableValue() : getData().getFormattedValue()); - rm.done(); - } - }); - } - } - - public String getFormattedValue(Object element, String formatId) { - return getValue(element, formatId, false); - } - - public String getEditableValue(Object element, String formatId) { - return getValue(element, formatId, true); - } - - private String getValue(Object element, String formatId, boolean editable) { - - /* - * Get the DMC and the session. If element is not an register DMC, or - * session is stale, then bail out. - */ - IFormattedDataDMContext dmc = getFormattedDMC(element); - if (dmc == null) return null; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) return null; - - /* - * Create the query to write the value to the service. Note: no need to - * guard against RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - GetFormattedValueValueQuery query = new GetFormattedValueValueQuery(dmc, formatId, editable); - session.getExecutor().execute(query); - - /* - * Now we have the data, go and get it. Since the call is completed now - * the ".get()" will not suspend it will immediately return with the - * data. - */ - try { - return (String) query.get(); - } catch (InterruptedException e) { - assert false; - return null; - } catch (ExecutionException e) { - return null; - } - } - - /** - * @since 1.1 - */ - public class CanWriteExpressionQuery extends Query<Boolean> { - - private IExpressionDMContext fDmc; - - public CanWriteExpressionQuery(IExpressionDMContext dmc) { - super(); - fDmc = dmc; - } - - @Override - protected void execute(final DataRequestMonitor<Boolean> rm) { - /* - * We're in another dispatch, so we must guard against executor - * shutdown again. - */ - final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); - if (session == null) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Debug session already shut down.", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - /* - * Guard against a disposed service - */ - IExpressions service = getService(); - if (service == null) { - rm .setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Service unavailable", null)); //$NON-NLS-1$ - rm.done(); - return; - } - - service.canWriteExpression(fDmc, new DataRequestMonitor<Boolean>(session.getExecutor(), rm) { - @Override - protected void handleSuccess() { - /* - * All good set return value. - */ - rm.setData(getData()); - rm.done(); - } - }); - } - } - - public boolean canWriteExpression(Object element) { - /* - * Get the DMC and the session. If element is not an expression DMC, or - * session is stale, then bail out. - */ - IExpressionDMContext dmc = getExpressionDMC(element); - if (dmc == null) return false; - DsfSession session = DsfSession.getSession(dmc.getSessionId()); - if (session == null) return false; - - /* - * Create the query to make the request to the service. Note: no need to - * guard against RejectedExecutionException, because - * DsfSession.getSession() above would only return an active session. - */ - CanWriteExpressionQuery query = new CanWriteExpressionQuery(dmc); - session.getExecutor().execute(query); - - /* - * Now we have the data, go and get it. Since the call is completed now - * the ".get()" will not suspend it will immediately return with the - * data. - */ - try { - return query.get(); - } catch (InterruptedException e) { - assert false; - return false; - } catch (ExecutionException e) { - return false; - } - } - - + IFormattedDataDMContext dmc = getFormattedDMC(element); + if (dmc == null) + return null; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return null; + + /* + * Create the query to write the value to the service. Note: no need to + * guard against RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + GetSupportFormatsValueQuery query = new GetSupportFormatsValueQuery(dmc); + session.getExecutor().execute(query); + + /* + * Now we have the data, go and get it. Since the call is completed now + * the ".get()" will not suspend it will immediately return with the + * data. + */ + try { + return (String[]) query.get(); + } catch (InterruptedException e) { + assert false; + return null; + } catch (ExecutionException e) { + return null; + } + } + + public class GetFormattedValueValueQuery extends Query<Object> { + + private IFormattedDataDMContext fDmc; + private String fFormatId; + private boolean fEditable; + + public GetFormattedValueValueQuery(IFormattedDataDMContext dmc, String formatId) { + this(dmc, formatId, false); + } + + public GetFormattedValueValueQuery(IFormattedDataDMContext dmc, String formatId, boolean editable) { + super(); + fDmc = dmc; + fFormatId = formatId; + fEditable = editable; + } + + @Override + protected void execute(final DataRequestMonitor<Object> rm) { + /* + * We're in another dispatch, so we must guard against executor + * shutdown again. + */ + final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); + if (session == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Debug session already shut down.", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + /* + * Guard against a disposed service + */ + IExpressions service = getService(); + if (service == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Service unavailable", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + /* + * Convert to the proper formatting DMC then go get the formatted value. + */ + + FormattedValueDMContext formDmc = service.getFormattedValueContext(fDmc, fFormatId); + + service.getFormattedExpressionValue(formDmc, + new DataRequestMonitor<FormattedValueDMData>(session.getExecutor(), rm) { + @Override + protected void handleSuccess() { + rm.setData(fEditable ? getData().getEditableValue() : getData().getFormattedValue()); + rm.done(); + } + }); + } + } + + public String getFormattedValue(Object element, String formatId) { + return getValue(element, formatId, false); + } + + public String getEditableValue(Object element, String formatId) { + return getValue(element, formatId, true); + } + + private String getValue(Object element, String formatId, boolean editable) { + + /* + * Get the DMC and the session. If element is not an register DMC, or + * session is stale, then bail out. + */ + IFormattedDataDMContext dmc = getFormattedDMC(element); + if (dmc == null) + return null; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return null; + + /* + * Create the query to write the value to the service. Note: no need to + * guard against RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + GetFormattedValueValueQuery query = new GetFormattedValueValueQuery(dmc, formatId, editable); + session.getExecutor().execute(query); + + /* + * Now we have the data, go and get it. Since the call is completed now + * the ".get()" will not suspend it will immediately return with the + * data. + */ + try { + return (String) query.get(); + } catch (InterruptedException e) { + assert false; + return null; + } catch (ExecutionException e) { + return null; + } + } + + /** + * @since 1.1 + */ + public class CanWriteExpressionQuery extends Query<Boolean> { + + private IExpressionDMContext fDmc; + + public CanWriteExpressionQuery(IExpressionDMContext dmc) { + super(); + fDmc = dmc; + } + + @Override + protected void execute(final DataRequestMonitor<Boolean> rm) { + /* + * We're in another dispatch, so we must guard against executor + * shutdown again. + */ + final DsfSession session = DsfSession.getSession(fDmc.getSessionId()); + if (session == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Debug session already shut down.", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + /* + * Guard against a disposed service + */ + IExpressions service = getService(); + if (service == null) { + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Service unavailable", null)); //$NON-NLS-1$ + rm.done(); + return; + } + + service.canWriteExpression(fDmc, new DataRequestMonitor<Boolean>(session.getExecutor(), rm) { + @Override + protected void handleSuccess() { + /* + * All good set return value. + */ + rm.setData(getData()); + rm.done(); + } + }); + } + } + + public boolean canWriteExpression(Object element) { + /* + * Get the DMC and the session. If element is not an expression DMC, or + * session is stale, then bail out. + */ + IExpressionDMContext dmc = getExpressionDMC(element); + if (dmc == null) + return false; + DsfSession session = DsfSession.getSession(dmc.getSessionId()); + if (session == null) + return false; + + /* + * Create the query to make the request to the service. Note: no need to + * guard against RejectedExecutionException, because + * DsfSession.getSession() above would only return an active session. + */ + CanWriteExpressionQuery query = new CanWriteExpressionQuery(dmc); + session.getExecutor().execute(query); + + /* + * Now we have the data, go and get it. Since the call is completed now + * the ".get()" will not suspend it will immediately return with the + * data. + */ + try { + return query.get(); + } catch (InterruptedException e) { + assert false; + return false; + } catch (ExecutionException e) { + return false; + } + } + } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableCellModifier.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableCellModifier.java index 5c6b4e25253..b03d4578061 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableCellModifier.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableCellModifier.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Winnie Lai (Texas Instruments) - Individual Element Number Format in editing (Bug 343021) @@ -25,121 +25,117 @@ import org.eclipse.cdt.dsf.ui.viewmodel.update.UserEditEvent; import org.eclipse.core.runtime.IAdaptable; public class VariableCellModifier extends WatchExpressionCellModifier { - - private AbstractCachingVMProvider fProvider; - private SyncVariableDataAccess fDataAccess = null; - protected String formatInEditing; - - public VariableCellModifier(AbstractCachingVMProvider provider, SyncVariableDataAccess access) - { - fProvider = provider; - fDataAccess = access; - } - - /* - * Used to make sure we are dealing with a valid variable. - */ - private IExpressionDMContext getVariableDMC(Object element) { - if (element instanceof IAdaptable) { - return ((IAdaptable)element).getAdapter(IExpressionDMContext.class); - } - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.WatchExpressionCellModifier#canModify(java.lang.Object, java.lang.String) - */ - @Override - public boolean canModify(Object element, String property) { - // If we're in the column value, modify the register data. Otherwise, call the super-class to edit - // the watch expression. - - if (IDebugVMConstants.COLUMN_ID__VALUE.equals(property)) { - // Make sure we are are dealing with a valid set of information. - - if (getVariableDMC(element) == null) { - return false; - } - - return fDataAccess.canWriteExpression(element); - } - - return super.canModify(element, property); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.WatchExpressionCellModifier#getValue(java.lang.Object, java.lang.String) - */ - @Override - public Object getValue(Object element, String property) { - // If we're in the column value, modify the variable value. Otherwise, call the super-class to edit - // the watch expression. - - if (IDebugVMConstants.COLUMN_ID__VALUE.equals(property)) { - /* - * We let the Model provider supply the current format. - */ - String formatId = null; - - if ( element instanceof IVMContext) { - formatId = queryFormat((IVMContext) element); - } - else { - formatId = IFormattedValues.NATURAL_FORMAT; - } - formatInEditing = formatId; - String value = fDataAccess.getEditableValue(element, formatId); - - if (value == null) { - return "..."; //$NON-NLS-1$ - } - - return value; - } - - return super.getValue(element, property); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.WatchExpressionCellModifier#modify(java.lang.Object, java.lang.String, java.lang.Object) - */ - @Override - public void modify(final Object element, String property, Object value) { + + private AbstractCachingVMProvider fProvider; + private SyncVariableDataAccess fDataAccess = null; + protected String formatInEditing; + + public VariableCellModifier(AbstractCachingVMProvider provider, SyncVariableDataAccess access) { + fProvider = provider; + fDataAccess = access; + } + + /* + * Used to make sure we are dealing with a valid variable. + */ + private IExpressionDMContext getVariableDMC(Object element) { + if (element instanceof IAdaptable) { + return ((IAdaptable) element).getAdapter(IExpressionDMContext.class); + } + return null; + } + + /* (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.WatchExpressionCellModifier#canModify(java.lang.Object, java.lang.String) + */ + @Override + public boolean canModify(Object element, String property) { + // If we're in the column value, modify the register data. Otherwise, call the super-class to edit + // the watch expression. + + if (IDebugVMConstants.COLUMN_ID__VALUE.equals(property)) { + // Make sure we are are dealing with a valid set of information. + + if (getVariableDMC(element) == null) { + return false; + } + + return fDataAccess.canWriteExpression(element); + } + + return super.canModify(element, property); + } + + /* (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.WatchExpressionCellModifier#getValue(java.lang.Object, java.lang.String) + */ + @Override + public Object getValue(Object element, String property) { + // If we're in the column value, modify the variable value. Otherwise, call the super-class to edit + // the watch expression. + + if (IDebugVMConstants.COLUMN_ID__VALUE.equals(property)) { + /* + * We let the Model provider supply the current format. + */ + String formatId = null; + + if (element instanceof IVMContext) { + formatId = queryFormat((IVMContext) element); + } else { + formatId = IFormattedValues.NATURAL_FORMAT; + } + formatInEditing = formatId; + String value = fDataAccess.getEditableValue(element, formatId); + + if (value == null) { + return "..."; //$NON-NLS-1$ + } + + return value; + } + + return super.getValue(element, property); + } + + /* (non-Javadoc) + * @see org.eclipse.cdt.dsf.debug.ui.viewmodel.expression.WatchExpressionCellModifier#modify(java.lang.Object, java.lang.String, java.lang.Object) + */ + @Override + public void modify(final Object element, String property, Object value) { /* * If we're in the Value column, modify the variable/register data. The * other columns in the Variables and Registers view are non-modifiable. * If we're called for another column, pass the request to our super * class; the column is likely a column it handles (Expression, for * example). - */ - if (IDebugVMConstants.COLUMN_ID__VALUE.equals(property)) { - if (value instanceof String) { - /* - * We let the Model provider supply the current format. - */ - String formatId = formatInEditing; - - if ( element instanceof IVMContext) { - if (formatId == null) { - formatId = queryFormat((IVMContext) element); - } - } - else { - formatId = IFormattedValues.NATURAL_FORMAT; - } - - fDataAccess.writeVariable(element, (String) value, formatId); - fProvider.getExecutor().execute(new DsfRunnable() { - @Override + */ + if (IDebugVMConstants.COLUMN_ID__VALUE.equals(property)) { + if (value instanceof String) { + /* + * We let the Model provider supply the current format. + */ + String formatId = formatInEditing; + + if (element instanceof IVMContext) { + if (formatId == null) { + formatId = queryFormat((IVMContext) element); + } + } else { + formatId = IFormattedValues.NATURAL_FORMAT; + } + + fDataAccess.writeVariable(element, (String) value, formatId); + fProvider.getExecutor().execute(new DsfRunnable() { + @Override public void run() { - fProvider.handleEvent(new UserEditEvent(element)); - } - }); - } - } - else { - super.modify(element, property, value); - } - } + fProvider.handleEvent(new UserEditEvent(element)); + } + }); + } + } else { + super.modify(element, property, value); + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableColumnPresentation.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableColumnPresentation.java index a442a75191d..e962e7e2164 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableColumnPresentation.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableColumnPresentation.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,62 +20,66 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationCont import org.eclipse.jface.resource.ImageDescriptor; /** - * + * */ public class VariableColumnPresentation implements IColumnPresentation { - public static final String ID = DsfUIPlugin.PLUGIN_ID + ".VARIABLES_COLUMN_PRESENTATION_ID"; //$NON-NLS-1$ - - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#init(org.eclipse.debug.internal.ui.viewers.provisional.IPresentationContext) - @Override - public void init(IPresentationContext context) {} + public static final String ID = DsfUIPlugin.PLUGIN_ID + ".VARIABLES_COLUMN_PRESENTATION_ID"; //$NON-NLS-1$ + + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#init(org.eclipse.debug.internal.ui.viewers.provisional.IPresentationContext) + @Override + public void init(IPresentationContext context) { + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#dispose() - @Override - public void dispose() {} + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#dispose() + @Override + public void dispose() { + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getAvailableColumns() - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getAvailableColumns() + @Override public String[] getAvailableColumns() { - return new String[] { IDebugVMConstants.COLUMN_ID__NAME, IDebugVMConstants.COLUMN_ID__TYPE, IDebugVMConstants.COLUMN_ID__VALUE, IDebugVMConstants.COLUMN_ID__ADDRESS }; - } + return new String[] { IDebugVMConstants.COLUMN_ID__NAME, IDebugVMConstants.COLUMN_ID__TYPE, + IDebugVMConstants.COLUMN_ID__VALUE, IDebugVMConstants.COLUMN_ID__ADDRESS }; + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getHeader(java.lang.String) - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getHeader(java.lang.String) + @Override public String getHeader(String id) { - if (IDebugVMConstants.COLUMN_ID__NAME.equals(id)) { - return MessagesForVariablesVM.VariableColumnPresentation_name; - } else if (IDebugVMConstants.COLUMN_ID__TYPE.equals(id)) { - return MessagesForVariablesVM.VariableColumnPresentation_type; - } else if (IDebugVMConstants.COLUMN_ID__VALUE.equals(id)) { - return MessagesForVariablesVM.VariableColumnPresentation_value; - } else if (IDebugVMConstants.COLUMN_ID__ADDRESS.equals(id)) { - return MessagesForVariablesVM.VariableColumnPresentation_location; - } - return null; - } + if (IDebugVMConstants.COLUMN_ID__NAME.equals(id)) { + return MessagesForVariablesVM.VariableColumnPresentation_name; + } else if (IDebugVMConstants.COLUMN_ID__TYPE.equals(id)) { + return MessagesForVariablesVM.VariableColumnPresentation_type; + } else if (IDebugVMConstants.COLUMN_ID__VALUE.equals(id)) { + return MessagesForVariablesVM.VariableColumnPresentation_value; + } else if (IDebugVMConstants.COLUMN_ID__ADDRESS.equals(id)) { + return MessagesForVariablesVM.VariableColumnPresentation_location; + } + return null; + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getId() - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getId() + @Override public String getId() { - return ID; - } + return ID; + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getImageDescriptor(java.lang.String) - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getImageDescriptor(java.lang.String) + @Override public ImageDescriptor getImageDescriptor(String id) { - return null; - } + return null; + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getInitialColumns() - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#getInitialColumns() + @Override public String[] getInitialColumns() { - return new String[] { IDebugVMConstants.COLUMN_ID__NAME, IDebugVMConstants.COLUMN_ID__TYPE, IDebugVMConstants.COLUMN_ID__VALUE }; - } + return new String[] { IDebugVMConstants.COLUMN_ID__NAME, IDebugVMConstants.COLUMN_ID__TYPE, + IDebugVMConstants.COLUMN_ID__VALUE }; + } - // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#isOptional() - @Override + // @see org.eclipse.debug.internal.ui.viewers.provisional.IColumnPresentation#isOptional() + @Override public boolean isOptional() { - return true; - } + return true; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableLabelFont.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableLabelFont.java index 786b37561d8..a215f121301 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableLabelFont.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableLabelFont.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -22,10 +22,10 @@ import org.eclipse.swt.graphics.FontData; * @since 2.0 */ public class VariableLabelFont extends LabelFont { - - public VariableLabelFont() { - super(JFaceResources.getFontRegistry().getFontData(IDebugUIConstants.PREF_VARIABLE_TEXT_FONT)[0]); - } + + public VariableLabelFont() { + super(JFaceResources.getFontRegistry().getFontData(IDebugUIConstants.PREF_VARIABLE_TEXT_FONT)[0]); + } @Override public FontData getFontData() { diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableVMNode.java index 0b715ccb475..26f3935bbbc 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Marc Khouzam (Ericsson) - Add support disable "View Memory" action (bug 418710) @@ -114,108 +114,108 @@ import org.eclipse.jface.viewers.TreePath; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IMemento; -public class VariableVMNode extends AbstractExpressionVMNode - implements IElementEditor, IElementLabelProvider, IElementPropertiesProvider, IElementMementoProvider -{ - /** - * @since 2.1 - */ - public static final String PROP_VARIABLE_TYPE_NAME = "variable_type_name"; //$NON-NLS-1$ - - /** - * @since 2.1 - */ - public static final String PROP_VARIABLE_BASIC_TYPE = "variable_basic_type"; //$NON-NLS-1$ - - /** - * @since 2.1 - */ - public static final String PROP_VARIABLE_ADDRESS = "variable_address"; //$NON-NLS-1$ - - /** - * @since 2.1 - */ - public static final String PROP_VARIABLE_SHOW_TYPE_NAMES = "variable_show_type_names"; //$NON-NLS-1$ - - /** - * @since 2.1 - */ - public static final String PROP_VARIABLE_ADDRESS_CHANGED = ICachingVMProvider.PROP_IS_CHANGED_PREFIX + PROP_VARIABLE_ADDRESS; - - /** - * 'PROP_VARIABLE_BASIC_TYPE' property value for indexed partitions - */ - private static final String INDEXED_PARTITION_TYPE = "indexed_partition_type"; //$NON-NLS-1$ - - private final SyncVariableDataAccess fSyncVariableDataAccess; - - /** - * The label provider delegate. This VM node will delegate label updates to this provider - * which can be created by sub-classes. - * - * @since 2.0 - */ - private final IElementLabelProvider fLabelProvider; - - /** - * Retriever for formatted values configured for this VM node. - * @since 2.2 - */ - private final FormattedValueRetriever fFormattedValueRetriever; - - public class VariableExpressionVMC extends DMVMContext implements IFormattedValueVMContext, IViewInMemory { - - private IExpression fExpression; - - public VariableExpressionVMC(IDMContext dmc) { - super(dmc); - } +public class VariableVMNode extends AbstractExpressionVMNode + implements IElementEditor, IElementLabelProvider, IElementPropertiesProvider, IElementMementoProvider { + /** + * @since 2.1 + */ + public static final String PROP_VARIABLE_TYPE_NAME = "variable_type_name"; //$NON-NLS-1$ + + /** + * @since 2.1 + */ + public static final String PROP_VARIABLE_BASIC_TYPE = "variable_basic_type"; //$NON-NLS-1$ + + /** + * @since 2.1 + */ + public static final String PROP_VARIABLE_ADDRESS = "variable_address"; //$NON-NLS-1$ + + /** + * @since 2.1 + */ + public static final String PROP_VARIABLE_SHOW_TYPE_NAMES = "variable_show_type_names"; //$NON-NLS-1$ + + /** + * @since 2.1 + */ + public static final String PROP_VARIABLE_ADDRESS_CHANGED = ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + PROP_VARIABLE_ADDRESS; + + /** + * 'PROP_VARIABLE_BASIC_TYPE' property value for indexed partitions + */ + private static final String INDEXED_PARTITION_TYPE = "indexed_partition_type"; //$NON-NLS-1$ + + private final SyncVariableDataAccess fSyncVariableDataAccess; + + /** + * The label provider delegate. This VM node will delegate label updates to this provider + * which can be created by sub-classes. + * + * @since 2.0 + */ + private final IElementLabelProvider fLabelProvider; + + /** + * Retriever for formatted values configured for this VM node. + * @since 2.2 + */ + private final FormattedValueRetriever fFormattedValueRetriever; + + public class VariableExpressionVMC extends DMVMContext implements IFormattedValueVMContext, IViewInMemory { + + private IExpression fExpression; + + public VariableExpressionVMC(IDMContext dmc) { + super(dmc); + } /* (non-Javadoc) * @see org.eclipse.cdt.debug.internal.core.IWatchpointTarget#getExpression() */ public String getExpression() { - final IExpressionDMContext exprDmc = DMContexts.getAncestorOfType(getDMContext(), IExpressionDMContext.class); + final IExpressionDMContext exprDmc = DMContexts.getAncestorOfType(getDMContext(), + IExpressionDMContext.class); if (exprDmc != null) { return exprDmc.getExpression(); } return ""; //$NON-NLS-1$ } - public void setExpression(IExpression expression) { - fExpression = expression; - } + public void setExpression(IExpression expression) { + fExpression = expression; + } - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) @Override - public Object getAdapter(Class adapter) { - if (fExpression != null && adapter.isAssignableFrom(fExpression.getClass())) { - return fExpression; - } else if (adapter.isAssignableFrom(IWatchExpressionFactoryAdapter2.class)) { - return fVariableExpressionFactory; + public Object getAdapter(Class adapter) { + if (fExpression != null && adapter.isAssignableFrom(fExpression.getClass())) { + return fExpression; + } else if (adapter.isAssignableFrom(IWatchExpressionFactoryAdapter2.class)) { + return fVariableExpressionFactory; } else if (fCastToTypeSupport != null && getDMContext() instanceof IExpressionDMContext - && (adapter.isAssignableFrom(ICastToType.class) - || adapter.isAssignableFrom(ICastToArray.class))) { + && (adapter.isAssignableFrom(ICastToType.class) || adapter.isAssignableFrom(ICastToArray.class))) { return fCastToTypeSupport.getCastImpl((IExpressionDMContext) getDMContext()); - } else { - return super.getAdapter(adapter); - } - } - - @Override - public boolean equals(Object other) { - if (other instanceof VariableExpressionVMC && super.equals(other)) { - VariableExpressionVMC otherGroup = (VariableExpressionVMC)other; - return (otherGroup.fExpression == null && fExpression == null) || - (otherGroup.fExpression != null && otherGroup.fExpression.equals(fExpression)); - } - return false; - } - - @Override - public int hashCode() { - return super.hashCode() + (fExpression != null ? fExpression.hashCode() : 0); - } + } else { + return super.getAdapter(adapter); + } + } + + @Override + public boolean equals(Object other) { + if (other instanceof VariableExpressionVMC && super.equals(other)) { + VariableExpressionVMC otherGroup = (VariableExpressionVMC) other; + return (otherGroup.fExpression == null && fExpression == null) + || (otherGroup.fExpression != null && otherGroup.fExpression.equals(fExpression)); + } + return false; + } + + @Override + public int hashCode() { + return super.hashCode() + (fExpression != null ? fExpression.hashCode() : 0); + } @Override public boolean canViewInMemory() { @@ -226,1227 +226,1153 @@ public class VariableVMNode extends AbstractExpressionVMNode public void viewInMemory() { assert false : "VariableExpressionVMC.viewInMemory() not implemented"; //$NON-NLS-1$ } - } - - protected class VariableExpressionFactory implements IWatchExpressionFactoryAdapter2 { - - @Override - public boolean canCreateWatchExpression(Object element) { - return element instanceof VariableExpressionVMC; - } - - @Override - public String createWatchExpression(Object element) throws CoreException { - - VariableExpressionVMC exprVmc = (VariableExpressionVMC) element; - - IExpressionDMContext exprDmc = DMContexts.getAncestorOfType(exprVmc.getDMContext(), IExpressionDMContext.class); - if (exprDmc != null) { - return exprDmc.getExpression(); - } - - return null; - } - } - - final protected VariableExpressionFactory fVariableExpressionFactory = new VariableExpressionFactory(); + } + + protected class VariableExpressionFactory implements IWatchExpressionFactoryAdapter2 { + + @Override + public boolean canCreateWatchExpression(Object element) { + return element instanceof VariableExpressionVMC; + } + + @Override + public String createWatchExpression(Object element) throws CoreException { + + VariableExpressionVMC exprVmc = (VariableExpressionVMC) element; + + IExpressionDMContext exprDmc = DMContexts.getAncestorOfType(exprVmc.getDMContext(), + IExpressionDMContext.class); + if (exprDmc != null) { + return exprDmc.getExpression(); + } + + return null; + } + } + + final protected VariableExpressionFactory fVariableExpressionFactory = new VariableExpressionFactory(); protected DsfCastToTypeSupport fCastToTypeSupport; - public VariableVMNode(AbstractDMVMProvider provider, DsfSession session, - SyncVariableDataAccess syncVariableDataAccess) - { - super(provider, session, IExpressions.IExpressionDMContext.class); - fSyncVariableDataAccess = syncVariableDataAccess; - fLabelProvider = createLabelProvider(); - fFormattedValueRetriever = - new FormattedValueRetriever(this, session, IExpressions.class, IExpressionDMContext.class); - } - - /** - * Set the cast support target. This is only meaningful if the {@link IExpressions2} - * service is available. - * @param castToTypeSupport - */ - public void setCastToTypeSupport(DsfCastToTypeSupport castToTypeSupport) { - this.fCastToTypeSupport = castToTypeSupport; - } - - /** - * Creates the label provider delegate. This VM node will delegate label - * updates to this provider which can be created by sub-classes. - * - * @return Returns the label provider for this node. - * - * @since 2.0 - */ - private LabelBackground columnIdValueBackground; - private LabelBackground columnNoColumnsBackground; - private IPropertyChangeListener fPreferenceChangeListener; - - /* - * (non-Javadoc) - * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#dispose() - * - * We need to take over the dispose so we can get rid of the preference listener we created. - */ - @Override + public VariableVMNode(AbstractDMVMProvider provider, DsfSession session, + SyncVariableDataAccess syncVariableDataAccess) { + super(provider, session, IExpressions.IExpressionDMContext.class); + fSyncVariableDataAccess = syncVariableDataAccess; + fLabelProvider = createLabelProvider(); + fFormattedValueRetriever = new FormattedValueRetriever(this, session, IExpressions.class, + IExpressionDMContext.class); + } + + /** + * Set the cast support target. This is only meaningful if the {@link IExpressions2} + * service is available. + * @param castToTypeSupport + */ + public void setCastToTypeSupport(DsfCastToTypeSupport castToTypeSupport) { + this.fCastToTypeSupport = castToTypeSupport; + } + + /** + * Creates the label provider delegate. This VM node will delegate label + * updates to this provider which can be created by sub-classes. + * + * @return Returns the label provider for this node. + * + * @since 2.0 + */ + private LabelBackground columnIdValueBackground; + private LabelBackground columnNoColumnsBackground; + private IPropertyChangeListener fPreferenceChangeListener; + + /* + * (non-Javadoc) + * @see org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode#dispose() + * + * We need to take over the dispose so we can get rid of the preference listener we created. + */ + @Override public void dispose() { - - if ( fPreferenceChangeListener != null ) { - DebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferenceChangeListener); - } - - - super.dispose(); - - fFormattedValueRetriever.dispose(); - } - - /** - * Create label image objects which are used in more than one column. - * - * @since 2.1 - * - * Pointer image is used for variable and function pointers. - */ - public final static LabelImage POINTER_LABEL_IMAGE = new LabelImage(CDebugImages.DESC_OBJS_VARIABLE_POINTER) { - { setPropertyNames(new String[] { PROP_VARIABLE_BASIC_TYPE }); } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - String type = (String)properties.get(PROP_VARIABLE_BASIC_TYPE); - return IExpressionDMData.BasicType.pointer.name().equals(type) || - IExpressionDMData.BasicType.function.name().equals(type); - }; - }; - - /** - * @since 2.1 - * - * Aggregate image is used for array, struct, etc. - */ - public final static LabelImage AGGREGATE_LABEL_IMAGE = new LabelImage(CDebugImages.DESC_OBJS_VARIABLE_AGGREGATE) { - { setPropertyNames(new String[] { PROP_VARIABLE_BASIC_TYPE }); } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - String type = (String)properties.get(PROP_VARIABLE_BASIC_TYPE); - return IExpressionDMData.BasicType.array.name().equals(type) || - IExpressionDMData.BasicType.composite.name().equals(type); - }; - }; - - /** - * @since 2.1 - * - * Simple variable image is used for all other types, except when there is no type specified. - */ - public final static LabelImage SIMPLE_LABEL_IMAGE = new LabelImage(CDebugImages.DESC_OBJS_VARIABLE_SIMPLE) { - { setPropertyNames(new String[] { PROP_VARIABLE_BASIC_TYPE }); } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - String type = (String)properties.get(PROP_VARIABLE_BASIC_TYPE); - return type != null; - }; - }; - - public final static LabelImage PARTITION_LABEL_IMAGE = new LabelImage(CDebugImages.DESC_OBJS_ARRAY_PARTITION) { - { setPropertyNames(new String[] { PROP_VARIABLE_BASIC_TYPE }); } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - String type = (String)properties.get(PROP_VARIABLE_BASIC_TYPE); - return INDEXED_PARTITION_TYPE.equals(type); - }; - }; - - protected IElementLabelProvider createLabelProvider() { - - // - // Create the foreground/background colors which can be dynamically modified. - // - columnIdValueBackground = new LabelBackground( - DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()) - { - { - setPropertyNames(new String[] { - FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT}); - } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - Boolean activeFormatChanged = (Boolean)properties.get( - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); - Boolean activeChanged = (Boolean)properties.get( - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); - Boolean stringChanged = (Boolean)properties.get( - ICachingVMProvider.PROP_IS_CHANGED_PREFIX + FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT)); - return Boolean.TRUE.equals(stringChanged) || - ( Boolean.TRUE.equals(activeChanged) && !Boolean.TRUE.equals(activeFormatChanged)); - }; - }; - - columnNoColumnsBackground = new LabelBackground(DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()) - { - { - setPropertyNames(new String[] { - FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), - IDebugVMConstants.PROP_IS_STRING_FORMAT_VALUE_CHANGED, - IDebugVMConstants.PROP_IS_ACTIVE_FORMATTED_VALUE_CHANGED}); - } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - Boolean stringChanged = (Boolean)properties.get(IDebugVMConstants.PROP_IS_STRING_FORMAT_VALUE_CHANGED); - Boolean activeChanged = (Boolean)properties.get(IDebugVMConstants.PROP_IS_ACTIVE_FORMATTED_VALUE_CHANGED); - return Boolean.TRUE.equals(stringChanged) || Boolean.TRUE.equals(activeChanged); - } - }; - - // Get rid of the previous listener if it exists and then create a new one and sign it up. - if ( fPreferenceChangeListener != null ) { - DebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferenceChangeListener); - } - - fPreferenceChangeListener = new IPropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent event) { - if ( event.getProperty().equals(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND) ) { - columnIdValueBackground.setBackground(DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()); - columnNoColumnsBackground.setBackground(DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()); - } - } - }; - - DebugUITools.getPreferenceStore().addPropertyChangeListener(fPreferenceChangeListener); - - // Create the initial properties provider which can be built on. - PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); - - // The name column consists of the expression name. The name column image depends on the variable type. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__NAME, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForVariablesVM.VariableVMNode_Name_column__text_format, - new String[] { PROP_NAME }), - POINTER_LABEL_IMAGE, - AGGREGATE_LABEL_IMAGE, - PARTITION_LABEL_IMAGE, - SIMPLE_LABEL_IMAGE, - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // Expression column is visible only in the expressions view. It shows the expression string that the user - // entered. Expression column images are the same as for the name column. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__EXPRESSION, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForVariablesVM.VariableVMNode_Expression_column__text_format, - new String[] { PROP_ELEMENT_EXPRESSION }), - POINTER_LABEL_IMAGE, - AGGREGATE_LABEL_IMAGE, - PARTITION_LABEL_IMAGE, - SIMPLE_LABEL_IMAGE, - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // Type column only contains the type name. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__TYPE, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForVariablesVM.VariableVMNode_Type_column__text_format, - new String[] { PROP_VARIABLE_TYPE_NAME }), - new LabelText( MessagesForVariablesVM.VariableVMNode_Type_column__Error__text_format, new String[] {}), - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // Value column is more complicated: - // - If a STRING value format is supported. Then the value label consists of the active format label followed - // by the string format. - // - If the STRIGN value format is not supported. Then only show the active value format. The GDB reference - // implementation currently does not support the string format, but by default it does append extra - // information to the value label itself. - // - // In case of error, show the error message in the value column (instead of the usual "...". This is needed - // for the expressions view, where an invalid expression entered by the user is a normal use case. - // - // For changed value high-lighting check both the string value and the value in the active format. But, - // ignore the active format value change if the format itself has changed. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__VALUE, - new LabelColumnInfo(new LabelAttribute[] { - new FormattedValueLabelText( - MessagesForVariablesVM.VariableVMNode_Value_column__text_format, - new String[] { - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), - IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS}) - { - @Override - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - String[] formatIds = - (String[])properties.get(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS); - String activeFormat = (String)properties.get(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); - return - !IFormattedValues.STRING_FORMAT.equals(activeFormat) && - formatIds != null && - Arrays.asList(formatIds).contains(IFormattedValues.STRING_FORMAT) && - super.isEnabled(status, properties); - } - }, - new FormattedValueLabelText(), - new ErrorLabelText(), - new ErrorLabelForeground(), - columnIdValueBackground, - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // Address column shows the variable's address. It is highlighted with the change background color when the - // address value changes. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__ADDRESS, - new LabelColumnInfo(new LabelAttribute[] { - new LabelText( - MessagesForVariablesVM.VariableVMNode_Location_column__text_format, - new String[] { PROP_VARIABLE_ADDRESS }), - new LabelText(MessagesForVariablesVM.VariableVMNode_Location_column__Error__text_format, new String[] {}), - new LabelBackground( - DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()) - { - { setPropertyNames(new String[] { PROP_VARIABLE_ADDRESS, PROP_VARIABLE_ADDRESS_CHANGED}); } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - Boolean changed = (Boolean)properties.get(PROP_VARIABLE_ADDRESS_CHANGED); - return Boolean.TRUE.equals(changed); - }; - }, - new StaleDataLabelForeground(), - new VariableLabelFont(), - })); - - // Description column is shown in the expression view, but is not supported for variables. - provider.setColumnInfo( - IDebugVMConstants.COLUMN_ID__DESCRIPTION, - - new LabelColumnInfo(new LabelAttribute[] { - new LabelText(MessagesForVariablesVM.VariableVMNode_Description_column__text_format, new String[] {}), - new VariableLabelFont(), - })); - - // Configure the case where there are no columns visible. It basically combines the name and the value columns only. - provider.setColumnInfo( - PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, - new LabelColumnInfo(new LabelAttribute[] { - new FormattedValueLabelText( - MessagesForVariablesVM.VariableVMNode_NoColumns_column__text_format, - new String[] { - PROP_NAME, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), - IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, - IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, - PROP_VARIABLE_SHOW_TYPE_NAMES}) - { + + if (fPreferenceChangeListener != null) { + DebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferenceChangeListener); + } + + super.dispose(); + + fFormattedValueRetriever.dispose(); + } + + /** + * Create label image objects which are used in more than one column. + * + * @since 2.1 + * + * Pointer image is used for variable and function pointers. + */ + public final static LabelImage POINTER_LABEL_IMAGE = new LabelImage(CDebugImages.DESC_OBJS_VARIABLE_POINTER) { + { + setPropertyNames(new String[] { PROP_VARIABLE_BASIC_TYPE }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + String type = (String) properties.get(PROP_VARIABLE_BASIC_TYPE); + return IExpressionDMData.BasicType.pointer.name().equals(type) + || IExpressionDMData.BasicType.function.name().equals(type); + }; + }; + + /** + * @since 2.1 + * + * Aggregate image is used for array, struct, etc. + */ + public final static LabelImage AGGREGATE_LABEL_IMAGE = new LabelImage(CDebugImages.DESC_OBJS_VARIABLE_AGGREGATE) { + { + setPropertyNames(new String[] { PROP_VARIABLE_BASIC_TYPE }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + String type = (String) properties.get(PROP_VARIABLE_BASIC_TYPE); + return IExpressionDMData.BasicType.array.name().equals(type) + || IExpressionDMData.BasicType.composite.name().equals(type); + }; + }; + + /** + * @since 2.1 + * + * Simple variable image is used for all other types, except when there is no type specified. + */ + public final static LabelImage SIMPLE_LABEL_IMAGE = new LabelImage(CDebugImages.DESC_OBJS_VARIABLE_SIMPLE) { + { + setPropertyNames(new String[] { PROP_VARIABLE_BASIC_TYPE }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + String type = (String) properties.get(PROP_VARIABLE_BASIC_TYPE); + return type != null; + }; + }; + + public final static LabelImage PARTITION_LABEL_IMAGE = new LabelImage(CDebugImages.DESC_OBJS_ARRAY_PARTITION) { + { + setPropertyNames(new String[] { PROP_VARIABLE_BASIC_TYPE }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + String type = (String) properties.get(PROP_VARIABLE_BASIC_TYPE); + return INDEXED_PARTITION_TYPE.equals(type); + }; + }; + + protected IElementLabelProvider createLabelProvider() { + + // + // Create the foreground/background colors which can be dynamically modified. + // + columnIdValueBackground = new LabelBackground( + DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()) { + { + setPropertyNames(new String[] { + FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), + ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + Boolean activeFormatChanged = (Boolean) properties.get(ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); + Boolean activeChanged = (Boolean) properties.get(ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE); + Boolean stringChanged = (Boolean) properties.get(ICachingVMProvider.PROP_IS_CHANGED_PREFIX + + FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT)); + return Boolean.TRUE.equals(stringChanged) + || (Boolean.TRUE.equals(activeChanged) && !Boolean.TRUE.equals(activeFormatChanged)); + }; + }; + + columnNoColumnsBackground = new LabelBackground( + DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()) { + { + setPropertyNames( + new String[] { FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), + IDebugVMConstants.PROP_IS_STRING_FORMAT_VALUE_CHANGED, + IDebugVMConstants.PROP_IS_ACTIVE_FORMATTED_VALUE_CHANGED }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + Boolean stringChanged = (Boolean) properties.get(IDebugVMConstants.PROP_IS_STRING_FORMAT_VALUE_CHANGED); + Boolean activeChanged = (Boolean) properties + .get(IDebugVMConstants.PROP_IS_ACTIVE_FORMATTED_VALUE_CHANGED); + return Boolean.TRUE.equals(stringChanged) || Boolean.TRUE.equals(activeChanged); + } + }; + + // Get rid of the previous listener if it exists and then create a new one and sign it up. + if (fPreferenceChangeListener != null) { + DebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferenceChangeListener); + } + + fPreferenceChangeListener = new IPropertyChangeListener() { + @Override + public void propertyChange(PropertyChangeEvent event) { + if (event.getProperty().equals(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND)) { + columnIdValueBackground.setBackground( + DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()); + columnNoColumnsBackground.setBackground( + DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()); + } + } + }; + + DebugUITools.getPreferenceStore().addPropertyChangeListener(fPreferenceChangeListener); + + // Create the initial properties provider which can be built on. + PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider(); + + // The name column consists of the expression name. The name column image depends on the variable type. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__NAME, new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForVariablesVM.VariableVMNode_Name_column__text_format, + new String[] { PROP_NAME }), + POINTER_LABEL_IMAGE, AGGREGATE_LABEL_IMAGE, PARTITION_LABEL_IMAGE, SIMPLE_LABEL_IMAGE, + new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // Expression column is visible only in the expressions view. It shows the expression string that the user + // entered. Expression column images are the same as for the name column. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__EXPRESSION, new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForVariablesVM.VariableVMNode_Expression_column__text_format, + new String[] { PROP_ELEMENT_EXPRESSION }), + POINTER_LABEL_IMAGE, AGGREGATE_LABEL_IMAGE, PARTITION_LABEL_IMAGE, SIMPLE_LABEL_IMAGE, + new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // Type column only contains the type name. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__TYPE, new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForVariablesVM.VariableVMNode_Type_column__text_format, + new String[] { PROP_VARIABLE_TYPE_NAME }), + new LabelText(MessagesForVariablesVM.VariableVMNode_Type_column__Error__text_format, new String[] {}), + new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // Value column is more complicated: + // - If a STRING value format is supported. Then the value label consists of the active format label followed + // by the string format. + // - If the STRIGN value format is not supported. Then only show the active value format. The GDB reference + // implementation currently does not support the string format, but by default it does append extra + // information to the value label itself. + // + // In case of error, show the error message in the value column (instead of the usual "...". This is needed + // for the expressions view, where an invalid expression entered by the user is a normal use case. + // + // For changed value high-lighting check both the string value and the value in the active format. But, + // ignore the active format value change if the format itself has changed. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__VALUE, + new LabelColumnInfo(new LabelAttribute[] { + new FormattedValueLabelText(MessagesForVariablesVM.VariableVMNode_Value_column__text_format, + new String[] { IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), + IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS }) { + @Override + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + String[] formatIds = (String[]) properties + .get(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS); + String activeFormat = (String) properties + .get(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); + return !IFormattedValues.STRING_FORMAT.equals(activeFormat) && formatIds != null + && Arrays.asList(formatIds).contains(IFormattedValues.STRING_FORMAT) + && super.isEnabled(status, properties); + } + }, new FormattedValueLabelText(), new ErrorLabelText(), new ErrorLabelForeground(), + columnIdValueBackground, new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // Address column shows the variable's address. It is highlighted with the change background color when the + // address value changes. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__ADDRESS, new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForVariablesVM.VariableVMNode_Location_column__text_format, + new String[] { PROP_VARIABLE_ADDRESS }), + new LabelText(MessagesForVariablesVM.VariableVMNode_Location_column__Error__text_format, + new String[] {}), + new LabelBackground( + DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_VALUE_BACKGROUND).getRGB()) { + { + setPropertyNames(new String[] { PROP_VARIABLE_ADDRESS, PROP_VARIABLE_ADDRESS_CHANGED }); + } + @Override - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - Boolean showTypeNames = (Boolean) properties.get(PROP_VARIABLE_SHOW_TYPE_NAMES); - String[] formatIds = (String[]) properties.get(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS); - String activeFormat = (String) properties.get(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); - return - showTypeNames != null && - !showTypeNames.booleanValue() && - !IFormattedValues.STRING_FORMAT.equals(activeFormat) && - formatIds != null && - Arrays.asList(formatIds).contains(IFormattedValues.STRING_FORMAT) && - super.isEnabled(status, properties); - } - }, - new FormattedValueLabelText( - MessagesForVariablesVM.VariableVMNode_NoColumns_column__No_string__text_format, - new String[] { - PROP_NAME, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, - IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, - PROP_VARIABLE_SHOW_TYPE_NAMES}) - { - @Override - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - Boolean showTypeNames = (Boolean) properties.get(PROP_VARIABLE_SHOW_TYPE_NAMES); - return - showTypeNames != null && - !showTypeNames.booleanValue() && - super.isEnabled(status, properties); - } - }, - new FormattedValueLabelText( - MessagesForVariablesVM.VariableVMNode_NoColumns_column__text_format_with_type, - new String[] { - PROP_NAME, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), - PROP_VARIABLE_TYPE_NAME, - IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, - IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, - PROP_VARIABLE_SHOW_TYPE_NAMES}) - { - @Override - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - Boolean showTypeNames = (Boolean) properties.get(PROP_VARIABLE_SHOW_TYPE_NAMES); - String[] formatIds = (String[]) properties.get(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS); - String activeFormat = (String) properties.get(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); - return - showTypeNames != null && - showTypeNames.booleanValue() && - !IFormattedValues.STRING_FORMAT.equals(activeFormat) && - formatIds != null && - Arrays.asList(formatIds).contains(IFormattedValues.STRING_FORMAT) && - super.isEnabled(status, properties); - } - }, - new FormattedValueLabelText( - MessagesForVariablesVM.VariableVMNode_NoColumns_column__No_string__text_format_with_type, - new String[] { - PROP_NAME, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, - PROP_VARIABLE_TYPE_NAME, - IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS, - IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, - IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, - PROP_VARIABLE_SHOW_TYPE_NAMES}) - { - @Override - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - Boolean showTypeNames = (Boolean) properties.get(PROP_VARIABLE_SHOW_TYPE_NAMES); - return - showTypeNames != null && - showTypeNames.booleanValue() && - super.isEnabled(status, properties); - } - }, - new ErrorLabelText( - MessagesForVariablesVM.VariableVMNode_NoColumns_column__Error__text_format, - new String[] { PROP_NAME }), - POINTER_LABEL_IMAGE, - AGGREGATE_LABEL_IMAGE, - SIMPLE_LABEL_IMAGE, - new ErrorLabelForeground(), - new LabelForeground( - DebugUITools.getPreferenceColor(IDebugUIConstants.PREF_CHANGED_DEBUG_ELEMENT_COLOR).getRGB()) - { - { - setPropertyNames(new String[] { - FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), - IDebugVMConstants.PROP_IS_STRING_FORMAT_VALUE_CHANGED, - IDebugVMConstants.PROP_IS_ACTIVE_FORMATTED_VALUE_CHANGED}); - } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - Boolean stringChanged = - (Boolean)properties.get(IDebugVMConstants.PROP_IS_STRING_FORMAT_VALUE_CHANGED); - Boolean activeChanged = - (Boolean)properties.get(IDebugVMConstants.PROP_IS_ACTIVE_FORMATTED_VALUE_CHANGED); - return Boolean.TRUE.equals(stringChanged) || Boolean.TRUE.equals(activeChanged); - }; - }, - columnNoColumnsBackground, - new StaleDataLabelBackground(), - new VariableLabelFont(), - })); - - return provider; - } - - @Override - public String toString() { - return "VariableVMNode(" + getSession().getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - } - - @Override - protected IDMVMContext createVMContext(IDMContext dmc) { - return new VariableExpressionVMC(dmc); - } - - - @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + Boolean changed = (Boolean) properties.get(PROP_VARIABLE_ADDRESS_CHANGED); + return Boolean.TRUE.equals(changed); + }; + }, new StaleDataLabelForeground(), new VariableLabelFont(), })); + + // Description column is shown in the expression view, but is not supported for variables. + provider.setColumnInfo(IDebugVMConstants.COLUMN_ID__DESCRIPTION, + + new LabelColumnInfo(new LabelAttribute[] { + new LabelText(MessagesForVariablesVM.VariableVMNode_Description_column__text_format, + new String[] {}), + new VariableLabelFont(), })); + + // Configure the case where there are no columns visible. It basically combines the name and the value columns only. + provider.setColumnInfo(PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS, + new LabelColumnInfo(new LabelAttribute[] { + new FormattedValueLabelText(MessagesForVariablesVM.VariableVMNode_NoColumns_column__text_format, + new String[] { PROP_NAME, IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), + IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS, + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, + IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, + PROP_VARIABLE_SHOW_TYPE_NAMES }) { + @Override + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + Boolean showTypeNames = (Boolean) properties.get(PROP_VARIABLE_SHOW_TYPE_NAMES); + String[] formatIds = (String[]) properties + .get(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS); + String activeFormat = (String) properties + .get(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); + return showTypeNames != null && !showTypeNames.booleanValue() + && !IFormattedValues.STRING_FORMAT.equals(activeFormat) && formatIds != null + && Arrays.asList(formatIds).contains(IFormattedValues.STRING_FORMAT) + && super.isEnabled(status, properties); + } + }, + new FormattedValueLabelText( + MessagesForVariablesVM.VariableVMNode_NoColumns_column__No_string__text_format, + new String[] { PROP_NAME, IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS, + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, + IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, + PROP_VARIABLE_SHOW_TYPE_NAMES }) { + @Override + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + Boolean showTypeNames = (Boolean) properties.get(PROP_VARIABLE_SHOW_TYPE_NAMES); + return showTypeNames != null && !showTypeNames.booleanValue() + && super.isEnabled(status, properties); + } + }, + new FormattedValueLabelText( + MessagesForVariablesVM.VariableVMNode_NoColumns_column__text_format_with_type, + new String[] { PROP_NAME, IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), + PROP_VARIABLE_TYPE_NAME, + IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS, + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, + IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, + PROP_VARIABLE_SHOW_TYPE_NAMES }) { + @Override + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + Boolean showTypeNames = (Boolean) properties.get(PROP_VARIABLE_SHOW_TYPE_NAMES); + String[] formatIds = (String[]) properties + .get(IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS); + String activeFormat = (String) properties + .get(IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT); + return showTypeNames != null && showTypeNames.booleanValue() + && !IFormattedValues.STRING_FORMAT.equals(activeFormat) && formatIds != null + && Arrays.asList(formatIds).contains(IFormattedValues.STRING_FORMAT) + && super.isEnabled(status, properties); + } + }, + new FormattedValueLabelText( + MessagesForVariablesVM.VariableVMNode_NoColumns_column__No_string__text_format_with_type, + new String[] { PROP_NAME, IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE, + PROP_VARIABLE_TYPE_NAME, + IDebugVMConstants.PROP_FORMATTED_VALUE_AVAILABLE_FORMATS, + IDebugVMConstants.PROP_FORMATTED_VALUE_ACTIVE_FORMAT, + IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, + PROP_VARIABLE_SHOW_TYPE_NAMES }) { + @Override + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + Boolean showTypeNames = (Boolean) properties.get(PROP_VARIABLE_SHOW_TYPE_NAMES); + return showTypeNames != null && showTypeNames.booleanValue() + && super.isEnabled(status, properties); + } + }, + new ErrorLabelText(MessagesForVariablesVM.VariableVMNode_NoColumns_column__Error__text_format, + new String[] { PROP_NAME }), + POINTER_LABEL_IMAGE, AGGREGATE_LABEL_IMAGE, SIMPLE_LABEL_IMAGE, new ErrorLabelForeground(), + new LabelForeground(DebugUITools + .getPreferenceColor(IDebugUIConstants.PREF_CHANGED_DEBUG_ELEMENT_COLOR).getRGB()) { + { + setPropertyNames(new String[] { + FormattedValueVMUtil.getPropertyForFormatId(IFormattedValues.STRING_FORMAT), + IDebugVMConstants.PROP_IS_STRING_FORMAT_VALUE_CHANGED, + IDebugVMConstants.PROP_IS_ACTIVE_FORMATTED_VALUE_CHANGED }); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + Boolean stringChanged = (Boolean) properties + .get(IDebugVMConstants.PROP_IS_STRING_FORMAT_VALUE_CHANGED); + Boolean activeChanged = (Boolean) properties + .get(IDebugVMConstants.PROP_IS_ACTIVE_FORMATTED_VALUE_CHANGED); + return Boolean.TRUE.equals(stringChanged) || Boolean.TRUE.equals(activeChanged); + }; + }, columnNoColumnsBackground, new StaleDataLabelBackground(), new VariableLabelFont(), })); + + return provider; + } + + @Override + public String toString() { + return "VariableVMNode(" + getSession().getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } + + @Override + protected IDMVMContext createVMContext(IDMContext dmc) { + return new VariableExpressionVMC(dmc); + } + + @Override public void update(final ILabelUpdate[] updates) { - fLabelProvider.update(updates); - } - - /** - * Update the variable view properties. The formatted values need to be - * updated in the VM executor thread while the rest of the properties is - * updated in the service session's executor thread. The implementation - * splits the handling of the updates to accomplish that. - * - * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) - * - * @since 2.0 - */ - @Override + fLabelProvider.update(updates); + } + + /** + * Update the variable view properties. The formatted values need to be + * updated in the VM executor thread while the rest of the properties is + * updated in the service session's executor thread. The implementation + * splits the handling of the updates to accomplish that. + * + * @see IElementPropertiesProvider#update(IPropertiesUpdate[]) + * + * @since 2.0 + */ + @Override public void update(final IPropertiesUpdate[] updates) { - final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), null) { - @Override - protected void handleCompleted() { - for (int i = 0; i < updates.length; i++) { - updates[i].done(); - } - }; - }; - int count = 0; - - fFormattedValueRetriever.update(updates, countingRm); - count++; - - final IPropertiesUpdate[] subUpdates = new IPropertiesUpdate[updates.length]; - for (int i = 0; i < updates.length; i++) { - final IPropertiesUpdate update = updates[i]; - subUpdates[i] = new VMDelegatingPropertiesUpdate(update, countingRm); - count++; - } - countingRm.setDoneCount(count); - - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), null) { + @Override + protected void handleCompleted() { + for (int i = 0; i < updates.length; i++) { + updates[i].done(); + } + }; + }; + int count = 0; + + fFormattedValueRetriever.update(updates, countingRm); + count++; + + final IPropertiesUpdate[] subUpdates = new IPropertiesUpdate[updates.length]; + for (int i = 0; i < updates.length; i++) { + final IPropertiesUpdate update = updates[i]; + subUpdates[i] = new VMDelegatingPropertiesUpdate(update, countingRm); + count++; + } + countingRm.setDoneCount(count); + + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - updatePropertiesInSessionThread(subUpdates); - }}); - } catch (RejectedExecutionException e) { - for (IPropertiesUpdate subUpdate : subUpdates) { - subUpdate.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, "Session executor shut down " + getSession().getExecutor(), e)); //$NON-NLS-1$ - subUpdate.done(); - } - } - } - - // - // @param return-value Boolean.TRUE --> Show Types ICON is selected/depressed - // @param return-value Boolean.FALSE --> Show Types ICON is not selected/depressed - // - private Boolean getShowTypeNamesState( IPresentationContext context ) { - Boolean attribute = (Boolean) context.getProperty(IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES); - - if (attribute != null) { - return attribute; - } - - return Boolean.FALSE; - } - - /** - * @since 2.0 - */ - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { - IExpressions service = getServicesTracker().getService(IExpressions.class, null); - - final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), null) { - @Override - protected void handleCompleted() { - for (final IPropertiesUpdate update : updates) { - update.done(); - } - }; - }; - int count = 0; - - for (final IPropertiesUpdate update : updates) { - final IExpression expression = (IExpression)DebugPlugin.getAdapter(update.getElement(), IExpression.class); - if (expression != null) { - update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, expression.getExpressionText()); - } - - // Capture the current "Show Type Names" ICON state in case there are no columns. - if (update.getProperties().contains(PROP_VARIABLE_SHOW_TYPE_NAMES)) { - update.setProperty(PROP_VARIABLE_SHOW_TYPE_NAMES, getShowTypeNamesState(update.getPresentationContext())); - } - - IExpressionDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IExpressions.IExpressionDMContext.class); - if ( dmc == null || service == null) { - update.setStatus(DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_STATE, "Invalid context or service not available.", null)); //$NON-NLS-1$ - continue; - } - - if (update.getProperties().contains(PROP_NAME) || - update.getProperties().contains(PROP_VARIABLE_TYPE_NAME) || - update.getProperties().contains(PROP_VARIABLE_BASIC_TYPE)) - { - service.getExpressionData( - dmc, - // Use the ViewerDataRequestMonitor in order to propagate the update's cancel request. Use an immediate - // executor to avoid the possibility of a rejected execution exception. - new ViewerDataRequestMonitor<IExpressionDMData>(ImmediateExecutor.getInstance(), update) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - fillExpressionDataProperties(update, getData()); - } else { - // In case of an error fill in the expression text in the name column and expressions columns. - IExpressionDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IExpressions.IExpressionDMContext.class); - if (dmc != null && dmc.getExpression() != null) { - String displayName = getExpressionDisplayName(dmc, dmc.getExpression()); - update.setProperty(PROP_NAME, displayName); - if (expression == null) { - update.setProperty(PROP_ELEMENT_EXPRESSION, displayName); - } - if (dmc instanceof IIndexedPartitionDMContext) - update.setProperty(PROP_VARIABLE_BASIC_TYPE, INDEXED_PARTITION_TYPE); - } - update.setStatus(getStatus()); - } - countingRm.done(); - } - }); - - count++; - } - - if (update.getProperties().contains(PROP_VARIABLE_ADDRESS)) { - service.getExpressionAddressData( - dmc, - // Use the ViewerDataRequestMonitor in order to propagate the update's cancel request. Use an immediate - // executor to avoid the possibility of a rejected execution exception. - new ViewerDataRequestMonitor<IExpressionDMAddress>(ImmediateExecutor.getInstance(), update) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - fillAddressDataProperties(update, getData()); - } else if (getStatus().getCode() != IDsfStatusConstants.NOT_SUPPORTED && - getStatus().getCode() != IDsfStatusConstants.INVALID_STATE) - { - update.setStatus(getStatus()); - } - countingRm.done(); - } - }); - count++; - } - } - countingRm.setDoneCount(count); - } - - /** - * @since 2.0 - */ - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void fillExpressionDataProperties(IPropertiesUpdate update, IExpressionDMData data) - { - IExpressionDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IExpressions.IExpressionDMContext.class); - String displayName = data.getName(); - if (dmc != null) { - displayName = getExpressionDisplayName(dmc, displayName); - } - update.setProperty(PROP_NAME, displayName); - update.setProperty(PROP_VARIABLE_TYPE_NAME, data.getTypeName()); - String typeValue = null; - if (dmc instanceof IIndexedPartitionDMContext) - typeValue = INDEXED_PARTITION_TYPE; - else { - IExpressionDMData.BasicType type = data.getBasicType(); - if (type != null) - typeValue = type.name(); - } - if (typeValue != null) { - update.setProperty(PROP_VARIABLE_BASIC_TYPE, typeValue); - } - - // - // If this node has an expression then it has already been filled in by the higher - // level logic. If not then we need to supply something. In the previous version - // ( pre-property based ) we supplied the name. So we will do that here also. - // - IExpression expression = (IExpression)DebugPlugin.getAdapter(update.getElement(), IExpression.class); - if (expression == null) { - update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, displayName); - } - } - - /** - * Private data access routine which performs the extra level of data access needed to - * get the formatted data value for a specific register. - */ - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void fillAddressDataProperties(IPropertiesUpdate update, IExpressionDMAddress address) - { - if (address instanceof IExpressionDMLocation) - update.setProperty(PROP_VARIABLE_ADDRESS, ((IExpressionDMLocation)address).getLocation()); - else - update.setProperty(PROP_VARIABLE_ADDRESS, "0x" + address.getAddress().toString(16)); //$NON-NLS-1$ - } - - @Override + updatePropertiesInSessionThread(subUpdates); + } + }); + } catch (RejectedExecutionException e) { + for (IPropertiesUpdate subUpdate : subUpdates) { + subUpdate.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.REQUEST_FAILED, + "Session executor shut down " + getSession().getExecutor(), e)); //$NON-NLS-1$ + subUpdate.done(); + } + } + } + + // + // @param return-value Boolean.TRUE --> Show Types ICON is selected/depressed + // @param return-value Boolean.FALSE --> Show Types ICON is not selected/depressed + // + private Boolean getShowTypeNamesState(IPresentationContext context) { + Boolean attribute = (Boolean) context.getProperty(IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES); + + if (attribute != null) { + return attribute; + } + + return Boolean.FALSE; + } + + /** + * @since 2.0 + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void updatePropertiesInSessionThread(final IPropertiesUpdate[] updates) { + IExpressions service = getServicesTracker().getService(IExpressions.class, null); + + final CountingRequestMonitor countingRm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), null) { + @Override + protected void handleCompleted() { + for (final IPropertiesUpdate update : updates) { + update.done(); + } + }; + }; + int count = 0; + + for (final IPropertiesUpdate update : updates) { + final IExpression expression = (IExpression) DebugPlugin.getAdapter(update.getElement(), IExpression.class); + if (expression != null) { + update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, expression.getExpressionText()); + } + + // Capture the current "Show Type Names" ICON state in case there are no columns. + if (update.getProperties().contains(PROP_VARIABLE_SHOW_TYPE_NAMES)) { + update.setProperty(PROP_VARIABLE_SHOW_TYPE_NAMES, + getShowTypeNamesState(update.getPresentationContext())); + } + + IExpressionDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IExpressions.IExpressionDMContext.class); + if (dmc == null || service == null) { + update.setStatus(DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_STATE, + "Invalid context or service not available.", null)); //$NON-NLS-1$ + continue; + } + + if (update.getProperties().contains(PROP_NAME) || update.getProperties().contains(PROP_VARIABLE_TYPE_NAME) + || update.getProperties().contains(PROP_VARIABLE_BASIC_TYPE)) { + service.getExpressionData(dmc, + // Use the ViewerDataRequestMonitor in order to propagate the update's cancel request. Use an immediate + // executor to avoid the possibility of a rejected execution exception. + new ViewerDataRequestMonitor<IExpressionDMData>(ImmediateExecutor.getInstance(), update) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + fillExpressionDataProperties(update, getData()); + } else { + // In case of an error fill in the expression text in the name column and expressions columns. + IExpressionDMContext dmc = findDmcInPath(update.getViewerInput(), + update.getElementPath(), IExpressions.IExpressionDMContext.class); + if (dmc != null && dmc.getExpression() != null) { + String displayName = getExpressionDisplayName(dmc, dmc.getExpression()); + update.setProperty(PROP_NAME, displayName); + if (expression == null) { + update.setProperty(PROP_ELEMENT_EXPRESSION, displayName); + } + if (dmc instanceof IIndexedPartitionDMContext) + update.setProperty(PROP_VARIABLE_BASIC_TYPE, INDEXED_PARTITION_TYPE); + } + update.setStatus(getStatus()); + } + countingRm.done(); + } + }); + + count++; + } + + if (update.getProperties().contains(PROP_VARIABLE_ADDRESS)) { + service.getExpressionAddressData(dmc, + // Use the ViewerDataRequestMonitor in order to propagate the update's cancel request. Use an immediate + // executor to avoid the possibility of a rejected execution exception. + new ViewerDataRequestMonitor<IExpressionDMAddress>(ImmediateExecutor.getInstance(), update) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + fillAddressDataProperties(update, getData()); + } else if (getStatus().getCode() != IDsfStatusConstants.NOT_SUPPORTED + && getStatus().getCode() != IDsfStatusConstants.INVALID_STATE) { + update.setStatus(getStatus()); + } + countingRm.done(); + } + }); + count++; + } + } + countingRm.setDoneCount(count); + } + + /** + * @since 2.0 + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void fillExpressionDataProperties(IPropertiesUpdate update, IExpressionDMData data) { + IExpressionDMContext dmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IExpressions.IExpressionDMContext.class); + String displayName = data.getName(); + if (dmc != null) { + displayName = getExpressionDisplayName(dmc, displayName); + } + update.setProperty(PROP_NAME, displayName); + update.setProperty(PROP_VARIABLE_TYPE_NAME, data.getTypeName()); + String typeValue = null; + if (dmc instanceof IIndexedPartitionDMContext) + typeValue = INDEXED_PARTITION_TYPE; + else { + IExpressionDMData.BasicType type = data.getBasicType(); + if (type != null) + typeValue = type.name(); + } + if (typeValue != null) { + update.setProperty(PROP_VARIABLE_BASIC_TYPE, typeValue); + } + + // + // If this node has an expression then it has already been filled in by the higher + // level logic. If not then we need to supply something. In the previous version + // ( pre-property based ) we supplied the name. So we will do that here also. + // + IExpression expression = (IExpression) DebugPlugin.getAdapter(update.getElement(), IExpression.class); + if (expression == null) { + update.setProperty(AbstractExpressionVMNode.PROP_ELEMENT_EXPRESSION, displayName); + } + } + + /** + * Private data access routine which performs the extra level of data access needed to + * get the formatted data value for a specific register. + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void fillAddressDataProperties(IPropertiesUpdate update, IExpressionDMAddress address) { + if (address instanceof IExpressionDMLocation) + update.setProperty(PROP_VARIABLE_ADDRESS, ((IExpressionDMLocation) address).getLocation()); + else + update.setProperty(PROP_VARIABLE_ADDRESS, "0x" + address.getAddress().toString(16)); //$NON-NLS-1$ + } + + @Override public CellEditor getCellEditor(IPresentationContext context, String columnId, Object element, Composite parent) { - if (IDebugVMConstants.COLUMN_ID__VALUE.equals(columnId)) { - return new TextCellEditor(parent); - } - else if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnId)) { - return new TextCellEditor(parent); - } + if (IDebugVMConstants.COLUMN_ID__VALUE.equals(columnId)) { + return new TextCellEditor(parent); + } else if (IDebugVMConstants.COLUMN_ID__EXPRESSION.equals(columnId)) { + return new TextCellEditor(parent); + } - return null; - } + return null; + } - @Override + @Override public ICellModifier getCellModifier(IPresentationContext context, Object element) { - return new VariableCellModifier(getDMVMProvider(), fSyncVariableDataAccess); - } - - @Override + return new VariableCellModifier(getDMVMProvider(), fSyncVariableDataAccess); + } + + @Override public boolean canParseExpression(IExpression expression) { - // At this point we are going to say we will allow anything as an expression. - // Since the evaluation of VM Node implementations searches in the order of - // registration and we always make sure we register the VariableVMNode last, - // we know that the other possible handlers have passed the expression by. So - // we are going to say OK and let the expression evaluation of whatever debug - // backend is connected to decide. This does not allow us to put up any good - // diagnostic error message ( instead the error will come from the backend ). - // But it does allow for the most flexibility - - return true; - } - - @Override - public void update(final IExpressionUpdate update) { - try { - getSession().getExecutor().execute(new Runnable() { - @Override + // At this point we are going to say we will allow anything as an expression. + // Since the evaluation of VM Node implementations searches in the order of + // registration and we always make sure we register the VariableVMNode last, + // we know that the other possible handlers have passed the expression by. So + // we are going to say OK and let the expression evaluation of whatever debug + // backend is connected to decide. This does not allow us to put up any good + // diagnostic error message ( instead the error will come from the backend ). + // But it does allow for the most flexibility + + return true; + } + + @Override + public void update(final IExpressionUpdate update) { + try { + getSession().getExecutor().execute(new Runnable() { + @Override public void run() { - final IExpressions expressionService = getServicesTracker().getService(IExpressions.class); - if (expressionService != null) { - IExpressionDMContext expressionDMC = createExpression(expressionService, - createCompositeDMVMContext(update), - update.getExpression().getExpressionText()); - - VariableExpressionVMC variableVmc = (VariableExpressionVMC)createVMContext(expressionDMC); - variableVmc.setExpression(update.getExpression()); - - update.setExpressionElement(variableVmc); - update.done(); - } else { - handleFailedUpdate(update); - } - } - }); - } catch (RejectedExecutionException e) { - handleFailedUpdate(update); - } - } - - - @Override - protected void handleFailedUpdate(IViewerUpdate update) { - if (update instanceof IExpressionUpdate) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, "Update failed", null)); //$NON-NLS-1$ - update.done(); - } else { - super.handleFailedUpdate(update); - } - } - @Override - protected void associateExpression(Object element, IExpression expression) { - if (element instanceof VariableExpressionVMC) { - ((VariableExpressionVMC)element).setExpression(expression); - } - } - - @Override - protected void updateHasElementsInSessionThread(final IHasChildrenUpdate update) { - // Get the data model context object for the current node in the hierarchy. - - final IExpressionDMContext expressionDMC = findDmcInPath(update.getViewerInput(), update.getElementPath(), IExpressionDMContext.class); - - if (expressionDMC != null) { - final IExpressions expressionService = getServicesTracker().getService(IExpressions.class); - - if (expressionService == null) { - handleFailedUpdate(update); - return; - } - - if (expressionService instanceof IExpressions3) { - ((IExpressions3)expressionService).getExpressionDataExtension( - expressionDMC, - new ViewerDataRequestMonitor<IExpressionDMDataExtension>(getExecutor(), update) { - @Override - protected void handleCompleted() { - if (!isSuccess()) { - handleFailedUpdate(update); - return; - } - IExpressionDMDataExtension data = getData(); - update.setHasChilren(data.hasChildren()); - update.done(); - } - }); - } - else { - expressionService.getSubExpressionCount( - expressionDMC, - new ViewerDataRequestMonitor<Integer>(getExecutor(), update) { - @Override - public void handleCompleted() { - if (!isSuccess()) { - handleFailedUpdate(update); - return; - } - update.setHasChilren(getData() > 0); - update.done(); - } - }); - } - } - else { - super.updateHasElementsInSessionThread(update); - } - } - - @Override - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void updateElementCountInSessionThread(final IChildrenCountUpdate update) { - // Get the data model context object for the current node in the hierarchy. - - final IExpressionDMContext expressionDMC = findDmcInPath(update.getViewerInput(), update.getElementPath(), IExpressionDMContext.class); - - if ( expressionDMC != null ) { - final IExpressions expressionService = getServicesTracker().getService(IExpressions.class); - - if (expressionService == null) { - handleFailedUpdate(update); - return; - } - - expressionService.getSubExpressionCount( - expressionDMC, - new ViewerDataRequestMonitor<Integer>(getExecutor(), update) { - @Override - public void handleCompleted() { - if (!isSuccess()) { - handleFailedUpdate(update); - return; - } - update.setChildCount(getData()); - update.done(); - } - }); - } - else { - super.updateElementCountInSessionThread(update); - } - } - - @Override - protected void updateElementsInSessionThread(final IChildrenUpdate update) { - // Get the data model context object for the current node in the hierarchy. - - final IExpressionDMContext expressionDMC = findDmcInPath(update.getViewerInput(), update.getElementPath(), IExpressionDMContext.class); - - if ( expressionDMC != null ) { - getSubexpressionsUpdateElementsInSessionThread( update ); - } - else { - getLocalsUpdateElementsInSessionThread( update ); - } - } - - private void getSubexpressionsUpdateElementsInSessionThread(final IChildrenUpdate update) { - - final IExpressionDMContext expressionDMC = findDmcInPath(update.getViewerInput(), update.getElementPath(), IExpressionDMContext.class); - - if ( expressionDMC != null ) { - - // Get the services we need to use. - - final IExpressions expressionService = getServicesTracker().getService(IExpressions.class); - - if (expressionService == null) { - handleFailedUpdate(update); - return; - } - - final DsfExecutor dsfExecutor = getSession().getExecutor(); - - // Call IExpressions.getSubExpressions() to get an Iterable of IExpressionDMContext objects representing - // the sub-expressions of the expression represented by the current expression node. - - final DataRequestMonitor<IExpressionDMContext[]> rm = - new ViewerDataRequestMonitor<IExpressionDMContext[]>(dsfExecutor, update) { - @Override - public void handleCompleted() { - if (!isSuccess()) { - handleFailedUpdate(update); - return; - } - - IExpressionDMContext[] data = getData(); - - // If any of these expressions use casts, replace them. - if (fCastToTypeSupport != null) { - for (int i = 0; i < data.length; i++) { - data[i] = fCastToTypeSupport.replaceWithCastedExpression(data[i]); - } - } - - if (update.getOffset() < 0) { - fillUpdateWithVMCs(update, data); - } else { - fillUpdateWithVMCs(update, data, update.getOffset()); - } - update.done(); - } - }; - - // Make the asynchronous call to IExpressions.getSubExpressions(). The results are processed in the - // DataRequestMonitor.handleCompleted() above. - - if (update.getOffset() < 0 || update.getLength() < 0) { - // If the range is not specified, get all expressions. - expressionService.getSubExpressions(expressionDMC, rm); - } else { - expressionService.getSubExpressions(expressionDMC, update.getOffset(), update.getLength(), rm); - } - } else { - handleFailedUpdate(update); - } - } - - private void getLocalsUpdateElementsInSessionThread(final IChildrenUpdate update) { - - final IFrameDMContext frameDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), IFrameDMContext.class); - - // Get the services we need to use. - - final IExpressions expressionService = getServicesTracker().getService(IExpressions.class); - final IStack stackFrameService = getServicesTracker().getService(IStack.class); - - if ( frameDmc == null || expressionService == null || stackFrameService == null) { - handleFailedUpdate(update); - return; - } - - final DsfExecutor dsfExecutor = getSession().getExecutor(); - - // Call IStack.getLocals() to get an array of IVariableDMContext objects representing the local - // variables in the stack frame represented by frameDmc. - - final DataRequestMonitor<IVariableDMContext[]> rm = - new ViewerDataRequestMonitor<IVariableDMContext[]>(dsfExecutor, update) { - @Override - public void handleCompleted() { - if (!isSuccess()) { - handleFailedUpdate(update); - return; - } - - // For each IVariableDMContext object returned by IStack.getLocals(), call - // MIStackFrameService.getModelData() to get the IVariableDMData object. This requires - // a MultiRequestMonitor object. - - // First, get the data model context objects for the local variables. - - IVariableDMContext[] localsDMCs = getData(); - - if (localsDMCs == null) { - handleFailedUpdate(update); - return; - } - - if ( localsDMCs.length == 0 ) { - // There are no locals so just complete the request - update.done(); - return; - } - - // Create a List in which we store the DM data objects for the local variables. This is - // necessary because there is no MultiDataRequestMonitor. :) - - final List<IVariableDMData> localsDMData = new ArrayList<IVariableDMData>(); - - // Create the MultiRequestMonitor to handle completion of the set of getModelData() calls. - - final CountingRequestMonitor crm = new ViewerCountingRequestMonitor(dsfExecutor, update) { - @Override - public void handleCompleted() { - // Now that all the calls to getModelData() are complete, we create an - // IExpressionDMContext object for each local variable name, saving them all - // in an array. - - if (!isSuccess()) { - handleFailedUpdate(update); - return; - } - - IExpressionDMContext[] expressionDMCs = new IExpressionDMContext[localsDMData.size()]; - - int i = 0; - for (IVariableDMData localDMData : localsDMData) { - expressionDMCs[i++] = createExpression(expressionService, frameDmc, localDMData.getName()); - } - - // Lastly, we fill the update from the array of view model context objects - // that reference the ExpressionDMC objects for the local variables. This is - // the last code to run for a given call to updateElementsInSessionThread(). - // We can now leave anonymous-inner-class hell. - - fillUpdateWithVMCs(update, expressionDMCs); - update.done(); - } - }; - int countRM = 0; - - // Perform a set of getModelData() calls, one for each local variable's data model - // context object. In the handleCompleted() method of the DataRequestMonitor, add the - // IVariableDMData object to the localsDMData List for later processing (see above). - - for (IVariableDMContext localDMC : localsDMCs) { - DataRequestMonitor<IVariableDMData> rm = - new DataRequestMonitor<IVariableDMData>(dsfExecutor, crm) { - @Override - public void handleSuccess() { - localsDMData.add(getData()); - crm.done(); - } - }; - - stackFrameService.getVariableData(localDMC, rm); - countRM++; - } - crm.setDoneCount(countRM); - } - }; - - // Make the asynchronous call to IStack.getLocals(). The results are processed in the - // DataRequestMonitor.handleCompleted() above. - - stackFrameService.getLocals(frameDmc, rm); - } - - - private IExpressionDMContext createExpression( - IExpressions expressionService, - final IDMContext dmc, final String expression) { - IExpressionDMContext exprDMC = expressionService.createExpression(dmc, expression); - - if (fCastToTypeSupport != null) { - exprDMC = fCastToTypeSupport.replaceWithCastedExpression(exprDMC); - } - return exprDMC; + final IExpressions expressionService = getServicesTracker().getService(IExpressions.class); + if (expressionService != null) { + IExpressionDMContext expressionDMC = createExpression(expressionService, + createCompositeDMVMContext(update), update.getExpression().getExpressionText()); + + VariableExpressionVMC variableVmc = (VariableExpressionVMC) createVMContext(expressionDMC); + variableVmc.setExpression(update.getExpression()); + + update.setExpressionElement(variableVmc); + update.done(); + } else { + handleFailedUpdate(update); + } + } + }); + } catch (RejectedExecutionException e) { + handleFailedUpdate(update); + } + } + + @Override + protected void handleFailedUpdate(IViewerUpdate update) { + if (update instanceof IExpressionUpdate) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INVALID_STATE, + "Update failed", null)); //$NON-NLS-1$ + update.done(); + } else { + super.handleFailedUpdate(update); + } + } + + @Override + protected void associateExpression(Object element, IExpression expression) { + if (element instanceof VariableExpressionVMC) { + ((VariableExpressionVMC) element).setExpression(expression); + } + } + + @Override + protected void updateHasElementsInSessionThread(final IHasChildrenUpdate update) { + // Get the data model context object for the current node in the hierarchy. + + final IExpressionDMContext expressionDMC = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IExpressionDMContext.class); + + if (expressionDMC != null) { + final IExpressions expressionService = getServicesTracker().getService(IExpressions.class); + + if (expressionService == null) { + handleFailedUpdate(update); + return; + } + + if (expressionService instanceof IExpressions3) { + ((IExpressions3) expressionService).getExpressionDataExtension(expressionDMC, + new ViewerDataRequestMonitor<IExpressionDMDataExtension>(getExecutor(), update) { + @Override + protected void handleCompleted() { + if (!isSuccess()) { + handleFailedUpdate(update); + return; + } + IExpressionDMDataExtension data = getData(); + update.setHasChilren(data.hasChildren()); + update.done(); + } + }); + } else { + expressionService.getSubExpressionCount(expressionDMC, + new ViewerDataRequestMonitor<Integer>(getExecutor(), update) { + @Override + public void handleCompleted() { + if (!isSuccess()) { + handleFailedUpdate(update); + return; + } + update.setHasChilren(getData() > 0); + update.done(); + } + }); + } + } else { + super.updateHasElementsInSessionThread(update); + } + } + + @Override + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void updateElementCountInSessionThread(final IChildrenCountUpdate update) { + // Get the data model context object for the current node in the hierarchy. + + final IExpressionDMContext expressionDMC = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IExpressionDMContext.class); + + if (expressionDMC != null) { + final IExpressions expressionService = getServicesTracker().getService(IExpressions.class); + + if (expressionService == null) { + handleFailedUpdate(update); + return; + } + + expressionService.getSubExpressionCount(expressionDMC, + new ViewerDataRequestMonitor<Integer>(getExecutor(), update) { + @Override + public void handleCompleted() { + if (!isSuccess()) { + handleFailedUpdate(update); + return; + } + update.setChildCount(getData()); + update.done(); + } + }); + } else { + super.updateElementCountInSessionThread(update); + } + } + + @Override + protected void updateElementsInSessionThread(final IChildrenUpdate update) { + // Get the data model context object for the current node in the hierarchy. + + final IExpressionDMContext expressionDMC = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IExpressionDMContext.class); + + if (expressionDMC != null) { + getSubexpressionsUpdateElementsInSessionThread(update); + } else { + getLocalsUpdateElementsInSessionThread(update); + } + } + + private void getSubexpressionsUpdateElementsInSessionThread(final IChildrenUpdate update) { + + final IExpressionDMContext expressionDMC = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IExpressionDMContext.class); + + if (expressionDMC != null) { + + // Get the services we need to use. + + final IExpressions expressionService = getServicesTracker().getService(IExpressions.class); + + if (expressionService == null) { + handleFailedUpdate(update); + return; + } + + final DsfExecutor dsfExecutor = getSession().getExecutor(); + + // Call IExpressions.getSubExpressions() to get an Iterable of IExpressionDMContext objects representing + // the sub-expressions of the expression represented by the current expression node. + + final DataRequestMonitor<IExpressionDMContext[]> rm = new ViewerDataRequestMonitor<IExpressionDMContext[]>( + dsfExecutor, update) { + @Override + public void handleCompleted() { + if (!isSuccess()) { + handleFailedUpdate(update); + return; + } + + IExpressionDMContext[] data = getData(); + + // If any of these expressions use casts, replace them. + if (fCastToTypeSupport != null) { + for (int i = 0; i < data.length; i++) { + data[i] = fCastToTypeSupport.replaceWithCastedExpression(data[i]); + } + } + + if (update.getOffset() < 0) { + fillUpdateWithVMCs(update, data); + } else { + fillUpdateWithVMCs(update, data, update.getOffset()); + } + update.done(); + } + }; + + // Make the asynchronous call to IExpressions.getSubExpressions(). The results are processed in the + // DataRequestMonitor.handleCompleted() above. + + if (update.getOffset() < 0 || update.getLength() < 0) { + // If the range is not specified, get all expressions. + expressionService.getSubExpressions(expressionDMC, rm); + } else { + expressionService.getSubExpressions(expressionDMC, update.getOffset(), update.getLength(), rm); + } + } else { + handleFailedUpdate(update); + } + } + + private void getLocalsUpdateElementsInSessionThread(final IChildrenUpdate update) { + + final IFrameDMContext frameDmc = findDmcInPath(update.getViewerInput(), update.getElementPath(), + IFrameDMContext.class); + + // Get the services we need to use. + + final IExpressions expressionService = getServicesTracker().getService(IExpressions.class); + final IStack stackFrameService = getServicesTracker().getService(IStack.class); + + if (frameDmc == null || expressionService == null || stackFrameService == null) { + handleFailedUpdate(update); + return; + } + + final DsfExecutor dsfExecutor = getSession().getExecutor(); + + // Call IStack.getLocals() to get an array of IVariableDMContext objects representing the local + // variables in the stack frame represented by frameDmc. + + final DataRequestMonitor<IVariableDMContext[]> rm = new ViewerDataRequestMonitor<IVariableDMContext[]>( + dsfExecutor, update) { + @Override + public void handleCompleted() { + if (!isSuccess()) { + handleFailedUpdate(update); + return; + } + + // For each IVariableDMContext object returned by IStack.getLocals(), call + // MIStackFrameService.getModelData() to get the IVariableDMData object. This requires + // a MultiRequestMonitor object. + + // First, get the data model context objects for the local variables. + + IVariableDMContext[] localsDMCs = getData(); + + if (localsDMCs == null) { + handleFailedUpdate(update); + return; + } + + if (localsDMCs.length == 0) { + // There are no locals so just complete the request + update.done(); + return; + } + + // Create a List in which we store the DM data objects for the local variables. This is + // necessary because there is no MultiDataRequestMonitor. :) + + final List<IVariableDMData> localsDMData = new ArrayList<IVariableDMData>(); + + // Create the MultiRequestMonitor to handle completion of the set of getModelData() calls. + + final CountingRequestMonitor crm = new ViewerCountingRequestMonitor(dsfExecutor, update) { + @Override + public void handleCompleted() { + // Now that all the calls to getModelData() are complete, we create an + // IExpressionDMContext object for each local variable name, saving them all + // in an array. + + if (!isSuccess()) { + handleFailedUpdate(update); + return; + } + + IExpressionDMContext[] expressionDMCs = new IExpressionDMContext[localsDMData.size()]; + + int i = 0; + for (IVariableDMData localDMData : localsDMData) { + expressionDMCs[i++] = createExpression(expressionService, frameDmc, localDMData.getName()); + } + + // Lastly, we fill the update from the array of view model context objects + // that reference the ExpressionDMC objects for the local variables. This is + // the last code to run for a given call to updateElementsInSessionThread(). + // We can now leave anonymous-inner-class hell. + + fillUpdateWithVMCs(update, expressionDMCs); + update.done(); + } + }; + int countRM = 0; + + // Perform a set of getModelData() calls, one for each local variable's data model + // context object. In the handleCompleted() method of the DataRequestMonitor, add the + // IVariableDMData object to the localsDMData List for later processing (see above). + + for (IVariableDMContext localDMC : localsDMCs) { + DataRequestMonitor<IVariableDMData> rm = new DataRequestMonitor<IVariableDMData>(dsfExecutor, crm) { + @Override + public void handleSuccess() { + localsDMData.add(getData()); + crm.done(); + } + }; + + stackFrameService.getVariableData(localDMC, rm); + countRM++; + } + crm.setDoneCount(countRM); + } + }; + + // Make the asynchronous call to IStack.getLocals(). The results are processed in the + // DataRequestMonitor.handleCompleted() above. + + stackFrameService.getLocals(frameDmc, rm); + } + + private IExpressionDMContext createExpression(IExpressions expressionService, final IDMContext dmc, + final String expression) { + IExpressionDMContext exprDMC = expressionService.createExpression(dmc, expression); + + if (fCastToTypeSupport != null) { + exprDMC = fCastToTypeSupport.replaceWithCastedExpression(exprDMC); + } + return exprDMC; } @Override public int getDeltaFlags(Object e) { - if ( e instanceof ISuspendedDMEvent || - e instanceof IMemoryChangedEvent || - e instanceof IExpressionChangedDMEvent || - (e instanceof PropertyChangeEvent && - (((PropertyChangeEvent)e).getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE || - ((PropertyChangeEvent)e).getProperty() == IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES)) ) - { - return IModelDelta.CONTENT; - } - - if ( e instanceof ElementFormatEvent ) - { - int depth = ((ElementFormatEvent)e).getApplyDepth(); - if (depth == 0) return IModelDelta.NO_CHANGE; - if (depth == 1) return IModelDelta.STATE; - return IModelDelta.CONTENT; - } - - return IModelDelta.NO_CHANGE; - } - - @Override - public void buildDelta(final Object e, final VMDelta parentDelta, final int nodeOffset, final RequestMonitor requestMonitor) { - - // The following events can affect any expression's values, - // refresh the contents of the parent element (i.e. all the expressions). - if ( e instanceof ISuspendedDMEvent || - e instanceof IMemoryChangedEvent || - e instanceof IExpressionChangedDMEvent || - (e instanceof PropertyChangeEvent && - (((PropertyChangeEvent)e).getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE || - ((PropertyChangeEvent)e).getProperty() == IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES)) ) - { - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } - else if ( e instanceof ElementFormatEvent ) - { - int depth = ((ElementFormatEvent)e).getApplyDepth(); - if (depth != 0) { - int deltaType = IModelDelta.CONTENT; - if (depth == 1) deltaType = IModelDelta.STATE; - - Set<Object> elements = ((ElementFormatEvent)e).getElements(); - for (Object elem : elements) { - parentDelta.addNode(elem, deltaType); - } - } - } - - requestMonitor.done(); - } - - @Override - public int getDeltaFlagsForExpression(IExpression expression, Object event) { - if ( event instanceof IExpressionChangedDMEvent || - event instanceof IMemoryChangedEvent || - (event instanceof PropertyChangeEvent && - (((PropertyChangeEvent)event).getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE || - ((PropertyChangeEvent)event).getProperty() == IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES)) ) - { - return IModelDelta.CONTENT; - } - - if (event instanceof ISuspendedDMEvent) - { - return IModelDelta.CONTENT; - } - - if (event instanceof ElementFormatEvent) - { - int depth = ((ElementFormatEvent)event).getApplyDepth(); - if (depth == 0) return IModelDelta.NO_CHANGE; - if (depth == 1) return IModelDelta.STATE; - return IModelDelta.CONTENT; - } - - return IModelDelta.NO_CHANGE; - } - - @Override - public void buildDeltaForExpression(IExpression expression, int elementIdx, Object event, VMDelta parentDelta, - TreePath path, RequestMonitor rm) - { - // The following events can affect any expression's values, - // refresh the contents of the parent element (i.e. all the expressions). - if (event instanceof ISuspendedDMEvent || - event instanceof IMemoryChangedEvent || - event instanceof IExpressionChangedDMEvent || - (event instanceof PropertyChangeEvent && - ((PropertyChangeEvent)event).getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE) ) { - parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); - } - else if (event instanceof ElementFormatEvent ) - { - int depth = ((ElementFormatEvent)event).getApplyDepth(); - if (depth != 0) { - int deltaType = IModelDelta.CONTENT; - if (depth == 1) deltaType = IModelDelta.STATE; - - Set<Object> elements = ((ElementFormatEvent)event).getElements(); - for (Object elem : elements) { - parentDelta.addNode(elem, deltaType); - } - } - } - - rm.done(); - } - - @Override - public void buildDeltaForExpressionElement(Object element, int elementIdx, Object event, VMDelta parentDelta, - RequestMonitor rm) - { - // The following events can affect expression values, refresh the state - // of the expression. - if ( event instanceof IExpressionChangedDMEvent || - event instanceof IMemoryChangedEvent || - (event instanceof PropertyChangeEvent && - ((PropertyChangeEvent)event).getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE) ) - { - parentDelta.addNode(element, IModelDelta.CONTENT); - } - - rm.done(); - } - - - - private String produceExpressionElementName( String viewName , IExpressionDMContext expression ) { - - return "Variable." + expression.getExpression(); //$NON-NLS-1$ - } - - private final String MEMENTO_NAME = "VARIABLE_MEMENTO_NAME"; //$NON-NLS-1$ - - @Override - public void compareElements(IElementCompareRequest[] requests) { - - for ( IElementCompareRequest request : requests ) { - - Object element = request.getElement(); - IMemento memento = request.getMemento(); - String mementoName = memento.getString(MEMENTO_NAME); - - if (mementoName != null) { - if (element instanceof IDMVMContext) { - - IDMContext dmc = ((IDMVMContext)element).getDMContext(); - - if ( dmc instanceof IExpressionDMContext) { - - String elementName = produceExpressionElementName( request.getPresentationContext().getId(), (IExpressionDMContext) dmc ); - request.setEqual( elementName.equals( mementoName ) ); - } - } - } - request.done(); - } - } - - @Override - public void encodeElements(IElementMementoRequest[] requests) { - - for ( IElementMementoRequest request : requests ) { - - Object element = request.getElement(); - IMemento memento = request.getMemento(); - - if (element instanceof IDMVMContext) { - - IDMContext dmc = ((IDMVMContext)element).getDMContext(); - - if ( dmc instanceof IExpressionDMContext) { - - String elementName = produceExpressionElementName( request.getPresentationContext().getId(), (IExpressionDMContext) dmc ); - memento.putString(MEMENTO_NAME, elementName); - } - } - request.done(); - } - } - - /** - * Returns the label for the element with the given context. - */ - protected String getExpressionDisplayName(IExpressionDMContext dmc, String name) { - if (dmc instanceof IIndexedPartitionDMContext) { - IIndexedPartitionDMContext ipDmc = (IIndexedPartitionDMContext)dmc; - name = String.format( - "[%d...%d]", //$NON-NLS-1$ - ipDmc.getIndex(), - ipDmc.getIndex() + ipDmc.getLength() - 1); - } - return name; - } + if (e instanceof ISuspendedDMEvent || e instanceof IMemoryChangedEvent || e instanceof IExpressionChangedDMEvent + || (e instanceof PropertyChangeEvent && (((PropertyChangeEvent) e) + .getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE + || ((PropertyChangeEvent) e) + .getProperty() == IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES))) { + return IModelDelta.CONTENT; + } + + if (e instanceof ElementFormatEvent) { + int depth = ((ElementFormatEvent) e).getApplyDepth(); + if (depth == 0) + return IModelDelta.NO_CHANGE; + if (depth == 1) + return IModelDelta.STATE; + return IModelDelta.CONTENT; + } + + return IModelDelta.NO_CHANGE; + } + + @Override + public void buildDelta(final Object e, final VMDelta parentDelta, final int nodeOffset, + final RequestMonitor requestMonitor) { + + // The following events can affect any expression's values, + // refresh the contents of the parent element (i.e. all the expressions). + if (e instanceof ISuspendedDMEvent || e instanceof IMemoryChangedEvent || e instanceof IExpressionChangedDMEvent + || (e instanceof PropertyChangeEvent && (((PropertyChangeEvent) e) + .getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE + || ((PropertyChangeEvent) e) + .getProperty() == IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES))) { + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } else if (e instanceof ElementFormatEvent) { + int depth = ((ElementFormatEvent) e).getApplyDepth(); + if (depth != 0) { + int deltaType = IModelDelta.CONTENT; + if (depth == 1) + deltaType = IModelDelta.STATE; + + Set<Object> elements = ((ElementFormatEvent) e).getElements(); + for (Object elem : elements) { + parentDelta.addNode(elem, deltaType); + } + } + } + + requestMonitor.done(); + } + + @Override + public int getDeltaFlagsForExpression(IExpression expression, Object event) { + if (event instanceof IExpressionChangedDMEvent || event instanceof IMemoryChangedEvent + || (event instanceof PropertyChangeEvent && (((PropertyChangeEvent) event) + .getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE + || ((PropertyChangeEvent) event) + .getProperty() == IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES))) { + return IModelDelta.CONTENT; + } + + if (event instanceof ISuspendedDMEvent) { + return IModelDelta.CONTENT; + } + + if (event instanceof ElementFormatEvent) { + int depth = ((ElementFormatEvent) event).getApplyDepth(); + if (depth == 0) + return IModelDelta.NO_CHANGE; + if (depth == 1) + return IModelDelta.STATE; + return IModelDelta.CONTENT; + } + + return IModelDelta.NO_CHANGE; + } + + @Override + public void buildDeltaForExpression(IExpression expression, int elementIdx, Object event, VMDelta parentDelta, + TreePath path, RequestMonitor rm) { + // The following events can affect any expression's values, + // refresh the contents of the parent element (i.e. all the expressions). + if (event instanceof ISuspendedDMEvent || event instanceof IMemoryChangedEvent + || event instanceof IExpressionChangedDMEvent + || (event instanceof PropertyChangeEvent && ((PropertyChangeEvent) event) + .getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE)) { + parentDelta.setFlags(parentDelta.getFlags() | IModelDelta.CONTENT); + } else if (event instanceof ElementFormatEvent) { + int depth = ((ElementFormatEvent) event).getApplyDepth(); + if (depth != 0) { + int deltaType = IModelDelta.CONTENT; + if (depth == 1) + deltaType = IModelDelta.STATE; + + Set<Object> elements = ((ElementFormatEvent) event).getElements(); + for (Object elem : elements) { + parentDelta.addNode(elem, deltaType); + } + } + } + + rm.done(); + } + + @Override + public void buildDeltaForExpressionElement(Object element, int elementIdx, Object event, VMDelta parentDelta, + RequestMonitor rm) { + // The following events can affect expression values, refresh the state + // of the expression. + if (event instanceof IExpressionChangedDMEvent || event instanceof IMemoryChangedEvent + || (event instanceof PropertyChangeEvent && ((PropertyChangeEvent) event) + .getProperty() == IDebugVMConstants.PROP_FORMATTED_VALUE_FORMAT_PREFERENCE)) { + parentDelta.addNode(element, IModelDelta.CONTENT); + } + + rm.done(); + } + + private String produceExpressionElementName(String viewName, IExpressionDMContext expression) { + + return "Variable." + expression.getExpression(); //$NON-NLS-1$ + } + + private final String MEMENTO_NAME = "VARIABLE_MEMENTO_NAME"; //$NON-NLS-1$ + + @Override + public void compareElements(IElementCompareRequest[] requests) { + + for (IElementCompareRequest request : requests) { + + Object element = request.getElement(); + IMemento memento = request.getMemento(); + String mementoName = memento.getString(MEMENTO_NAME); + + if (mementoName != null) { + if (element instanceof IDMVMContext) { + + IDMContext dmc = ((IDMVMContext) element).getDMContext(); + + if (dmc instanceof IExpressionDMContext) { + + String elementName = produceExpressionElementName(request.getPresentationContext().getId(), + (IExpressionDMContext) dmc); + request.setEqual(elementName.equals(mementoName)); + } + } + } + request.done(); + } + } + + @Override + public void encodeElements(IElementMementoRequest[] requests) { + + for (IElementMementoRequest request : requests) { + + Object element = request.getElement(); + IMemento memento = request.getMemento(); + + if (element instanceof IDMVMContext) { + + IDMContext dmc = ((IDMVMContext) element).getDMContext(); + + if (dmc instanceof IExpressionDMContext) { + + String elementName = produceExpressionElementName(request.getPresentationContext().getId(), + (IExpressionDMContext) dmc); + memento.putString(MEMENTO_NAME, elementName); + } + } + request.done(); + } + } + + /** + * Returns the label for the element with the given context. + */ + protected String getExpressionDisplayName(IExpressionDMContext dmc, String name) { + if (dmc instanceof IIndexedPartitionDMContext) { + IIndexedPartitionDMContext ipDmc = (IIndexedPartitionDMContext) dmc; + name = String.format("[%d...%d]", //$NON-NLS-1$ + ipDmc.getIndex(), ipDmc.getIndex() + ipDmc.getLength() - 1); + } + return name; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableVMProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableVMProvider.java index 1c5e06f48da..25332d8966b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableVMProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/ui/viewmodel/variable/VariableVMProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -42,139 +42,140 @@ import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; -public class VariableVMProvider extends AbstractElementVMProvider - implements IColumnPresentationFactory -{ - private IPropertyChangeListener fPreferencesListener = new IPropertyChangeListener() { - @Override +public class VariableVMProvider extends AbstractElementVMProvider implements IColumnPresentationFactory { + private IPropertyChangeListener fPreferencesListener = new IPropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent event) { - String property = event.getProperty(); + String property = event.getProperty(); if (property.equals(IDsfDebugUIConstants.PREF_WAIT_FOR_VIEW_UPDATE_AFTER_STEP_ENABLE)) { - IPreferenceStore store = DsfDebugUITools.getPreferenceStore(); - setDelayEventHandleForViewUpdate(store.getBoolean(property)); - } - } - }; - - private IPropertyChangeListener fPresentationContextListener = new IPropertyChangeListener() { - @Override + IPreferenceStore store = DsfDebugUITools.getPreferenceStore(); + setDelayEventHandleForViewUpdate(store.getBoolean(property)); + } + } + }; + + private IPropertyChangeListener fPresentationContextListener = new IPropertyChangeListener() { + @Override public void propertyChange(final PropertyChangeEvent event) { - getExecutor().execute(new DsfRunnable() { - @Override + getExecutor().execute(new DsfRunnable() { + @Override public void run() { - handleEvent(event); - }; - }); - } - }; - + handleEvent(event); + }; + }); + } + }; + public VariableVMProvider(AbstractVMAdapter adapter, IPresentationContext context, DsfSession session) { - super(adapter, context, session); + super(adapter, context, session); + + context.addPropertyChangeListener(fPresentationContextListener); + + IPreferenceStore store = DsfDebugUITools.getPreferenceStore(); + store.addPropertyChangeListener(fPreferencesListener); + setDelayEventHandleForViewUpdate( + store.getBoolean(IDsfDebugUIConstants.PREF_WAIT_FOR_VIEW_UPDATE_AFTER_STEP_ENABLE)); + + configureLayout(); + } + + @Override + public void dispose() { + DsfDebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferencesListener); + getPresentationContext().removePropertyChangeListener(fPresentationContextListener); + super.dispose(); + } + + /** + * Configures the nodes of this provider. This method may be over-ridden by + * sub classes to create an alternate configuration in this provider. + * + * @since 2.1 + */ + protected void configureLayout() { + + // Create the variable data access routines. + SyncVariableDataAccess varAccess = new SyncVariableDataAccess(getSession()); - context.addPropertyChangeListener(fPresentationContextListener); + // Create the top level node to deal with the root selection. + IRootVMNode rootNode = new RootDMVMNode(this); + setRootNode(rootNode); - IPreferenceStore store = DsfDebugUITools.getPreferenceStore(); - store.addPropertyChangeListener(fPreferencesListener); - setDelayEventHandleForViewUpdate(store.getBoolean(IDsfDebugUIConstants.PREF_WAIT_FOR_VIEW_UPDATE_AFTER_STEP_ENABLE)); + // Create the next level which represents members of structs/unions/enums and elements of arrays. + VariableVMNode subExpressioNode = new VariableVMNode(this, getSession(), varAccess); + addChildNodes(rootNode, new IVMNode[] { subExpressioNode }); - configureLayout(); + // Wire up the casting support if the IExpressions2 service is available. + hookUpCastingSupport(varAccess, subExpressioNode); + + // Configure the sub-expression node to be a child of itself. This way the content + // provider will recursively drill-down the variable hierarchy. + addChildNodes(subExpressioNode, new IVMNode[] { subExpressioNode }); } - - @Override - public void dispose() { - DsfDebugUITools.getPreferenceStore().removePropertyChangeListener(fPreferencesListener); - getPresentationContext().removePropertyChangeListener(fPresentationContextListener); - super.dispose(); - } - - /** - * Configures the nodes of this provider. This method may be over-ridden by - * sub classes to create an alternate configuration in this provider. - * - * @since 2.1 - */ - protected void configureLayout() { - - // Create the variable data access routines. - SyncVariableDataAccess varAccess = new SyncVariableDataAccess(getSession()) ; - - // Create the top level node to deal with the root selection. - IRootVMNode rootNode = new RootDMVMNode(this); - setRootNode(rootNode); - - // Create the next level which represents members of structs/unions/enums and elements of arrays. - VariableVMNode subExpressioNode = new VariableVMNode(this, getSession(), varAccess); - addChildNodes(rootNode, new IVMNode[] { subExpressioNode }); - - // Wire up the casting support if the IExpressions2 service is available. - hookUpCastingSupport(varAccess, subExpressioNode); - - // Configure the sub-expression node to be a child of itself. This way the content - // provider will recursively drill-down the variable hierarchy. - addChildNodes(subExpressioNode, new IVMNode[] { subExpressioNode }); - } private void hookUpCastingSupport(final SyncVariableDataAccess syncvarDataAccess, final VariableVMNode variableNode) { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), getSession().getId()); - IExpressions2 expressions2 = tracker.getService(IExpressions2.class); - if (expressions2 != null) { - variableNode.setCastToTypeSupport(new DsfCastToTypeSupport( - getSession(), VariableVMProvider.this, syncvarDataAccess)); - } - tracker.dispose(); - } - }); - } catch (RejectedExecutionException e) { - // Session disposed, ignore. - } + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + getSession().getId()); + IExpressions2 expressions2 = tracker.getService(IExpressions2.class); + if (expressions2 != null) { + variableNode.setCastToTypeSupport( + new DsfCastToTypeSupport(getSession(), VariableVMProvider.this, syncvarDataAccess)); + } + tracker.dispose(); + } + }); + } catch (RejectedExecutionException e) { + // Session disposed, ignore. + } + } + + @Override + public IColumnPresentation createColumnPresentation(IPresentationContext context, Object element) { + return new VariableColumnPresentation(); } - - - @Override - public IColumnPresentation createColumnPresentation(IPresentationContext context, Object element) { - return new VariableColumnPresentation(); - } - - @Override - public String getColumnPresentationId(IPresentationContext context, Object element) { - return VariableColumnPresentation.ID; - } - - @Override - protected IVMUpdatePolicy[] createUpdateModes() { - return new IVMUpdatePolicy[] { new AutomaticUpdatePolicy(), new DebugManualUpdatePolicy(), new BreakpointHitUpdatePolicy() }; - } - - @Override - protected boolean canSkipHandlingEvent(Object newEvent, Object eventToSkip) { - // To optimize the performance of the view when stepping rapidly, skip all - // other events when a suspended event is received, including older suspended - // events. - return newEvent instanceof ISuspendedDMEvent; - } - - @Override - public void refresh() { - super.refresh(); - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + + @Override + public String getColumnPresentationId(IPresentationContext context, Object element) { + return VariableColumnPresentation.ID; + } + + @Override + protected IVMUpdatePolicy[] createUpdateModes() { + return new IVMUpdatePolicy[] { new AutomaticUpdatePolicy(), new DebugManualUpdatePolicy(), + new BreakpointHitUpdatePolicy() }; + } + + @Override + protected boolean canSkipHandlingEvent(Object newEvent, Object eventToSkip) { + // To optimize the performance of the view when stepping rapidly, skip all + // other events when a suspended event is received, including older suspended + // events. + return newEvent instanceof ISuspendedDMEvent; + } + + @Override + public void refresh() { + super.refresh(); + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), getSession().getId()); - IExpressions expressionsService = tracker.getService(IExpressions.class); - if (expressionsService instanceof ICachingService) { - ((ICachingService)expressionsService).flushCache(null); - } - tracker.dispose(); - } - }); - } catch (RejectedExecutionException e) { - // Session disposed, ignore. - } - } + DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), + getSession().getId()); + IExpressions expressionsService = tracker.getService(IExpressions.class); + if (expressionsService instanceof ICachingService) { + ((ICachingService) expressionsService).flushCache(null); + } + tracker.dispose(); + } + }); + } catch (RejectedExecutionException e) { + // Session disposed, ignore. + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/internal/ui/DsfUILabelImage.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/internal/ui/DsfUILabelImage.java index 762eb484924..072302de1eb 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/internal/ui/DsfUILabelImage.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/internal/ui/DsfUILabelImage.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -16,10 +16,10 @@ package org.eclipse.cdt.dsf.internal.ui; import org.eclipse.cdt.dsf.ui.viewmodel.properties.LabelImage; /** - * @since 2.0 + * @since 2.0 */ public class DsfUILabelImage extends LabelImage { - public DsfUILabelImage(String imageId) { - super(DsfUIPlugin.getImageDescriptor(imageId)); - } + public DsfUILabelImage(String imageId) { + super(DsfUIPlugin.getImageDescriptor(imageId)); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/internal/ui/DsfUIPlugin.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/internal/ui/DsfUIPlugin.java index 2ca89958846..7b114953697 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/internal/ui/DsfUIPlugin.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/internal/ui/DsfUIPlugin.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation * Alvaro Sanchez-Leon (Ericsson) - Allow user to edit the register groups (Bug 235747) @@ -41,13 +41,13 @@ public class DsfUIPlugin extends AbstractUIPlugin { // The shared instance private static DsfUIPlugin fgPlugin; - - private static BundleContext fgBundleContext; - // The document provider for source documents in the disassembly. - private SourceDocumentProvider fSourceDocumentProvider; + private static BundleContext fgBundleContext; + + // The document provider for source documents in the disassembly. + private SourceDocumentProvider fSourceDocumentProvider; - public static boolean DEBUG = false; + public static boolean DEBUG = false; /** * The constructor @@ -61,23 +61,23 @@ public class DsfUIPlugin extends AbstractUIPlugin { * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ @Override - public void start(BundleContext context) throws Exception { - fgBundleContext = context; + public void start(BundleContext context) throws Exception { + fgBundleContext = context; super.start(context); - DEBUG = Boolean.parseBoolean(Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug")); //$NON-NLS-1$ + DEBUG = Boolean.parseBoolean(Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug")); //$NON-NLS-1$ + + fSourceDocumentProvider = new SourceDocumentProvider(); - fSourceDocumentProvider = new SourceDocumentProvider(); - EvaluationContextManager.startup(); - + // Register the DSF backend for our disassembly view (the CDT debug UI // plugin registers the CDI one) - Platform.getAdapterManager().registerAdapters(new DisassemblyBackendDsfFactory(), IDMVMContext.class); + Platform.getAdapterManager().registerAdapters(new DisassemblyBackendDsfFactory(), IDMVMContext.class); // Register the factory that provides descriptions of stack frames - // to the CSourceNotFoundEditor. - Platform.getAdapterManager().registerAdapters(new CSourceNotFoundDescriptionFactory(), IFrameDMContext.class); + // to the CSourceNotFoundEditor. + Platform.getAdapterManager().registerAdapters(new CSourceNotFoundDescriptionFactory(), IFrameDMContext.class); - DsfDebugUITools.enableActivity("org.eclipse.cdt.debug.ui.cdtActivity", true); //$NON-NLS-1$ + DsfDebugUITools.enableActivity("org.eclipse.cdt.debug.ui.cdtActivity", true); //$NON-NLS-1$ } /* @@ -85,11 +85,11 @@ public class DsfUIPlugin extends AbstractUIPlugin { * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ @Override - public void stop(BundleContext context) throws Exception { - fSourceDocumentProvider.dispose(); - fSourceDocumentProvider = null; + public void stop(BundleContext context) throws Exception { + fSourceDocumentProvider.dispose(); + fSourceDocumentProvider = null; fgPlugin = null; - fgBundleContext = null; + fgBundleContext = null; super.stop(context); } @@ -102,82 +102,82 @@ public class DsfUIPlugin extends AbstractUIPlugin { return fgPlugin; } - public static BundleContext getBundleContext() { - return fgBundleContext; - } - - /** - * Returns an image descriptor for the image file at the given - * plug-in relative path - * - * @param path the path - * @return the image descriptor - */ - public static ImageDescriptor getImageDescriptor(String path) { - return imageDescriptorFromPlugin(PLUGIN_ID, path); - } - - public static SourceDocumentProvider getSourceDocumentProvider() { - return getDefault().fSourceDocumentProvider; - } - - - /** - * If the debug flag is set the specified message is printed to the console - * @param message - */ - public static void debug(String message) { - if (DEBUG) { - System.out.println(message); - } - } - - /** - * Logs the specified status with this plug-in's log. - * - * @param status status to log - */ - public static void log(IStatus status) { - getDefault().getLog().log(status); - } - - /** - * Logs the specified throwable with this plug-in's log. - * - * @param t throwable to log - */ - public static void log(Throwable t) { - log(newErrorStatus(IDsfStatusConstants.INTERNAL_ERROR, "Error logged from Debug UI: ", t)); //$NON-NLS-1$ - } - - /** - * Logs an internal error with the specified message. - * - * @param message the error message to log - */ - public static void logErrorMessage(String message) { - // this message is intentionally not internationalized, as an exception may - // be due to the resource bundle itself - log(newErrorStatus(IDsfStatusConstants.INTERNAL_ERROR, "Internal message logged from Debug UI: " + message, null)); //$NON-NLS-1$ - } - - /** - * Returns a new error status for this plug-in with the given message - * - * @param message the message to be included in the status - * @param error code - * @param exception the exception to be included in the status or <code>null</code> if none - * @return a new error status - * - * @since 2.0 - */ - public static IStatus newErrorStatus(int code, String message, Throwable exception) { - return new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, code, message, exception); - } - + public static BundleContext getBundleContext() { + return fgBundleContext; + } + + /** + * Returns an image descriptor for the image file at the given + * plug-in relative path + * + * @param path the path + * @return the image descriptor + */ + public static ImageDescriptor getImageDescriptor(String path) { + return imageDescriptorFromPlugin(PLUGIN_ID, path); + } + + public static SourceDocumentProvider getSourceDocumentProvider() { + return getDefault().fSourceDocumentProvider; + } + + /** + * If the debug flag is set the specified message is printed to the console + * @param message + */ + public static void debug(String message) { + if (DEBUG) { + System.out.println(message); + } + } + + /** + * Logs the specified status with this plug-in's log. + * + * @param status status to log + */ + public static void log(IStatus status) { + getDefault().getLog().log(status); + } + + /** + * Logs the specified throwable with this plug-in's log. + * + * @param t throwable to log + */ + public static void log(Throwable t) { + log(newErrorStatus(IDsfStatusConstants.INTERNAL_ERROR, "Error logged from Debug UI: ", t)); //$NON-NLS-1$ + } + + /** + * Logs an internal error with the specified message. + * + * @param message the error message to log + */ + public static void logErrorMessage(String message) { + // this message is intentionally not internationalized, as an exception may + // be due to the resource bundle itself + log(newErrorStatus(IDsfStatusConstants.INTERNAL_ERROR, "Internal message logged from Debug UI: " + message, //$NON-NLS-1$ + null)); + } + + /** + * Returns a new error status for this plug-in with the given message + * + * @param message the message to be included in the status + * @param error code + * @param exception the exception to be included in the status or <code>null</code> if none + * @return a new error status + * + * @since 2.0 + */ + public static IStatus newErrorStatus(int code, String message, Throwable exception) { + return new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, code, message, exception); + } + /** * Returns the active workbench shell or <code>null</code> if none - * + * * @return the active workbench shell or <code>null</code> if none */ public static Shell getActiveWorkbenchShell() { @@ -185,7 +185,7 @@ public class DsfUIPlugin extends AbstractUIPlugin { if (window != null) { return window.getShell(); } - + return null; } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/DisplayDsfExecutor.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/DisplayDsfExecutor.java index 1c569f956f8..8b308a9445e 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/DisplayDsfExecutor.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/DisplayDsfExecutor.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -33,72 +33,72 @@ import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; /** - * DSF executor which uses the display thread to run the submitted runnables - * and callables. The implementation is based on the default DSF executor + * DSF executor which uses the display thread to run the submitted runnables + * and callables. The implementation is based on the default DSF executor * which still creates its own thread. However this thread blocks when running - * each executable in the display thread. - * + * each executable in the display thread. + * * @since 1.0 */ -public class DisplayDsfExecutor extends DefaultDsfExecutor -{ - /** - * Internal mapping of display objects to executors. - */ - private static Map<Display, DisplayDsfExecutor> fExecutors = Collections.synchronizedMap( new HashMap<Display, DisplayDsfExecutor>() ); +public class DisplayDsfExecutor extends DefaultDsfExecutor { + /** + * Internal mapping of display objects to executors. + */ + private static Map<Display, DisplayDsfExecutor> fExecutors = Collections + .synchronizedMap(new HashMap<Display, DisplayDsfExecutor>()); /** * Factory method for display executors. - * + * * <p> * Call this from the GUI thread unless you are certain an instance has * already been created for the given display (creation of new instance will * fail on a non-GUI thread). - * + * * @param display * Display to create an executor for. * @return The new (or re-used) executor. */ - public static DisplayDsfExecutor getDisplayDsfExecutor(Display display) { - synchronized (fExecutors) { - DisplayDsfExecutor executor = fExecutors.get(display); - if (executor == null) { - executor = new DisplayDsfExecutor(display); - fExecutors.put(display, executor); - } - return executor; - } - } - - /** - * The display class used by this executor to execute the submitted runnables. - */ - private final Display fDisplay; - + public static DisplayDsfExecutor getDisplayDsfExecutor(Display display) { + synchronized (fExecutors) { + DisplayDsfExecutor executor = fExecutors.get(display); + if (executor == null) { + executor = new DisplayDsfExecutor(display); + fExecutors.put(display, executor); + } + return executor; + } + } + + /** + * The display class used by this executor to execute the submitted runnables. + */ + private final Display fDisplay; + private DisplayDsfExecutor(Display display) { super("Display DSF Executor"); //$NON-NLS-1$ fDisplay = display; fDisplay.addListener(SWT.Dispose, new Listener() { - @Override + @Override public void handleEvent(Event event) { - if (event.type == SWT.Dispose) { - DisplayDsfExecutor.super.shutdownNow(); - } - } + if (event.type == SWT.Dispose) { + DisplayDsfExecutor.super.shutdownNow(); + } + } }); } - + /** * Override to check if we're in the display thread rather than the helper * thread of the super-class. */ @Override public boolean isInExecutorThread() { - return Thread.currentThread().equals(fDisplay.getThread()); + return Thread.currentThread().equals(fDisplay.getThread()); } - + /** - * Creates a callable wrapper, which delegates to the display to perform the + * Creates a callable wrapper, which delegates to the display to perform the * operation. The callable blocks the executor thread while each call * is executed in the display thred. * @param <V> Type used in the callable. @@ -106,170 +106,178 @@ public class DisplayDsfExecutor extends DefaultDsfExecutor * @return Wrapper callable. */ private <V> Callable<V> createSWTDispatchCallable(final Callable<V> callable) { - // Check if executable wasn't executed already. - if (DEBUG_EXECUTOR && callable instanceof DsfExecutable) { - assert !((DsfExecutable)callable).getSubmitted() : "Executable was previously executed."; //$NON-NLS-1$ - ((DsfExecutable)callable).setSubmitted(); - } + // Check if executable wasn't executed already. + if (DEBUG_EXECUTOR && callable instanceof DsfExecutable) { + assert !((DsfExecutable) callable).getSubmitted() : "Executable was previously executed."; //$NON-NLS-1$ + ((DsfExecutable) callable).setSubmitted(); + } - return new Callable<V>() { + return new Callable<V>() { @Override @SuppressWarnings("unchecked") - public V call() throws Exception { + public V call() throws Exception { final Object[] v = new Object[1]; final Throwable[] e = new Throwable[1]; - - try { - fDisplay.syncExec(new Runnable() { - @Override + + try { + fDisplay.syncExec(new Runnable() { + @Override public void run() { - try { - v[0] = callable.call(); - } catch(Throwable exception) { - e[0] = exception; - } - } - }); - } catch (SWTException swtException) { - if (swtException.code == SWT.ERROR_DEVICE_DISPOSED) { - DisplayDsfExecutor.super.shutdown(); - } - } + try { + v[0] = callable.call(); + } catch (Throwable exception) { + e[0] = exception; + } + } + }); + } catch (SWTException swtException) { + if (swtException.code == SWT.ERROR_DEVICE_DISPOSED) { + DisplayDsfExecutor.super.shutdown(); + } + } - if(e[0] instanceof RuntimeException) { + if (e[0] instanceof RuntimeException) { throw (RuntimeException) e[0]; - } else if (e[0] instanceof Error) { - throw (Error) e[0]; - } else if(e[0] instanceof Exception) { + } else if (e[0] instanceof Error) { + throw (Error) e[0]; + } else if (e[0] instanceof Exception) { throw (Exception) e[0]; - } - + } + return (V) v[0]; } }; } - - /** - * Creates a runnable wrapper, which delegates to the display to perform the - * operation. The runnable blocks the executor thread while each call - * is executed in the display thred. - * @param runnable Runnable to wrap. - * @return Wrapper runnable. - */ + + /** + * Creates a runnable wrapper, which delegates to the display to perform the + * operation. The runnable blocks the executor thread while each call + * is executed in the display thred. + * @param runnable Runnable to wrap. + * @return Wrapper runnable. + */ private Runnable createSWTDispatchRunnable(final Runnable runnable) { - // Check if executable wasn't executed already. - if (DEBUG_EXECUTOR && runnable instanceof DsfExecutable) { - assert !((DsfExecutable)runnable).getSubmitted() : "Executable was previously executed."; //$NON-NLS-1$ - ((DsfExecutable)runnable).setSubmitted(); - } + // Check if executable wasn't executed already. + if (DEBUG_EXECUTOR && runnable instanceof DsfExecutable) { + assert !((DsfExecutable) runnable).getSubmitted() : "Executable was previously executed."; //$NON-NLS-1$ + ((DsfExecutable) runnable).setSubmitted(); + } - return new Runnable() { + return new Runnable() { @Override public void run() { try { - fDisplay.syncExec(new Runnable() { - @Override + fDisplay.syncExec(new Runnable() { + @Override public void run() { - runnable.run(); - } - }); + runnable.run(); + } + }); } catch (SWTException swtException) { - if (swtException.code == SWT.ERROR_DEVICE_DISPOSED) { - DisplayDsfExecutor.super.shutdownNow(); - } + if (swtException.code == SWT.ERROR_DEVICE_DISPOSED) { + DisplayDsfExecutor.super.shutdownNow(); + } } } }; } - + @Override public <V> ScheduledFuture<V> schedule(final Callable<V> callable, long delay, TimeUnit unit) { - if (fDisplay.isDisposed()) { - if (!super.isShutdown()) super.shutdown(); - throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ - } + if (fDisplay.isDisposed()) { + if (!super.isShutdown()) + super.shutdown(); + throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ + } return super.schedule(createSWTDispatchCallable(callable), delay, unit); } @Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { - if (fDisplay.isDisposed()) { - if (!super.isShutdown()) super.shutdown(); - throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ - } + if (fDisplay.isDisposed()) { + if (!super.isShutdown()) + super.shutdown(); + throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ + } return super.schedule(createSWTDispatchRunnable(command), delay, unit); } @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { - if (fDisplay.isDisposed()) { - if (!super.isShutdown()) super.shutdown(); - throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ - } + if (fDisplay.isDisposed()) { + if (!super.isShutdown()) + super.shutdown(); + throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ + } return super.scheduleAtFixedRate(createSWTDispatchRunnable(command), initialDelay, period, unit); } @Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { - if (fDisplay.isDisposed()) { - if (!super.isShutdown()) super.shutdown(); - throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ - } + if (fDisplay.isDisposed()) { + if (!super.isShutdown()) + super.shutdown(); + throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ + } return super.scheduleWithFixedDelay(createSWTDispatchRunnable(command), initialDelay, delay, unit); } @Override public void execute(Runnable command) { - if (fDisplay.isDisposed()) { - if (!super.isShutdown()) super.shutdown(); - throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ - } + if (fDisplay.isDisposed()) { + if (!super.isShutdown()) + super.shutdown(); + throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ + } super.execute(createSWTDispatchRunnable(command)); } @Override public <T> Future<T> submit(Callable<T> callable) { - if (fDisplay.isDisposed()) { - if (!super.isShutdown()) super.shutdown(); - throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ - } + if (fDisplay.isDisposed()) { + if (!super.isShutdown()) + super.shutdown(); + throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ + } return super.submit(createSWTDispatchCallable(callable)); } @Override public <T> Future<T> submit(Runnable command, T result) { - if (fDisplay.isDisposed()) { - if (!super.isShutdown()) super.shutdown(); - throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ - } + if (fDisplay.isDisposed()) { + if (!super.isShutdown()) + super.shutdown(); + throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ + } return super.submit(createSWTDispatchRunnable(command), result); } @Override public Future<?> submit(Runnable command) { - if (fDisplay.isDisposed()) { - if (!super.isShutdown()) super.shutdown(); - throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ - } + if (fDisplay.isDisposed()) { + if (!super.isShutdown()) + super.shutdown(); + throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$ + } return super.submit(createSWTDispatchRunnable(command)); } - - /** - * Override to prevent clients from shutting down. The executor will be - * shut down when the underlying display is discovered to be shut down. - */ + + /** + * Override to prevent clients from shutting down. The executor will be + * shut down when the underlying display is discovered to be shut down. + */ @Override public void shutdown() { } - - /** - * Override to prevent clients from shutting down. The executor will be - * shut down when the underlying display is discovered to be shut down. - */ + + /** + * Override to prevent clients from shutting down. The executor will be + * shut down when the underlying display is discovered to be shut down. + */ @SuppressWarnings({ "cast", "unchecked" }) - @Override + @Override public List<Runnable> shutdownNow() { - return (List<Runnable>)Collections.EMPTY_LIST; + return (List<Runnable>) Collections.EMPTY_LIST; } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/SimpleDisplayExecutor.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/SimpleDisplayExecutor.java index 20d2a58147e..22e85fe8f92 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/SimpleDisplayExecutor.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/SimpleDisplayExecutor.java @@ -37,87 +37,88 @@ import org.eclipse.swt.widgets.Display; * * @since 1.0 */ -public class SimpleDisplayExecutor implements Executor{ - /** - * Internal mapping of display objects to executors. - */ - private static Map<Display, SimpleDisplayExecutor> fExecutors = Collections.synchronizedMap( new HashMap<Display, SimpleDisplayExecutor>() ); +public class SimpleDisplayExecutor implements Executor { + /** + * Internal mapping of display objects to executors. + */ + private static Map<Display, SimpleDisplayExecutor> fExecutors = Collections + .synchronizedMap(new HashMap<Display, SimpleDisplayExecutor>()); - /** - * Factory method for display executors. - * @param display Display to create an executor for. - * @return The new (or re-used) executor. - */ - public static SimpleDisplayExecutor getSimpleDisplayExecutor(final Display display) { - synchronized (fExecutors) { - SimpleDisplayExecutor executor = fExecutors.get(display); - if (executor == null) { - executor = new SimpleDisplayExecutor(display); - fExecutors.put(display, executor); - } - return executor; - } - } + /** + * Factory method for display executors. + * @param display Display to create an executor for. + * @return The new (or re-used) executor. + */ + public static SimpleDisplayExecutor getSimpleDisplayExecutor(final Display display) { + synchronized (fExecutors) { + SimpleDisplayExecutor executor = fExecutors.get(display); + if (executor == null) { + executor = new SimpleDisplayExecutor(display); + fExecutors.put(display, executor); + } + return executor; + } + } - /** - * The display class used by this executor to execute the submitted runnables. - */ - private final Display fDisplay; - /** - * Runnables waiting for the UI loop iteration - */ - private Queue<Runnable> runnables; + /** + * The display class used by this executor to execute the submitted runnables. + */ + private final Display fDisplay; + /** + * Runnables waiting for the UI loop iteration + */ + private Queue<Runnable> runnables; - private SimpleDisplayExecutor(final Display display) { - fDisplay = display; - } + private SimpleDisplayExecutor(final Display display) { + fDisplay = display; + } - @Override - public void execute(final Runnable command) { - final boolean needsPosting = enqueue(command); - if (needsPosting) { - try { - fDisplay.asyncExec(new Runnable() { - @Override - public void run() { - runInSwtThread(); - } - }); - } catch (final SWTException e) { - if (e.code == SWT.ERROR_DEVICE_DISPOSED) { - throw new RejectedExecutionException("Display " + fDisplay + " is disposed", e); //$NON-NLS-1$ //$NON-NLS-2$ - } else { - throw e; - } - } - } - } + @Override + public void execute(final Runnable command) { + final boolean needsPosting = enqueue(command); + if (needsPosting) { + try { + fDisplay.asyncExec(new Runnable() { + @Override + public void run() { + runInSwtThread(); + } + }); + } catch (final SWTException e) { + if (e.code == SWT.ERROR_DEVICE_DISPOSED) { + throw new RejectedExecutionException("Display " + fDisplay + " is disposed", e); //$NON-NLS-1$ //$NON-NLS-2$ + } else { + throw e; + } + } + } + } - private synchronized boolean enqueue(final Runnable runnable) { - boolean needsPosting = false; - if (runnables == null) { - runnables = new LinkedList<Runnable>(); - needsPosting = true; - } - runnables.offer(runnable); - return needsPosting; - } + private synchronized boolean enqueue(final Runnable runnable) { + boolean needsPosting = false; + if (runnables == null) { + runnables = new LinkedList<Runnable>(); + needsPosting = true; + } + runnables.offer(runnable); + return needsPosting; + } - private synchronized Runnable getNextRunnable() { - final Runnable runnable = runnables.poll(); - if (runnable == null) { - runnables = null; - return null; - } else { - return runnable; - } - } + private synchronized Runnable getNextRunnable() { + final Runnable runnable = runnables.poll(); + if (runnable == null) { + runnables = null; + return null; + } else { + return runnable; + } + } - /** @since 2.3 */ - protected void runInSwtThread() { - Runnable runnable; - while ((runnable = getNextRunnable()) != null) { - runnable.run(); - } - } + /** @since 2.3 */ + protected void runInSwtThread() { + Runnable runnable; + while ((runnable = getNextRunnable()) != null) { + runnable.run(); + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/ViewerCountingRequestMonitor.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/ViewerCountingRequestMonitor.java index d352fb25715..bf2e1e55ee3 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/ViewerCountingRequestMonitor.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/ViewerCountingRequestMonitor.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,44 +19,45 @@ import org.eclipse.cdt.dsf.concurrent.CountingRequestMonitor; import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; /** - * Counting multi data request monitor that takes a <code>IViewerUpdate</code> - * as a parent. If the IViewerUpdate is canceled, this request monitor becomes - * canceled as well. - * + * Counting multi data request monitor that takes a <code>IViewerUpdate</code> + * as a parent. If the IViewerUpdate is canceled, this request monitor becomes + * canceled as well. + * * @see IViewerUpdate. - * + * * @since 1.0 */ public class ViewerCountingRequestMonitor extends CountingRequestMonitor { - private final IViewerUpdate fUpdate; - public ViewerCountingRequestMonitor(Executor executor, IViewerUpdate update) { - super(executor, null); - fUpdate = update; - } - - @Override - public synchronized boolean isCanceled() { - // isCanceled() is called implicitly by the super-constructor before fUpdate - // is initialized. The fUpdate != null is here to protect against an NPE - // from that. - return (fUpdate != null && fUpdate.isCanceled()) || super.isCanceled(); - } - - @Override - protected void handleSuccess() { - fUpdate.done(); - } - - @Override - protected void handleErrorOrWarning() { - fUpdate.setStatus(getStatus()); - fUpdate.done(); - } - - @Override - protected void handleCancel() { - fUpdate.setStatus(getStatus()); - fUpdate.done(); - } + private final IViewerUpdate fUpdate; + + public ViewerCountingRequestMonitor(Executor executor, IViewerUpdate update) { + super(executor, null); + fUpdate = update; + } + + @Override + public synchronized boolean isCanceled() { + // isCanceled() is called implicitly by the super-constructor before fUpdate + // is initialized. The fUpdate != null is here to protect against an NPE + // from that. + return (fUpdate != null && fUpdate.isCanceled()) || super.isCanceled(); + } + + @Override + protected void handleSuccess() { + fUpdate.done(); + } + + @Override + protected void handleErrorOrWarning() { + fUpdate.setStatus(getStatus()); + fUpdate.done(); + } + + @Override + protected void handleCancel() { + fUpdate.setStatus(getStatus()); + fUpdate.done(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/ViewerDataRequestMonitor.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/ViewerDataRequestMonitor.java index 5678b4e4909..eb1ba794926 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/ViewerDataRequestMonitor.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/ViewerDataRequestMonitor.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -28,51 +28,49 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; * Data Request monitor that takes <code>IViewerUpdate</code> as a parent. * If the IViewerUpdate is canceled, this request monitor becomes canceled as well. * @see IViewerUpdate - * + * * @since 1.0 */ public class ViewerDataRequestMonitor<V> extends DataRequestMonitor<V> { - /** - * Same as {@link DsfExecutable#DEBUG_MONITORS} - */ - static private boolean DEBUG_MONITORS = DsfPlugin.DEBUG && Boolean.parseBoolean( - Platform.getDebugOption("org.eclipse.cdt.dsf/debug/monitors")); //$NON-NLS-1$ - - - private final IViewerUpdate fUpdate; - - - public ViewerDataRequestMonitor(Executor executor, IViewerUpdate update) { - super(executor, null); - fUpdate = update; - - if (DEBUG_MONITORS) { - createMonitorBacktrace(); - } - } - - @Override - public synchronized boolean isCanceled() { - return fUpdate.isCanceled() || super.isCanceled(); - } - - @Override - protected void handleSuccess() { - fUpdate.done(); - } - - @Override - protected void handleErrorOrWarning() { - fUpdate.setStatus(getStatus()); - fUpdate.done(); - } - - @Override - protected void handleCancel() { - fUpdate.setStatus(getStatus()); - fUpdate.done(); - } + /** + * Same as {@link DsfExecutable#DEBUG_MONITORS} + */ + static private boolean DEBUG_MONITORS = DsfPlugin.DEBUG + && Boolean.parseBoolean(Platform.getDebugOption("org.eclipse.cdt.dsf/debug/monitors")); //$NON-NLS-1$ + + private final IViewerUpdate fUpdate; + + public ViewerDataRequestMonitor(Executor executor, IViewerUpdate update) { + super(executor, null); + fUpdate = update; + + if (DEBUG_MONITORS) { + createMonitorBacktrace(); + } + } + + @Override + public synchronized boolean isCanceled() { + return fUpdate.isCanceled() || super.isCanceled(); + } + + @Override + protected void handleSuccess() { + fUpdate.done(); + } + + @Override + protected void handleErrorOrWarning() { + fUpdate.setStatus(getStatus()); + fUpdate.done(); + } + + @Override + protected void handleCancel() { + fUpdate.setStatus(getStatus()); + fUpdate.done(); + } /** * Instrument this object with a backtrace of the monitors this instance is @@ -81,61 +79,57 @@ public class ViewerDataRequestMonitor<V> extends DataRequestMonitor<V> { * not production code. This stuff will only ever run when tracing is turned * on. */ - private void createMonitorBacktrace() { - StringBuilder str = new StringBuilder(); - - RequestMonitor nextrm = this; - VMViewerUpdate nextupdate = null; - String type = null; - while (true) { - StackTraceElement topFrame = null; - if (nextupdate != null) { - type = "update "; //$NON-NLS-1$ extra space to match length of 'monitor' - topFrame = getCreatedAtTopFrame(nextupdate); - nextrm = getMonitor(nextupdate); - nextupdate = null; - } - else if (nextrm != null) { + private void createMonitorBacktrace() { + StringBuilder str = new StringBuilder(); + + RequestMonitor nextrm = this; + VMViewerUpdate nextupdate = null; + String type = null; + while (true) { + StackTraceElement topFrame = null; + if (nextupdate != null) { + type = "update "; //$NON-NLS-1$ extra space to match length of 'monitor' + topFrame = getCreatedAtTopFrame(nextupdate); + nextrm = getMonitor(nextupdate); + nextupdate = null; + } else if (nextrm != null) { type = "monitor"; //$NON-NLS-1$ - topFrame = getCreatedAtTopFrame(nextrm); - if (nextrm instanceof ViewerDataRequestMonitor<?>) { - ViewerDataRequestMonitor<?> vdrm = (ViewerDataRequestMonitor<?>)nextrm; - nextupdate = (vdrm.fUpdate instanceof VMViewerUpdate) ? (VMViewerUpdate)vdrm.fUpdate : null; - nextrm = null; - } - else { - nextrm = getParentMonitor(nextrm); - nextupdate = null; - } - } - else { - break; - } + topFrame = getCreatedAtTopFrame(nextrm); + if (nextrm instanceof ViewerDataRequestMonitor<?>) { + ViewerDataRequestMonitor<?> vdrm = (ViewerDataRequestMonitor<?>) nextrm; + nextupdate = (vdrm.fUpdate instanceof VMViewerUpdate) ? (VMViewerUpdate) vdrm.fUpdate : null; + nextrm = null; + } else { + nextrm = getParentMonitor(nextrm); + nextupdate = null; + } + } else { + break; + } if (topFrame != null) { str.append('[').append(type).append("] ").append(topFrame).append('\n'); //$NON-NLS-1$ - } - else { + } else { str.append("<unknown>\n"); //$NON-NLS-1$ } - } + } Field field; try { field = RequestMonitor.class.getDeclaredField("fMonitorBacktrace"); //$NON-NLS-1$ field.setAccessible(true); field.set(this, str.toString()); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException e) { } catch (SecurityException e) { } catch (NoSuchFieldException e) { } - } + } /** * Utility used by {@link #createMonitorBacktrace()}. Subverts access * protection. */ - private static RequestMonitor getMonitor(VMViewerUpdate update) { - try { + private static RequestMonitor getMonitor(VMViewerUpdate update) { + try { Field field = VMViewerUpdate.class.getDeclaredField("fRequestMonitor"); //$NON-NLS-1$ field.setAccessible(true); return (RequestMonitor) field.get(update); @@ -145,14 +139,14 @@ public class ViewerDataRequestMonitor<V> extends DataRequestMonitor<V> { } catch (ClassCastException e) { } return null; - } + } /** * Utility used by {@link #createMonitorBacktrace()}. Subverts access * protection. */ - private static RequestMonitor getParentMonitor(RequestMonitor rm) { - try { + private static RequestMonitor getParentMonitor(RequestMonitor rm) { + try { Field field = RequestMonitor.class.getDeclaredField("fParentRequestMonitor"); //$NON-NLS-1$ field.setAccessible(true); return (RequestMonitor) field.get(rm); @@ -160,21 +154,21 @@ public class ViewerDataRequestMonitor<V> extends DataRequestMonitor<V> { } catch (NoSuchFieldException e) { } return null; - } + } /** * Utility used by {@link #createMonitorBacktrace()}. Subverts access * protection. */ - private static <T extends DsfExecutable> StackTraceElement getCreatedAtTopFrame(T dsfExecutable) { - try { + private static <T extends DsfExecutable> StackTraceElement getCreatedAtTopFrame(T dsfExecutable) { + try { Field field_fCreatedAt = DsfExecutable.class.getDeclaredField("fCreatedAt"); //$NON-NLS-1$ field_fCreatedAt.setAccessible(true); Object obj_fCreatedAt = field_fCreatedAt.get(dsfExecutable); Class<?> class_StackTraceElement = Class.forName("org.eclipse.cdt.dsf.concurrent.StackTraceWrapper"); //$NON-NLS-1$ Field field_fStackTraceElements = class_StackTraceElement.getDeclaredField("fStackTraceElements"); //$NON-NLS-1$ field_fStackTraceElements.setAccessible(true); - StackTraceElement[] frames = (StackTraceElement[])field_fStackTraceElements.get(obj_fCreatedAt); + StackTraceElement[] frames = (StackTraceElement[]) field_fStackTraceElements.get(obj_fCreatedAt); if (frames != null && frames.length > 0) { return frames[0]; } @@ -183,5 +177,5 @@ public class ViewerDataRequestMonitor<V> extends DataRequestMonitor<V> { } catch (ClassNotFoundException e) { } return null; - } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/ViewerRequestMonitor.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/ViewerRequestMonitor.java index 3ee06716d2c..fdf1928b95c 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/ViewerRequestMonitor.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/concurrent/ViewerRequestMonitor.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -22,36 +22,37 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; * Data Request monitor that takes <code>IViewerUpdate</code> as a parent. * If the IViewerUpdate is canceled, this request monitor becomes canceled as well. * @see IViewerUpdate - * + * * @since 2.0 */ public class ViewerRequestMonitor extends RequestMonitor { - - private final IViewerUpdate fUpdate; - public ViewerRequestMonitor(Executor executor, IViewerUpdate update) { - super(executor, null); - fUpdate = update; - } - - @Override - public synchronized boolean isCanceled() { - return fUpdate.isCanceled() || super.isCanceled(); - } - - @Override - protected void handleSuccess() { - fUpdate.done(); - } - - @Override - protected void handleErrorOrWarning() { - fUpdate.setStatus(getStatus()); - fUpdate.done(); - } - - @Override - protected void handleCancel() { - fUpdate.setStatus(getStatus()); - fUpdate.done(); - } + + private final IViewerUpdate fUpdate; + + public ViewerRequestMonitor(Executor executor, IViewerUpdate update) { + super(executor, null); + fUpdate = update; + } + + @Override + public synchronized boolean isCanceled() { + return fUpdate.isCanceled() || super.isCanceled(); + } + + @Override + protected void handleSuccess() { + fUpdate.done(); + } + + @Override + protected void handleErrorOrWarning() { + fUpdate.setStatus(getStatus()); + fUpdate.done(); + } + + @Override + protected void handleCancel() { + fUpdate.setStatus(getStatus()); + fUpdate.done(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMAdapter.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMAdapter.java index c814b5df206..ddf8a90d190 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMAdapter.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMAdapter.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -38,206 +38,205 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationCont import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerInputUpdate; import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; -/** +/** * Base implementation for View Model Adapters. The implementation uses - * its own single-thread executor for communicating with providers and - * layout nodes. - * + * its own single-thread executor for communicating with providers and + * layout nodes. + * * @since 1.0 */ @ThreadSafe -abstract public class AbstractVMAdapter implements IVMAdapter -{ - +abstract public class AbstractVMAdapter implements IVMAdapter { + private boolean fDisposed; - private final Map<IPresentationContext, IVMProvider> fViewModelProviders = - Collections.synchronizedMap( new HashMap<IPresentationContext, IVMProvider>() ); + private final Map<IPresentationContext, IVMProvider> fViewModelProviders = Collections + .synchronizedMap(new HashMap<IPresentationContext, IVMProvider>()); - /** - * Constructor for the View Model session. It is tempting to have the - * adapter register itself here with the session as the model adapter, but - * that would mean that the adapter might get accessed on another thread - * even before the deriving class is fully constructed. So it it better - * to have the owner of this object register it with the session. - * @param session - */ - public AbstractVMAdapter() { - } + /** + * Constructor for the View Model session. It is tempting to have the + * adapter register itself here with the session as the model adapter, but + * that would mean that the adapter might get accessed on another thread + * even before the deriving class is fully constructed. So it it better + * to have the owner of this object register it with the session. + * @param session + */ + public AbstractVMAdapter() { + } - @Override + @Override @ThreadSafe - public IVMProvider getVMProvider(IPresentationContext context) { - synchronized(fViewModelProviders) { - if (fDisposed) return null; + public IVMProvider getVMProvider(IPresentationContext context) { + synchronized (fViewModelProviders) { + if (fDisposed) + return null; - IVMProvider provider = fViewModelProviders.get(context); - if (provider == null) { - provider = createViewModelProvider(context); - if (provider != null) { - fViewModelProviders.put(context, provider); - } - } - return provider; - } - } + IVMProvider provider = fViewModelProviders.get(context); + if (provider == null) { + provider = createViewModelProvider(context); + if (provider != null) { + fViewModelProviders.put(context, provider); + } + } + return provider; + } + } - /** - * {@inheritDoc} - * + /** + * {@inheritDoc} + * * @since 1.1 */ - @Override + @Override public IVMProvider[] getActiveProviders() { - synchronized(fViewModelProviders) { - return fViewModelProviders.values().toArray(new IVMProvider[fViewModelProviders.size()]); - } - } + synchronized (fViewModelProviders) { + return fViewModelProviders.values().toArray(new IVMProvider[fViewModelProviders.size()]); + } + } - public void dispose() { - IVMProvider[] providers = new IVMProvider[0]; - synchronized(fViewModelProviders) { - providers = fViewModelProviders.values().toArray(new IVMProvider[fViewModelProviders.size()]); - fViewModelProviders.clear(); - fDisposed = true; - } - - for (final IVMProvider provider : providers) { - try { - provider.getExecutor().execute(new Runnable() { - @Override + public void dispose() { + IVMProvider[] providers = new IVMProvider[0]; + synchronized (fViewModelProviders) { + providers = fViewModelProviders.values().toArray(new IVMProvider[fViewModelProviders.size()]); + fViewModelProviders.clear(); + fDisposed = true; + } + + for (final IVMProvider provider : providers) { + try { + provider.getExecutor().execute(new Runnable() { + @Override public void run() { - provider.dispose(); - } - }); - } catch (RejectedExecutionException e) { - // Not much we can do at this point. - } - } - } - - /** + provider.dispose(); + } + }); + } catch (RejectedExecutionException e) { + // Not much we can do at this point. + } + } + } + + /** * @return whether this VM adapter is disposed. - * - * @since 1.1 + * + * @since 1.1 */ public boolean isDisposed() { return fDisposed; } - @Override + @Override public void update(IHasChildrenUpdate[] updates) { - handleUpdate(updates); - } - - @Override + handleUpdate(updates); + } + + @Override public void update(IChildrenCountUpdate[] updates) { - handleUpdate(updates); - } - - @Override + handleUpdate(updates); + } + + @Override public void update(final IChildrenUpdate[] updates) { - handleUpdate(updates); - } - - private void handleUpdate(IViewerUpdate[] updates) { - IVMProvider provider = getVMProvider(updates[0].getPresentationContext()); - if (provider != null) { - updateProvider(provider, updates); - } else { - for (IViewerUpdate update : updates) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, - "No model provider for update " + update, null)); //$NON-NLS-1$ - update.done(); - } - } - } + handleUpdate(updates); + } + + private void handleUpdate(IViewerUpdate[] updates) { + IVMProvider provider = getVMProvider(updates[0].getPresentationContext()); + if (provider != null) { + updateProvider(provider, updates); + } else { + for (IViewerUpdate update : updates) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, + "No model provider for update " + update, null)); //$NON-NLS-1$ + update.done(); + } + } + } - private void updateProvider(final IVMProvider provider, final IViewerUpdate[] updates) { - try { - provider.getExecutor().execute(new Runnable() { - @Override + private void updateProvider(final IVMProvider provider, final IViewerUpdate[] updates) { + try { + provider.getExecutor().execute(new Runnable() { + @Override public void run() { - if (updates instanceof IHasChildrenUpdate[]) { - provider.update((IHasChildrenUpdate[])updates); - } else if (updates instanceof IChildrenCountUpdate[]) { - provider.update((IChildrenCountUpdate[])updates); - } else if (updates instanceof IChildrenUpdate[]) { - provider.update((IChildrenUpdate[])updates); - } - } - }); - } catch (RejectedExecutionException e) { - for (IViewerUpdate update : updates) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, - "Display is disposed, cannot complete update " + update, null)); //$NON-NLS-1$ - update.done(); - } - } - } - - @Override + if (updates instanceof IHasChildrenUpdate[]) { + provider.update((IHasChildrenUpdate[]) updates); + } else if (updates instanceof IChildrenCountUpdate[]) { + provider.update((IChildrenCountUpdate[]) updates); + } else if (updates instanceof IChildrenUpdate[]) { + provider.update((IChildrenUpdate[]) updates); + } + } + }); + } catch (RejectedExecutionException e) { + for (IViewerUpdate update : updates) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, + "Display is disposed, cannot complete update " + update, null)); //$NON-NLS-1$ + update.done(); + } + } + } + + @Override public IModelProxy createModelProxy(Object element, IPresentationContext context) { - IVMProvider provider = getVMProvider(context); - if (provider != null) { - return provider.createModelProxy(element, context); - } - return null; - } - - @Override + IVMProvider provider = getVMProvider(context); + if (provider != null) { + return provider.createModelProxy(element, context); + } + return null; + } + + @Override public IColumnPresentation createColumnPresentation(IPresentationContext context, Object element) { - final IVMProvider provider = getVMProvider(context); - if (provider != null) { - return provider.createColumnPresentation(context, element); - } - return null; - } - - @Override - public String getColumnPresentationId(IPresentationContext context, Object element) { - final IVMProvider provider = getVMProvider(context); - if (provider != null) { - return provider.getColumnPresentationId(context, element); - } - return null; - } + final IVMProvider provider = getVMProvider(context); + if (provider != null) { + return provider.createColumnPresentation(context, element); + } + return null; + } + @Override + public String getColumnPresentationId(IPresentationContext context, Object element) { + final IVMProvider provider = getVMProvider(context); + if (provider != null) { + return provider.getColumnPresentationId(context, element); + } + return null; + } - @Override + @Override public void update(IViewerInputUpdate update) { - final IVMProvider provider = getVMProvider(update.getPresentationContext()); - if (provider != null) { - provider.update(update); - } else { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, "not supported")); //$NON-NLS-1$ - update.done(); - } - } + final IVMProvider provider = getVMProvider(update.getPresentationContext()); + if (provider != null) { + provider.update(update); + } else { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, "not supported")); //$NON-NLS-1$ + update.done(); + } + } + + /** + * Creates a new View Model Provider for given presentation context. Returns null + * if the presentation context is not supported. + */ + @ThreadSafe + abstract protected IVMProvider createViewModelProvider(IPresentationContext context); - /** - * Creates a new View Model Provider for given presentation context. Returns null - * if the presentation context is not supported. - */ - @ThreadSafe - abstract protected IVMProvider createViewModelProvider(IPresentationContext context); - /** * Dispatch given event to VM providers interested in events. - * + * * @since 1.1 */ protected final void handleEvent(final Object event) { - final List<IVMEventListener> eventListeners = new ArrayList<IVMEventListener>(); + final List<IVMEventListener> eventListeners = new ArrayList<IVMEventListener>(); + + aboutToHandleEvent(event); - aboutToHandleEvent(event); - for (IVMProvider vmProvider : getActiveProviders()) { if (vmProvider instanceof IVMEventListener) { - eventListeners.add((IVMEventListener)vmProvider); + eventListeners.add((IVMEventListener) vmProvider); } } - + if (!eventListeners.isEmpty()) { final CountingRequestMonitor crm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), null) { @Override @@ -245,50 +244,51 @@ abstract public class AbstractVMAdapter implements IVMAdapter if (isDisposed()) { return; } - doneHandleEvent(event); + doneHandleEvent(event); } }; int count = 0; for (final IVMEventListener vmEventListener : eventListeners) { - RequestMonitor listenerRm = null; - if (vmEventListener.shouldWaitHandleEventToComplete()) { - listenerRm = crm; - count++; - } else { - // Create a dummy request monitor for the handling of this event. - listenerRm = new RequestMonitor(ImmediateExecutor.getInstance(), null); - } - final RequestMonitor finalListenerRm = listenerRm; - vmEventListener.getExecutor().execute(new DsfRunnable() { + RequestMonitor listenerRm = null; + if (vmEventListener.shouldWaitHandleEventToComplete()) { + listenerRm = crm; + count++; + } else { + // Create a dummy request monitor for the handling of this event. + listenerRm = new RequestMonitor(ImmediateExecutor.getInstance(), null); + } + final RequestMonitor finalListenerRm = listenerRm; + vmEventListener.getExecutor().execute(new DsfRunnable() { @Override public void run() { vmEventListener.handleEvent(event, finalListenerRm); - }}); + } + }); } - crm.setDoneCount(count); + crm.setDoneCount(count); } else { - doneHandleEvent(event); + doneHandleEvent(event); } } - /** - * Given event is about to be handled. - * - * @param event - * - * @since 1.1 - */ - protected void aboutToHandleEvent(final Object event) { - } + /** + * Given event is about to be handled. + * + * @param event + * + * @since 1.1 + */ + protected void aboutToHandleEvent(final Object event) { + } - /** - * Given event has been processed by all VM event listeners. - * - * @param event - * - * @since 1.1 - */ - protected void doneHandleEvent(final Object event) { - } + /** + * Given event has been processed by all VM event listeners. + * + * @param event + * + * @since 1.1 + */ + protected void doneHandleEvent(final Object event) { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMContext.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMContext.java index 1ac7f4b31de..64cf9c09695 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMContext.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMContext.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -17,7 +17,7 @@ import org.eclipse.core.runtime.Platform; /** * Implementation of basic view model context interface. - * <p> The main purpose of the VMC wrapper is to re-direct adapter + * <p> The main purpose of the VMC wrapper is to re-direct adapter * queries. The redirecting of adapter queries follows this order: * <ol> * <li>If context implements the adapter itself, it is returned.</li> @@ -25,51 +25,53 @@ import org.eclipse.core.runtime.Platform; * <li>If the VM Provider implements the adapter, the VM Provider is returned.</li> * <li>If the VM Node implements the adapter, the VM Node is returned.</li> * </ol> - * </p> - * <p> + * </p> + * <p> * Note: Deriving classes must override the Object.equals/hashCode methods. - * This is because the view model context objects are just wrappers that are - * created by the view model on demand, so the equals methods must use the - * object being wrapped to perform a meaningful comparison. - * + * This is because the view model context objects are just wrappers that are + * created by the view model on demand, so the equals methods must use the + * object being wrapped to perform a meaningful comparison. + * * @since 1.0 */ abstract public class AbstractVMContext implements IVMContext { - protected final IVMNode fNode; - - public AbstractVMContext(IVMNode node) { - fNode = node; - } - - @Override - public IVMNode getVMNode() { return fNode; } + protected final IVMNode fNode; + + public AbstractVMContext(IVMNode node) { + fNode = node; + } + + @Override + public IVMNode getVMNode() { + return fNode; + } - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") @Override - public <T> T getAdapter(Class<T> adapter) { - // If the context implements the given adapter directly, it always takes - // precedence. - if (adapter.isInstance(this)) { - return (T)this; - } - - IVMProvider vmProvider = getVMNode().getVMProvider(); - IVMAdapter vmAdapter = vmProvider.getVMAdapter(); - if (adapter.isInstance(vmAdapter)) { - return (T)vmAdapter; - } else if (adapter.isInstance(vmProvider)) { - return (T)vmProvider; - } else if (adapter.isInstance(getVMNode())) { - return (T)getVMNode(); - } - return Platform.getAdapterManager().getAdapter(this, adapter); - } + public <T> T getAdapter(Class<T> adapter) { + // If the context implements the given adapter directly, it always takes + // precedence. + if (adapter.isInstance(this)) { + return (T) this; + } - /** Deriving classes must override. */ - @Override - abstract public boolean equals(Object obj); - - /** Deriving classes must override. */ - @Override - abstract public int hashCode(); + IVMProvider vmProvider = getVMNode().getVMProvider(); + IVMAdapter vmAdapter = vmProvider.getVMAdapter(); + if (adapter.isInstance(vmAdapter)) { + return (T) vmAdapter; + } else if (adapter.isInstance(vmProvider)) { + return (T) vmProvider; + } else if (adapter.isInstance(getVMNode())) { + return (T) getVMNode(); + } + return Platform.getAdapterManager().getAdapter(this, adapter); + } + + /** Deriving classes must override. */ + @Override + abstract public boolean equals(Object obj); + + /** Deriving classes must override. */ + @Override + abstract public int hashCode(); }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMNode.java index 834a4c3beb7..6feccddfd49 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -26,47 +26,47 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate; import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; /** - * Base implementation of the view model node. - * The main functionality implemented here is for building the view model - * deltas (IModelDelta), based on the flags returned by child nodes. - * + * Base implementation of the view model node. + * The main functionality implemented here is for building the view model + * deltas (IModelDelta), based on the flags returned by child nodes. + * * @since 1.0 */ abstract public class AbstractVMNode implements IVMNode { - private final IVMProvider fProvider; - private boolean fDisposed = false; - - public AbstractVMNode(IVMProvider provider) { - fProvider = provider; - } + private final IVMProvider fProvider; + private boolean fDisposed = false; - /** - * Accessor method for sub-classes. - */ - protected Executor getExecutor() { - return fProvider.getExecutor(); - } + public AbstractVMNode(IVMProvider provider) { + fProvider = provider; + } - @Override + /** + * Accessor method for sub-classes. + */ + protected Executor getExecutor() { + return fProvider.getExecutor(); + } + + @Override public IVMProvider getVMProvider() { - return fProvider; - } - - @Override + return fProvider; + } + + @Override public void dispose() { - fDisposed = true; - } + fDisposed = true; + } - @Override + @Override public void getContextsForEvent(VMDelta parentDelta, Object event, DataRequestMonitor<IVMContext[]> rm) { - rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "", null)); //$NON-NLS-1$ - rm.done(); - } - - protected boolean isDisposed() { - return fDisposed; - } + rm.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "", null)); //$NON-NLS-1$ + rm.done(); + } + + protected boolean isDisposed() { + return fDisposed; + } /** * Checks whether there are any fundamental roadblocks which will prevent @@ -77,45 +77,45 @@ abstract public class AbstractVMNode implements IVMNode { * should probably call the base implementation first; if the base * determines the request is a no-go, there's no point in the subclass doing * any further checking. - * + * * <p> * If a roadblock is found, the implementation should give the update * request some appropriate default result (if applicable) and call its * <code>done</code> method. * - * @param update the update request - * @return false if a roadblock is found, otherwise true - */ - protected boolean checkUpdate(IViewerUpdate update) { - if (update.isCanceled()) { - update.done(); - return false; - } - if (fDisposed) { - handleFailedUpdate(update); - return false; - } - return true; - } - - /** - * A convenience method that completes update object in case of an error. - * Different types of update need to have some data configured to exhibit - * desired behavior in the viewer. - * @param update Update to handle. - */ - protected void handleFailedUpdate(IViewerUpdate update) { - if (update instanceof IHasChildrenUpdate) { - ((IHasChildrenUpdate)update).setHasChilren(false); - } else if (update instanceof IChildrenCountUpdate) { - ((IChildrenCountUpdate)update).setChildCount(0); - } else if (update instanceof ILabelUpdate) { - ILabelUpdate labelUpdate = (ILabelUpdate)update; - String[] columns = labelUpdate.getColumnIds(); - for (int i = 0; i < (columns != null ? columns.length : 1); i++) { - labelUpdate.setLabel("...", i); //$NON-NLS-1$ - } - } - update.done(); - } + * @param update the update request + * @return false if a roadblock is found, otherwise true + */ + protected boolean checkUpdate(IViewerUpdate update) { + if (update.isCanceled()) { + update.done(); + return false; + } + if (fDisposed) { + handleFailedUpdate(update); + return false; + } + return true; + } + + /** + * A convenience method that completes update object in case of an error. + * Different types of update need to have some data configured to exhibit + * desired behavior in the viewer. + * @param update Update to handle. + */ + protected void handleFailedUpdate(IViewerUpdate update) { + if (update instanceof IHasChildrenUpdate) { + ((IHasChildrenUpdate) update).setHasChilren(false); + } else if (update instanceof IChildrenCountUpdate) { + ((IChildrenCountUpdate) update).setChildCount(0); + } else if (update instanceof ILabelUpdate) { + ILabelUpdate labelUpdate = (ILabelUpdate) update; + String[] columns = labelUpdate.getColumnIds(); + for (int i = 0; i < (columns != null ? columns.length : 1); i++) { + labelUpdate.setLabel("...", i); //$NON-NLS-1$ + } + } + update.done(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMProvider.java index 8b2d523d9d4..5ff02ffa5a9 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/AbstractVMProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -47,515 +47,521 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerInputUpdat import org.eclipse.swt.widgets.Display; /** - * View model provider implements the asynchronous view model functionality for + * View model provider implements the asynchronous view model functionality for * a single view. This provider is just a holder which further delegates the * model provider functionality to the view model nodes that need * to be configured with each provider. - * + * * <p/> - * The view model provider, often does not provide the model for the entire + * The view model provider, often does not provide the model for the entire * view. Rather, it needs to be able to plug in at any level in the viewer's * content model and provide data for a sub-tree. - * + * * <p/> * Clients are intended to extend this class. - * + * * @see IModelProxy * @see IVMNode - * + * * @since 1.0 */ -abstract public class AbstractVMProvider implements IVMProvider, IVMEventListener -{ - // debug flags - /** @since 1.1 */ - public static String DEBUG_PRESENTATION_ID = null; - - /** @since 1.1 */ - public static boolean DEBUG_CONTENT_PROVIDER = false; - - /** @since 1.1 */ - public static boolean DEBUG_DELTA = false; - - static { - DEBUG_PRESENTATION_ID = Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/vm/presentationId"); //$NON-NLS-1$ - if (!DsfUIPlugin.DEBUG || "".equals(DEBUG_PRESENTATION_ID)) { //$NON-NLS-1$ - DEBUG_PRESENTATION_ID = null; - } - DEBUG_CONTENT_PROVIDER = DsfUIPlugin.DEBUG && Boolean.parseBoolean( - Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/vm/contentProvider")); //$NON-NLS-1$ - - DEBUG_DELTA = DsfUIPlugin.DEBUG && Boolean.parseBoolean( - Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/vm/delta")); //$NON-NLS-1$ - } - - /** Reference to the VM adapter that owns this provider */ - private final AbstractVMAdapter fVMAdapter; - - /** The presentation context that this provider is associated with */ - private final IPresentationContext fPresentationContext; - - /** - * The executor that this VM provider operates in. This executor will be - * initialized properly when we can access the display from the - * IPresentationContext object (bug 213629). For now utilize the - * assumption that there is only one display. - */ - private final Executor fExecutor = SimpleDisplayExecutor.getSimpleDisplayExecutor(Display.getDefault()); - - /** - * The element content provider implementation that this provider delegates to. - * Sub-classes may override the content strategy used for custom functionality. - */ - private final IElementContentProvider fContentStrategy; - - /** - * The list of active model proxies in this provider. A new model - * proxy is created when a viewer has a new input element - * (see {@link #createModelProxy(Object, IPresentationContext)}). - * Typically there will be only one active model proxy in a given - * provider. However, if a view model provider fills only a sub-tree - * in a viewer, and there are several sub-trees active in the same viewer - * at the same time, each of these sub-trees will have it's own model - * proxy. - */ - private List<IVMModelProxy> fActiveModelProxies = new LinkedList<IVMModelProxy>(); - - /** - * Convenience constant. - */ - private static final IVMNode[] EMPTY_NODES_ARRAY = new IVMNode[0]; - - - /** - * The mapping of parent to child nodes. - */ - private Map<IVMNode,IVMNode[]> fChildNodesMap = - new HashMap<IVMNode,IVMNode[]>(); - - /** - * Cached array of all the configured view model nodes. It is generated - * based on the child nodes map. - */ - private IVMNode[] fNodesListCache = null; - - /** - * Flag indicating that the provider is disposed. - */ - private boolean fDisposed = false; - - /** - * The root node for this model provider. The root layout node could be - * null when first created, to allow sub-classes to properly configure the - * root node in the sub-class constructor. - */ - private IRootVMNode fRootNode; - - private class EventInfo { - EventInfo(Object event, RequestMonitor rm) { - fEvent = event; - fClientRm = rm; - } - Object fEvent; - RequestMonitor fClientRm; - } - - private class ModelProxyEventQueue { - /** The event actively being handled */ - EventInfo fCurrentEvent; +abstract public class AbstractVMProvider implements IVMProvider, IVMEventListener { + // debug flags + /** @since 1.1 */ + public static String DEBUG_PRESENTATION_ID = null; + + /** @since 1.1 */ + public static boolean DEBUG_CONTENT_PROVIDER = false; + + /** @since 1.1 */ + public static boolean DEBUG_DELTA = false; + + static { + DEBUG_PRESENTATION_ID = Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/vm/presentationId"); //$NON-NLS-1$ + if (!DsfUIPlugin.DEBUG || "".equals(DEBUG_PRESENTATION_ID)) { //$NON-NLS-1$ + DEBUG_PRESENTATION_ID = null; + } + DEBUG_CONTENT_PROVIDER = DsfUIPlugin.DEBUG + && Boolean.parseBoolean(Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/vm/contentProvider")); //$NON-NLS-1$ + + DEBUG_DELTA = DsfUIPlugin.DEBUG + && Boolean.parseBoolean(Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/vm/delta")); //$NON-NLS-1$ + } + + /** Reference to the VM adapter that owns this provider */ + private final AbstractVMAdapter fVMAdapter; + + /** The presentation context that this provider is associated with */ + private final IPresentationContext fPresentationContext; + + /** + * The executor that this VM provider operates in. This executor will be + * initialized properly when we can access the display from the + * IPresentationContext object (bug 213629). For now utilize the + * assumption that there is only one display. + */ + private final Executor fExecutor = SimpleDisplayExecutor.getSimpleDisplayExecutor(Display.getDefault()); + + /** + * The element content provider implementation that this provider delegates to. + * Sub-classes may override the content strategy used for custom functionality. + */ + private final IElementContentProvider fContentStrategy; + + /** + * The list of active model proxies in this provider. A new model + * proxy is created when a viewer has a new input element + * (see {@link #createModelProxy(Object, IPresentationContext)}). + * Typically there will be only one active model proxy in a given + * provider. However, if a view model provider fills only a sub-tree + * in a viewer, and there are several sub-trees active in the same viewer + * at the same time, each of these sub-trees will have it's own model + * proxy. + */ + private List<IVMModelProxy> fActiveModelProxies = new LinkedList<IVMModelProxy>(); + + /** + * Convenience constant. + */ + private static final IVMNode[] EMPTY_NODES_ARRAY = new IVMNode[0]; + + /** + * The mapping of parent to child nodes. + */ + private Map<IVMNode, IVMNode[]> fChildNodesMap = new HashMap<IVMNode, IVMNode[]>(); + + /** + * Cached array of all the configured view model nodes. It is generated + * based on the child nodes map. + */ + private IVMNode[] fNodesListCache = null; + + /** + * Flag indicating that the provider is disposed. + */ + private boolean fDisposed = false; + + /** + * The root node for this model provider. The root layout node could be + * null when first created, to allow sub-classes to properly configure the + * root node in the sub-class constructor. + */ + private IRootVMNode fRootNode; + + private class EventInfo { + EventInfo(Object event, RequestMonitor rm) { + fEvent = event; + fClientRm = rm; + } + + Object fEvent; + RequestMonitor fClientRm; + } + + private class ModelProxyEventQueue { + /** The event actively being handled */ + EventInfo fCurrentEvent; /** * The request monitor we created to handle fCurrentEvent. It is * responsible for calling <code>done</code> on the client RM of that * event. */ - RequestMonitor fCurrentRm; - - /** The queue */ - List<EventInfo> fEventQueue = new LinkedList<EventInfo>(); - } - - private Map<IVMModelProxy, ModelProxyEventQueue> fProxyEventQueues = new HashMap<IVMModelProxy, ModelProxyEventQueue>(); - - /** - * Constructs the view model provider for given DSF session. The - * constructor is thread-safe to allow VM provider to be constructed - * synchronously when a call to getAdapter() is made on an element - * in a view. - */ - public AbstractVMProvider(AbstractVMAdapter adapter, IPresentationContext presentationContext) { - fVMAdapter = adapter; - fPresentationContext = presentationContext; - fContentStrategy = createContentStrategy(); - } - - @Override - public IPresentationContext getPresentationContext() { - return fPresentationContext; - } - - @Override - public AbstractVMAdapter getVMAdapter() { - return fVMAdapter; - } - - /** - * Creates the strategy class that will be used to implement the content - * provider interface of this view model provider. This method can be - * overridden by sub-classes to provider custom content provider strategy. - * <p/> - * Note this method can be called by the base class constructor, therefore - * it should not reference any fields initialized in the sub-class. - * - * @return New content provider implementation. - */ - protected IElementContentProvider createContentStrategy() { - return new DefaultVMContentProviderStrategy(this); - } - - /** - * Access method for the content provider strategy. - * - * @return Content provider implementation currently being used by this - * class. - */ - protected IElementContentProvider getContentStrategy() { - return fContentStrategy; - } - - /** - * Creates the strategy class that will be used to implement the content - * model proxy of this view model provider. It is normally called by - * {@link #createModelProxy(Object, IPresentationContext)} every time the - * input in the viewer is updated. This method can be overridden by - * sub-classes to provider custom model proxy strategy. - * - * @return New model proxy implementation. - */ - protected IVMModelProxy createModelProxyStrategy(Object rootElement) { - return new DefaultVMModelProxyStrategy(this, rootElement); - } - - /** - * Returns the list of active proxies in this provider. The returned - * list is not a copy and if a sub-class modifies this list, it will - * modify the current list of active proxies. This allows the - * sub-classes to change how the active proxies are managed and - * retained. - */ - protected List<IVMModelProxy> getActiveModelProxies() { - return fActiveModelProxies; - } - - /** - * Processes the given event in the given provider, sending model - * deltas if necessary. - */ + RequestMonitor fCurrentRm; + + /** The queue */ + List<EventInfo> fEventQueue = new LinkedList<EventInfo>(); + } + + private Map<IVMModelProxy, ModelProxyEventQueue> fProxyEventQueues = new HashMap<IVMModelProxy, ModelProxyEventQueue>(); + + /** + * Constructs the view model provider for given DSF session. The + * constructor is thread-safe to allow VM provider to be constructed + * synchronously when a call to getAdapter() is made on an element + * in a view. + */ + public AbstractVMProvider(AbstractVMAdapter adapter, IPresentationContext presentationContext) { + fVMAdapter = adapter; + fPresentationContext = presentationContext; + fContentStrategy = createContentStrategy(); + } + + @Override + public IPresentationContext getPresentationContext() { + return fPresentationContext; + } + + @Override + public AbstractVMAdapter getVMAdapter() { + return fVMAdapter; + } + + /** + * Creates the strategy class that will be used to implement the content + * provider interface of this view model provider. This method can be + * overridden by sub-classes to provider custom content provider strategy. + * <p/> + * Note this method can be called by the base class constructor, therefore + * it should not reference any fields initialized in the sub-class. + * + * @return New content provider implementation. + */ + protected IElementContentProvider createContentStrategy() { + return new DefaultVMContentProviderStrategy(this); + } + + /** + * Access method for the content provider strategy. + * + * @return Content provider implementation currently being used by this + * class. + */ + protected IElementContentProvider getContentStrategy() { + return fContentStrategy; + } + + /** + * Creates the strategy class that will be used to implement the content + * model proxy of this view model provider. It is normally called by + * {@link #createModelProxy(Object, IPresentationContext)} every time the + * input in the viewer is updated. This method can be overridden by + * sub-classes to provider custom model proxy strategy. + * + * @return New model proxy implementation. + */ + protected IVMModelProxy createModelProxyStrategy(Object rootElement) { + return new DefaultVMModelProxyStrategy(this, rootElement); + } + + /** + * Returns the list of active proxies in this provider. The returned + * list is not a copy and if a sub-class modifies this list, it will + * modify the current list of active proxies. This allows the + * sub-classes to change how the active proxies are managed and + * retained. + */ + protected List<IVMModelProxy> getActiveModelProxies() { + return fActiveModelProxies; + } + + /** + * Processes the given event in the given provider, sending model + * deltas if necessary. + */ public void handleEvent(final Object event) { - handleEvent(event, null); - } - - /** - * {@inheritDoc} + handleEvent(event, null); + } + + /** + * {@inheritDoc} * @since 1.1 */ - @Override - public void handleEvent(final Object event, RequestMonitor rm) { - if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - trace(event, null, null, EventHandlerAction.received); - } - - CountingRequestMonitor crm = new CountingRequestMonitor(getExecutor(), rm); - final List<IVMModelProxy> activeModelProxies= new ArrayList<IVMModelProxy>(getActiveModelProxies()); - crm.setDoneCount(activeModelProxies.size()); - - for (final IVMModelProxy proxyStrategy : activeModelProxies) { - // If the event is generated by the model proxy, only process it for the proxy that created it. - if ( event instanceof ModelProxyInstalledEvent && - !((ModelProxyInstalledEvent)event).getModelProxy().equals(proxyStrategy) ) - { - crm.done(); - continue; - } - - // Process the event only if there are potential delta flags that may be generated. - // Also, process the event if it is a result of the user modifying something - // so that the cache is properly updated. - if (proxyStrategy.isDeltaEvent(event) || event instanceof UserEditEvent) { - if (!fProxyEventQueues.containsKey(proxyStrategy)) { - fProxyEventQueues.put(proxyStrategy, new ModelProxyEventQueue()); - } - // If the event queue is empty, directly handle the new event. Otherwise queue it. - final ModelProxyEventQueue queue = fProxyEventQueues.get(proxyStrategy); - if (queue.fCurrentEvent != null) { - assert queue.fCurrentRm != null; - // Iterate through the events in the queue and check if - // they can be skipped. If they can be skipped, then just - // mark their RM as done. Stop iterating through the queue - // if an event that cannot be skipped is encountered. - while (!queue.fEventQueue.isEmpty()) { - EventInfo eventToSkipInfo = queue.fEventQueue.get(queue.fEventQueue.size() - 1); - - if (canSkipHandlingEvent(event, eventToSkipInfo.fEvent)) { - if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - trace(event, eventToSkipInfo.fEvent, proxyStrategy, EventHandlerAction.skipped); - } - queue.fEventQueue.remove(queue.fEventQueue.size() - 1); - eventToSkipInfo.fClientRm.done(); - } else { - break; - } - } - // If the queue is empty check if the current event - // being processed can be skipped. If so, cancel its - // processing - if (queue.fEventQueue.isEmpty() && canSkipHandlingEvent(event, queue.fCurrentEvent.fEvent)) { - if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - trace(event, queue.fCurrentEvent.fEvent, proxyStrategy, EventHandlerAction.canceled); - } - queue.fCurrentRm.cancel(); - } - - if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - trace(event, null, proxyStrategy, EventHandlerAction.queued); - } - queue.fEventQueue.add(new EventInfo(event, crm)); - } else { - doHandleEvent(queue, proxyStrategy, new EventInfo(event, crm)); - } - } else { - crm.done(); - } - } - - // Discard the event queues of proxies that have been removed - List<IVMModelProxy> activeProxies = getActiveModelProxies(); - for (Iterator<IVMModelProxy> itr = fProxyEventQueues.keySet().iterator(); itr.hasNext();) { - if (!activeProxies.contains(itr.next())) { - itr.remove(); - } - } - } - - private void doHandleEvent(final ModelProxyEventQueue queue, final IVMModelProxy proxyStrategy, final EventInfo eventInfo) { - // Do handle event is a sort of a recursive asynchronous method. It - // calls the asynchronous handleEvent() to process the event from the - // eventInfo argument. When handleEvent() completes, this method - // (doHandleEvent) checks whether there is any more events in the queue - // that should be handled. If there are, doHandleEvent calls itself - // to process the next event in the queue. - assert queue.fCurrentEvent == null && queue.fCurrentRm == null; - - queue.fCurrentEvent = eventInfo; - queue.fCurrentRm = new RequestMonitor(getExecutor(), eventInfo.fClientRm) { - @Override - protected void handleCompleted() { - eventInfo.fClientRm.done(); - queue.fCurrentEvent = null; - queue.fCurrentRm = null; - if (!queue.fEventQueue.isEmpty() && !fDisposed) { - EventInfo nextEventInfo = queue.fEventQueue.remove(0); - doHandleEvent(queue, proxyStrategy, nextEventInfo); - } - } - }; - handleEvent(proxyStrategy, eventInfo.fEvent, queue.fCurrentRm); - } - - /** - * Handles the given event for the given proxy strategy. - * <p> - * This method is called by the base {@link #handleEvent(Object)} - * implementation to handle the given event using the given model proxy. - * The default implementation of this method checks whether the given - * proxy is active and if the proxy is active, it is called to generate the - * delta which is then sent to the viewer. - * </p> - * @param proxyStrategy Model proxy strategy to use to process this event. - * @param event Event to process. - * @param rm Request monitor to call when processing the event is - * completed. - */ - protected void handleEvent(final IVMModelProxy proxyStrategy, final Object event, final RequestMonitor rm) { - if (!proxyStrategy.isDisposed()) { - if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - trace(event, null, proxyStrategy, EventHandlerAction.processing); - } - proxyStrategy.createDelta( - event, - new DataRequestMonitor<IModelDelta>(getExecutor(), rm) { - @Override - public void handleSuccess() { - proxyStrategy.fireModelChanged(getData()); - if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - trace(event, null, proxyStrategy, EventHandlerAction.firedDeltaFor); - } - rm.done(); - } - @Override public String toString() { - return "Result of a delta for event: '" + event.toString() + "' in VMP: '" + AbstractVMProvider.this + "'" + "\n" + getData().toString(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - }); - } else { - rm.done(); - } - } - - /** - * Determines whether processing of a given event can be skipped. This - * method is called when there are multiple events waiting to be processed - * by the provider. As new events are received from the model, they are - * compared with the events in the queue using this method, events at the - * end of the queue are tested for removal. If this method returns that a - * given event can be skipped in favor of the new event, the skipped event - * is removed from the queue. This process is repeated with the new event - * until an event which cannot be stopped is found or the queue goes empty. - * <p> - * This method may be overriden by specific view model provider - * implementations extending this abstract class. - * </p> - * @param newEvent New event that was received from the model. - * @param eventToSkip Event which is currently at the end of the queue. - * @return True if the event at the end of the queue can be skipped in - * favor of the new event. - */ - protected boolean canSkipHandlingEvent(Object newEvent, Object eventToSkip) { - return false; - } - - /** @since 1.1 */ - @Override - public boolean shouldWaitHandleEventToComplete() { - return false; - } - - @Override - public IRootVMNode getRootVMNode() { - return fRootNode; - } - - @Override - public IVMNode[] getAllVMNodes() { - if (fNodesListCache != null) { - return fNodesListCache; - } - List<IVMNode> list = new ArrayList<IVMNode>(); - for (IVMNode node : fChildNodesMap.keySet()) { - if (node != null) { - list.add(node); - } - } - fNodesListCache = list.toArray(new IVMNode[list.size()]);; - return fNodesListCache; - } - - @Override - public IVMNode[] getChildVMNodes(IVMNode node) { - IVMNode[] retVal = fChildNodesMap.get(node); - if (retVal != null) { - return retVal; - } - return EMPTY_NODES_ARRAY; - } - - /** - * Configures the given array of nodes as children of the given parent node. - * Sub-classes should call this method to define the hierarchy of nodes. - */ - protected void addChildNodes(IVMNode parentNode, IVMNode[] childNodes) { - // Add to the child nodes array. - IVMNode[] existingChildNodes = fChildNodesMap.get(parentNode); - if (existingChildNodes == null) { - fChildNodesMap.put(parentNode, childNodes); - } else { - IVMNode[] newNodes = new IVMNode[existingChildNodes.length + childNodes.length]; - System.arraycopy(existingChildNodes, 0, newNodes, 0, existingChildNodes.length); - System.arraycopy(childNodes, 0, newNodes, existingChildNodes.length, childNodes.length); - fChildNodesMap.put(parentNode, newNodes); - } - - // Make sure that each new expression node has an entry of its own. - for (IVMNode childNode : childNodes) { - addNode(childNode); - } - - fNodesListCache = null; - } - - /** - * Adds the given node to configured nodes, without creating any - * parent-child relationship for it. It is useful for providers which do have - * a strict tree hierarchy of nodes. - */ - protected void addNode(IVMNode node) { - if (!fChildNodesMap.containsKey(node)) { - fChildNodesMap.put(node, EMPTY_NODES_ARRAY); - } - } - - /** - * Clears all configured nodes, including the root node. This allows a - * subclass to reset and reconfigure its nodes. - */ - protected void clearNodes() { - clearNodes(true); - for (IVMNode node : fChildNodesMap.keySet()) { - node.dispose(); - } - fChildNodesMap.clear(); - fRootNode = null; - } - - /** - * Clears all configured nodes. This allows a subclass to reset and - * reconfigure its nodes. - * - * @param clearRootNode Flag indicating whether to also clear the root node. - * @since 2.1 - */ - protected void clearNodes(boolean clearRootNode) { - for (IVMNode node : fChildNodesMap.keySet()) { - if ( !clearRootNode || !node.equals(getRootVMNode()) ) { - node.dispose(); - } - } - fChildNodesMap.clear(); - if (clearRootNode) { - fRootNode = null; - } else { - fChildNodesMap.put(getRootVMNode(), EMPTY_NODES_ARRAY); - } - } - - /** - * Sets the root node for this provider. - */ - protected void setRootNode(IRootVMNode rootNode) { - fRootNode = rootNode; - } - - /** Called to dispose the provider. */ - @Override - public void dispose() { - clearNodes(); - fRootNode = null; - fDisposed = true; - } - - @Override - public void update(final IHasChildrenUpdate[] updates) { - fContentStrategy.update(updates); - } - - @Override - public void update(final IChildrenCountUpdate[] updates) { - fContentStrategy.update(updates); - } - - @Override - public void update(final IChildrenUpdate[] updates) { - fContentStrategy.update(updates); - } + @Override + public void handleEvent(final Object event, RequestMonitor rm) { + if (DEBUG_DELTA + && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + trace(event, null, null, EventHandlerAction.received); + } + + CountingRequestMonitor crm = new CountingRequestMonitor(getExecutor(), rm); + final List<IVMModelProxy> activeModelProxies = new ArrayList<IVMModelProxy>(getActiveModelProxies()); + crm.setDoneCount(activeModelProxies.size()); + + for (final IVMModelProxy proxyStrategy : activeModelProxies) { + // If the event is generated by the model proxy, only process it for the proxy that created it. + if (event instanceof ModelProxyInstalledEvent + && !((ModelProxyInstalledEvent) event).getModelProxy().equals(proxyStrategy)) { + crm.done(); + continue; + } + + // Process the event only if there are potential delta flags that may be generated. + // Also, process the event if it is a result of the user modifying something + // so that the cache is properly updated. + if (proxyStrategy.isDeltaEvent(event) || event instanceof UserEditEvent) { + if (!fProxyEventQueues.containsKey(proxyStrategy)) { + fProxyEventQueues.put(proxyStrategy, new ModelProxyEventQueue()); + } + // If the event queue is empty, directly handle the new event. Otherwise queue it. + final ModelProxyEventQueue queue = fProxyEventQueues.get(proxyStrategy); + if (queue.fCurrentEvent != null) { + assert queue.fCurrentRm != null; + // Iterate through the events in the queue and check if + // they can be skipped. If they can be skipped, then just + // mark their RM as done. Stop iterating through the queue + // if an event that cannot be skipped is encountered. + while (!queue.fEventQueue.isEmpty()) { + EventInfo eventToSkipInfo = queue.fEventQueue.get(queue.fEventQueue.size() - 1); + + if (canSkipHandlingEvent(event, eventToSkipInfo.fEvent)) { + if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + trace(event, eventToSkipInfo.fEvent, proxyStrategy, EventHandlerAction.skipped); + } + queue.fEventQueue.remove(queue.fEventQueue.size() - 1); + eventToSkipInfo.fClientRm.done(); + } else { + break; + } + } + // If the queue is empty check if the current event + // being processed can be skipped. If so, cancel its + // processing + if (queue.fEventQueue.isEmpty() && canSkipHandlingEvent(event, queue.fCurrentEvent.fEvent)) { + if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + trace(event, queue.fCurrentEvent.fEvent, proxyStrategy, EventHandlerAction.canceled); + } + queue.fCurrentRm.cancel(); + } + + if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + trace(event, null, proxyStrategy, EventHandlerAction.queued); + } + queue.fEventQueue.add(new EventInfo(event, crm)); + } else { + doHandleEvent(queue, proxyStrategy, new EventInfo(event, crm)); + } + } else { + crm.done(); + } + } + + // Discard the event queues of proxies that have been removed + List<IVMModelProxy> activeProxies = getActiveModelProxies(); + for (Iterator<IVMModelProxy> itr = fProxyEventQueues.keySet().iterator(); itr.hasNext();) { + if (!activeProxies.contains(itr.next())) { + itr.remove(); + } + } + } + + private void doHandleEvent(final ModelProxyEventQueue queue, final IVMModelProxy proxyStrategy, + final EventInfo eventInfo) { + // Do handle event is a sort of a recursive asynchronous method. It + // calls the asynchronous handleEvent() to process the event from the + // eventInfo argument. When handleEvent() completes, this method + // (doHandleEvent) checks whether there is any more events in the queue + // that should be handled. If there are, doHandleEvent calls itself + // to process the next event in the queue. + assert queue.fCurrentEvent == null && queue.fCurrentRm == null; + + queue.fCurrentEvent = eventInfo; + queue.fCurrentRm = new RequestMonitor(getExecutor(), eventInfo.fClientRm) { + @Override + protected void handleCompleted() { + eventInfo.fClientRm.done(); + queue.fCurrentEvent = null; + queue.fCurrentRm = null; + if (!queue.fEventQueue.isEmpty() && !fDisposed) { + EventInfo nextEventInfo = queue.fEventQueue.remove(0); + doHandleEvent(queue, proxyStrategy, nextEventInfo); + } + } + }; + handleEvent(proxyStrategy, eventInfo.fEvent, queue.fCurrentRm); + } + + /** + * Handles the given event for the given proxy strategy. + * <p> + * This method is called by the base {@link #handleEvent(Object)} + * implementation to handle the given event using the given model proxy. + * The default implementation of this method checks whether the given + * proxy is active and if the proxy is active, it is called to generate the + * delta which is then sent to the viewer. + * </p> + * @param proxyStrategy Model proxy strategy to use to process this event. + * @param event Event to process. + * @param rm Request monitor to call when processing the event is + * completed. + */ + protected void handleEvent(final IVMModelProxy proxyStrategy, final Object event, final RequestMonitor rm) { + if (!proxyStrategy.isDisposed()) { + if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + trace(event, null, proxyStrategy, EventHandlerAction.processing); + } + proxyStrategy.createDelta(event, new DataRequestMonitor<IModelDelta>(getExecutor(), rm) { + @Override + public void handleSuccess() { + proxyStrategy.fireModelChanged(getData()); + if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + trace(event, null, proxyStrategy, EventHandlerAction.firedDeltaFor); + } + rm.done(); + } + + @Override + public String toString() { + return "Result of a delta for event: '" + event.toString() + "' in VMP: '" + AbstractVMProvider.this //$NON-NLS-1$//$NON-NLS-2$ + + "'" + "\n" + getData().toString(); //$NON-NLS-1$ //$NON-NLS-2$ + } + }); + } else { + rm.done(); + } + } + + /** + * Determines whether processing of a given event can be skipped. This + * method is called when there are multiple events waiting to be processed + * by the provider. As new events are received from the model, they are + * compared with the events in the queue using this method, events at the + * end of the queue are tested for removal. If this method returns that a + * given event can be skipped in favor of the new event, the skipped event + * is removed from the queue. This process is repeated with the new event + * until an event which cannot be stopped is found or the queue goes empty. + * <p> + * This method may be overriden by specific view model provider + * implementations extending this abstract class. + * </p> + * @param newEvent New event that was received from the model. + * @param eventToSkip Event which is currently at the end of the queue. + * @return True if the event at the end of the queue can be skipped in + * favor of the new event. + */ + protected boolean canSkipHandlingEvent(Object newEvent, Object eventToSkip) { + return false; + } + + /** @since 1.1 */ + @Override + public boolean shouldWaitHandleEventToComplete() { + return false; + } + + @Override + public IRootVMNode getRootVMNode() { + return fRootNode; + } + + @Override + public IVMNode[] getAllVMNodes() { + if (fNodesListCache != null) { + return fNodesListCache; + } + List<IVMNode> list = new ArrayList<IVMNode>(); + for (IVMNode node : fChildNodesMap.keySet()) { + if (node != null) { + list.add(node); + } + } + fNodesListCache = list.toArray(new IVMNode[list.size()]); + ; + return fNodesListCache; + } + + @Override + public IVMNode[] getChildVMNodes(IVMNode node) { + IVMNode[] retVal = fChildNodesMap.get(node); + if (retVal != null) { + return retVal; + } + return EMPTY_NODES_ARRAY; + } + + /** + * Configures the given array of nodes as children of the given parent node. + * Sub-classes should call this method to define the hierarchy of nodes. + */ + protected void addChildNodes(IVMNode parentNode, IVMNode[] childNodes) { + // Add to the child nodes array. + IVMNode[] existingChildNodes = fChildNodesMap.get(parentNode); + if (existingChildNodes == null) { + fChildNodesMap.put(parentNode, childNodes); + } else { + IVMNode[] newNodes = new IVMNode[existingChildNodes.length + childNodes.length]; + System.arraycopy(existingChildNodes, 0, newNodes, 0, existingChildNodes.length); + System.arraycopy(childNodes, 0, newNodes, existingChildNodes.length, childNodes.length); + fChildNodesMap.put(parentNode, newNodes); + } + + // Make sure that each new expression node has an entry of its own. + for (IVMNode childNode : childNodes) { + addNode(childNode); + } + + fNodesListCache = null; + } + + /** + * Adds the given node to configured nodes, without creating any + * parent-child relationship for it. It is useful for providers which do have + * a strict tree hierarchy of nodes. + */ + protected void addNode(IVMNode node) { + if (!fChildNodesMap.containsKey(node)) { + fChildNodesMap.put(node, EMPTY_NODES_ARRAY); + } + } + + /** + * Clears all configured nodes, including the root node. This allows a + * subclass to reset and reconfigure its nodes. + */ + protected void clearNodes() { + clearNodes(true); + for (IVMNode node : fChildNodesMap.keySet()) { + node.dispose(); + } + fChildNodesMap.clear(); + fRootNode = null; + } + + /** + * Clears all configured nodes. This allows a subclass to reset and + * reconfigure its nodes. + * + * @param clearRootNode Flag indicating whether to also clear the root node. + * @since 2.1 + */ + protected void clearNodes(boolean clearRootNode) { + for (IVMNode node : fChildNodesMap.keySet()) { + if (!clearRootNode || !node.equals(getRootVMNode())) { + node.dispose(); + } + } + fChildNodesMap.clear(); + if (clearRootNode) { + fRootNode = null; + } else { + fChildNodesMap.put(getRootVMNode(), EMPTY_NODES_ARRAY); + } + } + + /** + * Sets the root node for this provider. + */ + protected void setRootNode(IRootVMNode rootNode) { + fRootNode = rootNode; + } + + /** Called to dispose the provider. */ + @Override + public void dispose() { + clearNodes(); + fRootNode = null; + fDisposed = true; + } + + @Override + public void update(final IHasChildrenUpdate[] updates) { + fContentStrategy.update(updates); + } + + @Override + public void update(final IChildrenCountUpdate[] updates) { + fContentStrategy.update(updates); + } + + @Override + public void update(final IChildrenUpdate[] updates) { + fContentStrategy.update(updates); + } /** * Calls the given view model node to perform the given updates. This method @@ -564,256 +570,245 @@ abstract public class AbstractVMProvider implements IVMProvider, IVMEventListene * processing of the update. For example the AbstractCachingVMProvider * overrides this method to optionally return the results for an update from * a cache. - * + * * [node] represents the type of the child element, not of the parent. In * other words, the update requests are asking if one or more model elements * of a particular type (thread, e.g.) have children. But [node] does not * represent that type. It represents the type of the potential children * (frame, e.g.) */ - @Override - public void updateNode(final IVMNode node, IHasChildrenUpdate[] updates) { - IHasChildrenUpdate[] updateProxies = new IHasChildrenUpdate[updates.length]; - for (int i = 0; i < updates.length; i++) { - final IHasChildrenUpdate update = updates[i]; - if (DEBUG_CONTENT_PROVIDER && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("updateNodeHasChildren(node = " + node + ", update = " + update + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - updateProxies[i] = new VMHasChildrenUpdate( - update, - new ViewerDataRequestMonitor<Boolean>(getExecutor(), update) { - @Override - protected void handleSuccess() { - update.setHasChilren(getData()); - update.done(); - } - - @Override - protected void handleErrorOrWarning() { - if (getStatus().getCode() == IDsfStatusConstants.NOT_SUPPORTED) { - if (DEBUG_CONTENT_PROVIDER && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("not-supported:updateNodeHasChildren(node = " + node + ", update = " + update + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - updateNode( - node, - new VMChildrenUpdate( - update, -1, -1, - new ViewerDataRequestMonitor<List<Object>>(getExecutor(), update) { - @Override - protected void handleSuccess() { - update.setHasChilren( !getData().isEmpty() ); - update.done(); - } - }) - ); - - } else { - update.setStatus(getStatus()); - update.done(); - } - } - - }); - } - node.update(updateProxies); - } - - /** - * Calls the given view model node to perform the given updates. This - * method is called by view model provider and it's helper classes instead - * of calling the IVMNode method directly, in order to allow additional - * processing of the update. For example the AbstractCachingVMProvider - * overrides this method to optionally return the results for an update from - * a cache. - */ - @Override - public void updateNode(final IVMNode node, final IChildrenCountUpdate update) { - if (DEBUG_CONTENT_PROVIDER && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("updateNodeChildCount(node = " + node + ", update = " + update + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - node.update(new IChildrenCountUpdate[] { - new VMChildrenCountUpdate( - update, - new ViewerDataRequestMonitor<Integer>(getExecutor(), update) { - @Override - protected void handleSuccess() { - update.setChildCount(getData()); - update.done(); - } - - @Override - protected void handleErrorOrWarning() { - if (getStatus().getCode() == IDsfStatusConstants.NOT_SUPPORTED) { - if (DEBUG_CONTENT_PROVIDER && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("not-supported:updateNodeChildCount(node = " + node + ", update = " + update + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - updateNode( - node, - new VMChildrenUpdate( - update, -1, -1, - new ViewerDataRequestMonitor<List<Object>>(getExecutor(), update) { - @Override - protected void handleSuccess() { - update.setChildCount( getData().size() ); - update.done(); - } - }) - ); - } else { - super.handleErrorOrWarning(); - } - } - - }) - }); - } - - /** - * Calls the given view model node to perform the given updates. This - * method is called by view model provider and it's helper classes instead - * of calling the IVMNode method directly, in order to allow additional - * processing of the update. For example the AbstractCachingVMProvider - * overrides this method to optionally return the results for an update from - * a cache. - */ - @Override - public void updateNode(IVMNode node, IChildrenUpdate update) { - if (DEBUG_CONTENT_PROVIDER && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("updateNodeChildren(node = " + node + ", update = " + update + ")"); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$ - } - node.update(new IChildrenUpdate[] { update }); - } - - - /** - * Returns whether this provider has been disposed. - */ - protected boolean isDisposed() { - return fDisposed; - } - - /** - * The abstract provider uses a the display-thread executor so that the - * provider will operate on the same thread as the viewer. This way no - * synchronization is necessary when the provider is called by the viewer. - * Also, the display thread is likely to be shut down long after any of the - * view models are disposed, so the users of this abstract provider do not - * need to worry about the executor throwing the {@link RejectedExecutionException} - * exception. - */ - @Override - public Executor getExecutor() { - return fExecutor; - } - - @Override - public IModelProxy createModelProxy(Object element, IPresentationContext context) { - - // Iterate through the current active proxies to try to find a proxy with the same - // element and re-use it if found. Only disposed proxies can be re-used because - // multiple viewers cannot use the same proxy. Also at this time purge other proxies - // that are no longer installed. - IVMModelProxy proxy = null; - for (Iterator<IVMModelProxy> itr = getActiveModelProxies().iterator(); itr.hasNext();) { - IVMModelProxy next = itr.next(); - if (next != null) { - if (next.getRootElement().equals(element) && next.isDisposed()) { - proxy = next; - } else if (next.isDisposed()) { - itr.remove(); - } - } - } - - if (proxy == null) { - proxy = createModelProxyStrategy(element); - getActiveModelProxies().add(proxy); - } else if (proxy.isDisposed()) { - // DSF is capable of re-using old proxies which were previously - // disposed. However, the viewer which installs a proxy using - // a background job to install the proxy calls - // IModelProxy.isDisposed(), to check whether the proxy was disposed - // before it could be installed. We need to clear the disposed flag - // of the re-used proxy here, otherwise the proxy will never get used. - // Calling init here will cause the init() method to be called twice - // so the IVMModelProxy needs to be prepared for that. - // See bug 241024. - proxy.init(context); - } - return proxy; - } - - /** - * Creates the column presentation for the given object. This method is meant - * to be overriden by deriving class to provide view-specific functionality. - * The default is to return null, meaning no columns. - * <p> - * The viewer only reads the column presentation for the root/input element of - * the tree/table, so the VMProvider must be configured to own the root element - * in the view in order for this setting to be effective. - * <p> - * Note: since the IColumnEditorFactory interface is synchronous, and since - * column info is fairly static, this method is thread-safe, and it will - * not be called on the executor thread. - * - * @see IColumnPresentationFactory#createColumnPresentation(IPresentationContext, Object) - */ - @Override - public IColumnPresentation createColumnPresentation(IPresentationContext context, Object element) { - return null; - } - - /** - * Returns the ID of the column presentation for the given object. This method - * is meant to be overriden by deriving class to provide view-specific - * functionality. The default is to return null, meaning no columns. - * <p> - * The viewer only reads the column presentation for the root/input element of - * the tree/table, so the VMProvider must be configured to own the root element - * in the view in order for this setting to be effective. - * <p> - * Note: since the IColumnEditorFactory interface is synchronous, and since - * column info is fairly static, this method is thread-safe, and it will - * not be called on the executor thread. - * - * @see IColumnEditorFactory#getColumnEditorId(IPresentationContext, Object) - */ - @Override - public String getColumnPresentationId(IPresentationContext context, Object element) { - return null; - } - - /** - * Calculates the proxy input object to be used for the given input in the given - * viewer. By default no proxy object is used an the given element is used - * as the input into the view. - * <p> - * Sub classes can override this method for view-specific behavior. - * - * @see IViewerInputProvider - */ - @Override - public void update(IViewerInputUpdate update) { - update.setInputElement(update.getElement()); - update.done(); - } - - /** - * Used for tracing event handling - */ - private enum EventHandlerAction { - received, - queued, - processing, - firedDeltaFor, - skipped, - canceled - } + @Override + public void updateNode(final IVMNode node, IHasChildrenUpdate[] updates) { + IHasChildrenUpdate[] updateProxies = new IHasChildrenUpdate[updates.length]; + for (int i = 0; i < updates.length; i++) { + final IHasChildrenUpdate update = updates[i]; + if (DEBUG_CONTENT_PROVIDER && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("updateNodeHasChildren(node = " + node + ", update = " + update + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + updateProxies[i] = new VMHasChildrenUpdate(update, + new ViewerDataRequestMonitor<Boolean>(getExecutor(), update) { + @Override + protected void handleSuccess() { + update.setHasChilren(getData()); + update.done(); + } + + @Override + protected void handleErrorOrWarning() { + if (getStatus().getCode() == IDsfStatusConstants.NOT_SUPPORTED) { + if (DEBUG_CONTENT_PROVIDER && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("not-supported:updateNodeHasChildren(node = " + node //$NON-NLS-1$ + + ", update = " + update + ")"); //$NON-NLS-1$ //$NON-NLS-2$ + } + updateNode(node, new VMChildrenUpdate(update, -1, -1, + new ViewerDataRequestMonitor<List<Object>>(getExecutor(), update) { + @Override + protected void handleSuccess() { + update.setHasChilren(!getData().isEmpty()); + update.done(); + } + })); + + } else { + update.setStatus(getStatus()); + update.done(); + } + } + + }); + } + node.update(updateProxies); + } + + /** + * Calls the given view model node to perform the given updates. This + * method is called by view model provider and it's helper classes instead + * of calling the IVMNode method directly, in order to allow additional + * processing of the update. For example the AbstractCachingVMProvider + * overrides this method to optionally return the results for an update from + * a cache. + */ + @Override + public void updateNode(final IVMNode node, final IChildrenCountUpdate update) { + if (DEBUG_CONTENT_PROVIDER + && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("updateNodeChildCount(node = " + node + ", update = " + update + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + node.update(new IChildrenCountUpdate[] { + new VMChildrenCountUpdate(update, new ViewerDataRequestMonitor<Integer>(getExecutor(), update) { + @Override + protected void handleSuccess() { + update.setChildCount(getData()); + update.done(); + } + + @Override + protected void handleErrorOrWarning() { + if (getStatus().getCode() == IDsfStatusConstants.NOT_SUPPORTED) { + if (DEBUG_CONTENT_PROVIDER && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("not-supported:updateNodeChildCount(node = " + node + ", update = " //$NON-NLS-1$//$NON-NLS-2$ + + update + ")"); //$NON-NLS-1$ + } + updateNode(node, new VMChildrenUpdate(update, -1, -1, + new ViewerDataRequestMonitor<List<Object>>(getExecutor(), update) { + @Override + protected void handleSuccess() { + update.setChildCount(getData().size()); + update.done(); + } + })); + } else { + super.handleErrorOrWarning(); + } + } + + }) }); + } + + /** + * Calls the given view model node to perform the given updates. This + * method is called by view model provider and it's helper classes instead + * of calling the IVMNode method directly, in order to allow additional + * processing of the update. For example the AbstractCachingVMProvider + * overrides this method to optionally return the results for an update from + * a cache. + */ + @Override + public void updateNode(IVMNode node, IChildrenUpdate update) { + if (DEBUG_CONTENT_PROVIDER + && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("updateNodeChildren(node = " + node + ", update = " + update + ")"); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$ + } + node.update(new IChildrenUpdate[] { update }); + } + + /** + * Returns whether this provider has been disposed. + */ + protected boolean isDisposed() { + return fDisposed; + } + + /** + * The abstract provider uses a the display-thread executor so that the + * provider will operate on the same thread as the viewer. This way no + * synchronization is necessary when the provider is called by the viewer. + * Also, the display thread is likely to be shut down long after any of the + * view models are disposed, so the users of this abstract provider do not + * need to worry about the executor throwing the {@link RejectedExecutionException} + * exception. + */ + @Override + public Executor getExecutor() { + return fExecutor; + } + + @Override + public IModelProxy createModelProxy(Object element, IPresentationContext context) { + + // Iterate through the current active proxies to try to find a proxy with the same + // element and re-use it if found. Only disposed proxies can be re-used because + // multiple viewers cannot use the same proxy. Also at this time purge other proxies + // that are no longer installed. + IVMModelProxy proxy = null; + for (Iterator<IVMModelProxy> itr = getActiveModelProxies().iterator(); itr.hasNext();) { + IVMModelProxy next = itr.next(); + if (next != null) { + if (next.getRootElement().equals(element) && next.isDisposed()) { + proxy = next; + } else if (next.isDisposed()) { + itr.remove(); + } + } + } + + if (proxy == null) { + proxy = createModelProxyStrategy(element); + getActiveModelProxies().add(proxy); + } else if (proxy.isDisposed()) { + // DSF is capable of re-using old proxies which were previously + // disposed. However, the viewer which installs a proxy using + // a background job to install the proxy calls + // IModelProxy.isDisposed(), to check whether the proxy was disposed + // before it could be installed. We need to clear the disposed flag + // of the re-used proxy here, otherwise the proxy will never get used. + // Calling init here will cause the init() method to be called twice + // so the IVMModelProxy needs to be prepared for that. + // See bug 241024. + proxy.init(context); + } + return proxy; + } + + /** + * Creates the column presentation for the given object. This method is meant + * to be overriden by deriving class to provide view-specific functionality. + * The default is to return null, meaning no columns. + * <p> + * The viewer only reads the column presentation for the root/input element of + * the tree/table, so the VMProvider must be configured to own the root element + * in the view in order for this setting to be effective. + * <p> + * Note: since the IColumnEditorFactory interface is synchronous, and since + * column info is fairly static, this method is thread-safe, and it will + * not be called on the executor thread. + * + * @see IColumnPresentationFactory#createColumnPresentation(IPresentationContext, Object) + */ + @Override + public IColumnPresentation createColumnPresentation(IPresentationContext context, Object element) { + return null; + } + + /** + * Returns the ID of the column presentation for the given object. This method + * is meant to be overriden by deriving class to provide view-specific + * functionality. The default is to return null, meaning no columns. + * <p> + * The viewer only reads the column presentation for the root/input element of + * the tree/table, so the VMProvider must be configured to own the root element + * in the view in order for this setting to be effective. + * <p> + * Note: since the IColumnEditorFactory interface is synchronous, and since + * column info is fairly static, this method is thread-safe, and it will + * not be called on the executor thread. + * + * @see IColumnEditorFactory#getColumnEditorId(IPresentationContext, Object) + */ + @Override + public String getColumnPresentationId(IPresentationContext context, Object element) { + return null; + } + + /** + * Calculates the proxy input object to be used for the given input in the given + * viewer. By default no proxy object is used an the given element is used + * as the input into the view. + * <p> + * Sub classes can override this method for view-specific behavior. + * + * @see IViewerInputProvider + */ + @Override + public void update(IViewerInputUpdate update) { + update.setInputElement(update.getElement()); + update.done(); + } + + /** + * Used for tracing event handling + */ + private enum EventHandlerAction { + received, queued, processing, firedDeltaFor, skipped, canceled + } /** * Trace that we've reached a particular phase of the handling of an event * for a particular proxy. - * + * * @param event * the event being handled * @param skippedOrCanceledEvent @@ -824,21 +819,24 @@ abstract public class AbstractVMProvider implements IVMProvider, IVMEventListene * @param action * what phased of the event handling has been reached */ - private void trace(Object event, Object skippedOrCanceledEvent, IVMModelProxy proxy, EventHandlerAction action) { - assert DEBUG_DELTA; - StringBuilder str = new StringBuilder(); - str.append(DsfPlugin.getDebugTime()); - str.append(' '); - if (action == EventHandlerAction.skipped || action == EventHandlerAction.canceled) { - str.append(LoggingUtils.toString(this)).append(' ').append(action).append(" event ").append(LoggingUtils.toString(skippedOrCanceledEvent)).append(" because of event ").append(LoggingUtils.toString(event)); //$NON-NLS-1$ //$NON-NLS-2$ - } - else { - str.append(LoggingUtils.toString(this)).append(' ').append(action).append(" event ").append(LoggingUtils.toString(event)); //$NON-NLS-1$ - } - - if (action != EventHandlerAction.received) { - str.append(" for proxy ").append(LoggingUtils.toString(proxy)).append(", whose root is ").append(LoggingUtils.toString(proxy.getRootElement())); //$NON-NLS-1$ //$NON-NLS-2$ - } - DsfUIPlugin.debug(str.toString()); - } + private void trace(Object event, Object skippedOrCanceledEvent, IVMModelProxy proxy, EventHandlerAction action) { + assert DEBUG_DELTA; + StringBuilder str = new StringBuilder(); + str.append(DsfPlugin.getDebugTime()); + str.append(' '); + if (action == EventHandlerAction.skipped || action == EventHandlerAction.canceled) { + str.append(LoggingUtils.toString(this)).append(' ').append(action).append(" event ") //$NON-NLS-1$ + .append(LoggingUtils.toString(skippedOrCanceledEvent)).append(" because of event ") //$NON-NLS-1$ + .append(LoggingUtils.toString(event)); + } else { + str.append(LoggingUtils.toString(this)).append(' ').append(action).append(" event ") //$NON-NLS-1$ + .append(LoggingUtils.toString(event)); + } + + if (action != EventHandlerAction.received) { + str.append(" for proxy ").append(LoggingUtils.toString(proxy)).append(", whose root is ") //$NON-NLS-1$//$NON-NLS-2$ + .append(LoggingUtils.toString(proxy.getRootElement())); + } + DsfUIPlugin.debug(str.toString()); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/DefaultVMContentProviderStrategy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/DefaultVMContentProviderStrategy.java index fa77c9a9a41..a7d41e0846d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/DefaultVMContentProviderStrategy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/DefaultVMContentProviderStrategy.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -42,70 +42,70 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; * This class is closely linked with a view model provider which is required for * the constructor. The view model provider is used to access the correct * executor and the node hierarchy. - * + * * @since 1.0 */ @ConfinedToDsfExecutor("#getExecutor()") public class DefaultVMContentProviderStrategy implements IElementContentProvider { - private final AbstractVMProvider fVMProvider; + private final AbstractVMProvider fVMProvider; - public DefaultVMContentProviderStrategy(AbstractVMProvider provider) { - fVMProvider = provider; - } + public DefaultVMContentProviderStrategy(AbstractVMProvider provider) { + fVMProvider = provider; + } - /** - * Returns the view model provider that this strategy is configured for. - * - * @return - */ - protected AbstractVMProvider getVMProvider() { - return fVMProvider; - } + /** + * Returns the view model provider that this strategy is configured for. + * + * @return + */ + protected AbstractVMProvider getVMProvider() { + return fVMProvider; + } - @Override + @Override public void update(final IHasChildrenUpdate[] updates) { - if (updates.length == 0) - return; - - // Optimization: if all the updates belong to the same node, avoid - // creating any new lists/arrays. - boolean allNodesTheSame = true; - IVMNode firstNode = getNodeForElement(updates[0].getElement()); - for (int i = 1; i < updates.length; i++) { - if (firstNode != getNodeForElement(updates[i].getElement())) { - allNodesTheSame = false; - break; - } - } - - if (allNodesTheSame) { - updateNodeChildren(firstNode, updates); - } else { - // Sort the updates by the node. - Map<IVMNode, List<IHasChildrenUpdate>> nodeUpdatesMap = new HashMap<IVMNode, List<IHasChildrenUpdate>>(); - for (IHasChildrenUpdate update : updates) { - // Get the VM Context for last element in path. - IVMNode node = getNodeForElement(update.getElement()); - if (node == null) { - // Stale update, most likely as a result of the nodes being - // changed. Just ignore it. - update.done(); - continue; - } - if (!nodeUpdatesMap.containsKey(node)) { - nodeUpdatesMap.put(node, new ArrayList<IHasChildrenUpdate>()); - } - nodeUpdatesMap.get(node).add(update); - } - - // Iterate through the nodes in the sorted map. - for (IVMNode node : nodeUpdatesMap.keySet()) { - updateNodeChildren(node, nodeUpdatesMap.get(node).toArray( - new IHasChildrenUpdate[nodeUpdatesMap.get(node).size()])); - } - } - } + if (updates.length == 0) + return; + + // Optimization: if all the updates belong to the same node, avoid + // creating any new lists/arrays. + boolean allNodesTheSame = true; + IVMNode firstNode = getNodeForElement(updates[0].getElement()); + for (int i = 1; i < updates.length; i++) { + if (firstNode != getNodeForElement(updates[i].getElement())) { + allNodesTheSame = false; + break; + } + } + + if (allNodesTheSame) { + updateNodeChildren(firstNode, updates); + } else { + // Sort the updates by the node. + Map<IVMNode, List<IHasChildrenUpdate>> nodeUpdatesMap = new HashMap<IVMNode, List<IHasChildrenUpdate>>(); + for (IHasChildrenUpdate update : updates) { + // Get the VM Context for last element in path. + IVMNode node = getNodeForElement(update.getElement()); + if (node == null) { + // Stale update, most likely as a result of the nodes being + // changed. Just ignore it. + update.done(); + continue; + } + if (!nodeUpdatesMap.containsKey(node)) { + nodeUpdatesMap.put(node, new ArrayList<IHasChildrenUpdate>()); + } + nodeUpdatesMap.get(node).add(update); + } + + // Iterate through the nodes in the sorted map. + for (IVMNode node : nodeUpdatesMap.keySet()) { + updateNodeChildren(node, + nodeUpdatesMap.get(node).toArray(new IHasChildrenUpdate[nodeUpdatesMap.get(node).size()])); + } + } + } /** * @param node @@ -115,21 +115,21 @@ public class DefaultVMContentProviderStrategy implements IElementContentProvider * @param updates * the has-children requests */ - private void updateNodeChildren(IVMNode node, final IHasChildrenUpdate[] updates) { - final IVMNode[] childNodes = getVMProvider().getChildVMNodes(node); - if (childNodes.length == 0) { - // If parent element's node has no children, just set the - // result and continue to next element. - for (IHasChildrenUpdate update : updates) { - update.setHasChilren(false); - update.done(); - } - } else if (childNodes.length == 1) { - // Optimization: if there is only one child node, just pass on the - // update to the child node. - getVMProvider().updateNode(childNodes[0], updates); - } else { - // Create a matrix of element updates: + private void updateNodeChildren(IVMNode node, final IHasChildrenUpdate[] updates) { + final IVMNode[] childNodes = getVMProvider().getChildVMNodes(node); + if (childNodes.length == 0) { + // If parent element's node has no children, just set the + // result and continue to next element. + for (IHasChildrenUpdate update : updates) { + update.setHasChilren(false); + update.done(); + } + } else if (childNodes.length == 1) { + // Optimization: if there is only one child node, just pass on the + // update to the child node. + getVMProvider().updateNode(childNodes[0], updates); + } else { + // Create a matrix of element updates: // The first dimension "i" is the list of children updates that came // from the viewer. For each of these updates, there are "j" number // of element updates corresponding to the number of child nodes in @@ -137,268 +137,263 @@ public class DefaultVMContentProviderStrategy implements IElementContentProvider // all the child nodes fill in their elements update. Once the // matrix is constructed, the child nodes are given the list of // updates equal to the updates requested by the viewer. - VMHasChildrenUpdate[][] elementsUpdates = new VMHasChildrenUpdate[childNodes.length][updates.length]; - for (int i = 0; i < updates.length; i++) { - final IHasChildrenUpdate update = updates[i]; - - final MultiRequestMonitor<DataRequestMonitor<Boolean>> hasChildrenMultiRequestMon = new MultiRequestMonitor<DataRequestMonitor<Boolean>>( - getVMProvider().getExecutor(), null) { - @Override - protected void handleCompleted() { - // Status is OK, only if all request monitors are OK. - if (isSuccess()) { - boolean isContainer = false; - for (DataRequestMonitor<Boolean> hasElementsDone : getRequestMonitors()) { - isContainer |= hasElementsDone.isSuccess() && hasElementsDone.getData().booleanValue(); - } - update.setHasChilren(isContainer); - } else { - update.setStatus(getStatus()); - } - update.done(); - } - }; - hasChildrenMultiRequestMon.requireDoneAdding(); - - for (int j = 0; j < childNodes.length; j++) { - elementsUpdates[j][i] = new VMHasChildrenUpdate(update, hasChildrenMultiRequestMon - .add(new ViewerDataRequestMonitor<Boolean>(getVMProvider().getExecutor(), update) { - @Override - protected void handleCompleted() { - hasChildrenMultiRequestMon.requestMonitorDone(this); - } - })); - } - hasChildrenMultiRequestMon.doneAdding(); - } - - for (int j = 0; j < childNodes.length; j++) { - getVMProvider().updateNode(childNodes[j], elementsUpdates[j]); - } - } - } - - @Override + VMHasChildrenUpdate[][] elementsUpdates = new VMHasChildrenUpdate[childNodes.length][updates.length]; + for (int i = 0; i < updates.length; i++) { + final IHasChildrenUpdate update = updates[i]; + + final MultiRequestMonitor<DataRequestMonitor<Boolean>> hasChildrenMultiRequestMon = new MultiRequestMonitor<DataRequestMonitor<Boolean>>( + getVMProvider().getExecutor(), null) { + @Override + protected void handleCompleted() { + // Status is OK, only if all request monitors are OK. + if (isSuccess()) { + boolean isContainer = false; + for (DataRequestMonitor<Boolean> hasElementsDone : getRequestMonitors()) { + isContainer |= hasElementsDone.isSuccess() && hasElementsDone.getData().booleanValue(); + } + update.setHasChilren(isContainer); + } else { + update.setStatus(getStatus()); + } + update.done(); + } + }; + hasChildrenMultiRequestMon.requireDoneAdding(); + + for (int j = 0; j < childNodes.length; j++) { + elementsUpdates[j][i] = new VMHasChildrenUpdate(update, hasChildrenMultiRequestMon + .add(new ViewerDataRequestMonitor<Boolean>(getVMProvider().getExecutor(), update) { + @Override + protected void handleCompleted() { + hasChildrenMultiRequestMon.requestMonitorDone(this); + } + })); + } + hasChildrenMultiRequestMon.doneAdding(); + } + + for (int j = 0; j < childNodes.length; j++) { + getVMProvider().updateNode(childNodes[j], elementsUpdates[j]); + } + } + } + + @Override public void update(final IChildrenCountUpdate[] updates) { - for (final IChildrenCountUpdate update : updates) { - IVMNode node = getNodeForElement(update.getElement()); - - if (node != null && !update.isCanceled()) { - IVMNode[] childNodes = getVMProvider().getChildVMNodes(node); - - if (childNodes.length == 0) { - // If there is no child nodes, logically the child count is 0. - update.setChildCount(0); - update.done(); - } else if (childNodes.length == 1) { - // Optimization: there is only one child node, just pass on the child count to it. - getVMProvider().updateNode(childNodes[0], update); - } else { - getChildrenCountsForNode( - update, node, - new ViewerDataRequestMonitor<Integer[]>(getVMProvider().getExecutor(), update) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - int numChildren = 0; - for (Integer count : getData()) { - numChildren += count.intValue(); - } - update.setChildCount(numChildren); - } else { - update.setChildCount(0); - } - update.done(); - } - }); - } - } else { - update.done(); - } - - } - } - - @Override + for (final IChildrenCountUpdate update : updates) { + IVMNode node = getNodeForElement(update.getElement()); + + if (node != null && !update.isCanceled()) { + IVMNode[] childNodes = getVMProvider().getChildVMNodes(node); + + if (childNodes.length == 0) { + // If there is no child nodes, logically the child count is 0. + update.setChildCount(0); + update.done(); + } else if (childNodes.length == 1) { + // Optimization: there is only one child node, just pass on the child count to it. + getVMProvider().updateNode(childNodes[0], update); + } else { + getChildrenCountsForNode(update, node, + new ViewerDataRequestMonitor<Integer[]>(getVMProvider().getExecutor(), update) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + int numChildren = 0; + for (Integer count : getData()) { + numChildren += count.intValue(); + } + update.setChildCount(numChildren); + } else { + update.setChildCount(0); + } + update.done(); + } + }); + } + } else { + update.done(); + } + + } + } + + @Override public void update(final IChildrenUpdate[] updates) { - for (final IChildrenUpdate update : updates) { - // Get the VM Context for last element in path. - final IVMNode node = getNodeForElement(update.getElement()); - if (node != null && !update.isCanceled()) { - IVMNode[] childNodes = getVMProvider().getChildVMNodes(node); - if (childNodes.length == 0) { - // Invalid update, just mark done. - update.done(); - } else if (childNodes.length == 1) { - // Optimization: there is only one child node, pass the updates to it. - getVMProvider().updateNode(childNodes[0], update); - } else { - getChildrenCountsForNode( - update, node, - new ViewerDataRequestMonitor<Integer[]>(getVMProvider().getExecutor(), update) { - @Override - protected void handleCompleted() { - if (!isSuccess()) { - update.done(); - return; - } - - updateChildrenWithCounts(update, node, getData()); - } - }); - } - } else { - // Stale update. Just ignore. - update.done(); - } - - } - } - - /** - * Calculates the number of elements in each child node for the element in - * update. These counts are then used to delegate the children update to the - * correct nodes. - */ - private void getChildrenCountsForNode(IViewerUpdate update, IVMNode updateNode, - final DataRequestMonitor<Integer[]> rm) { - - IVMNode[] childNodes = getVMProvider().getChildVMNodes(updateNode); - - // Check for an invalid call - assert childNodes.length != 0; - - // Get the mapping of all the counts. - final Integer[] counts = new Integer[childNodes.length]; - final CountingRequestMonitor crm = new CountingRequestMonitor(getVMProvider().getExecutor(), rm) { - @Override - protected void handleSuccess() { - rm.setData(counts); - rm.done(); - } - }; - int countRM = 0; - - for (int i = 0; i < childNodes.length; i++) { - final int nodeIndex = i; - getVMProvider().updateNode( - childNodes[i], - new VMChildrenCountUpdate(update, new DataRequestMonitor<Integer>(getVMProvider().getExecutor(), crm) { - @Override - protected void handleSuccess() { - counts[nodeIndex] = getData(); - crm.done(); - } - })); - countRM++; - } - crm.setDoneCount(countRM); - } - - /** - * Splits the given children update among the configured child nodes. Then - * calls each child node to complete the update. - */ - private void updateChildrenWithCounts(final IChildrenUpdate update, IVMNode node, Integer[] nodeElementCounts) { - // Create the multi request monitor to mark update when querying all - // children nodes is finished. - CountingRequestMonitor multiRm = new ViewerCountingRequestMonitor(getVMProvider().getExecutor(), update) { - @Override - protected void handleCompleted() { - update.done(); - } - }; - int multiRmCount = 0; - - // Iterate through all child nodes and if requested range matches, call - // them to get their elements. - int updateStartIdx = update.getOffset(); - if (updateStartIdx < 0) { - updateStartIdx = 0; - } - int updateEndIdx; - int length = update.getLength(); - if (length <= 0) { - updateEndIdx = Integer.MAX_VALUE; - } else { + for (final IChildrenUpdate update : updates) { + // Get the VM Context for last element in path. + final IVMNode node = getNodeForElement(update.getElement()); + if (node != null && !update.isCanceled()) { + IVMNode[] childNodes = getVMProvider().getChildVMNodes(node); + if (childNodes.length == 0) { + // Invalid update, just mark done. + update.done(); + } else if (childNodes.length == 1) { + // Optimization: there is only one child node, pass the updates to it. + getVMProvider().updateNode(childNodes[0], update); + } else { + getChildrenCountsForNode(update, node, + new ViewerDataRequestMonitor<Integer[]>(getVMProvider().getExecutor(), update) { + @Override + protected void handleCompleted() { + if (!isSuccess()) { + update.done(); + return; + } + + updateChildrenWithCounts(update, node, getData()); + } + }); + } + } else { + // Stale update. Just ignore. + update.done(); + } + + } + } + + /** + * Calculates the number of elements in each child node for the element in + * update. These counts are then used to delegate the children update to the + * correct nodes. + */ + private void getChildrenCountsForNode(IViewerUpdate update, IVMNode updateNode, + final DataRequestMonitor<Integer[]> rm) { + + IVMNode[] childNodes = getVMProvider().getChildVMNodes(updateNode); + + // Check for an invalid call + assert childNodes.length != 0; + + // Get the mapping of all the counts. + final Integer[] counts = new Integer[childNodes.length]; + final CountingRequestMonitor crm = new CountingRequestMonitor(getVMProvider().getExecutor(), rm) { + @Override + protected void handleSuccess() { + rm.setData(counts); + rm.done(); + } + }; + int countRM = 0; + + for (int i = 0; i < childNodes.length; i++) { + final int nodeIndex = i; + getVMProvider().updateNode(childNodes[i], new VMChildrenCountUpdate(update, + new DataRequestMonitor<Integer>(getVMProvider().getExecutor(), crm) { + @Override + protected void handleSuccess() { + counts[nodeIndex] = getData(); + crm.done(); + } + })); + countRM++; + } + crm.setDoneCount(countRM); + } + + /** + * Splits the given children update among the configured child nodes. Then + * calls each child node to complete the update. + */ + private void updateChildrenWithCounts(final IChildrenUpdate update, IVMNode node, Integer[] nodeElementCounts) { + // Create the multi request monitor to mark update when querying all + // children nodes is finished. + CountingRequestMonitor multiRm = new ViewerCountingRequestMonitor(getVMProvider().getExecutor(), update) { + @Override + protected void handleCompleted() { + update.done(); + } + }; + int multiRmCount = 0; + + // Iterate through all child nodes and if requested range matches, call + // them to get their elements. + int updateStartIdx = update.getOffset(); + if (updateStartIdx < 0) { + updateStartIdx = 0; + } + int updateEndIdx; + int length = update.getLength(); + if (length <= 0) { + updateEndIdx = Integer.MAX_VALUE; + } else { updateEndIdx = updateStartIdx + length; - } - int idx = 0; - IVMNode[] nodes = getVMProvider().getChildVMNodes(node); - for (int i = 0; i < nodes.length; i++) { - final int nodeStartIdx = idx; - final int nodeEndIdx = idx + nodeElementCounts[i]; - idx = nodeEndIdx; - - // Check if update range overlaps the node's range. - if (updateStartIdx <= nodeEndIdx && updateEndIdx > nodeStartIdx) { - final int elementsStartIdx = Math.max(updateStartIdx - nodeStartIdx, 0); - final int elementsEndIdx = Math.min(updateEndIdx - nodeStartIdx, nodeElementCounts[i]); - final int elementsLength = elementsEndIdx - elementsStartIdx; - if (elementsLength > 0) { - getVMProvider().updateNode( - nodes[i], - new VMChildrenUpdate(update, elementsStartIdx, elementsLength, - new DataRequestMonitor<List<Object>>(getVMProvider().getExecutor(), multiRm) { - @Override - protected void handleCompleted() { - // Workaround for a bug caused by an - // optimization in the viewer: - // The viewer may request more children then - // there are at a given level. - // This causes the update to return with an - // error. - // See - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=202109 - // Instead of checking isSuccess(), check - // getData() != null. - if (getData() != null) { - for (int i = 0; i < elementsLength && i < getData().size(); i++) { - Object child = getData().get(i); - if (child != null) { - update.setChild(getData().get(i), elementsStartIdx + nodeStartIdx + i); - } - } - } - super.handleCompleted(); - } - })); - multiRmCount++; - } - } - } - - // Guard against invalid queries. - multiRm.setDoneCount(multiRmCount); - } - - /** - * Convenience method that finds the VM node corresponding to given element. - * It returns the root node if the element is not a VM Context or if it was - * created by another view. - * - * @param element Element to find the VM Node for. - * @return View Model Node that this element was created by. - */ - protected IVMNode getNodeForElement(Object element) { - if (element instanceof IVMContext) { - IVMNode node = ((IVMContext) element).getVMNode(); - if (isOurNode(((IVMContext) element).getVMNode())) { - return node; - } - } - return getVMProvider().getRootVMNode(); - } - - /** - * Convenience method which checks whether given layout node is a node that - * is configured in this ViewModelProvider. - * <br> - * Note: isOurNode() will also return true if the given node was previously - * configured in the VM provider but was later disposed. - */ - private boolean isOurNode(IVMNode node) { - return node.getVMProvider() == getVMProvider(); - } + } + int idx = 0; + IVMNode[] nodes = getVMProvider().getChildVMNodes(node); + for (int i = 0; i < nodes.length; i++) { + final int nodeStartIdx = idx; + final int nodeEndIdx = idx + nodeElementCounts[i]; + idx = nodeEndIdx; + + // Check if update range overlaps the node's range. + if (updateStartIdx <= nodeEndIdx && updateEndIdx > nodeStartIdx) { + final int elementsStartIdx = Math.max(updateStartIdx - nodeStartIdx, 0); + final int elementsEndIdx = Math.min(updateEndIdx - nodeStartIdx, nodeElementCounts[i]); + final int elementsLength = elementsEndIdx - elementsStartIdx; + if (elementsLength > 0) { + getVMProvider().updateNode(nodes[i], new VMChildrenUpdate(update, elementsStartIdx, elementsLength, + new DataRequestMonitor<List<Object>>(getVMProvider().getExecutor(), multiRm) { + @Override + protected void handleCompleted() { + // Workaround for a bug caused by an + // optimization in the viewer: + // The viewer may request more children then + // there are at a given level. + // This causes the update to return with an + // error. + // See + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=202109 + // Instead of checking isSuccess(), check + // getData() != null. + if (getData() != null) { + for (int i = 0; i < elementsLength && i < getData().size(); i++) { + Object child = getData().get(i); + if (child != null) { + update.setChild(getData().get(i), elementsStartIdx + nodeStartIdx + i); + } + } + } + super.handleCompleted(); + } + })); + multiRmCount++; + } + } + } + + // Guard against invalid queries. + multiRm.setDoneCount(multiRmCount); + } + + /** + * Convenience method that finds the VM node corresponding to given element. + * It returns the root node if the element is not a VM Context or if it was + * created by another view. + * + * @param element Element to find the VM Node for. + * @return View Model Node that this element was created by. + */ + protected IVMNode getNodeForElement(Object element) { + if (element instanceof IVMContext) { + IVMNode node = ((IVMContext) element).getVMNode(); + if (isOurNode(((IVMContext) element).getVMNode())) { + return node; + } + } + return getVMProvider().getRootVMNode(); + } + + /** + * Convenience method which checks whether given layout node is a node that + * is configured in this ViewModelProvider. + * <br> + * Note: isOurNode() will also return true if the given node was previously + * configured in the VM provider but was later disposed. + */ + private boolean isOurNode(IVMNode node) { + return node.getVMProvider() == getVMProvider(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/DefaultVMModelProxyStrategy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/DefaultVMModelProxyStrategy.java index a0696573a70..5fe9191845d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/DefaultVMModelProxyStrategy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/DefaultVMModelProxyStrategy.java @@ -7,11 +7,11 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation * Wind River Systems - adapted to use with DSF - * Dobrin Alexiev (Texas Instruments) - user groups support (bug 240208) + * Dobrin Alexiev (Texas Instruments) - user groups support (bug 240208) * Marc Dumais (Ericsson) - bug 485170 *******************************************************************************/ package org.eclipse.cdt.dsf.ui.viewmodel; @@ -45,266 +45,262 @@ import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.Viewer; - /** - * This is the default implementation of {@link IModelProxy} interface for + * This is the default implementation of {@link IModelProxy} interface for * use by a view model provider. It implements an algorithm to walk the * tree hierarchy of nodes configured with a provider in order to compose * an {@link IModelDelta} for a given data model event. * <p/> * This class is closely linked with a view model provider which is required * for the constructor. The view model provider is used to access the correct - * executor and the node hierarchy. - * + * executor and the node hierarchy. + * * @since 1.0 */ @ConfinedToDsfExecutor("#getProvider()#getExecutor()") @SuppressWarnings("restriction") public class DefaultVMModelProxyStrategy implements IVMModelProxy { - private final AbstractVMProvider fProvider; - private final Object fRootElement; - private IPresentationContext fContext; - private Viewer fViewer; - private boolean fDisposed = false; - private ListenerList<IModelChangedListener> fListeners = new ListenerList<>(); + private final AbstractVMProvider fProvider; + private final Object fRootElement; + private IPresentationContext fContext; + private Viewer fViewer; + private boolean fDisposed = false; + private ListenerList<IModelChangedListener> fListeners = new ListenerList<>(); private IDoubleClickListener fDoubleClickListener; private boolean fAllowRecursiveVMNodes = false; - - /** - * Creates this model proxy strategy for the given provider. - */ - public DefaultVMModelProxyStrategy(AbstractVMProvider provider, Object rootElement) { - fProvider = provider; - fRootElement = rootElement; - } - - @Override - public boolean isDeltaEvent(Object event) { - return getEventDeltaFlags(event) != IModelDelta.NO_CHANGE; - } - - @Override - public int getEventDeltaFlags(Object event) { - IRootVMNode rootNode = getVMProvider().getRootVMNode(); - if (rootNode != null && - rootNode.isDeltaEvent(getRootElement(), event)) - { - return getDeltaFlags(rootNode, null, event); - } - return IModelDelta.NO_CHANGE; - } - - - /** - * Returns the view model provider that this strategy is configured for. - * @return - */ - protected AbstractVMProvider getVMProvider() { - return fProvider; - } - - - private Object[] getListeners() { - return fListeners.getListeners(); - } - - @Override - public void addModelChangedListener(IModelChangedListener listener) { - fListeners.add(listener); - } - - @Override - public void removeModelChangedListener(IModelChangedListener listener) { - fListeners.remove(listener); - } - - @Override - public Object getRootElement() { - return fRootElement; - } - - /** @since 1.1 */ - @Override - public Object getViewerInput() { - return fRootElement; - } - - /** @since 1.1 */ - @Override - public TreePath getRootPath() { - return TreePath.EMPTY; - } - - /** - * Notifies registered listeners of the given delta. - * - * @param delta model delta to broadcast - */ - @Override - public void fireModelChanged(IModelDelta delta) { - final IModelDelta root = getRootDelta(delta); - Object[] listeners = getListeners(); - for (int i = 0; i < listeners.length; i++) { - final IModelChangedListener listener = (IModelChangedListener) listeners[i]; - ISafeRunnable safeRunnable = new ISafeRunnable() { - @Override - public void handleException(Throwable exception) { - DebugUIPlugin.log(exception); - } - - @Override - public void run() throws Exception { - listener.modelChanged(root, DefaultVMModelProxyStrategy.this); - } - - }; - SafeRunner.run(safeRunnable); - } - } - - /** - * Convenience method that returns the root node of the given delta. - * - * @param delta delta node - * @return returns the root of the given delta - */ - protected IModelDelta getRootDelta(IModelDelta delta) { - IModelDelta parent = delta.getParentDelta(); - while (parent != null) { - delta = parent; - parent = delta.getParentDelta(); - } - return delta; - } - - /* (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.IModelProxy#dispose() - */ - @Override - public void dispose() { - fDisposed = true; - if (fViewer instanceof StructuredViewer && fDoubleClickListener != null) { - ((StructuredViewer) fViewer).removeDoubleClickListener(fDoubleClickListener); - fDoubleClickListener= null; - } - } - - /* (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.IModelProxy#init(org.eclipse.debug.internal.ui.viewers.IPresentationContext) - */ - @Override - public void init(IPresentationContext context) { - fDisposed = false; - fContext = context; - } - - /** - * Returns the context this model proxy is installed in. - * - * @return presentation context, or <code>null</code> if this - * model proxy has been disposed - */ - public IPresentationContext getPresentationContext() { - return fContext; - } - - /* (non-Javadoc) - * - * Subclasses should override as required. - * - * @see org.eclipse.debug.internal.ui.viewers.provisional.IModelProxy#installed(org.eclipse.jface.viewers.Viewer) - */ - @Override - public void installed(final Viewer viewer) { - fViewer = viewer; - getVMProvider().getExecutor().execute( new DsfRunnable() { - @Override - public void run() { - fProvider.handleEvent(new ModelProxyInstalledEvent(DefaultVMModelProxyStrategy.this, viewer, fRootElement)); - } - }); - if (fViewer instanceof StructuredViewer && fDoubleClickListener == null) { - ((StructuredViewer) fViewer).addDoubleClickListener(fDoubleClickListener= new IDoubleClickListener() { - @Override - public void doubleClick(DoubleClickEvent e) { - handleDoubleClick(e); - } - }); - } - } - - /** - * Handle viewer double click. - * + + /** + * Creates this model proxy strategy for the given provider. + */ + public DefaultVMModelProxyStrategy(AbstractVMProvider provider, Object rootElement) { + fProvider = provider; + fRootElement = rootElement; + } + + @Override + public boolean isDeltaEvent(Object event) { + return getEventDeltaFlags(event) != IModelDelta.NO_CHANGE; + } + + @Override + public int getEventDeltaFlags(Object event) { + IRootVMNode rootNode = getVMProvider().getRootVMNode(); + if (rootNode != null && rootNode.isDeltaEvent(getRootElement(), event)) { + return getDeltaFlags(rootNode, null, event); + } + return IModelDelta.NO_CHANGE; + } + + /** + * Returns the view model provider that this strategy is configured for. + * @return + */ + protected AbstractVMProvider getVMProvider() { + return fProvider; + } + + private Object[] getListeners() { + return fListeners.getListeners(); + } + + @Override + public void addModelChangedListener(IModelChangedListener listener) { + fListeners.add(listener); + } + + @Override + public void removeModelChangedListener(IModelChangedListener listener) { + fListeners.remove(listener); + } + + @Override + public Object getRootElement() { + return fRootElement; + } + + /** @since 1.1 */ + @Override + public Object getViewerInput() { + return fRootElement; + } + + /** @since 1.1 */ + @Override + public TreePath getRootPath() { + return TreePath.EMPTY; + } + + /** + * Notifies registered listeners of the given delta. + * + * @param delta model delta to broadcast + */ + @Override + public void fireModelChanged(IModelDelta delta) { + final IModelDelta root = getRootDelta(delta); + Object[] listeners = getListeners(); + for (int i = 0; i < listeners.length; i++) { + final IModelChangedListener listener = (IModelChangedListener) listeners[i]; + ISafeRunnable safeRunnable = new ISafeRunnable() { + @Override + public void handleException(Throwable exception) { + DebugUIPlugin.log(exception); + } + + @Override + public void run() throws Exception { + listener.modelChanged(root, DefaultVMModelProxyStrategy.this); + } + + }; + SafeRunner.run(safeRunnable); + } + } + + /** + * Convenience method that returns the root node of the given delta. + * + * @param delta delta node + * @return returns the root of the given delta + */ + protected IModelDelta getRootDelta(IModelDelta delta) { + IModelDelta parent = delta.getParentDelta(); + while (parent != null) { + delta = parent; + parent = delta.getParentDelta(); + } + return delta; + } + + /* (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.IModelProxy#dispose() + */ + @Override + public void dispose() { + fDisposed = true; + if (fViewer instanceof StructuredViewer && fDoubleClickListener != null) { + ((StructuredViewer) fViewer).removeDoubleClickListener(fDoubleClickListener); + fDoubleClickListener = null; + } + } + + /* (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.IModelProxy#init(org.eclipse.debug.internal.ui.viewers.IPresentationContext) + */ + @Override + public void init(IPresentationContext context) { + fDisposed = false; + fContext = context; + } + + /** + * Returns the context this model proxy is installed in. + * + * @return presentation context, or <code>null</code> if this + * model proxy has been disposed + */ + public IPresentationContext getPresentationContext() { + return fContext; + } + + /* (non-Javadoc) + * + * Subclasses should override as required. + * + * @see org.eclipse.debug.internal.ui.viewers.provisional.IModelProxy#installed(org.eclipse.jface.viewers.Viewer) + */ + @Override + public void installed(final Viewer viewer) { + fViewer = viewer; + getVMProvider().getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + fProvider.handleEvent( + new ModelProxyInstalledEvent(DefaultVMModelProxyStrategy.this, viewer, fRootElement)); + } + }); + if (fViewer instanceof StructuredViewer && fDoubleClickListener == null) { + ((StructuredViewer) fViewer).addDoubleClickListener(fDoubleClickListener = new IDoubleClickListener() { + @Override + public void doubleClick(DoubleClickEvent e) { + handleDoubleClick(e); + } + }); + } + } + + /** + * Handle viewer double click. + * * @param e the event - * + * * @since 1.1 */ protected void handleDoubleClick(final DoubleClickEvent e) { - final AbstractVMProvider vmProvider= getVMProvider(); + final AbstractVMProvider vmProvider = getVMProvider(); if (!vmProvider.isDisposed()) { - ISelection selection = e.getSelection(); + ISelection selection = e.getSelection(); if (!selection.isEmpty() && selection instanceof ITreeSelection) { - final TreePath path = ((ITreeSelection)selection).getPaths()[0]; - final Object input = e.getViewer().getInput(); - - vmProvider.getExecutor().execute( new DsfRunnable() { - @Override - public void run() { - Object rootElement = getRootElement(); - boolean eventContainsRootElement = rootElement.equals(input); - for (int i = 0; !eventContainsRootElement && i < path.getSegmentCount(); i++) { - eventContainsRootElement = rootElement.equals(path.getSegment(i)); - } - - if (eventContainsRootElement) { - vmProvider.handleEvent(e); - } - } - }); - } + final TreePath path = ((ITreeSelection) selection).getPaths()[0]; + final Object input = e.getViewer().getInput(); + + vmProvider.getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + Object rootElement = getRootElement(); + boolean eventContainsRootElement = rootElement.equals(input); + for (int i = 0; !eventContainsRootElement && i < path.getSegmentCount(); i++) { + eventContainsRootElement = rootElement.equals(path.getSegment(i)); + } + + if (eventContainsRootElement) { + vmProvider.handleEvent(e); + } + } + }); + } } } /** - * Returns the viewer this proxy is installed in. - * - * @return viewer or <code>null</code> if not installed - * - * @since 1.1 - */ - @Override - public Viewer getViewer() { - return fViewer; - } - - /* (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IModelProxy#isDisposed() - */ - @Override - public boolean isDisposed() { - return fDisposed; - } + * Returns the viewer this proxy is installed in. + * + * @return viewer or <code>null</code> if not installed + * + * @since 1.1 + */ + @Override + public Viewer getViewer() { + return fViewer; + } + + /* (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IModelProxy#isDisposed() + */ + @Override + public boolean isDisposed() { + return fDisposed; + } /** * Recursively calls the VM nodes in the hierarchy of the given node to * determine how elements of those types may be (or are) affected by * [event], the answer being a collection of IModelDelta flags. - * + * * A response of IModeDelta.CONTENT has a special meaning. If we return that * flag for an IVMNode, it means the <i>collection</i> of elements of that * type are affected. It is not a statement on the elements themselves. - * + * * Optimization 1: If the first-level child node does not have * <code>IModelDelta.CONTENT</code> but one of its descendants does, then * for optimization reasons we return <code>IModelDelta.STATE</code> * instead. See {@link DefaultVMModelProxyStrategy#buildChildDeltasForAllContexts(IVMNode, Object, VMDelta, int, RequestMonitor)} - * + * * Optimization 2: If the parent delta contains * <code>IModelDelta.CONTENT</code>, we do not need to specify it for its * children. This can shorten delta processing considerably. - * + * * @param node * the IVMNode whose delta flags (and those of its descendants) * are being queried @@ -317,371 +313,357 @@ public class DefaultVMModelProxyStrategy implements IVMModelProxy { * @return the collective set of IModelDelta flags that reflect how [node] * and its descendants may be (or are) affected by [event] */ - protected int getDeltaFlags(IVMNode node, ModelDelta parentDelta, Object event) { - int flags = node.getDeltaFlags(event); - for (IVMNode childNode : getVMProvider().getChildVMNodes(node)) { - if (!childNode.equals(node)) { - int childNodeDeltaFlags = getDeltaFlags(childNode, parentDelta, event); - - // optimization 1; see above - if ((childNodeDeltaFlags & IModelDelta.CONTENT) != 0) { - childNodeDeltaFlags &= ~IModelDelta.CONTENT; - childNodeDeltaFlags |= IModelDelta.STATE; - } - - flags |= childNodeDeltaFlags; - } - } - - // optimization 2; see above - while (parentDelta != null) { - if ( (parentDelta.getFlags() & IModelDelta.CONTENT) != 0 ) { - flags = flags & ~IModelDelta.CONTENT & ~IModelDelta.STATE; - break; - } - parentDelta = (ModelDelta)parentDelta.getParentDelta(); - } - return flags; - } - - /** - * Default implementation creates a delta assuming that the root node - * is the input object into the view. - */ - @Override - public void createDelta(final Object event, final DataRequestMonitor<IModelDelta> rm) { - final IRootVMNode rootNode = getVMProvider().getRootVMNode(); - - // Always create the rootDelta, no matter what delta flags the child nodes have. - rootNode.createRootDelta( - getRootElement(), event, - new DataRequestMonitor<VMDelta>(getVMProvider().getExecutor(), rm) { - @Override - protected void handleSuccess() { - // The resulting delta will have parents if our - // VMProvider is registered to populate only a sub-tree - // of the viewer. Get the root node of the chain--i.e., - // the delta for the root element of the entire viewer. - final IModelDelta viewRootDelta = getRootDelta(getData()); - - // Find the child nodes that (may) have deltas for the given event. - final Map<IVMNode,Integer> childNodesWithDeltaFlags = getChildNodesWithDeltaFlags(rootNode, getData(), event); - - // If no child nodes have deltas we can stop here. - if (childNodesWithDeltaFlags.size() == 0) { - rm.setData(viewRootDelta); - rm.done(); - return; - } - - callChildNodesToBuildDelta( - rootNode, - childNodesWithDeltaFlags, getData(), event, - new RequestMonitor(getVMProvider().getExecutor(), rm) { - @Override - protected void handleSuccess() { - // Get rid of redundant CONTENT and STATE flags in delta and prune - // nodes without flags - rm.setData(pruneDelta((VMDelta)viewRootDelta)); - rm.done(); - } - }); - } - }); - } - - protected VMDelta pruneDelta(VMDelta delta) { - delta.accept(new IModelDeltaVisitor() { - @Override - public boolean visit(IModelDelta deltaNode, int depth) { - if ((deltaNode.getFlags() & (IModelDelta.CONTENT | IModelDelta.STATE)) != 0) { - VMDelta parent = (VMDelta)deltaNode.getParentDelta(); - while (parent != null) { - if ((parent.getFlags() & IModelDelta.CONTENT) != 0) { - ((VMDelta)deltaNode).setFlags(deltaNode.getFlags() & ~(IModelDelta.CONTENT | IModelDelta.STATE)); - break; - } - parent = parent.getParentDelta(); - } - } - return true; - } - }); - return delta; - } - - /** - * Base implementation that handles calling child nodes to build - * the model delta. This method delegates to two other methods: - * {@link #buildChildDeltasForEventContext(IVMContext[], IVMNode, Object, VMDelta, int, RequestMonitor)} - * and {@link #buildChildDeltasForAllContexts(IVMNode, Object, VMDelta, int, RequestMonitor)}, - * depending on the result of calling{@link IVMNode#getContextsForEvent(VMDelta, Object, DataRequestMonitor)}. - * @see IVMNode#buildDelta(Object, ModelDelta, int, RequestMonitor) - */ - protected void buildChildDeltas(final IVMNode node, final Object event, final VMDelta parentDelta, - final int nodeOffset, final RequestMonitor rm) - { - node.getContextsForEvent( - parentDelta, - event, - new DataRequestMonitor<IVMContext[]>(getVMProvider().getExecutor(), rm) { - @Override - protected void handleCompleted() { - if (isSuccess()) { - assert getData() != null; - buildChildDeltasForEventContext(getData(), node, event, parentDelta, nodeOffset, rm); - } - else if (getStatus().getCode() == IDsfStatusConstants.NOT_SUPPORTED) { - // The DMC for this node was not found in the event. Call the - // super-class to resort to the default behavior which will add a - // delta for every element in this node. - buildChildDeltasForAllContexts(node, event, parentDelta, nodeOffset, rm); - } - else { - super.handleCompleted(); - } - } - }); - } - - /** - * Base implementation that handles calling child nodes to build - * the model delta. This method is called with the context obtained - * by calling{@link IVMNode#getContextsForEvent(VMDelta, Object, DataRequestMonitor)}. - * @see IVMNode#buildDelta(Object, ModelDelta, int, RequestMonitor) - */ - protected void buildChildDeltasForEventContext(final IVMContext[] vmcs, final IVMNode node, final Object event, - final VMDelta parentDelta, final int nodeOffset, final RequestMonitor rm) - { - final Map<IVMNode,Integer> childNodesWithDeltaFlags = getChildNodesWithDeltaFlags(node, parentDelta, event); - if (childNodesWithDeltaFlags.size() == 0) { - // There are no child nodes with deltas, just return to parent. - rm.done(); - return; - } - - // Check if any of the child nodes are will generate IModelDelta.SELECT or - // IModelDelta.EXPAND flags. If so, we must calculate the index for this - // VMC. - boolean calculateIndex = false; - if (nodeOffset >= 0) { - for (int childDelta : childNodesWithDeltaFlags.values()) { - if ( (childDelta & (IModelDelta.SELECT | IModelDelta.EXPAND)) != 0 ) { - calculateIndex = true; - break; - } - } - } - - if (calculateIndex) { - // Calculate the index of this node by retrieving all the - // elements and then finding the DMC that the event is for. - getVMProvider().updateNode( - node, - new VMChildrenUpdate( - parentDelta, getVMProvider().getPresentationContext(), -1, -1, - new DataRequestMonitor<List<Object>>(getVMProvider().getExecutor(), rm) { - @Override - protected void handleSuccess() { - // Check for an empty list of elements. If it's empty then we - // don't have to call the children nodes, so return here. - // No need to propagate error, there's no means or need to display it. - if (getData().isEmpty()) { - rm.done(); - return; - } - - CountingRequestMonitor countingRm = - new CountingRequestMonitor(getVMProvider().getExecutor(), rm); - - int count = 0; - for (IVMContext vmc : vmcs) { - // Find the index of the vmc in the full list of elements. - int i; - for (i = 0; i < getData().size(); i++) { - if (vmc.equals(getData().get(i))) break; - } - if (i == getData().size()) { - // Element not found, no need to generate the delta. - continue; - } - - // Optimization: Try to find a delta with a matching element, if found use it. - // Otherwise create a new delta for the event element. - int elementIndex = nodeOffset + i; - VMDelta delta = parentDelta.getChildDelta(vmc); - if (delta == null || delta.getIndex() != elementIndex) { - delta = parentDelta.addNode(vmc, elementIndex, IModelDelta.NO_CHANGE); - } - - callChildNodesToBuildDelta( - node, childNodesWithDeltaFlags, delta, event, countingRm); - count++; - } - countingRm.setDoneCount(count); - } - })); - } else { - CountingRequestMonitor countingRm = - new CountingRequestMonitor(getVMProvider().getExecutor(), rm); - int count = 0; - for (IVMContext vmc : vmcs) { - // Optimization: Try to find a delta with a matching element, if found use it. - // Otherwise create a new delta for the event element. - VMDelta delta = parentDelta.getChildDelta(vmc); - if (delta == null) { - delta = parentDelta.addNode(vmc, IModelDelta.NO_CHANGE); - } - callChildNodesToBuildDelta(node, childNodesWithDeltaFlags, delta, event, countingRm); - count++; - } - countingRm.setDoneCount(count); - } - } - - /** - * Base implementation that handles calling child nodes to build - * the model delta. The child nodes are called with all the elements - * in this node, which could be very inefficient. This method is only - * called if {@link IVMNode#getContextsForEvent(VMDelta, Object, DataRequestMonitor)} - * is not supported by the node for the given element. - * @see IVMNode#buildDelta(Object, ModelDelta, int, RequestMonitor) - */ - protected void buildChildDeltasForAllContexts(final IVMNode node, final Object event, final VMDelta parentDelta, - final int nodeOffset, final RequestMonitor rm) - { - final Map<IVMNode,Integer> childNodesWithDeltaFlags = getChildNodesWithDeltaFlags(node, parentDelta, event); - if (childNodesWithDeltaFlags.size() == 0) { - // There are no child nodes with deltas, just return to parent. - rm.done(); - return; - } + protected int getDeltaFlags(IVMNode node, ModelDelta parentDelta, Object event) { + int flags = node.getDeltaFlags(event); + for (IVMNode childNode : getVMProvider().getChildVMNodes(node)) { + if (!childNode.equals(node)) { + int childNodeDeltaFlags = getDeltaFlags(childNode, parentDelta, event); + + // optimization 1; see above + if ((childNodeDeltaFlags & IModelDelta.CONTENT) != 0) { + childNodeDeltaFlags &= ~IModelDelta.CONTENT; + childNodeDeltaFlags |= IModelDelta.STATE; + } + + flags |= childNodeDeltaFlags; + } + } + + // optimization 2; see above + while (parentDelta != null) { + if ((parentDelta.getFlags() & IModelDelta.CONTENT) != 0) { + flags = flags & ~IModelDelta.CONTENT & ~IModelDelta.STATE; + break; + } + parentDelta = (ModelDelta) parentDelta.getParentDelta(); + } + return flags; + } + + /** + * Default implementation creates a delta assuming that the root node + * is the input object into the view. + */ + @Override + public void createDelta(final Object event, final DataRequestMonitor<IModelDelta> rm) { + final IRootVMNode rootNode = getVMProvider().getRootVMNode(); + + // Always create the rootDelta, no matter what delta flags the child nodes have. + rootNode.createRootDelta(getRootElement(), event, + new DataRequestMonitor<VMDelta>(getVMProvider().getExecutor(), rm) { + @Override + protected void handleSuccess() { + // The resulting delta will have parents if our + // VMProvider is registered to populate only a sub-tree + // of the viewer. Get the root node of the chain--i.e., + // the delta for the root element of the entire viewer. + final IModelDelta viewRootDelta = getRootDelta(getData()); + + // Find the child nodes that (may) have deltas for the given event. + final Map<IVMNode, Integer> childNodesWithDeltaFlags = getChildNodesWithDeltaFlags(rootNode, + getData(), event); + + // If no child nodes have deltas we can stop here. + if (childNodesWithDeltaFlags.size() == 0) { + rm.setData(viewRootDelta); + rm.done(); + return; + } + + callChildNodesToBuildDelta(rootNode, childNodesWithDeltaFlags, getData(), event, + new RequestMonitor(getVMProvider().getExecutor(), rm) { + @Override + protected void handleSuccess() { + // Get rid of redundant CONTENT and STATE flags in delta and prune + // nodes without flags + rm.setData(pruneDelta((VMDelta) viewRootDelta)); + rm.done(); + } + }); + } + }); + } + + protected VMDelta pruneDelta(VMDelta delta) { + delta.accept(new IModelDeltaVisitor() { + @Override + public boolean visit(IModelDelta deltaNode, int depth) { + if ((deltaNode.getFlags() & (IModelDelta.CONTENT | IModelDelta.STATE)) != 0) { + VMDelta parent = (VMDelta) deltaNode.getParentDelta(); + while (parent != null) { + if ((parent.getFlags() & IModelDelta.CONTENT) != 0) { + ((VMDelta) deltaNode) + .setFlags(deltaNode.getFlags() & ~(IModelDelta.CONTENT | IModelDelta.STATE)); + break; + } + parent = parent.getParentDelta(); + } + } + return true; + } + }); + return delta; + } + + /** + * Base implementation that handles calling child nodes to build + * the model delta. This method delegates to two other methods: + * {@link #buildChildDeltasForEventContext(IVMContext[], IVMNode, Object, VMDelta, int, RequestMonitor)} + * and {@link #buildChildDeltasForAllContexts(IVMNode, Object, VMDelta, int, RequestMonitor)}, + * depending on the result of calling{@link IVMNode#getContextsForEvent(VMDelta, Object, DataRequestMonitor)}. + * @see IVMNode#buildDelta(Object, ModelDelta, int, RequestMonitor) + */ + protected void buildChildDeltas(final IVMNode node, final Object event, final VMDelta parentDelta, + final int nodeOffset, final RequestMonitor rm) { + node.getContextsForEvent(parentDelta, event, + new DataRequestMonitor<IVMContext[]>(getVMProvider().getExecutor(), rm) { + @Override + protected void handleCompleted() { + if (isSuccess()) { + assert getData() != null; + buildChildDeltasForEventContext(getData(), node, event, parentDelta, nodeOffset, rm); + } else if (getStatus().getCode() == IDsfStatusConstants.NOT_SUPPORTED) { + // The DMC for this node was not found in the event. Call the + // super-class to resort to the default behavior which will add a + // delta for every element in this node. + buildChildDeltasForAllContexts(node, event, parentDelta, nodeOffset, rm); + } else { + super.handleCompleted(); + } + } + }); + } + + /** + * Base implementation that handles calling child nodes to build + * the model delta. This method is called with the context obtained + * by calling{@link IVMNode#getContextsForEvent(VMDelta, Object, DataRequestMonitor)}. + * @see IVMNode#buildDelta(Object, ModelDelta, int, RequestMonitor) + */ + protected void buildChildDeltasForEventContext(final IVMContext[] vmcs, final IVMNode node, final Object event, + final VMDelta parentDelta, final int nodeOffset, final RequestMonitor rm) { + final Map<IVMNode, Integer> childNodesWithDeltaFlags = getChildNodesWithDeltaFlags(node, parentDelta, event); + if (childNodesWithDeltaFlags.size() == 0) { + // There are no child nodes with deltas, just return to parent. + rm.done(); + return; + } + + // Check if any of the child nodes are will generate IModelDelta.SELECT or + // IModelDelta.EXPAND flags. If so, we must calculate the index for this + // VMC. + boolean calculateIndex = false; + if (nodeOffset >= 0) { + for (int childDelta : childNodesWithDeltaFlags.values()) { + if ((childDelta & (IModelDelta.SELECT | IModelDelta.EXPAND)) != 0) { + calculateIndex = true; + break; + } + } + } + + if (calculateIndex) { + // Calculate the index of this node by retrieving all the + // elements and then finding the DMC that the event is for. + getVMProvider().updateNode(node, new VMChildrenUpdate(parentDelta, getVMProvider().getPresentationContext(), + -1, -1, new DataRequestMonitor<List<Object>>(getVMProvider().getExecutor(), rm) { + @Override + protected void handleSuccess() { + // Check for an empty list of elements. If it's empty then we + // don't have to call the children nodes, so return here. + // No need to propagate error, there's no means or need to display it. + if (getData().isEmpty()) { + rm.done(); + return; + } + + CountingRequestMonitor countingRm = new CountingRequestMonitor( + getVMProvider().getExecutor(), rm); + + int count = 0; + for (IVMContext vmc : vmcs) { + // Find the index of the vmc in the full list of elements. + int i; + for (i = 0; i < getData().size(); i++) { + if (vmc.equals(getData().get(i))) + break; + } + if (i == getData().size()) { + // Element not found, no need to generate the delta. + continue; + } + + // Optimization: Try to find a delta with a matching element, if found use it. + // Otherwise create a new delta for the event element. + int elementIndex = nodeOffset + i; + VMDelta delta = parentDelta.getChildDelta(vmc); + if (delta == null || delta.getIndex() != elementIndex) { + delta = parentDelta.addNode(vmc, elementIndex, IModelDelta.NO_CHANGE); + } + + callChildNodesToBuildDelta(node, childNodesWithDeltaFlags, delta, event, countingRm); + count++; + } + countingRm.setDoneCount(count); + } + })); + } else { + CountingRequestMonitor countingRm = new CountingRequestMonitor(getVMProvider().getExecutor(), rm); + int count = 0; + for (IVMContext vmc : vmcs) { + // Optimization: Try to find a delta with a matching element, if found use it. + // Otherwise create a new delta for the event element. + VMDelta delta = parentDelta.getChildDelta(vmc); + if (delta == null) { + delta = parentDelta.addNode(vmc, IModelDelta.NO_CHANGE); + } + callChildNodesToBuildDelta(node, childNodesWithDeltaFlags, delta, event, countingRm); + count++; + } + countingRm.setDoneCount(count); + } + } + + /** + * Base implementation that handles calling child nodes to build + * the model delta. The child nodes are called with all the elements + * in this node, which could be very inefficient. This method is only + * called if {@link IVMNode#getContextsForEvent(VMDelta, Object, DataRequestMonitor)} + * is not supported by the node for the given element. + * @see IVMNode#buildDelta(Object, ModelDelta, int, RequestMonitor) + */ + protected void buildChildDeltasForAllContexts(final IVMNode node, final Object event, final VMDelta parentDelta, + final int nodeOffset, final RequestMonitor rm) { + final Map<IVMNode, Integer> childNodesWithDeltaFlags = getChildNodesWithDeltaFlags(node, parentDelta, event); + if (childNodesWithDeltaFlags.size() == 0) { + // There are no child nodes with deltas, just return to parent. + rm.done(); + return; + } // Check if the child delta only has an IModelDelta.STATE flag. If // that's the case, we can skip creating a delta for this node, because // the Debug Platform's handling of that flag does not require ancestor // deltas (doesn't need to know the path to the element) - // + // // We can skip the delta for this node even if a deeper IVMNode child // calls for an IModelDelta.CONTENT flag, since what we do in that case // is have the CONTENT flag applied to the first ancestor delta that has // something other than IModelDelta.STATE. - // - // The main benefit of this optimization is that the viewer is left - // to retrieve the elements that need to be refreshed, rather - // than having this proxy do it. Since the viewer is lazy loading - // it may not need to retrieve as many elements in the hierarchy. - // - // For example: suppose the model looks like: - // A- - // |-1 - // |-I - // | |-a - // | |-b - // |-II - // | |-c - // |-III - // |-d - // + // + // The main benefit of this optimization is that the viewer is left + // to retrieve the elements that need to be refreshed, rather + // than having this proxy do it. Since the viewer is lazy loading + // it may not need to retrieve as many elements in the hierarchy. + // + // For example: suppose the model looks like: + // A- + // |-1 + // |-I + // | |-a + // | |-b + // |-II + // | |-c + // |-III + // |-d + // // And if VM Node responsible for element a, b, c, d needs a CONTENT // update, then the delta may look like this: - // - // Element: A - // Flags: CONTENT - // Index: 0 Child Count:-1 - // - // Instead of: - // - // Element: A - // Flags: NO_CHANGE - // Index: 0 Child Count: 1 - // Element: 1 - // Flags: NO_CHANGE - // Index: 0 Child Count: 3 - // Element: I - // Flags: CONTENT - // Index: 0 Child Count: 2 - // Element: II - // Flags: CONTENT - // Index: 1 Child Count: 1 - // Element: III - // Flags: CONTENT - // Index: 2 Child Count: 1 - boolean mustGetElements = false; - boolean _updateFlagsOnly = true; - for (int childDelta : childNodesWithDeltaFlags.values()) { - if ((childDelta & ~IModelDelta.STATE) != 0) { - mustGetElements = true; - } - if ((childDelta & ~(IModelDelta.STATE | IModelDelta.CONTENT)) != 0) { - _updateFlagsOnly = false; - } - } - final boolean updateFlagsOnly = _updateFlagsOnly; - - if (!mustGetElements) { - callChildNodesToBuildDelta( - node, childNodesWithDeltaFlags, parentDelta, event, - new RequestMonitor(getVMProvider().getExecutor(), rm) { - @Override - protected void handleError() { - super.handleError(); - } - }); - } else { - // The given child nodes have deltas potentially for all elements - // from this node. Retrieve all elements and call the child nodes with - // each element as the parent of their delta. - getVMProvider().updateNode( - node, - new VMChildrenUpdate( - parentDelta, getVMProvider().getPresentationContext(), -1, -1, - new DataRequestMonitor<List<Object>>(getVMProvider().getExecutor(), rm) { - @Override - protected void handleCompleted() { - if (fDisposed) return; - - final List<Object> childElements = getData(); - - // Check for an empty list of elements. If the list of elements is empty - // still call the child nodes using the parent delta only. Do this only if - // an optimization was used to build the delta, so that the child node can - // adds the optimized delta flags without the full delta (bug 280770). - if (childElements == null || childElements.size() == 0) { - if (updateFlagsOnly) { - callChildNodesToBuildDelta( - node, childNodesWithDeltaFlags, parentDelta, event, rm); - } else { - rm.done(); - return; - } - } else { - final CountingRequestMonitor countingRM = new CountingRequestMonitor(getVMProvider().getExecutor(), rm); - int rmCount = 0; - - // For each element from this node, create a new delta, - // and then call all the child nodes to build their delta. - for (int i = 0; i < childElements.size(); i++) { - int elementIndex = nodeOffset >= 0 ? nodeOffset + i : -1; - VMDelta delta= parentDelta.getChildDelta(childElements.get(i)); - if (delta == null) { - delta= parentDelta.addNode(childElements.get(i), elementIndex, IModelDelta.NO_CHANGE); - } - callChildNodesToBuildDelta(node, childNodesWithDeltaFlags, delta, event, countingRM); - rmCount++; - } - countingRM.setDoneCount(rmCount); - } - } - }) - ); - } - } + // + // Element: A + // Flags: CONTENT + // Index: 0 Child Count:-1 + // + // Instead of: + // + // Element: A + // Flags: NO_CHANGE + // Index: 0 Child Count: 1 + // Element: 1 + // Flags: NO_CHANGE + // Index: 0 Child Count: 3 + // Element: I + // Flags: CONTENT + // Index: 0 Child Count: 2 + // Element: II + // Flags: CONTENT + // Index: 1 Child Count: 1 + // Element: III + // Flags: CONTENT + // Index: 2 Child Count: 1 + boolean mustGetElements = false; + boolean _updateFlagsOnly = true; + for (int childDelta : childNodesWithDeltaFlags.values()) { + if ((childDelta & ~IModelDelta.STATE) != 0) { + mustGetElements = true; + } + if ((childDelta & ~(IModelDelta.STATE | IModelDelta.CONTENT)) != 0) { + _updateFlagsOnly = false; + } + } + final boolean updateFlagsOnly = _updateFlagsOnly; + + if (!mustGetElements) { + callChildNodesToBuildDelta(node, childNodesWithDeltaFlags, parentDelta, event, + new RequestMonitor(getVMProvider().getExecutor(), rm) { + @Override + protected void handleError() { + super.handleError(); + } + }); + } else { + // The given child nodes have deltas potentially for all elements + // from this node. Retrieve all elements and call the child nodes with + // each element as the parent of their delta. + getVMProvider().updateNode(node, new VMChildrenUpdate(parentDelta, getVMProvider().getPresentationContext(), + -1, -1, new DataRequestMonitor<List<Object>>(getVMProvider().getExecutor(), rm) { + @Override + protected void handleCompleted() { + if (fDisposed) + return; + + final List<Object> childElements = getData(); + + // Check for an empty list of elements. If the list of elements is empty + // still call the child nodes using the parent delta only. Do this only if + // an optimization was used to build the delta, so that the child node can + // adds the optimized delta flags without the full delta (bug 280770). + if (childElements == null || childElements.size() == 0) { + if (updateFlagsOnly) { + callChildNodesToBuildDelta(node, childNodesWithDeltaFlags, parentDelta, event, rm); + } else { + rm.done(); + return; + } + } else { + final CountingRequestMonitor countingRM = new CountingRequestMonitor( + getVMProvider().getExecutor(), rm); + int rmCount = 0; + + // For each element from this node, create a new delta, + // and then call all the child nodes to build their delta. + for (int i = 0; i < childElements.size(); i++) { + int elementIndex = nodeOffset >= 0 ? nodeOffset + i : -1; + VMDelta delta = parentDelta.getChildDelta(childElements.get(i)); + if (delta == null) { + delta = parentDelta.addNode(childElements.get(i), elementIndex, + IModelDelta.NO_CHANGE); + } + callChildNodesToBuildDelta(node, childNodesWithDeltaFlags, delta, event, + countingRM); + rmCount++; + } + countingRM.setDoneCount(rmCount); + } + } + })); + } + } /** * Calls the specified child nodes (of [node]) to build the delta for the * given event. - * + * * @param childNodes * Map of nodes to be invoked, and the corresponding delta flags * that they may (or will) generate. This map is generated with a @@ -695,218 +677,211 @@ public class DefaultVMModelProxyStrategy implements IVMModelProxy { * @param rm * The result monitor to invoke when the delta is completed. */ - protected void callChildNodesToBuildDelta(final IVMNode node, final Map<IVMNode,Integer> childNodes, final VMDelta delta, - final Object event, final RequestMonitor rm) - { - assert childNodes.size() != 0; + protected void callChildNodesToBuildDelta(final IVMNode node, final Map<IVMNode, Integer> childNodes, + final VMDelta delta, final Object event, final RequestMonitor rm) { + assert childNodes.size() != 0; // Check if any of the child nodes might generate a delta that requires // us to calculate the index for this VMC. - boolean calculateOffsets = false; - for (int childDelta : childNodes.values()) { - if ( (childDelta & (IModelDelta.SELECT | IModelDelta.EXPAND | IModelDelta.INSERTED | IModelDelta.REMOVED)) != 0 ) { - calculateOffsets = true; - break; - } - } - - getChildNodesElementOffsets( - node, delta, calculateOffsets, - new DataRequestMonitor<Map<IVMNode, Integer>>(getVMProvider().getExecutor(), rm) { - @Override - protected void handleSuccess() { - final CountingRequestMonitor multiRm = new CountingRequestMonitor(getVMProvider().getExecutor(), rm); - int multiRmCount = 0; - - // Set the total count of number of children in the parent delta. - delta.setChildCount(getData().get(null)); - - for (final IVMNode childNode : childNodes.keySet()) { - - if (node.equals(childNode)) { - - // Avoid descending into recursive node hierarchy's when calculating the delta. - // if recursive nodes are not allowed. - if( !allowRecursiveVMNodes()) - continue; - - // get into recursion to build the delta only if the recursive context is added. - // - // We user current assumption that recursive container can be added as first children - // if the list of VMNodes. If we decide to make the patch more generic ( allow recursive - // node to be at different index) we need to remove this simplification. - // - if (isDeltaElementOfType(delta, childNode)) { - childNode.buildDelta( - event, delta, 0, - new RequestMonitor(getVMProvider().getExecutor(), multiRm) { - @Override - protected void handleSuccess() { - buildChildDeltas( - childNode, event, delta, 0, - new RequestMonitor(getVMProvider().getExecutor(), multiRm)); - } - }); - multiRmCount++; - } - - continue; - } - - final int nodeOffset = getData().get(childNode); - childNode.buildDelta( - event, delta, nodeOffset, - new RequestMonitor(getVMProvider().getExecutor(), multiRm) { - @Override - protected void handleSuccess() { - buildChildDeltas( - childNode, event, delta, nodeOffset, - new RequestMonitor(getVMProvider().getExecutor(), multiRm)); - } - }); - multiRmCount++; - } - multiRm.setDoneCount(multiRmCount); - } - }); - } - - /** - * Calculates the indexes at which the elements of each of the child - * nodes begin. These indexes are necessary to correctly - * calculate the deltas for elements in the child nodes. - * @param delta The delta object to build on. This delta should have been - * generated by this node, unless the full delta path is not being calculated - * due to an optimization. - * @param doCalculdateOffsets If true, the method calls each node to get its - * element count. If false, it causes this method to fill the return data - * structure with dummy values. The dummy values indicate that the indexes - * are not known and are acceptable in the delta if the delta flags being - * generated do not require full index information. - * @param rm Return token containing the results. The result data is a - * mapping between the child nodes and the indexes at which the child nodes' - * elements begin. There is a special value in the map with a <code>null</code> - * key, which contains the full element count for all the nodes. - */ - private void getChildNodesElementOffsets(IVMNode node, IModelDelta delta, boolean calculdateOffsets, final DataRequestMonitor<Map<IVMNode, Integer>> rm) { - final IVMNode[] childNodes = getVMProvider().getChildVMNodes(node); - assert childNodes.length != 0; - - if (calculdateOffsets) { - final Integer[] counts = new Integer[childNodes.length]; - final CountingRequestMonitor crm = new CountingRequestMonitor(getVMProvider().getExecutor(), rm) { - @Override - protected void handleSuccess() { - Map<IVMNode, Integer> data = new HashMap<IVMNode, Integer>(); - int offset = 0; - for (int i = 0; i < childNodes.length; i++) { - data.put(childNodes[i], offset); - offset += counts[i]; - } - // As the final value, put the total count in the return map, with null key. - data.put(null, offset); - rm.setData(data); - rm.done(); - } - }; - int countRM = 0; - - for (int i = 0; i < childNodes.length; i++) { - final int nodeIndex = i; - getVMProvider().updateNode( - childNodes[i], - new VMChildrenCountUpdate( - delta, getVMProvider().getPresentationContext(), - new DataRequestMonitor<Integer>(getVMProvider().getExecutor(), crm) { - @Override - protected void handleCompleted() { - counts[nodeIndex] = getData(); - crm.done(); - } - } - ) - ); - countRM++; - } - crm.setDoneCount(countRM); - } else { - Map<IVMNode, Integer> data = new HashMap<IVMNode, Integer>(); - for (int i = 0; i < childNodes.length; i++) { - data.put(childNodes[i], -1); - } - data.put(null, -1); - rm.setData(data); - rm.done(); - } - } + boolean calculateOffsets = false; + for (int childDelta : childNodes.values()) { + if ((childDelta + & (IModelDelta.SELECT | IModelDelta.EXPAND | IModelDelta.INSERTED | IModelDelta.REMOVED)) != 0) { + calculateOffsets = true; + break; + } + } + + getChildNodesElementOffsets(node, delta, calculateOffsets, + new DataRequestMonitor<Map<IVMNode, Integer>>(getVMProvider().getExecutor(), rm) { + @Override + protected void handleSuccess() { + final CountingRequestMonitor multiRm = new CountingRequestMonitor(getVMProvider().getExecutor(), + rm); + int multiRmCount = 0; + + // Set the total count of number of children in the parent delta. + delta.setChildCount(getData().get(null)); + + for (final IVMNode childNode : childNodes.keySet()) { + + if (node.equals(childNode)) { + + // Avoid descending into recursive node hierarchy's when calculating the delta. + // if recursive nodes are not allowed. + if (!allowRecursiveVMNodes()) + continue; + + // get into recursion to build the delta only if the recursive context is added. + // + // We user current assumption that recursive container can be added as first children + // if the list of VMNodes. If we decide to make the patch more generic ( allow recursive + // node to be at different index) we need to remove this simplification. + // + if (isDeltaElementOfType(delta, childNode)) { + childNode.buildDelta(event, delta, 0, + new RequestMonitor(getVMProvider().getExecutor(), multiRm) { + @Override + protected void handleSuccess() { + buildChildDeltas(childNode, event, delta, 0, + new RequestMonitor(getVMProvider().getExecutor(), multiRm)); + } + }); + multiRmCount++; + } + + continue; + } + + final int nodeOffset = getData().get(childNode); + childNode.buildDelta(event, delta, nodeOffset, + new RequestMonitor(getVMProvider().getExecutor(), multiRm) { + @Override + protected void handleSuccess() { + buildChildDeltas(childNode, event, delta, nodeOffset, + new RequestMonitor(getVMProvider().getExecutor(), multiRm)); + } + }); + multiRmCount++; + } + multiRm.setDoneCount(multiRmCount); + } + }); + } + + /** + * Calculates the indexes at which the elements of each of the child + * nodes begin. These indexes are necessary to correctly + * calculate the deltas for elements in the child nodes. + * @param delta The delta object to build on. This delta should have been + * generated by this node, unless the full delta path is not being calculated + * due to an optimization. + * @param doCalculdateOffsets If true, the method calls each node to get its + * element count. If false, it causes this method to fill the return data + * structure with dummy values. The dummy values indicate that the indexes + * are not known and are acceptable in the delta if the delta flags being + * generated do not require full index information. + * @param rm Return token containing the results. The result data is a + * mapping between the child nodes and the indexes at which the child nodes' + * elements begin. There is a special value in the map with a <code>null</code> + * key, which contains the full element count for all the nodes. + */ + private void getChildNodesElementOffsets(IVMNode node, IModelDelta delta, boolean calculdateOffsets, + final DataRequestMonitor<Map<IVMNode, Integer>> rm) { + final IVMNode[] childNodes = getVMProvider().getChildVMNodes(node); + assert childNodes.length != 0; + + if (calculdateOffsets) { + final Integer[] counts = new Integer[childNodes.length]; + final CountingRequestMonitor crm = new CountingRequestMonitor(getVMProvider().getExecutor(), rm) { + @Override + protected void handleSuccess() { + Map<IVMNode, Integer> data = new HashMap<IVMNode, Integer>(); + int offset = 0; + for (int i = 0; i < childNodes.length; i++) { + data.put(childNodes[i], offset); + offset += counts[i]; + } + // As the final value, put the total count in the return map, with null key. + data.put(null, offset); + rm.setData(data); + rm.done(); + } + }; + int countRM = 0; + + for (int i = 0; i < childNodes.length; i++) { + final int nodeIndex = i; + getVMProvider().updateNode(childNodes[i], + new VMChildrenCountUpdate(delta, getVMProvider().getPresentationContext(), + new DataRequestMonitor<Integer>(getVMProvider().getExecutor(), crm) { + @Override + protected void handleCompleted() { + counts[nodeIndex] = getData(); + crm.done(); + } + })); + countRM++; + } + crm.setDoneCount(countRM); + } else { + Map<IVMNode, Integer> data = new HashMap<IVMNode, Integer>(); + for (int i = 0; i < childNodes.length; i++) { + data.put(childNodes[i], -1); + } + data.put(null, -1); + rm.setData(data); + rm.done(); + } + } /** * Convenience method that returns what each of the child nodes returns from * {@link #getDeltaFlags(IVMNode, ModelDelta, Object)}. Children that return * IModelDelta.NO_CHANGE are omitted. */ - protected Map<IVMNode, Integer> getChildNodesWithDeltaFlags(IVMNode node, ModelDelta parentDelta, Object e) { - Map<IVMNode, Integer> nodes = new HashMap<IVMNode, Integer>(); - for (final IVMNode childNode : getVMProvider().getChildVMNodes(node)) { - if (!childNode.equals(node) || allowRecursiveVMNodes()) { - int delta = getDeltaFlags(childNode, parentDelta, e); - if (delta != IModelDelta.NO_CHANGE) { - nodes.put(childNode, delta); - } - } - } - return nodes; - } - - /** - * Returns whether DefaultVMModelProxyStrategy allows to handle recursive VMNodes hierarchy. - * - * @see setAllowRecursiveVMNodes() - * @return true if this DefaultVMModelProxyStrategy allows recursive containers. - */ - public boolean allowRecursiveVMNodes() { - return fAllowRecursiveVMNodes; - } - - /** - * Allow DefaultVMModelProxyStrategy to handle recursive VMNodes hierarchy. - * - * For example if the client wants the debug view to display container nodes that - * have containers this flag has to be set. - * - * Launch1 - * Container-1 - * Container-1.1 - * Thread-1 - * Container-1.1.1 - * Thread-2 - * Thread-2 - * - * This will allow the client to setup a VMNode to be in the list of its children. - * addChildNodes(containerNode, new IVMNode[] { containerNode, threadsNode }); - * - * The client also needs to make sure the recursive VMNodes and their immediate children: - * 1. Handle buildDelta() by building one level at a time by examining the delta passed as parameter. - * 2. Return the correct level container inside getContextsForEvent() based on the delta passed. - * - * See org.eclipse.cdt.dsf.gdb.internal.ui.viewmodel.launch.ContainerVMNode for sample implementation. - * - * @param allow - whether to allow or not recursive containment of VMNodes. - */ - public void setAllowRecursiveVMNodes(boolean allow) { - fAllowRecursiveVMNodes = allow; - } - - /** - * Compares if the VMNode of element of the provided delta is the same as the provided IVMNode. - * - * @param delta - delta for which to compare the IDMVMContext - * @param node - the IVMNode we want to compare to. - * @return if the VMNode of element of the provided delta is the same as the provided IVMNode. - */ + protected Map<IVMNode, Integer> getChildNodesWithDeltaFlags(IVMNode node, ModelDelta parentDelta, Object e) { + Map<IVMNode, Integer> nodes = new HashMap<IVMNode, Integer>(); + for (final IVMNode childNode : getVMProvider().getChildVMNodes(node)) { + if (!childNode.equals(node) || allowRecursiveVMNodes()) { + int delta = getDeltaFlags(childNode, parentDelta, e); + if (delta != IModelDelta.NO_CHANGE) { + nodes.put(childNode, delta); + } + } + } + return nodes; + } + + /** + * Returns whether DefaultVMModelProxyStrategy allows to handle recursive VMNodes hierarchy. + * + * @see setAllowRecursiveVMNodes() + * @return true if this DefaultVMModelProxyStrategy allows recursive containers. + */ + public boolean allowRecursiveVMNodes() { + return fAllowRecursiveVMNodes; + } + + /** + * Allow DefaultVMModelProxyStrategy to handle recursive VMNodes hierarchy. + * + * For example if the client wants the debug view to display container nodes that + * have containers this flag has to be set. + * + * Launch1 + * Container-1 + * Container-1.1 + * Thread-1 + * Container-1.1.1 + * Thread-2 + * Thread-2 + * + * This will allow the client to setup a VMNode to be in the list of its children. + * addChildNodes(containerNode, new IVMNode[] { containerNode, threadsNode }); + * + * The client also needs to make sure the recursive VMNodes and their immediate children: + * 1. Handle buildDelta() by building one level at a time by examining the delta passed as parameter. + * 2. Return the correct level container inside getContextsForEvent() based on the delta passed. + * + * See org.eclipse.cdt.dsf.gdb.internal.ui.viewmodel.launch.ContainerVMNode for sample implementation. + * + * @param allow - whether to allow or not recursive containment of VMNodes. + */ + public void setAllowRecursiveVMNodes(boolean allow) { + fAllowRecursiveVMNodes = allow; + } + + /** + * Compares if the VMNode of element of the provided delta is the same as the provided IVMNode. + * + * @param delta - delta for which to compare the IDMVMContext + * @param node - the IVMNode we want to compare to. + * @return if the VMNode of element of the provided delta is the same as the provided IVMNode. + */ protected boolean isDeltaElementOfType(VMDelta delta, IVMNode node) { if (delta.getElement() instanceof IDMVMContext) { - IDMVMContext dmvmContext = (IDMVMContext)delta.getElement(); + IDMVMContext dmvmContext = (IDMVMContext) delta.getElement(); return dmvmContext.getVMNode().equals(node); } return false; diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IRootVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IRootVMNode.java index be776445a06..0948c178a50 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IRootVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IRootVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,24 +19,24 @@ import org.eclipse.cdt.dsf.concurrent.DataRequestMonitor; * Special type of the view model node, which can be used as a root node * for a hierarchy. The root node of a layout hierarchy has to implement this * interface. - * + * * @since 1.0 */ -public interface IRootVMNode extends IVMNode{ - - /** - * Returns whether the given event should be processed for delta generation. - * Root node is different than other nodes in that there is only one root - * element in the view model provider hierarchy. This method allows the root - * node to match up the root object of the provider with the given event. If - * the root node can determine that the given event does not apply to the root - * object, it should return false so that the event is ignored. - * - * @param rootObject The root object of the VM provider - * @param event - * @return - */ - public boolean isDeltaEvent(Object rootObject, Object event); +public interface IRootVMNode extends IVMNode { + + /** + * Returns whether the given event should be processed for delta generation. + * Root node is different than other nodes in that there is only one root + * element in the view model provider hierarchy. This method allows the root + * node to match up the root object of the provider with the given event. If + * the root node can determine that the given event does not apply to the root + * object, it should return false so that the event is ignored. + * + * @param rootObject The root object of the VM provider + * @param event + * @return + */ + public boolean isDeltaEvent(Object rootObject, Object event); /** * The VM proxy calls this to produce the starting point for a delta, which @@ -51,8 +51,8 @@ public interface IRootVMNode extends IVMNode{ * of delta nodes that reflect the path to the VMProvider's root element, * since deltas sent to the viewer must take into account the entire model. * However, the specific delta node returned should be the one associated - * with [rootObject]--i.e., the last node in the chain. - * + * with [rootObject]--i.e., the last node in the chain. + * * @param rootObject * the root model element being represented by our VMProvider * @param event diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMAdapter.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMAdapter.java index 756ef228b69..f108cbdcbf6 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMAdapter.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMAdapter.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -21,30 +21,29 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationCont import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerInputProvider; /** - * The View Model adapter handles the layout of a given data model within a - * set of viewers. This adapter should be returned by an adapter factory for - * the input object of the viewer, and this adapter implementation will then - * populate the view contents. - * + * The View Model adapter handles the layout of a given data model within a + * set of viewers. This adapter should be returned by an adapter factory for + * the input object of the viewer, and this adapter implementation will then + * populate the view contents. + * * @since 1.0 */ @ThreadSafe public interface IVMAdapter - extends IElementContentProvider, IModelProxyFactory, IColumnPresentationFactory, IViewerInputProvider -{ - /** - * Returns the View Model Provider that is registered for the given presentation - * context. Returns <code>null</code> if there is none. - */ - public IVMProvider getVMProvider(IPresentationContext presentationContext); + extends IElementContentProvider, IModelProxyFactory, IColumnPresentationFactory, IViewerInputProvider { + /** + * Returns the View Model Provider that is registered for the given presentation + * context. Returns <code>null</code> if there is none. + */ + public IVMProvider getVMProvider(IPresentationContext presentationContext); - /** - * Retrieves the currently active VM providers in this adapter. - * - * @return array of VM providers - * - * @since 2.0 - */ - public IVMProvider[] getActiveProviders(); + /** + * Retrieves the currently active VM providers in this adapter. + * + * @return array of VM providers + * + * @since 2.0 + */ + public IVMProvider[] getActiveProviders(); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMContext.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMContext.java index 45e9872c7d2..aa9138020ab 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMContext.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMContext.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -17,18 +17,18 @@ import org.eclipse.cdt.dsf.concurrent.Immutable; import org.eclipse.core.runtime.IAdaptable; /** - * View model element which is stored as the data object of nodes in the viewer. - * The implementation of this interface is usually a wrapper object for an object - * from some data model, which is then used to correctly implement the + * View model element which is stored as the data object of nodes in the viewer. + * The implementation of this interface is usually a wrapper object for an object + * from some data model, which is then used to correctly implement the * {@link #equals(Object)} and {@link #hashCode()} methods of this wrapper. - * + * * @since 1.0 */ @Immutable public interface IVMContext extends IAdaptable { - - /** - * Returns the view model node that originated this element. - */ - public IVMNode getVMNode(); + + /** + * Returns the view model node that originated this element. + */ + public IVMNode getVMNode(); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMEventListener.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMEventListener.java index 6c28a602fc3..80564197ba9 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMEventListener.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMEventListener.java @@ -21,18 +21,18 @@ import org.eclipse.cdt.dsf.concurrent.ThreadSafe; /** * A listener participating in event notifications sent out from VM adapter. - * + * * @since 1.1 */ @ConfinedToDsfExecutor("#getExecutor()") public interface IVMEventListener { - /** - * Returns the executor that needs to be used to access this event listener. - */ - @ThreadSafe - public Executor getExecutor(); - + /** + * Returns the executor that needs to be used to access this event listener. + */ + @ThreadSafe + public Executor getExecutor(); + /** * Process the given event and indicate completion with request monitor. */ diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMModelProxy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMModelProxy.java index 633feb7b4c8..3223935bb5c 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMModelProxy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMModelProxy.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -22,71 +22,71 @@ import org.eclipse.jface.viewers.Viewer; /** * View Model extension to the platform IModelProxy interface. This extension * allows the IVMProvider implementation to delegate the model proxy implementation - * into a separate object. - * <br/> - * Note: The IVMModelProxy.init() may be called twice when installed, as a - * workaround for bug 241024. - * + * into a separate object. + * <br/> + * Note: The IVMModelProxy.init() may be called twice when installed, as a + * workaround for bug 241024. + * * @since 1.0 */ public interface IVMModelProxy extends IModelProxy { - /** - * Returns the root element that this model proxy was created for. - */ - public Object getRootElement(); - - /** - * Returns whether the given event applies to the root element and the - * nodes in this model proxy. - * <p> - * This method is the equivalent of calling - * <code> getEventDeltaFlags(event) != IModelDelta.NO_CHANGE </code>. - * </p> - */ - public boolean isDeltaEvent(Object event); + /** + * Returns the root element that this model proxy was created for. + */ + public Object getRootElement(); + + /** + * Returns whether the given event applies to the root element and the + * nodes in this model proxy. + * <p> + * This method is the equivalent of calling + * <code> getEventDeltaFlags(event) != IModelDelta.NO_CHANGE </code>. + * </p> + */ + public boolean isDeltaEvent(Object event); - /** - * Creates a model delta for the given event. - */ - public void createDelta(final Object event, final DataRequestMonitor<IModelDelta> rm); + /** + * Creates a model delta for the given event. + */ + public void createDelta(final Object event, final DataRequestMonitor<IModelDelta> rm); - /** - * Sends the given delta to this model proxy's listeners. - */ - public void fireModelChanged(IModelDelta delta); + /** + * Sends the given delta to this model proxy's listeners. + */ + public void fireModelChanged(IModelDelta delta); - /** - * Returns the viewer. - * - * @since 2.0 - */ - public Viewer getViewer(); + /** + * Returns the viewer. + * + * @since 2.0 + */ + public Viewer getViewer(); - /** - * Returns the viewer input that was set to the viewer when this proxy - * was created. - * - * @since 2.0 - */ - public Object getViewerInput(); + /** + * Returns the viewer input that was set to the viewer when this proxy + * was created. + * + * @since 2.0 + */ + public Object getViewerInput(); - /** - * Returns the full path for the root element. If the path is empty, it - * means that the root element is the viewer input. - * - * @since 2.0 - */ - public TreePath getRootPath(); + /** + * Returns the full path for the root element. If the path is empty, it + * means that the root element is the viewer input. + * + * @since 2.0 + */ + public TreePath getRootPath(); - /** - * Returns the delta flags associated with this event. This method is - * - * @param event - * @return - * - * @since 2.1 - */ - public int getEventDeltaFlags(Object event); + /** + * Returns the delta flags associated with this event. This method is + * + * @param event + * @return + * + * @since 2.1 + */ + public int getEventDeltaFlags(Object event); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMNode.java index 6c55738f883..d4f064effd7 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -25,36 +25,35 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IHasChildrenUpdat import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDelta; /** - * View model nodes are configured with a view model provider to collectively - * define the layout of a view. Each layout node generates elements of type + * View model nodes are configured with a view model provider to collectively + * define the layout of a view. Each layout node generates elements of type * {@link IVMContext} which are then stored in the viewer. - * + * * <p/> - * NOTE: This interface extends <code>IElementContentProvider</code> but it has - * slightly different parameter requirements. For the - * {@link IElementContentProvider#update(IChildrenUpdate[])} method, this class - * can accept an update where {@link IChildrenUpdate#getOffset()} and - * {@link IChildrenUpdate#getLength()} may return -1. In this case the + * NOTE: This interface extends <code>IElementContentProvider</code> but it has + * slightly different parameter requirements. For the + * {@link IElementContentProvider#update(IChildrenUpdate[])} method, this class + * can accept an update where {@link IChildrenUpdate#getOffset()} and + * {@link IChildrenUpdate#getLength()} may return -1. In this case the * implementation should return all available elements for the given parent.<br> - * Also the for the {@link IElementContentProvider#update(IHasChildrenUpdate[])} and - * {@link IElementContentProvider#update(IChildrenCountUpdate[])} methods, the - * implementation may return an error with an error code of {@link IDsfService#NOT_SUPPORTED}. - * In this case the caller of this update should call + * Also the for the {@link IElementContentProvider#update(IHasChildrenUpdate[])} and + * {@link IElementContentProvider#update(IChildrenCountUpdate[])} methods, the + * implementation may return an error with an error code of {@link IDsfService#NOT_SUPPORTED}. + * In this case the caller of this update should call * {@link IElementContentProvider#update(IChildrenUpdate[])} * instead. - * + * * @see AbstractDMVMProvider * @see IElementContentProvider - * + * * @since 1.0 */ @ConfinedToDsfExecutor("") -public interface IVMNode extends IElementContentProvider -{ - /** - * Retrieves the view model provider that this node is configured with. - */ - public IVMProvider getVMProvider(); +public interface IVMNode extends IElementContentProvider { + /** + * Retrieves the view model provider that this node is configured with. + */ + public IVMProvider getVMProvider(); /** * Returns a set of IModelDelta delta flags that indicate how elements of @@ -64,19 +63,19 @@ public interface IVMNode extends IElementContentProvider * <i>may</i> be affected). If a delta flag is not returned, it means for * certain that elements of this node will not be affected in that way. That * information allows us to optimize the delta creation. - * + * * <p> * A response of IModeDelta.CONTENT has a special meaning. If we return that * flag, it means the <i>collection</i> of elements of our type are * affected. It is not a statement on the elements themselves. - * + * * @param event * the event the caller is processing * @return IModelDelta flags * @see #buildDelta(Object, VMDelta, int, RequestMonitor) * @see IModelDelta */ - public int getDeltaFlags(Object event); + public int getDeltaFlags(Object event); /** * Builds model delta information based on the given event. @@ -99,7 +98,7 @@ public interface IVMNode extends IElementContentProvider * <i>might</i> end up adding to the delta, but it doesn't mean we are * obligated to or will. * </p> - * + * * @param event * Event to process. * @param parent @@ -113,27 +112,27 @@ public interface IVMNode extends IElementContentProvider * Return token, which notifies the caller that the calculation * is complete. */ - public void buildDelta(Object event, VMDelta parent, int nodeOffset, RequestMonitor requestMonitor); + public void buildDelta(Object event, VMDelta parent, int nodeOffset, RequestMonitor requestMonitor); - /** - * Retrieves the view model elements for the given data model event. This method - * is optional and it allows the view model provider to optimize event processing - * by avoiding the need to retrieve all possible elements for the given node. - * </p> - * For example: If a threads node implementation is given a thread stopped event in - * this method, and the stopped event included a reference to the thread. Then - * the implementation should create a view model context for that thread and return it - * here. - * - * @param parentDelta The parent delta in the processing of this event. - * @param event The event to check for the data model object. - * @param Request monitor for the array of elements corresponding to the - * given event. - */ - public void getContextsForEvent(VMDelta parentDelta, Object event, DataRequestMonitor<IVMContext[]> rm); + /** + * Retrieves the view model elements for the given data model event. This method + * is optional and it allows the view model provider to optimize event processing + * by avoiding the need to retrieve all possible elements for the given node. + * </p> + * For example: If a threads node implementation is given a thread stopped event in + * this method, and the stopped event included a reference to the thread. Then + * the implementation should create a view model context for that thread and return it + * here. + * + * @param parentDelta The parent delta in the processing of this event. + * @param event The event to check for the data model object. + * @param Request monitor for the array of elements corresponding to the + * given event. + */ + public void getContextsForEvent(VMDelta parentDelta, Object event, DataRequestMonitor<IVMContext[]> rm); - /** - * Releases the resources held by this node. - */ - public void dispose(); + /** + * Releases the resources held by this node. + */ + public void dispose(); }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMProvider.java index f45d13089f1..ffa12b6ed5f 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/IVMProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -27,94 +27,92 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationCont import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerInputProvider; /** - * The view model provider handles the layout of a given model within a - * single viewer. The View Model Adapter delegates calls for view content to + * The view model provider handles the layout of a given model within a + * single viewer. The View Model Adapter delegates calls for view content to * this object for a view that this provider handles. - * + * * <p/> - * A given view model provider is typically configured with a number of - * {@link IVMNode} objects which are organized in a parent-child hierarchy. - * The node hierarchy has a root node which is retrieved using {@link #getRootVMNode()}. + * A given view model provider is typically configured with a number of + * {@link IVMNode} objects which are organized in a parent-child hierarchy. + * The node hierarchy has a root node which is retrieved using {@link #getRootVMNode()}. * * <p/> - * Note on concurency: The view model provider is single-threaded and it has to be - * accessed only using the <code>Executor</code> returned by {@link #getExecutor()}. + * Note on concurency: The view model provider is single-threaded and it has to be + * accessed only using the <code>Executor</code> returned by {@link #getExecutor()}. * The thread of this executor should be the display thread used by the viewer - * corresponding to the view model provider. Currently the flexible hierarchy + * corresponding to the view model provider. Currently the flexible hierarchy * interfaces that this interface extends do not guarantee that their methods - * will be called on the display thread, although from their use we are making - * this assumption (bug 213629). {@link IElementContentProvider} is an - * exception to this, it is called by the TreeModelViewer on a background - * thread, however it is not expected that the viewer will be calling the - * IVMProvider directly. Rather, it is expected that the viewer will call - * {@link IVMAdapter} which implements <code>IElementContentProvider</code>, - * and <code>IVMAdapter</code> implementation is expected to switch to + * will be called on the display thread, although from their use we are making + * this assumption (bug 213629). {@link IElementContentProvider} is an + * exception to this, it is called by the TreeModelViewer on a background + * thread, however it is not expected that the viewer will be calling the + * IVMProvider directly. Rather, it is expected that the viewer will call + * {@link IVMAdapter} which implements <code>IElementContentProvider</code>, + * and <code>IVMAdapter</code> implementation is expected to switch to * provider's thread before delegating the call to it. - * + * * @since 1.0 */ @ConfinedToDsfExecutor("#getExecutor()") -public interface IVMProvider - extends IElementContentProvider, IModelProxyFactory, IColumnPresentationFactory, IViewerInputProvider -{ - /** - * Returns the presentation context of the viewer that this provider - * is configured for. - */ - public IPresentationContext getPresentationContext(); +public interface IVMProvider + extends IElementContentProvider, IModelProxyFactory, IColumnPresentationFactory, IViewerInputProvider { + /** + * Returns the presentation context of the viewer that this provider + * is configured for. + */ + public IPresentationContext getPresentationContext(); + + /** + * Returns the VM Adapter associated with the provider. + */ + public IVMAdapter getVMAdapter(); + + /** + * Returns the executor that needs to be used to access this provider. + */ + @ThreadSafe + public Executor getExecutor(); + + /** + * Returns the root node that is configured in this provider. + * It may return null, if a root node is not yet configured. + */ + public IRootVMNode getRootVMNode(); + + /** + * Returns an array of nodes which are configured as child nodes of the given node. + */ + public IVMNode[] getChildVMNodes(IVMNode node); + + /** + * Retrieves the list of all nodes configured for this provider. + */ + public IVMNode[] getAllVMNodes(); - /** - * Returns the VM Adapter associated with the provider. - */ - public IVMAdapter getVMAdapter(); - - /** - * Returns the executor that needs to be used to access this provider. - */ - @ThreadSafe - public Executor getExecutor(); - - /** - * Returns the root node that is configured in this provider. - * It may return null, if a root node is not yet configured. - */ - public IRootVMNode getRootVMNode(); + /** + * Calls the given view model node to perform the given updates. This + * method is different than calling the IVMNode update method directly in that + * it allows the provider to do additional processing on the update such as caching. + */ + public void updateNode(final IVMNode node, IHasChildrenUpdate[] updates); - /** - * Returns an array of nodes which are configured as child nodes of the given node. - */ - public IVMNode[] getChildVMNodes(IVMNode node); + /** + * Calls the given view model node to perform the given updates. This + * method is different than calling the IVMNode update method directly in that + * it allows the provider to do additional processing on the update such as caching. + */ + public void updateNode(final IVMNode node, IChildrenCountUpdate updates); - /** - * Retrieves the list of all nodes configured for this provider. - */ - public IVMNode[] getAllVMNodes(); - - /** - * Calls the given view model node to perform the given updates. This - * method is different than calling the IVMNode update method directly in that - * it allows the provider to do additional processing on the update such as caching. - */ - public void updateNode(final IVMNode node, IHasChildrenUpdate[] updates); - - /** - * Calls the given view model node to perform the given updates. This - * method is different than calling the IVMNode update method directly in that - * it allows the provider to do additional processing on the update such as caching. - */ - public void updateNode(final IVMNode node, IChildrenCountUpdate updates); + /** + * Calls the given view model node to perform the given updates. This + * method is different than calling the IVMNode update method directly in that + * it allows the provider to do additional processing on the update such as caching. + */ + public void updateNode(IVMNode node, IChildrenUpdate updates); - /** - * Calls the given view model node to perform the given updates. This - * method is different than calling the IVMNode update method directly in that - * it allows the provider to do additional processing on the update such as caching. - */ - public void updateNode(IVMNode node, IChildrenUpdate updates); + /** + * Cleans up the resources associated with this provider. + */ + public void dispose(); - - /** - * Cleans up the resources associated with this provider. - */ - public void dispose(); - } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/ModelProxyInstalledEvent.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/ModelProxyInstalledEvent.java index 8b75765749a..584041d74a3 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/ModelProxyInstalledEvent.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/ModelProxyInstalledEvent.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -17,40 +17,40 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelProxy; import org.eclipse.jface.viewers.Viewer; /** - * Event generated by an IModelProxy implementation when it is installed + * Event generated by an IModelProxy implementation when it is installed * into a viewer. - * + * * @since 1.0 */ public class ModelProxyInstalledEvent { - private final IModelProxy fProxy; - private final Viewer fViewer; - private final Object fRootElement; - - public ModelProxyInstalledEvent(IModelProxy proxy, Viewer viewer, Object rootElement) { - fProxy = proxy; - fViewer = viewer; - fRootElement = rootElement; - } - - /** - * Returns the IModelProxy that generated this event. - */ - public IModelProxy getModelProxy() { - return fProxy; - } + private final IModelProxy fProxy; + private final Viewer fViewer; + private final Object fRootElement; + + public ModelProxyInstalledEvent(IModelProxy proxy, Viewer viewer, Object rootElement) { + fProxy = proxy; + fViewer = viewer; + fRootElement = rootElement; + } + + /** + * Returns the IModelProxy that generated this event. + */ + public IModelProxy getModelProxy() { + return fProxy; + } - /** - * Returns the element that this model proxy was registered for. - */ - public Object getRootElement() { - return fRootElement; - } + /** + * Returns the element that this model proxy was registered for. + */ + public Object getRootElement() { + return fRootElement; + } - /** - * Returns the viewer that installed this model proxy. - */ - public Viewer getViewer() { - return fViewer; - } + /** + * Returns the viewer that installed this model proxy. + */ + public Viewer getViewer() { + return fViewer; + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/RootVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/RootVMNode.java index 602b0d3847e..dc9c1669447 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/RootVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/RootVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -23,60 +23,59 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDelta; /** * Default implementation of a root view model node. This class may be sub-classed * to implement model-specific event handling. - * + * * @since 1.0 */ public class RootVMNode extends AbstractVMNode implements IRootVMNode { - public RootVMNode(AbstractVMProvider provider) { - super(provider); - } + public RootVMNode(AbstractVMProvider provider) { + super(provider); + } + + @Override + public void update(IChildrenUpdate[] updates) { + throw new UnsupportedOperationException("Root view model node should never be queried for list of elements."); //$NON-NLS-1$ + } + + @Override + public void update(IChildrenCountUpdate[] updates) { + throw new UnsupportedOperationException("Root view model node should never be queried for list of elements."); //$NON-NLS-1$ + } + + @Override + public void update(IHasChildrenUpdate[] updates) { + throw new UnsupportedOperationException("Root view model node should never be queried for list of elements."); //$NON-NLS-1$ + } + + /** + * Default implementation does not examine the event and assumes that every + * event should be processed to generate a delta. + */ + @Override + public boolean isDeltaEvent(Object rootObject, Object event) { + if (event instanceof ModelProxyInstalledEvent) { + return rootObject.equals(((ModelProxyInstalledEvent) event).getRootElement()); + } + return true; + } - @Override - public void update(IChildrenUpdate[] updates) { - throw new UnsupportedOperationException("Root view model node should never be queried for list of elements."); //$NON-NLS-1$ - } - - @Override - public void update(IChildrenCountUpdate[] updates) { - throw new UnsupportedOperationException("Root view model node should never be queried for list of elements."); //$NON-NLS-1$ - } + /** + * Default implementation creates a delta assuming that the root layout node + * is the input object into the view. + */ + @Override + public void createRootDelta(Object rootObject, Object event, final DataRequestMonitor<VMDelta> rm) { + rm.setData(new VMDelta(rootObject, 0, IModelDelta.NO_CHANGE)); + rm.done(); + } - @Override - public void update(IHasChildrenUpdate[] updates) { - throw new UnsupportedOperationException("Root view model node should never be queried for list of elements."); //$NON-NLS-1$ - } + @Override + public int getDeltaFlags(Object event) { + return IModelDelta.NO_CHANGE; + } - /** - * Default implementation does not examine the event and assumes that every - * event should be processed to generate a delta. - */ - @Override - public boolean isDeltaEvent(Object rootObject, Object event) { - if (event instanceof ModelProxyInstalledEvent) { - return rootObject.equals( ((ModelProxyInstalledEvent)event).getRootElement() ); - } - return true; - } - - /** - * Default implementation creates a delta assuming that the root layout node - * is the input object into the view. - */ - @Override - public void createRootDelta(Object rootObject, Object event, final DataRequestMonitor<VMDelta> rm) { - rm.setData(new VMDelta(rootObject, 0, IModelDelta.NO_CHANGE)); - rm.done(); - } - - - @Override - public int getDeltaFlags(Object event) { - return IModelDelta.NO_CHANGE; - } - - @Override - public void buildDelta(Object event, VMDelta parent, int nodeOffset, RequestMonitor requestMonitor) { - requestMonitor.done(); - } + @Override + public void buildDelta(Object event, VMDelta parent, int nodeOffset, RequestMonitor requestMonitor) { + requestMonitor.done(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMChildrenCountUpdate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMChildrenCountUpdate.java index 3e1bc52808a..6d730129c5b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMChildrenCountUpdate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMChildrenCountUpdate.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -24,55 +24,58 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationCont import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; import org.eclipse.jface.viewers.TreePath; import org.eclipse.cdt.dsf.debug.internal.ui.viewmodel.VMViewerUpdateTracing; -/** + +/** * Helper class implementation of the {@link IChildrenCountUpdate} update object. - * + * * @see VMViewerUpdate - * + * * @since 1.0 */ public class VMChildrenCountUpdate extends VMViewerUpdate implements IChildrenCountUpdate { - final private DataRequestMonitor<Integer> fCountRequestMonitor; - - public VMChildrenCountUpdate(IViewerUpdate clientUpdate, DataRequestMonitor<Integer> rm) { - super(clientUpdate, rm); - fCountRequestMonitor = rm; - } + final private DataRequestMonitor<Integer> fCountRequestMonitor; - public VMChildrenCountUpdate(IModelDelta delta, IPresentationContext presentationContext, DataRequestMonitor<Integer> rm) { - super(delta, presentationContext, rm); - fCountRequestMonitor = rm; - } + public VMChildrenCountUpdate(IViewerUpdate clientUpdate, DataRequestMonitor<Integer> rm) { + super(clientUpdate, rm); + fCountRequestMonitor = rm; + } - public VMChildrenCountUpdate(TreePath elementPath, Object viewerInput, IPresentationContext presentationContext, DataRequestMonitor<Integer> rm) { - super(elementPath, viewerInput, presentationContext, rm); - fCountRequestMonitor = rm; - } + public VMChildrenCountUpdate(IModelDelta delta, IPresentationContext presentationContext, + DataRequestMonitor<Integer> rm) { + super(delta, presentationContext, rm); + fCountRequestMonitor = rm; + } - @Override + public VMChildrenCountUpdate(TreePath elementPath, Object viewerInput, IPresentationContext presentationContext, + DataRequestMonitor<Integer> rm) { + super(elementPath, viewerInput, presentationContext, rm); + fCountRequestMonitor = rm; + } + + @Override public void setChildCount(int count) { - fCountRequestMonitor.setData(count); - } - - @Override - public String toString() { - return "VMChildrenCountUpdate: " + getElement(); //$NON-NLS-1$ - } - - @Override - public void done() { - assert isCanceled() || fCountRequestMonitor.getData() != null || !fCountRequestMonitor.isSuccess(); + fCountRequestMonitor.setData(count); + } + + @Override + public String toString() { + return "VMChildrenCountUpdate: " + getElement(); //$NON-NLS-1$ + } - // trace our result - if (VMViewerUpdateTracing.DEBUG_VMUPDATES && !isCanceled() && VMViewerUpdateTracing.matchesFilterRegex(this.getClass())) { - final Integer data = fCountRequestMonitor.getData(); + @Override + public void done() { + assert isCanceled() || fCountRequestMonitor.getData() != null || !fCountRequestMonitor.isSuccess(); + + // trace our result + if (VMViewerUpdateTracing.DEBUG_VMUPDATES && !isCanceled() + && VMViewerUpdateTracing.matchesFilterRegex(this.getClass())) { + final Integer data = fCountRequestMonitor.getData(); DsfUIPlugin.debug(DsfPlugin.getDebugTime() + " " //$NON-NLS-1$ + LoggingUtils.toString(this) + " marked done; element = " //$NON-NLS-1$ - + LoggingUtils.toString(getElement()) - + "\n child count = " + (data != null ? data : "<unset>") ); //$NON-NLS-1$ //$NON-NLS-2$ - } - - super.done(); - } + + LoggingUtils.toString(getElement()) + "\n child count = " + (data != null ? data : "<unset>")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + super.done(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMChildrenUpdate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMChildrenUpdate.java index 69186809ff3..570ab37e747 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMChildrenUpdate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMChildrenUpdate.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -27,121 +27,121 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationCont import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; import org.eclipse.jface.viewers.TreePath; -/** +/** * Helper class implementation of the {@link IChildrenUpdate} update object. - * + * * @see VMViewerUpdate - * + * * @since 1.0 */ public class VMChildrenUpdate extends VMViewerUpdate implements IChildrenUpdate { - private final int fOffset; - private final int fLength; - protected final List<Object> fElements; - - public VMChildrenUpdate(IViewerUpdate clientUpdate, int offset, int length, - DataRequestMonitor<List<Object>> requestMonitor) - { - super(clientUpdate, requestMonitor); - fOffset = offset; - fLength = length; - fElements = length > 0 ? new ArrayList<Object>(length) : new ArrayList<Object>(); - } - - public VMChildrenUpdate(IModelDelta delta, IPresentationContext presentationContext, int offset, int length, - DataRequestMonitor<List<Object>> rm) - { - super(delta, presentationContext, rm); - fOffset = offset; - fLength = length; - fElements = length > 0 ? new ArrayList<Object>(length) : new ArrayList<Object>(); - } - - public VMChildrenUpdate(TreePath elementPath, Object viewerInput, IPresentationContext presentationContext, - int offset, int length, DataRequestMonitor<List<Object>> rm) - { - super(elementPath, viewerInput, presentationContext, rm); - fOffset = offset; - fLength = length; - fElements = length > 0 ? new ArrayList<Object>(length) : new ArrayList<Object>(); - } - - @Override + private final int fOffset; + private final int fLength; + protected final List<Object> fElements; + + public VMChildrenUpdate(IViewerUpdate clientUpdate, int offset, int length, + DataRequestMonitor<List<Object>> requestMonitor) { + super(clientUpdate, requestMonitor); + fOffset = offset; + fLength = length; + fElements = length > 0 ? new ArrayList<Object>(length) : new ArrayList<Object>(); + } + + public VMChildrenUpdate(IModelDelta delta, IPresentationContext presentationContext, int offset, int length, + DataRequestMonitor<List<Object>> rm) { + super(delta, presentationContext, rm); + fOffset = offset; + fLength = length; + fElements = length > 0 ? new ArrayList<Object>(length) : new ArrayList<Object>(); + } + + public VMChildrenUpdate(TreePath elementPath, Object viewerInput, IPresentationContext presentationContext, + int offset, int length, DataRequestMonitor<List<Object>> rm) { + super(elementPath, viewerInput, presentationContext, rm); + fOffset = offset; + fLength = length; + fElements = length > 0 ? new ArrayList<Object>(length) : new ArrayList<Object>(); + } + + @Override public int getOffset() { - return fOffset; - } + return fOffset; + } - @Override + @Override public int getLength() { - return fLength; - } + return fLength; + } - @Override + @Override public void setChild(Object element, int offset) { - // Calculate the index in array based on configured offset. - int idx = offset - (fOffset > 0 ? fOffset : 0); - - // To make sure that index is in valid range. - if (idx < 0 || (fLength > 0 && idx >= fLength)) return; - - // Increase the list size if needed. - ensureElementsSize(idx + 1); - - // Finally set the element in elements list. - fElements.set(idx, element); - } - - private void ensureElementsSize(int size) { - while (fElements.size() < size) { - fElements.add(null); - } - } - - @Override - public String toString() { - return "VMChildrenUpdate:" + getElement() + " {"+ getOffset() + "->" + (getOffset() + getLength()) + "}"; //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$ //$NON-NLS-4$ - } - - @Override - public void done() { - @SuppressWarnings("unchecked") - DataRequestMonitor<List<Object>> rm = (DataRequestMonitor<List<Object>>)getRequestMonitor(); - - /* See https://bugs.eclipse.org/bugs/show_bug.cgi?id=202109 - * - * A flexible hierarchy bug/optimization causes query with incorrect - * IChildrenUpdate[] array length. - * - * The problem manifests itself while deleting a register node. - * For example, if the register view displays: - * PC - * EAX - * EBX - * ECX - * EDX - * And EBX is deleted, forcing a refresh, the viewer will query - * for IChildrenUpdate[5] and IChildrenCountUpdate at the same time. - * - * To avoid this problem do not generate an error if the list of - * children is smaller than the list of requested indexes. Also, - * do not check if any of the elements are null. - */ - rm.setData(fElements); - - // trace our result - if (VMViewerUpdateTracing.DEBUG_VMUPDATES && !isCanceled() && VMViewerUpdateTracing.matchesFilterRegex(this.getClass())) { - StringBuilder str = new StringBuilder(); - str.append(DsfPlugin.getDebugTime()).append(' ').append(LoggingUtils.toString(this)).append(" marked done; element = ").append(LoggingUtils.toString(getElement())); //$NON-NLS-1$ - if (fElements != null && !fElements.isEmpty()) { - for (Object element : fElements) { - str.append(" ").append(LoggingUtils.toString(element)).append('\n'); //$NON-NLS-1$ - } - str.deleteCharAt(str.length()-1); // remove trailing \n - } - DsfUIPlugin.debug(str.toString()); - } - - super.done(); - } - + // Calculate the index in array based on configured offset. + int idx = offset - (fOffset > 0 ? fOffset : 0); + + // To make sure that index is in valid range. + if (idx < 0 || (fLength > 0 && idx >= fLength)) + return; + + // Increase the list size if needed. + ensureElementsSize(idx + 1); + + // Finally set the element in elements list. + fElements.set(idx, element); + } + + private void ensureElementsSize(int size) { + while (fElements.size() < size) { + fElements.add(null); + } + } + + @Override + public String toString() { + return "VMChildrenUpdate:" + getElement() + " {" + getOffset() + "->" + (getOffset() + getLength()) + "}"; //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$ //$NON-NLS-4$ + } + + @Override + public void done() { + @SuppressWarnings("unchecked") + DataRequestMonitor<List<Object>> rm = (DataRequestMonitor<List<Object>>) getRequestMonitor(); + + /* See https://bugs.eclipse.org/bugs/show_bug.cgi?id=202109 + * + * A flexible hierarchy bug/optimization causes query with incorrect + * IChildrenUpdate[] array length. + * + * The problem manifests itself while deleting a register node. + * For example, if the register view displays: + * PC + * EAX + * EBX + * ECX + * EDX + * And EBX is deleted, forcing a refresh, the viewer will query + * for IChildrenUpdate[5] and IChildrenCountUpdate at the same time. + * + * To avoid this problem do not generate an error if the list of + * children is smaller than the list of requested indexes. Also, + * do not check if any of the elements are null. + */ + rm.setData(fElements); + + // trace our result + if (VMViewerUpdateTracing.DEBUG_VMUPDATES && !isCanceled() + && VMViewerUpdateTracing.matchesFilterRegex(this.getClass())) { + StringBuilder str = new StringBuilder(); + str.append(DsfPlugin.getDebugTime()).append(' ').append(LoggingUtils.toString(this)) + .append(" marked done; element = ").append(LoggingUtils.toString(getElement())); //$NON-NLS-1$ + if (fElements != null && !fElements.isEmpty()) { + for (Object element : fElements) { + str.append(" ").append(LoggingUtils.toString(element)).append('\n'); //$NON-NLS-1$ + } + str.deleteCharAt(str.length() - 1); // remove trailing \n + } + DsfUIPlugin.debug(str.toString()); + } + + super.done(); + } + } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMDelta.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMDelta.java index 4aff13e9f29..3b03d3aa411 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMDelta.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMDelta.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * IBM Corporation - initial API and implementation * Wind River Systems - adapted to use in DSF @@ -21,126 +21,126 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.ModelDelta; /** * This delta class mostly just duplicates the ModelDelta implementation, but - * it allows clients to modify the flags after the original object is - * constructed. + * it allows clients to modify the flags after the original object is + * constructed. * * @see IModelDelta#getNodes() - * + * * @since 1.0 */ public class VMDelta extends ModelDelta { private VMDelta fParent; - private Object fElement; + private Object fElement; private int fFlags; private VMDelta[] fNodes = EMPTY_NODES; private Object fReplacement; private int fIndex; private static final VMDelta[] EMPTY_NODES = new VMDelta[0]; - private int fChildCount = -1; + private int fChildCount = -1; /** * Constructs a new delta for the given element. - * + * * @param vmcElement model element * @param flags change flags */ public VMDelta(Object element, int flags) { - super(element, flags); - fElement = element; + super(element, flags); + fElement = element; fFlags = flags; } /** * Constructs a new delta for the given element to be replaced * with the specified replacement element. - * + * * @param vmcElement model element * @param replacement replacement element * @param flags change flags */ public VMDelta(Object element, Object replacement, int flags) { - super(element, replacement, flags); - fElement = element; - fReplacement = replacement; - fFlags = flags; - } + super(element, replacement, flags); + fElement = element; + fReplacement = replacement; + fFlags = flags; + } /** * Constructs a new delta for the given element to be inserted at * the specified index. - * + * * @param vmcElement model element * @param index insertion position * @param flags change flags */ - public VMDelta(Object element, int index, int flags) { - super(element, index, flags); - fElement = element; - fIndex = index; - fFlags = flags; - } - - /** - * Constructs a new delta for the given element at the specified index - * relative to its parent with the given number of children. - * - * @param element model element - * @param index insertion position - * @param flags change flags - * @param childCount number of children this node has - */ - public VMDelta(Object element, int index, int flags, int childCount) { - super(element, index, flags, childCount); - fElement = element; - fIndex = index; - fFlags = flags; - fChildCount = childCount; - } + public VMDelta(Object element, int index, int flags) { + super(element, index, flags); + fElement = element; + fIndex = index; + fFlags = flags; + } + + /** + * Constructs a new delta for the given element at the specified index + * relative to its parent with the given number of children. + * + * @param element model element + * @param index insertion position + * @param flags change flags + * @param childCount number of children this node has + */ + public VMDelta(Object element, int index, int flags, int childCount) { + super(element, index, flags, childCount); + fElement = element; + fIndex = index; + fFlags = flags; + fChildCount = childCount; + } - /** - * Returns the non-VMC element if one is set, otherwise returns the VMC - * element of this delta node. - * @see org.eclipse.debug.internal.ui.viewers.IModelDelta#getElement() - */ - @Override - public Object getElement() { + /** + * Returns the non-VMC element if one is set, otherwise returns the VMC + * element of this delta node. + * @see org.eclipse.debug.internal.ui.viewers.IModelDelta#getElement() + */ + @Override + public Object getElement() { return fElement; } /* (non-Javadoc) * @see org.eclipse.debug.internal.ui.viewers.IModelDelta#getFlags() */ - @Override + @Override public int getFlags() { return fFlags; } - /** - * Sets this delta's flags. - * - * @param flags - */ - @Override - public void setFlags(int flags) { - fFlags = flags; - } + /** + * Sets this delta's flags. + * + * @param flags + */ + @Override + public void setFlags(int flags) { + fFlags = flags; + } + + @Override + public void setChildCount(int count) { + fChildCount = count; + } - @Override - public void setChildCount(int count) { - fChildCount = count; - } - /** * Adds a child node to this delta with the given element and change flags, * and returns the child delta. - * + * * @param element child element to add * @param flags change flags for child * @return newly created child delta */ @Override - public VMDelta addNode(Object element, int flags) { + public VMDelta addNode(Object element, int flags) { VMDelta node = new VMDelta(element, flags); node.setParent(this); addDelta(node); @@ -149,63 +149,63 @@ public class VMDelta extends ModelDelta { /** * Adds a child node to this delta to replace the given element with the - * specified replacement element and change flags, and returns the + * specified replacement element and change flags, and returns the * newly created child delta. - * + * * @param element child element to add to this delta * @param replacement replacement element for the child element * @param flags change flags * @return newly created child delta */ - @Override - public VMDelta addNode(Object element, Object replacement, int flags) { - VMDelta node = new VMDelta(element, replacement, flags); - node.setParent(this); - addDelta(node); - return node; - } + @Override + public VMDelta addNode(Object element, Object replacement, int flags) { + VMDelta node = new VMDelta(element, replacement, flags); + node.setParent(this); + addDelta(node); + return node; + } - /** - * Adds a child delta to this delta to insert the specified element at - * the given index, and returns the newly created child delta. - * - * @param element child element in insert - * @param index index of insertion - * @param flags change flags - * @return newly created child delta - */ - @Override - public VMDelta addNode(Object element, int index, int flags) { - VMDelta node = new VMDelta(element, index, flags); - node.setParent(this); - addDelta(node); - return node; - } - - /** - * Adds a child delta to this delta at the specified index with the - * given number of children, and returns the newly created child delta. - * - * @param element child element in insert - * @param index index of the element relative to parent - * @param flags change flags - * @param numChildren the number of children the element has - * @return newly created child delta - */ - @Override - public VMDelta addNode(Object element, int index, int flags, int numChildren) { - VMDelta node = new VMDelta(element, index, flags, numChildren); - node.setParent(this); - addDelta(node); - return node; - } + /** + * Adds a child delta to this delta to insert the specified element at + * the given index, and returns the newly created child delta. + * + * @param element child element in insert + * @param index index of insertion + * @param flags change flags + * @return newly created child delta + */ + @Override + public VMDelta addNode(Object element, int index, int flags) { + VMDelta node = new VMDelta(element, index, flags); + node.setParent(this); + addDelta(node); + return node; + } + + /** + * Adds a child delta to this delta at the specified index with the + * given number of children, and returns the newly created child delta. + * + * @param element child element in insert + * @param index index of the element relative to parent + * @param flags change flags + * @param numChildren the number of children the element has + * @return newly created child delta + */ + @Override + public VMDelta addNode(Object element, int index, int flags, int numChildren) { + VMDelta node = new VMDelta(element, index, flags, numChildren); + node.setParent(this); + addDelta(node); + return node; + } /** * Returns the child delta for the given element, or <code>null</code> if none. - * + * * @param element child element * @return corresponding delta node, or <code>null</code> - * + * * @since 1.1 */ @Override @@ -221,11 +221,11 @@ public class VMDelta extends ModelDelta { return null; } - /** - * Sets the parent delta of this delta - * - * @param node parent delta - */ + /** + * Sets the parent delta of this delta + * + * @param node parent delta + */ void setParent(VMDelta node) { fParent = node; } @@ -233,38 +233,38 @@ public class VMDelta extends ModelDelta { /* (non-Javadoc) * @see org.eclipse.debug.internal.ui.viewers.IModelDelta#getParent() */ - @Override + @Override public VMDelta getParentDelta() { return fParent; } - /* (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.IModelDelta#getReplacementElement() - */ - @Override - public Object getReplacementElement() { - return fReplacement; - } + /* (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.IModelDelta#getReplacementElement() + */ + @Override + public Object getReplacementElement() { + return fReplacement; + } + + /* (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.IModelDelta#getIndex() + */ + @Override + public int getIndex() { + return fIndex; + } - /* (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.IModelDelta#getIndex() - */ - @Override - public int getIndex() { - return fIndex; - } - /* (non-Javadoc) * @see org.eclipse.debug.internal.ui.viewers.IModelDelta#getNodes() */ - @Override + @Override public VMDelta[] getChildDeltas() { return fNodes; } - + private void addDelta(VMDelta delta) { if (fNodes.length == 0) { - fNodes = new VMDelta[]{delta}; + fNodes = new VMDelta[] { delta }; } else { VMDelta[] nodes = new VMDelta[fNodes.length + 1]; System.arraycopy(fNodes, 0, nodes, 0, fNodes.length); @@ -272,8 +272,8 @@ public class VMDelta extends ModelDelta { fNodes = nodes; } } - - @Override + + @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("Model Delta Start\n"); //$NON-NLS-1$ @@ -281,100 +281,100 @@ public class VMDelta extends ModelDelta { buf.append("Model Delta End\n"); //$NON-NLS-1$ return buf.toString(); } - + private void appendDetail(StringBuilder buf, VMDelta delta, int depth) { String indent = ""; //$NON-NLS-1$ for (int i = 0; i < depth; i++) { indent += '\t'; } - buf.append(indent).append("\tElement: "); //$NON-NLS-1$ - buf.append(delta.getElement()); - buf.append('\n'); - buf.append(indent).append("\t\tFlags: "); //$NON-NLS-1$ - int flags = delta.getFlags(); - if (flags == 0) { - buf.append("NO_CHANGE"); //$NON-NLS-1$ - } else { - if ((flags & IModelDelta.ADDED) > 0) { - buf.append("ADDED | "); //$NON-NLS-1$ - } - if ((flags & IModelDelta.CONTENT) > 0) { - buf.append("CONTENT | "); //$NON-NLS-1$ - } - if ((flags & IModelDelta.EXPAND) > 0) { - buf.append("EXPAND | "); //$NON-NLS-1$ - } - if ((flags & IModelDelta.COLLAPSE) > 0) { - buf.append("COLLAPSE | "); //$NON-NLS-1$ - } - if ((flags & IModelDelta.INSERTED) > 0) { - buf.append("INSERTED | "); //$NON-NLS-1$ - } - if ((flags & IModelDelta.REMOVED) > 0) { - buf.append("REMOVED | "); //$NON-NLS-1$ - } - if ((flags & IModelDelta.REPLACED) > 0) { - buf.append("REPLACED | "); //$NON-NLS-1$ - } - if ((flags & IModelDelta.SELECT) > 0) { - buf.append("SELECT | "); //$NON-NLS-1$ - } - if ((flags & IModelDelta.STATE) > 0) { - buf.append("STATE | "); //$NON-NLS-1$ - } - if ((flags & IModelDelta.INSTALL) > 0) { - buf.append("INSTALL | "); //$NON-NLS-1$ - } - if ((flags & IModelDelta.UNINSTALL) > 0) { - buf.append("UNINSTALL | "); //$NON-NLS-1$ - } - if ((flags & IModelDelta.REVEAL) > 0) { - buf.append("REVEAL | "); //$NON-NLS-1$ - } - if ((flags & IModelDelta.FORCE) > 0) { - buf.append("FORCE | "); //$NON-NLS-1$ - } - } - buf.append('\n'); - buf.append(indent).append("\t\tIndex: "); //$NON-NLS-1$ - buf.append(delta.fIndex); - buf.append(" Child Count: "); //$NON-NLS-1$ - buf.append(delta.fChildCount); - buf.append('\n'); - IModelDelta[] nodes = delta.getChildDeltas(); - for (int i = 0; i < nodes.length; i++) { - appendDetail(buf, (VMDelta)nodes[i], depth+1); - } + buf.append(indent).append("\tElement: "); //$NON-NLS-1$ + buf.append(delta.getElement()); + buf.append('\n'); + buf.append(indent).append("\t\tFlags: "); //$NON-NLS-1$ + int flags = delta.getFlags(); + if (flags == 0) { + buf.append("NO_CHANGE"); //$NON-NLS-1$ + } else { + if ((flags & IModelDelta.ADDED) > 0) { + buf.append("ADDED | "); //$NON-NLS-1$ + } + if ((flags & IModelDelta.CONTENT) > 0) { + buf.append("CONTENT | "); //$NON-NLS-1$ + } + if ((flags & IModelDelta.EXPAND) > 0) { + buf.append("EXPAND | "); //$NON-NLS-1$ + } + if ((flags & IModelDelta.COLLAPSE) > 0) { + buf.append("COLLAPSE | "); //$NON-NLS-1$ + } + if ((flags & IModelDelta.INSERTED) > 0) { + buf.append("INSERTED | "); //$NON-NLS-1$ + } + if ((flags & IModelDelta.REMOVED) > 0) { + buf.append("REMOVED | "); //$NON-NLS-1$ + } + if ((flags & IModelDelta.REPLACED) > 0) { + buf.append("REPLACED | "); //$NON-NLS-1$ + } + if ((flags & IModelDelta.SELECT) > 0) { + buf.append("SELECT | "); //$NON-NLS-1$ + } + if ((flags & IModelDelta.STATE) > 0) { + buf.append("STATE | "); //$NON-NLS-1$ + } + if ((flags & IModelDelta.INSTALL) > 0) { + buf.append("INSTALL | "); //$NON-NLS-1$ + } + if ((flags & IModelDelta.UNINSTALL) > 0) { + buf.append("UNINSTALL | "); //$NON-NLS-1$ + } + if ((flags & IModelDelta.REVEAL) > 0) { + buf.append("REVEAL | "); //$NON-NLS-1$ + } + if ((flags & IModelDelta.FORCE) > 0) { + buf.append("FORCE | "); //$NON-NLS-1$ + } + } + buf.append('\n'); + buf.append(indent).append("\t\tIndex: "); //$NON-NLS-1$ + buf.append(delta.fIndex); + buf.append(" Child Count: "); //$NON-NLS-1$ + buf.append(delta.fChildCount); + buf.append('\n'); + IModelDelta[] nodes = delta.getChildDeltas(); + for (int i = 0; i < nodes.length; i++) { + appendDetail(buf, (VMDelta) nodes[i], depth + 1); + } + } + + /* (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.provisional.IModelDelta#getChildCount() + */ + @Override + public int getChildCount() { + return fChildCount; } - - /* (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.provisional.IModelDelta#getChildCount() - */ - @Override - public int getChildCount() { - return fChildCount; - } - - /* (non-Javadoc) - * @see org.eclipse.debug.internal.ui.viewers.provisional.IModelDelta#accept(org.eclipse.debug.internal.ui.viewers.provisional.IModelDeltaVisitor) - */ - @Override - public void accept(IModelDeltaVisitor visitor) { - doAccept(visitor, 0); - } - - @Override - protected void doAccept(IModelDeltaVisitor visitor, int depth) { - if (visitor.visit(this, depth)) { - ModelDelta[] childDeltas = getChildDeltas(); - for (int i = 0; i < childDeltas.length; i++) { - ((VMDelta)childDeltas[i]).doAccept(visitor, depth+1); - } - } - } - @Override - public void setIndex(final int index) { - fIndex = index; - } + /* (non-Javadoc) + * @see org.eclipse.debug.internal.ui.viewers.provisional.IModelDelta#accept(org.eclipse.debug.internal.ui.viewers.provisional.IModelDeltaVisitor) + */ + @Override + public void accept(IModelDeltaVisitor visitor) { + doAccept(visitor, 0); + } + + @Override + protected void doAccept(IModelDeltaVisitor visitor, int depth) { + if (visitor.visit(this, depth)) { + ModelDelta[] childDeltas = getChildDeltas(); + for (int i = 0; i < childDeltas.length; i++) { + ((VMDelta) childDeltas[i]).doAccept(visitor, depth + 1); + } + } + } + + @Override + public void setIndex(final int index) { + fIndex = index; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMHasChildrenUpdate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMHasChildrenUpdate.java index 9c94d998727..d16867e78bc 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMHasChildrenUpdate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMHasChildrenUpdate.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -24,56 +24,58 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationCont import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; import org.eclipse.jface.viewers.TreePath; -/** +/** * Helper class implementation of the {@link IHasChildrenUpdate} update object. - * + * * @see VMViewerUpdate - * + * * @since 1.0 */ public class VMHasChildrenUpdate extends VMViewerUpdate implements IHasChildrenUpdate { - final private DataRequestMonitor<Boolean> fHasElemsRequestMonitor; - - public VMHasChildrenUpdate(IViewerUpdate clientUpdate, DataRequestMonitor<Boolean> rm) { - super(clientUpdate, rm); - fHasElemsRequestMonitor = rm; - } - - public VMHasChildrenUpdate(IModelDelta delta, IPresentationContext presentationContext, DataRequestMonitor<Boolean> rm) { - super(delta, presentationContext, rm); - fHasElemsRequestMonitor = rm; - } + final private DataRequestMonitor<Boolean> fHasElemsRequestMonitor; - public VMHasChildrenUpdate(TreePath elementPath, Object viewerInput, IPresentationContext presentationContext, DataRequestMonitor<Boolean> rm) { - super(elementPath, viewerInput, presentationContext, rm); - fHasElemsRequestMonitor = rm; - } + public VMHasChildrenUpdate(IViewerUpdate clientUpdate, DataRequestMonitor<Boolean> rm) { + super(clientUpdate, rm); + fHasElemsRequestMonitor = rm; + } - @Override + public VMHasChildrenUpdate(IModelDelta delta, IPresentationContext presentationContext, + DataRequestMonitor<Boolean> rm) { + super(delta, presentationContext, rm); + fHasElemsRequestMonitor = rm; + } + + public VMHasChildrenUpdate(TreePath elementPath, Object viewerInput, IPresentationContext presentationContext, + DataRequestMonitor<Boolean> rm) { + super(elementPath, viewerInput, presentationContext, rm); + fHasElemsRequestMonitor = rm; + } + + @Override public void setHasChilren(boolean hasChildren) { - fHasElemsRequestMonitor.setData(hasChildren); - } + fHasElemsRequestMonitor.setData(hasChildren); + } + + @Override + public String toString() { + return "VMHasChildrenUpdate: " + getElement(); //$NON-NLS-1$ + } - @Override - public String toString() { - return "VMHasChildrenUpdate: " + getElement(); //$NON-NLS-1$ - } - - @Override - public void done() { - assert isCanceled() || fHasElemsRequestMonitor.getData() != null || !fHasElemsRequestMonitor.isSuccess(); + @Override + public void done() { + assert isCanceled() || fHasElemsRequestMonitor.getData() != null || !fHasElemsRequestMonitor.isSuccess(); - // trace our result - if (VMViewerUpdateTracing.DEBUG_VMUPDATES && !isCanceled() && VMViewerUpdateTracing.matchesFilterRegex(this.getClass())) { - final Boolean data = fHasElemsRequestMonitor.getData(); + // trace our result + if (VMViewerUpdateTracing.DEBUG_VMUPDATES && !isCanceled() + && VMViewerUpdateTracing.matchesFilterRegex(this.getClass())) { + final Boolean data = fHasElemsRequestMonitor.getData(); DsfUIPlugin.debug(DsfPlugin.getDebugTime() + " " //$NON-NLS-1$ + LoggingUtils.toString(this) + " marked done; element = " //$NON-NLS-1$ - + LoggingUtils.toString(getElement()) - + "\n has children = " //$NON-NLS-1$ - + (data != null ? data.toString() : "<unset>")); //$NON-NLS-1$ - } + + LoggingUtils.toString(getElement()) + "\n has children = " //$NON-NLS-1$ + + (data != null ? data.toString() : "<unset>")); //$NON-NLS-1$ + } - super.done(); - } + super.done(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMViewerUpdate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMViewerUpdate.java index 39766cf8dc6..4c8b1994bb6 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMViewerUpdate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMViewerUpdate.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -29,185 +29,213 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationCont import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; import org.eclipse.jface.viewers.TreePath; -/** - * Helper class implementation of the update objects used with - * {@link IElementContentProvider}, {@link IElementLabelProvider}, - * and {@link IElementMementoProvider}. The viewer update can be constructed - * using a higher level update object or a set of parameters to fulfill the - * <code>IViewerUpdate</code> interface. - * +/** + * Helper class implementation of the update objects used with + * {@link IElementContentProvider}, {@link IElementLabelProvider}, + * and {@link IElementMementoProvider}. The viewer update can be constructed + * using a higher level update object or a set of parameters to fulfill the + * <code>IViewerUpdate</code> interface. + * * @since 1.0 */ public class VMViewerUpdate extends DsfExecutable implements IViewerUpdate { - - /** - * The request monitor to be called when this update is completed. - */ - final private RequestMonitor fRequestMonitor; - - /** - * A higher-level update that this update is based on. If specified, the given - * update is used to delegate calls to {@link #cancel()} and {@link #isCanceled()}. - */ - final private IViewerUpdate fClientUpdate; - - /** - * Place holder for the client update. It is only used if the client update is - * not specified. - */ - private static class ClientUpdatePlaceHolder implements IViewerUpdate { - - ClientUpdatePlaceHolder(TreePath elementPath, Object viewerInput, IPresentationContext presentationContext) - { - fViewerInput = viewerInput; - fElementPath = elementPath; - fPresentationContext = presentationContext; - } - /** - * The flag indicating whether this update was canceled. - */ - private volatile boolean fCanceled; - - /** - * The viewer input object for this update. - */ - final private Object fViewerInput; - - /** - * The element path of this update. - */ - final private TreePath fElementPath; - - /** - * The presentation context of this update. - */ - final private IPresentationContext fPresentationContext; - - @Override + + /** + * The request monitor to be called when this update is completed. + */ + final private RequestMonitor fRequestMonitor; + + /** + * A higher-level update that this update is based on. If specified, the given + * update is used to delegate calls to {@link #cancel()} and {@link #isCanceled()}. + */ + final private IViewerUpdate fClientUpdate; + + /** + * Place holder for the client update. It is only used if the client update is + * not specified. + */ + private static class ClientUpdatePlaceHolder implements IViewerUpdate { + + ClientUpdatePlaceHolder(TreePath elementPath, Object viewerInput, IPresentationContext presentationContext) { + fViewerInput = viewerInput; + fElementPath = elementPath; + fPresentationContext = presentationContext; + } + + /** + * The flag indicating whether this update was canceled. + */ + private volatile boolean fCanceled; + + /** + * The viewer input object for this update. + */ + final private Object fViewerInput; + + /** + * The element path of this update. + */ + final private TreePath fElementPath; + + /** + * The presentation context of this update. + */ + final private IPresentationContext fPresentationContext; + + @Override public void cancel() { - fCanceled = true; - } - - @Override - public boolean isCanceled() { - return fCanceled; - } - - @Override + fCanceled = true; + } + + @Override + public boolean isCanceled() { + return fCanceled; + } + + @Override public IPresentationContext getPresentationContext() { - return fPresentationContext; - } + return fPresentationContext; + } - @Override + @Override public Object getElement() { - return fElementPath.getSegmentCount() != 0 ? fElementPath.getLastSegment() : fViewerInput; - } + return fElementPath.getSegmentCount() != 0 ? fElementPath.getLastSegment() : fViewerInput; + } - @Override + @Override public TreePath getElementPath() { - return fElementPath; - } + return fElementPath; + } - @Override + @Override public Object getViewerInput() { - return fViewerInput; - } - - @Override - public void done() { assert false; } // not used - @Override - public void setStatus(IStatus status) {assert false; } // not used - @Override - public IStatus getStatus() { assert false; return null; } // not used - - } - - /** - * Creates a viewer update based on a higher-level update. The update element - * information as well as cancel requests are delegated to the given client - * update. - * <p/> - * Note: this update will not automatically call the client update's - * {@link IRequest#done()} method. The user of this update should supply - * a request monitor which properly completes the client update. - * - * @param clientUpdate Client update that this update is based on. - * @param requestMonitor Call-back invoked when this update completes. - */ - public VMViewerUpdate(IViewerUpdate clientUpdate, RequestMonitor requestMonitor) { - fRequestMonitor = requestMonitor; - fClientUpdate = clientUpdate; - } - - /** - * Request monitor which uses a model delta to calculate the element information. - * This update is useful when calculating a model delta for a given view model node. - * - * @param delta Model delta of a parent element. - * @param presentationContext Presentation context for this update. - * @param requestMonitor Call-back invoked when this update completes. - */ - public VMViewerUpdate(IModelDelta delta, IPresentationContext presentationContext, RequestMonitor requestMonitor) { - List<Object> elementList = new LinkedList<Object>(); - IModelDelta listDelta = delta; - elementList.add(0, listDelta.getElement()); - while (listDelta.getParentDelta() != null) { - listDelta = listDelta.getParentDelta(); - elementList.add(0, listDelta.getElement()); - } - Object viewerInput = elementList.remove(0); - fClientUpdate = new ClientUpdatePlaceHolder( - new TreePath(elementList.toArray()), viewerInput, presentationContext); - fRequestMonitor = requestMonitor; - } - - /** - * Creates a viewer update with the given parameters. - * - * @param elementPath The path to the element for which the update is generated. - * @param viewerInput Input into the viewer of the update. - * @param presentationContext Presentation context for this update. - * @param requestMonitor Call-back invoked when this update completes. - */ - public VMViewerUpdate(TreePath elementPath, Object viewerInput, IPresentationContext presentationContext, RequestMonitor requestMonitor) { - fRequestMonitor = requestMonitor; - fClientUpdate = new ClientUpdatePlaceHolder(elementPath, viewerInput, presentationContext); - } - - protected RequestMonitor getRequestMonitor() { - return fRequestMonitor; - } - - @Override - public Object getViewerInput() { return fClientUpdate.getViewerInput(); } - @Override - public Object getElement() { return fClientUpdate.getElement(); } - @Override - public TreePath getElementPath() { return fClientUpdate.getElementPath(); } - @Override - public IPresentationContext getPresentationContext() { return fClientUpdate.getPresentationContext(); } - @Override - public IStatus getStatus() { return fRequestMonitor.getStatus(); } - @Override - public void setStatus(IStatus status) { fRequestMonitor.setStatus(status); } - - @Override - public boolean isCanceled() { - return fClientUpdate.isCanceled(); - } - @Override + return fViewerInput; + } + + @Override + public void done() { + assert false; + } // not used + + @Override + public void setStatus(IStatus status) { + assert false; + } // not used + + @Override + public IStatus getStatus() { + assert false; + return null; + } // not used + + } + + /** + * Creates a viewer update based on a higher-level update. The update element + * information as well as cancel requests are delegated to the given client + * update. + * <p/> + * Note: this update will not automatically call the client update's + * {@link IRequest#done()} method. The user of this update should supply + * a request monitor which properly completes the client update. + * + * @param clientUpdate Client update that this update is based on. + * @param requestMonitor Call-back invoked when this update completes. + */ + public VMViewerUpdate(IViewerUpdate clientUpdate, RequestMonitor requestMonitor) { + fRequestMonitor = requestMonitor; + fClientUpdate = clientUpdate; + } + + /** + * Request monitor which uses a model delta to calculate the element information. + * This update is useful when calculating a model delta for a given view model node. + * + * @param delta Model delta of a parent element. + * @param presentationContext Presentation context for this update. + * @param requestMonitor Call-back invoked when this update completes. + */ + public VMViewerUpdate(IModelDelta delta, IPresentationContext presentationContext, RequestMonitor requestMonitor) { + List<Object> elementList = new LinkedList<Object>(); + IModelDelta listDelta = delta; + elementList.add(0, listDelta.getElement()); + while (listDelta.getParentDelta() != null) { + listDelta = listDelta.getParentDelta(); + elementList.add(0, listDelta.getElement()); + } + Object viewerInput = elementList.remove(0); + fClientUpdate = new ClientUpdatePlaceHolder(new TreePath(elementList.toArray()), viewerInput, + presentationContext); + fRequestMonitor = requestMonitor; + } + + /** + * Creates a viewer update with the given parameters. + * + * @param elementPath The path to the element for which the update is generated. + * @param viewerInput Input into the viewer of the update. + * @param presentationContext Presentation context for this update. + * @param requestMonitor Call-back invoked when this update completes. + */ + public VMViewerUpdate(TreePath elementPath, Object viewerInput, IPresentationContext presentationContext, + RequestMonitor requestMonitor) { + fRequestMonitor = requestMonitor; + fClientUpdate = new ClientUpdatePlaceHolder(elementPath, viewerInput, presentationContext); + } + + protected RequestMonitor getRequestMonitor() { + return fRequestMonitor; + } + + @Override + public Object getViewerInput() { + return fClientUpdate.getViewerInput(); + } + + @Override + public Object getElement() { + return fClientUpdate.getElement(); + } + + @Override + public TreePath getElementPath() { + return fClientUpdate.getElementPath(); + } + + @Override + public IPresentationContext getPresentationContext() { + return fClientUpdate.getPresentationContext(); + } + + @Override + public IStatus getStatus() { + return fRequestMonitor.getStatus(); + } + + @Override + public void setStatus(IStatus status) { + fRequestMonitor.setStatus(status); + } + + @Override + public boolean isCanceled() { + return fClientUpdate.isCanceled(); + } + + @Override public void cancel() { - fClientUpdate.cancel(); - } - - @Override - public void done() { - setSubmitted(); - if ( isCanceled() ) { - fRequestMonitor.cancel(); - fRequestMonitor.setStatus(new Status( IStatus.CANCEL, DsfUIPlugin.PLUGIN_ID," Update was canceled") ); //$NON-NLS-1$ - } - fRequestMonitor.done(); - } + fClientUpdate.cancel(); + } + + @Override + public void done() { + setSubmitted(); + if (isCanceled()) { + fRequestMonitor.cancel(); + fRequestMonitor.setStatus(new Status(IStatus.CANCEL, DsfUIPlugin.PLUGIN_ID, " Update was canceled")); //$NON-NLS-1$ + } + fRequestMonitor.done(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/AbstractDMVMAdapter.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/AbstractDMVMAdapter.java index 3f0d7bdb648..3cd75ce3853 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/AbstractDMVMAdapter.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/AbstractDMVMAdapter.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -21,89 +21,91 @@ import org.eclipse.cdt.dsf.service.DsfServiceEventHandler; import org.eclipse.cdt.dsf.service.DsfSession; import org.eclipse.cdt.dsf.ui.viewmodel.AbstractVMAdapter; -/** +/** * Base implementation for DSF-based view model adapters. - * + * * @since 1.0 */ @ThreadSafe -abstract public class AbstractDMVMAdapter extends AbstractVMAdapter -{ - private final DsfSession fSession; +abstract public class AbstractDMVMAdapter extends AbstractVMAdapter { + private final DsfSession fSession; - /** - * It is theoretically possible for a VM adapter to be disposed before it - * has a chance to register itself as event listener. This flag is used - * to avoid removing itself as listener in such situation. - */ - private boolean fRegisteredAsEventListener = false; + /** + * It is theoretically possible for a VM adapter to be disposed before it + * has a chance to register itself as event listener. This flag is used + * to avoid removing itself as listener in such situation. + */ + private boolean fRegisteredAsEventListener = false; - /** - * Constructor for the View Model session. It is tempting to have the - * adapter register itself here with the session as the model adapter, but - * that would mean that the adapter might get accessed on another thread - * even before the deriving class is fully constructed. So it it better - * to have the owner of this object register it with the session. - * @param session - */ - public AbstractDMVMAdapter(DsfSession session) { - super(); - fSession = session; - // Add ourselves as listener for DM events events. - try { - session.getExecutor().execute(new Runnable() { - @Override + /** + * Constructor for the View Model session. It is tempting to have the + * adapter register itself here with the session as the model adapter, but + * that would mean that the adapter might get accessed on another thread + * even before the deriving class is fully constructed. So it it better + * to have the owner of this object register it with the session. + * @param session + */ + public AbstractDMVMAdapter(DsfSession session) { + super(); + fSession = session; + // Add ourselves as listener for DM events events. + try { + session.getExecutor().execute(new Runnable() { + @Override public void run() { - if (DsfSession.isSessionActive(getSession().getId())) { - getSession().addServiceEventListener(AbstractDMVMAdapter.this, null); - fRegisteredAsEventListener = true; - } - } - }); - } catch (RejectedExecutionException e) { - // Session shut down, not much we can do but wait to be disposed. - } - } + if (DsfSession.isSessionActive(getSession().getId())) { + getSession().addServiceEventListener(AbstractDMVMAdapter.this, null); + fRegisteredAsEventListener = true; + } + } + }); + } catch (RejectedExecutionException e) { + // Session shut down, not much we can do but wait to be disposed. + } + } - @Override - public void dispose() { - try { - getSession().getExecutor().execute(new Runnable() { - @Override + @Override + public void dispose() { + try { + getSession().getExecutor().execute(new Runnable() { + @Override public void run() { - if (fRegisteredAsEventListener && getSession().isActive()) { - fSession.removeServiceEventListener(AbstractDMVMAdapter.this); - } - } - }); - } catch (RejectedExecutionException e) { - // Session shut down. - } - super.dispose(); - } + if (fRegisteredAsEventListener && getSession().isActive()) { + fSession.removeServiceEventListener(AbstractDMVMAdapter.this); + } + } + }); + } catch (RejectedExecutionException e) { + // Session shut down. + } + super.dispose(); + } + + /** + * Returns the DSF session that this adapter is associated with. + * @return + */ + protected DsfSession getSession() { + return fSession; + } - /** - * Returns the DSF session that this adapter is associated with. - * @return - */ - protected DsfSession getSession() { return fSession; } - - /** - * Handle "data model changed" event by generating a delta object for each - * view and passing it to the corresponding view model provider. The view - * model provider is then responsible for filling-in and sending the delta - * to the viewer. - * - * @param event - * - * @since 1.1 - */ - @DsfServiceEventHandler - public final void eventDispatched(final IDMEvent<?> event) { - // We're in session's executor thread (session in which the event originated). - if (isDisposed()) return; + /** + * Handle "data model changed" event by generating a delta object for each + * view and passing it to the corresponding view model provider. The view + * model provider is then responsible for filling-in and sending the delta + * to the viewer. + * + * @param event + * + * @since 1.1 + */ + @DsfServiceEventHandler + public final void eventDispatched(final IDMEvent<?> event) { + // We're in session's executor thread (session in which the event originated). + if (isDisposed()) + return; - handleEvent(event); - } + handleEvent(event); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/AbstractDMVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/AbstractDMVMNode.java index 8e0534bc365..33c0ff83be5 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/AbstractDMVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/AbstractDMVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -46,345 +46,358 @@ import org.eclipse.jface.viewers.TreePath; /** * View model node based on a single IDMContext type. All the elements created * by this node are of that type. - * + * * @since 1.0 */ abstract public class AbstractDMVMNode extends AbstractVMNode implements IVMNode { - /** - * IVMContext implementation used for this schema node. - */ - @Immutable - protected class DMVMContext extends AbstractVMContext implements IDMVMContext { - private final IDMContext fDmc; - - public DMVMContext(IDMContext dmc) { - super(AbstractDMVMNode.this); - assert dmc != null; - fDmc = dmc; - } - - @Override - public IDMContext getDMContext() { return fDmc; } - - /** - * The IAdaptable implementation. If the adapter is the DM context, - * return the context, otherwise delegate to IDMContext.getAdapter(). - */ - @SuppressWarnings("unchecked") + /** + * IVMContext implementation used for this schema node. + */ + @Immutable + protected class DMVMContext extends AbstractVMContext implements IDMVMContext { + private final IDMContext fDmc; + + public DMVMContext(IDMContext dmc) { + super(AbstractDMVMNode.this); + assert dmc != null; + fDmc = dmc; + } + + @Override + public IDMContext getDMContext() { + return fDmc; + } + + /** + * The IAdaptable implementation. If the adapter is the DM context, + * return the context, otherwise delegate to IDMContext.getAdapter(). + */ + @SuppressWarnings("unchecked") + @Override + public <T> T getAdapter(Class<T> adapter) { + T superAdapter = super.getAdapter(adapter); + if (superAdapter != null) { + return superAdapter; + } else { + // Delegate to the Data Model to find the context. + if (adapter.isInstance(fDmc)) { + return (T) fDmc; + } else { + return fDmc.getAdapter(adapter); + } + } + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof AbstractDMVMNode.DMVMContext)) + return false; + DMVMContext otherVmc = (DMVMContext) other; + return AbstractDMVMNode.this.equals(otherVmc.getVMNode()) && fDmc.equals(otherVmc.fDmc); + } + @Override - public <T> T getAdapter(Class<T> adapter) { - T superAdapter = super.getAdapter(adapter); - if (superAdapter != null) { - return superAdapter; - } else { - // Delegate to the Data Model to find the context. - if (adapter.isInstance(fDmc)) { - return (T)fDmc; - } else { - return fDmc.getAdapter(adapter); - } - } - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof AbstractDMVMNode.DMVMContext)) return false; - DMVMContext otherVmc = (DMVMContext)other; - return AbstractDMVMNode.this.equals(otherVmc.getVMNode()) && - fDmc.equals(otherVmc.fDmc); - } - - @Override - public int hashCode() { - return AbstractDMVMNode.this.hashCode() + fDmc.hashCode(); - } - - @Override - public String toString() { - return fDmc.toString(); - } - } - - private DsfSession fSession; - - private DsfServicesTracker fServicesTracker; - - /** - * Concrete class type that the elements of this schema node are based on. - * This type is used by the standard event processing logic to find the - * element in the event which is managed by this VM node. - * - * @see #getContextsForEvent(VMDelta, Object, DataRequestMonitor) - */ - private Class<? extends IDMContext> fDMCClassType; - - /** - * Constructor initializes instance data, except for the child nodes. - * Child nodes must be initialized by calling setChildNodes() - * @param session - * @param dmcClassType - * @see #setChildNodes(IVMNode[]) - */ - public AbstractDMVMNode(AbstractDMVMProvider provider, DsfSession session, Class<? extends IDMContext> dmcClassType) { - super(provider); - fSession = session; - fServicesTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); - fDMCClassType = dmcClassType; - } - - @Override - public void dispose() { - fServicesTracker.dispose(); - super.dispose(); - } - - @Override - public void getContextsForEvent(VMDelta parentDelta, Object event, DataRequestMonitor<IVMContext[]> rm) { - if (event instanceof IDMEvent<?>) { - IDMEvent<?> dmEvent = (IDMEvent<?>)event; - IDMContext dmc = DMContexts.getAncestorOfType(dmEvent.getDMContext(), fDMCClassType); - if (dmc != null) { - rm.setData(new IVMContext[] { createVMContext(dmc) }); - rm.done(); - return; - } - } - super.getContextsForEvent(parentDelta, event, rm); - } - - protected AbstractDMVMProvider getDMVMProvider() { - return (AbstractDMVMProvider)getVMProvider(); - } - - protected DsfSession getSession() { - return fSession; - } - - protected DsfServicesTracker getServicesTracker() { - return fServicesTracker; - } - - @Override - protected boolean checkUpdate(IViewerUpdate update) { - if (!super.checkUpdate(update)) return false; - - // Extract the VMC from the update (whatever the update sub-class. - Object element = update.getElement(); - if (element instanceof IDMVMContext) { - // If update element is a DMC, check if session is still alive. - IDMContext dmc = ((IDMVMContext)element).getDMContext(); - if (!dmc.getSessionId().equals(getSession().getId()) || !DsfSession.isSessionActive(dmc.getSessionId())) { - handleFailedUpdate(update); - return false; - } - } - return true; - } - - @Override + public int hashCode() { + return AbstractDMVMNode.this.hashCode() + fDmc.hashCode(); + } + + @Override + public String toString() { + return fDmc.toString(); + } + } + + private DsfSession fSession; + + private DsfServicesTracker fServicesTracker; + + /** + * Concrete class type that the elements of this schema node are based on. + * This type is used by the standard event processing logic to find the + * element in the event which is managed by this VM node. + * + * @see #getContextsForEvent(VMDelta, Object, DataRequestMonitor) + */ + private Class<? extends IDMContext> fDMCClassType; + + /** + * Constructor initializes instance data, except for the child nodes. + * Child nodes must be initialized by calling setChildNodes() + * @param session + * @param dmcClassType + * @see #setChildNodes(IVMNode[]) + */ + public AbstractDMVMNode(AbstractDMVMProvider provider, DsfSession session, + Class<? extends IDMContext> dmcClassType) { + super(provider); + fSession = session; + fServicesTracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), session.getId()); + fDMCClassType = dmcClassType; + } + + @Override + public void dispose() { + fServicesTracker.dispose(); + super.dispose(); + } + + @Override + public void getContextsForEvent(VMDelta parentDelta, Object event, DataRequestMonitor<IVMContext[]> rm) { + if (event instanceof IDMEvent<?>) { + IDMEvent<?> dmEvent = (IDMEvent<?>) event; + IDMContext dmc = DMContexts.getAncestorOfType(dmEvent.getDMContext(), fDMCClassType); + if (dmc != null) { + rm.setData(new IVMContext[] { createVMContext(dmc) }); + rm.done(); + return; + } + } + super.getContextsForEvent(parentDelta, event, rm); + } + + protected AbstractDMVMProvider getDMVMProvider() { + return (AbstractDMVMProvider) getVMProvider(); + } + + protected DsfSession getSession() { + return fSession; + } + + protected DsfServicesTracker getServicesTracker() { + return fServicesTracker; + } + + @Override + protected boolean checkUpdate(IViewerUpdate update) { + if (!super.checkUpdate(update)) + return false; + + // Extract the VMC from the update (whatever the update sub-class. + Object element = update.getElement(); + if (element instanceof IDMVMContext) { + // If update element is a DMC, check if session is still alive. + IDMContext dmc = ((IDMVMContext) element).getDMContext(); + if (!dmc.getSessionId().equals(getSession().getId()) || !DsfSession.isSessionActive(dmc.getSessionId())) { + handleFailedUpdate(update); + return false; + } + } + return true; + } + + @Override public void update(final IHasChildrenUpdate[] updates) { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - for (IHasChildrenUpdate update : updates) { - if (!checkUpdate(update)) continue; - updateHasElementsInSessionThread(update); - } - }}); - } catch (RejectedExecutionException e) { - for (IViewerUpdate update : updates) { - handleFailedUpdate(update); - } - } - } - - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void updateHasElementsInSessionThread(final IHasChildrenUpdate update) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "Not implemented, clients should call to update all children instead.", null)); //$NON-NLS-1$ - update.done(); - } - - @Override + for (IHasChildrenUpdate update : updates) { + if (!checkUpdate(update)) + continue; + updateHasElementsInSessionThread(update); + } + } + }); + } catch (RejectedExecutionException e) { + for (IViewerUpdate update : updates) { + handleFailedUpdate(update); + } + } + } + + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void updateHasElementsInSessionThread(final IHasChildrenUpdate update) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, + "Not implemented, clients should call to update all children instead.", null)); //$NON-NLS-1$ + update.done(); + } + + @Override public void update(final IChildrenCountUpdate[] updates) { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - for (IChildrenCountUpdate update : updates) { - if (!checkUpdate(update)) continue; - updateElementCountInSessionThread(update); - } - }}); - } catch (RejectedExecutionException e) { - for (IViewerUpdate update : updates) { - handleFailedUpdate(update); - } - } - } - - @ConfinedToDsfExecutor("getSession().getExecutor()") - protected void updateElementCountInSessionThread(final IChildrenCountUpdate update) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, "Not implemented, clients should call to update all children instead.", null)); //$NON-NLS-1$ - update.done(); - } - - @Override + for (IChildrenCountUpdate update : updates) { + if (!checkUpdate(update)) + continue; + updateElementCountInSessionThread(update); + } + } + }); + } catch (RejectedExecutionException e) { + for (IViewerUpdate update : updates) { + handleFailedUpdate(update); + } + } + } + + @ConfinedToDsfExecutor("getSession().getExecutor()") + protected void updateElementCountInSessionThread(final IChildrenCountUpdate update) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, IDsfStatusConstants.NOT_SUPPORTED, + "Not implemented, clients should call to update all children instead.", null)); //$NON-NLS-1$ + update.done(); + } + + @Override public void update(final IChildrenUpdate[] updates) { - try { - getSession().getExecutor().execute(new DsfRunnable() { - @Override + try { + getSession().getExecutor().execute(new DsfRunnable() { + @Override public void run() { - // After every dispatch, must check if update still valid. - for (IChildrenUpdate update : updates) { - if (!checkUpdate(update)) continue; - updateElementsInSessionThread(update); - } - }}); - } catch (RejectedExecutionException e) { - for (IViewerUpdate update : updates) { - handleFailedUpdate(update); - } - } - } - - @ConfinedToDsfExecutor("getSession().getExecutor()") - abstract protected void updateElementsInSessionThread(IChildrenUpdate update); - - /** - * Utility method that takes an array of DMC object and creates a - * corresponding array of IVMContext elements base on that. - * @param parent The parent for generated IVMContext elements. - * @param dmcs Array of DMC objects to build return array on. - * @return Array of IVMContext objects. - */ - protected IVMContext[] dmcs2vmcs(IDMContext[] dmcs) { - IVMContext[] vmContexts = new IVMContext[dmcs.length]; - for (int i = 0; i < dmcs.length; i++) { - vmContexts[i] = createVMContext(dmcs[i]); - } - return vmContexts; - } - - /** - * Fill update request with view model contexts based on given data model contexts. - * Assumes that data model context elements start at index 0. - * - * @param update the viewer update request - * @param dmcs the data model contexts - */ - protected void fillUpdateWithVMCs(IChildrenUpdate update, IDMContext[] dmcs) { - fillUpdateWithVMCs(update, dmcs, 0); - } - - /** - * Fill update request with view model contexts based on given data model contexts. - * - * @param update the viewer update request - * @param dmcs the data model contexts - * @param firstIndex the index of the first data model context - * - * @since 1.1 - */ - protected void fillUpdateWithVMCs(IChildrenUpdate update, IDMContext[] dmcs, int firstIndex) { - int updateIdx = update.getOffset() != -1 ? update.getOffset() : 0; - final int endIdx = updateIdx + (update.getLength() != -1 ? update.getLength() : dmcs.length); - int dmcIdx = updateIdx - firstIndex; - if (dmcIdx < 0) { - updateIdx -= dmcIdx; - dmcIdx = 0; - } - while (updateIdx < endIdx && dmcIdx < dmcs.length) { - update.setChild(createVMContext(dmcs[dmcIdx++]), updateIdx++); - } - } - - protected IDMVMContext createVMContext(IDMContext dmc) { - return new DMVMContext(dmc); - } - - /** - * Creates a default CompositeDMVMContext which represents the selection. - * This can be overridden by view model providers which for their own purposes. - * @param update defines the selection to be updated to - * @return DM Context which represent the current selection - */ - protected IDMContext createCompositeDMVMContext(IViewerUpdate update) { - return new CompositeDMVMContext(update); - } - - /** - * Searches for a DMC of given type in the tree path contained in given - * VMC. Only a DMC in the same session will be returned. - * @param <V> Type of the DMC that will be returned. - * @param vmc VMC element to search. - * @param dmcType Class object for matching the type. - * @return DMC, or null if not found. - */ - protected <T extends IDMContext> T findDmcInPath(Object inputObject, TreePath path, Class<T> dmcType) { - T retVal = null; - for (int i = path.getSegmentCount() - 1; i >= 0; i--) { - if (path.getSegment(i) instanceof IDMVMContext) { - IDMContext dmc = ((IDMVMContext)path.getSegment(i)).getDMContext(); - if ( dmc.getSessionId().equals(getSession().getId()) ) { - retVal = DMContexts.getAncestorOfType(dmc, dmcType); - if (retVal != null) break; - } - } - } - // Search the root object of the layout hierarchy. - if (retVal == null) { - if (inputObject instanceof ITreeSelection) { - ITreeSelection inputSelection = (ITreeSelection)inputObject; - if (inputSelection.getPaths().length == 1) { - retVal = findDmcInPath(null, inputSelection.getPaths()[0], dmcType); - } - } else if (inputObject instanceof IStructuredSelection) { - Object rootElement = ((IStructuredSelection)inputObject).getFirstElement(); - if (rootElement instanceof IDMVMContext) { - retVal = DMContexts.getAncestorOfType(((IDMVMContext)rootElement).getDMContext(), dmcType); - } - } else if (inputObject instanceof IDMVMContext) { - retVal = DMContexts.getAncestorOfType(((IDMVMContext)inputObject).getDMContext(), dmcType); - } - } - - return retVal; - } - - /** - * This method looks for a specific DMC, used in a IVMNode type. If found, its index is returned, else - * index 0. - * - * @param nodeType the node to search on - * @param wantedCtx the dmc we are looking-for - * @param parentDelta delta for the parent VMNode - * @param rm request monitor - */ - protected void getVMCIndexForDmc(IVMNode nodetype, IDMContext wantedCtx, VMDelta parentDelta, DataRequestMonitor<Integer> rm) { - final int indexFailed = 0; - getVMProvider().updateNode(nodetype, new VMChildrenUpdate( - parentDelta, getVMProvider().getPresentationContext(), -1, -1, - new DataRequestMonitor<List<Object>>(getExecutor(), rm) { - @Override - protected void handleSuccess() { - boolean found = false; - for (int i = 0; i < getData().size(); i++) { - if (getData().get(i) instanceof IDMVMContext) { - IDMVMContext vmc = (IDMVMContext)getData().get(i); - if (vmc.getDMContext().equals(wantedCtx)) { - rm.setData(i); - found = true; - break; - } - } - } - if (!found) { - rm.setData(indexFailed); - } - rm.done(); - } - })); - } + // After every dispatch, must check if update still valid. + for (IChildrenUpdate update : updates) { + if (!checkUpdate(update)) + continue; + updateElementsInSessionThread(update); + } + } + }); + } catch (RejectedExecutionException e) { + for (IViewerUpdate update : updates) { + handleFailedUpdate(update); + } + } + } + + @ConfinedToDsfExecutor("getSession().getExecutor()") + abstract protected void updateElementsInSessionThread(IChildrenUpdate update); + + /** + * Utility method that takes an array of DMC object and creates a + * corresponding array of IVMContext elements base on that. + * @param parent The parent for generated IVMContext elements. + * @param dmcs Array of DMC objects to build return array on. + * @return Array of IVMContext objects. + */ + protected IVMContext[] dmcs2vmcs(IDMContext[] dmcs) { + IVMContext[] vmContexts = new IVMContext[dmcs.length]; + for (int i = 0; i < dmcs.length; i++) { + vmContexts[i] = createVMContext(dmcs[i]); + } + return vmContexts; + } + + /** + * Fill update request with view model contexts based on given data model contexts. + * Assumes that data model context elements start at index 0. + * + * @param update the viewer update request + * @param dmcs the data model contexts + */ + protected void fillUpdateWithVMCs(IChildrenUpdate update, IDMContext[] dmcs) { + fillUpdateWithVMCs(update, dmcs, 0); + } + + /** + * Fill update request with view model contexts based on given data model contexts. + * + * @param update the viewer update request + * @param dmcs the data model contexts + * @param firstIndex the index of the first data model context + * + * @since 1.1 + */ + protected void fillUpdateWithVMCs(IChildrenUpdate update, IDMContext[] dmcs, int firstIndex) { + int updateIdx = update.getOffset() != -1 ? update.getOffset() : 0; + final int endIdx = updateIdx + (update.getLength() != -1 ? update.getLength() : dmcs.length); + int dmcIdx = updateIdx - firstIndex; + if (dmcIdx < 0) { + updateIdx -= dmcIdx; + dmcIdx = 0; + } + while (updateIdx < endIdx && dmcIdx < dmcs.length) { + update.setChild(createVMContext(dmcs[dmcIdx++]), updateIdx++); + } + } + + protected IDMVMContext createVMContext(IDMContext dmc) { + return new DMVMContext(dmc); + } + + /** + * Creates a default CompositeDMVMContext which represents the selection. + * This can be overridden by view model providers which for their own purposes. + * @param update defines the selection to be updated to + * @return DM Context which represent the current selection + */ + protected IDMContext createCompositeDMVMContext(IViewerUpdate update) { + return new CompositeDMVMContext(update); + } + + /** + * Searches for a DMC of given type in the tree path contained in given + * VMC. Only a DMC in the same session will be returned. + * @param <V> Type of the DMC that will be returned. + * @param vmc VMC element to search. + * @param dmcType Class object for matching the type. + * @return DMC, or null if not found. + */ + protected <T extends IDMContext> T findDmcInPath(Object inputObject, TreePath path, Class<T> dmcType) { + T retVal = null; + for (int i = path.getSegmentCount() - 1; i >= 0; i--) { + if (path.getSegment(i) instanceof IDMVMContext) { + IDMContext dmc = ((IDMVMContext) path.getSegment(i)).getDMContext(); + if (dmc.getSessionId().equals(getSession().getId())) { + retVal = DMContexts.getAncestorOfType(dmc, dmcType); + if (retVal != null) + break; + } + } + } + // Search the root object of the layout hierarchy. + if (retVal == null) { + if (inputObject instanceof ITreeSelection) { + ITreeSelection inputSelection = (ITreeSelection) inputObject; + if (inputSelection.getPaths().length == 1) { + retVal = findDmcInPath(null, inputSelection.getPaths()[0], dmcType); + } + } else if (inputObject instanceof IStructuredSelection) { + Object rootElement = ((IStructuredSelection) inputObject).getFirstElement(); + if (rootElement instanceof IDMVMContext) { + retVal = DMContexts.getAncestorOfType(((IDMVMContext) rootElement).getDMContext(), dmcType); + } + } else if (inputObject instanceof IDMVMContext) { + retVal = DMContexts.getAncestorOfType(((IDMVMContext) inputObject).getDMContext(), dmcType); + } + } + + return retVal; + } + + /** + * This method looks for a specific DMC, used in a IVMNode type. If found, its index is returned, else + * index 0. + * + * @param nodeType the node to search on + * @param wantedCtx the dmc we are looking-for + * @param parentDelta delta for the parent VMNode + * @param rm request monitor + */ + protected void getVMCIndexForDmc(IVMNode nodetype, IDMContext wantedCtx, VMDelta parentDelta, + DataRequestMonitor<Integer> rm) { + final int indexFailed = 0; + getVMProvider().updateNode(nodetype, new VMChildrenUpdate(parentDelta, getVMProvider().getPresentationContext(), + -1, -1, new DataRequestMonitor<List<Object>>(getExecutor(), rm) { + @Override + protected void handleSuccess() { + boolean found = false; + for (int i = 0; i < getData().size(); i++) { + if (getData().get(i) instanceof IDMVMContext) { + IDMVMContext vmc = (IDMVMContext) getData().get(i); + if (vmc.getDMContext().equals(wantedCtx)) { + rm.setData(i); + found = true; + break; + } + } + } + if (!found) { + rm.setData(indexFailed); + } + rm.done(); + } + })); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/AbstractDMVMProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/AbstractDMVMProvider.java index b383fcd53f2..409e1bb7820 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/AbstractDMVMProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/AbstractDMVMProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -24,37 +24,40 @@ import org.eclipse.debug.internal.ui.viewers.provisional.IAsynchronousContentAda import org.eclipse.debug.internal.ui.viewers.provisional.IAsynchronousLabelAdapter; /** - * View model provider implements the asynchronous view model functionality for + * View model provider implements the asynchronous view model functionality for * a single view. This provider is just a holder which further delegates the * model provider functionality to the view model nodes that need * to be configured with each provider. * <p> - * The view model provider, often does not provide the model for the entire + * The view model provider, often does not provide the model for the entire * view. Rather, it needs to be able to plug in at any level in the viewer's * content model and provide data for a sub-tree. - * + * * @see IAsynchronousContentAdapter * @see IAsynchronousLabelAdapter * @see IModelProxy * @see IVMNode - * + * * @since 1.0 */ @ConfinedToDsfExecutor("fSession#getExecutor") @SuppressWarnings("restriction") -abstract public class AbstractDMVMProvider extends AbstractCachingVMProvider -{ - private final DsfSession fSession; - /** - * Constructs the view model provider for given DSF session. The - * constructor is thread-safe to allow VM provider to be constructed - * synchronously when a call to getAdapter() is made on an element - * in a view. - */ - public AbstractDMVMProvider(AbstractVMAdapter adapter, IPresentationContext presentationContext, DsfSession session) { - super(adapter, presentationContext); - fSession = session; - } +abstract public class AbstractDMVMProvider extends AbstractCachingVMProvider { + private final DsfSession fSession; + + /** + * Constructs the view model provider for given DSF session. The + * constructor is thread-safe to allow VM provider to be constructed + * synchronously when a call to getAdapter() is made on an element + * in a view. + */ + public AbstractDMVMProvider(AbstractVMAdapter adapter, IPresentationContext presentationContext, + DsfSession session) { + super(adapter, presentationContext); + fSession = session; + } - public DsfSession getSession() { return fSession; } + public DsfSession getSession() { + return fSession; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/CompositeDMVMContext.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/CompositeDMVMContext.java index c19c4d22783..dd8123d4fb6 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/CompositeDMVMContext.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/CompositeDMVMContext.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -22,53 +22,53 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; import org.eclipse.jface.viewers.TreePath; /** - * Object used to combine several DM Contexts found in a tree path of a viewer - * update. This object allows the view model to pass complete data model context - * information found in the view to the services. - * + * Object used to combine several DM Contexts found in a tree path of a viewer + * update. This object allows the view model to pass complete data model context + * information found in the view to the services. + * * @since 1.0 */ public class CompositeDMVMContext extends CompositeDMContext { - - /** - * Have to pass in an empty array of contexts to parent constructor - * in order to be able to calculate the - */ - private static IDMContext[] EMPTY_CONTEXTS_ARRAY = new IDMContext[0]; - /** - * The list of parent contexts derived from the input object and - * the path. It is calculated on demand. - */ - private IDMContext[] fParents; + /** + * Have to pass in an empty array of contexts to parent constructor + * in order to be able to calculate the + */ + private static IDMContext[] EMPTY_CONTEXTS_ARRAY = new IDMContext[0]; - /** - * Creates a composite context based in a viewer update. - */ - public CompositeDMVMContext(IViewerUpdate update) { - this(update.getViewerInput(), update.getElementPath()); - } + /** + * The list of parent contexts derived from the input object and + * the path. It is calculated on demand. + */ + private IDMContext[] fParents; - /** - * Creates a composite context based on a viewer input and a tree path. - */ - public CompositeDMVMContext(Object viewerInputObject, TreePath treePath) { - super(EMPTY_CONTEXTS_ARRAY); - List<IDMContext> parentsList = new ArrayList<IDMContext>(treePath.getSegmentCount() + 1); - for (int i = treePath.getSegmentCount() - 1; i >=0 ; i--) { - if (treePath.getSegment(i) instanceof IDMVMContext) { - parentsList.add( ((IDMVMContext)treePath.getSegment(i)).getDMContext() ); - } - } - if (viewerInputObject instanceof IDMVMContext) { - parentsList.add( ((IDMVMContext)viewerInputObject).getDMContext() ); - } - - fParents = parentsList.toArray(new IDMContext[parentsList.size()]); -} + /** + * Creates a composite context based in a viewer update. + */ + public CompositeDMVMContext(IViewerUpdate update) { + this(update.getViewerInput(), update.getElementPath()); + } + + /** + * Creates a composite context based on a viewer input and a tree path. + */ + public CompositeDMVMContext(Object viewerInputObject, TreePath treePath) { + super(EMPTY_CONTEXTS_ARRAY); + List<IDMContext> parentsList = new ArrayList<IDMContext>(treePath.getSegmentCount() + 1); + for (int i = treePath.getSegmentCount() - 1; i >= 0; i--) { + if (treePath.getSegment(i) instanceof IDMVMContext) { + parentsList.add(((IDMVMContext) treePath.getSegment(i)).getDMContext()); + } + } + if (viewerInputObject instanceof IDMVMContext) { + parentsList.add(((IDMVMContext) viewerInputObject).getDMContext()); + } + + fParents = parentsList.toArray(new IDMContext[parentsList.size()]); + } - @Override - public IDMContext[] getParents() { - return fParents; - } + @Override + public IDMContext[] getParents() { + return fParents; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/IDMVMContext.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/IDMVMContext.java index 47197e1adc9..a31ee1c31e2 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/IDMVMContext.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/IDMVMContext.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -17,16 +17,16 @@ import org.eclipse.cdt.dsf.datamodel.IDMContext; import org.eclipse.cdt.dsf.ui.viewmodel.IVMContext; /** - * Interface for a view model context based on a DSF data model context. - * + * Interface for a view model context based on a DSF data model context. + * * @since 1.0 */ public interface IDMVMContext extends IVMContext { - - public static Object REFRESH_EVENT = new Object(); - - /** - * returns the data model context that this view model context wraps. - */ - public IDMContext getDMContext(); + + public static Object REFRESH_EVENT = new Object(); + + /** + * returns the data model context that this view model context wraps. + */ + public IDMContext getDMContext(); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/RootDMVMNode.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/RootDMVMNode.java index 033c2447444..187a20f3a66 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/RootDMVMNode.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/datamodel/RootDMVMNode.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -22,76 +22,73 @@ import org.eclipse.cdt.dsf.ui.viewmodel.RootVMNode; /** * This is is a standard root node which listens to the selection in Debug View. - * Views such as variables and registers base their content on the + * Views such as variables and registers base their content on the * selection in Debug view, and this node provides tracking of that selection. * <p> - * Note: The variables/registers views track the selection using the same - * IDebugContextListener interface, but they only use the first element of the - * selection, as in IStructuredSelection.getFirstElement(). Therefore the root - * node also has to use the first element as the root object instead of the - * whole selection. - * + * Note: The variables/registers views track the selection using the same + * IDebugContextListener interface, but they only use the first element of the + * selection, as in IStructuredSelection.getFirstElement(). Therefore the root + * node also has to use the first element as the root object instead of the + * whole selection. + * * @since 1.0 */ -public class RootDMVMNode extends RootVMNode - implements IRootVMNode -{ - public RootDMVMNode(AbstractVMProvider provider) { - super(provider); - } +public class RootDMVMNode extends RootVMNode implements IRootVMNode { + public RootDMVMNode(AbstractVMProvider provider) { + super(provider); + } + + @Override + public String toString() { + return "RootDMVMNode"; //$NON-NLS-1$ + } + + /** + * If the input object is a Data Model context, and the event is a DMC event. + * Then we can filter the event to make sure that the view does not + * react to events that relate to objects outside this view. + * + * The logic is such: + * - iterate through the full hierarchy of the DMC in the event, + * - for each DMC in event, search for a DMC of the same type in the input + * event, + * - if an ancestor of that type is found, it indicates that the event + * and the input object share the same hierarchy + * - finally compare the DMContexts from the event to the DMC from the input + * object, + * - if there is a match then we know that the event relates + * to the hierarchy in view, + * - if there is no match, then we know that the event related to a + * some sibling of the input object, and no delta should be generated, + * - if none of the ancestor types matched, then the event is completely + * unrelated to the input object, and the layout nodes in the view must + * determine whether a delta is needed. + */ + @Override + public boolean isDeltaEvent(Object rootObject, Object event) { + if (rootObject instanceof IDMVMContext) { + IDMContext inputDmc = ((IDMVMContext) rootObject).getDMContext(); + if (event instanceof IDMEvent && inputDmc != null) { + boolean potentialMatchFound = false; + boolean matchFound = false; + IDMContext eventDmc = ((IDMEvent<?>) event).getDMContext(); + for (IDMContext eventDmcAncestor : DMContexts.toList(eventDmc)) { + IDMContext inputDmcAncestor = DMContexts.getAncestorOfType(inputDmc, eventDmcAncestor.getClass()); + if (inputDmcAncestor != null) { + potentialMatchFound = true; + if (inputDmcAncestor.equals(eventDmcAncestor)) { + return true; + } + } + } + if (potentialMatchFound && !matchFound) { + return false; + } + } + } - @Override - public String toString() { - return "RootDMVMNode"; //$NON-NLS-1$ - } + return true; + } - /** - * If the input object is a Data Model context, and the event is a DMC event. - * Then we can filter the event to make sure that the view does not - * react to events that relate to objects outside this view. - * - * The logic is such: - * - iterate through the full hierarchy of the DMC in the event, - * - for each DMC in event, search for a DMC of the same type in the input - * event, - * - if an ancestor of that type is found, it indicates that the event - * and the input object share the same hierarchy - * - finally compare the DMContexts from the event to the DMC from the input - * object, - * - if there is a match then we know that the event relates - * to the hierarchy in view, - * - if there is no match, then we know that the event related to a - * some sibling of the input object, and no delta should be generated, - * - if none of the ancestor types matched, then the event is completely - * unrelated to the input object, and the layout nodes in the view must - * determine whether a delta is needed. - */ - @Override - public boolean isDeltaEvent(Object rootObject, Object event) { - if (rootObject instanceof IDMVMContext) { - IDMContext inputDmc = ((IDMVMContext)rootObject).getDMContext(); - if (event instanceof IDMEvent && inputDmc != null) { - boolean potentialMatchFound = false; - boolean matchFound = false; - - IDMContext eventDmc = ((IDMEvent<?>)event).getDMContext(); - for (IDMContext eventDmcAncestor : DMContexts.toList(eventDmc)) { - IDMContext inputDmcAncestor = DMContexts.getAncestorOfType(inputDmc, eventDmcAncestor.getClass()); - if (inputDmcAncestor != null) { - potentialMatchFound = true; - if (inputDmcAncestor.equals(eventDmcAncestor)) { - return true; - } - } - } - if (potentialMatchFound && !matchFound) { - return false; - } - } - } - - return true; - } - } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/IElementPropertiesProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/IElementPropertiesProvider.java index 164feb702e9..dccecbd61a4 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/IElementPropertiesProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/IElementPropertiesProvider.java @@ -7,34 +7,33 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.dsf.ui.viewmodel.properties; - /** - * Provides context-sensitive properties. Can be registered as an adapter for + * Provides context-sensitive properties. Can be registered as an adapter for * an element or implemented directly - * + * * @since 1.0 */ public interface IElementPropertiesProvider { - /** - * Common property representing an element's name. This property can be - * used in future extensions for filtering and sorting. - * - * @since 2.0 - */ - public static final String PROP_NAME = "name"; //$NON-NLS-1$ - - /** - * Updates the specified property sets. - * - * @param updates each update specifies the element and context for which - * a set of properties is requested and stores them - */ - public void update(IPropertiesUpdate[] updates); + /** + * Common property representing an element's name. This property can be + * used in future extensions for filtering and sorting. + * + * @since 2.0 + */ + public static final String PROP_NAME = "name"; //$NON-NLS-1$ + + /** + * Updates the specified property sets. + * + * @param updates each update specifies the element and context for which + * a set of properties is requested and stores them + */ + public void update(IPropertiesUpdate[] updates); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/IPropertiesUpdate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/IPropertiesUpdate.java index 595f110bdcc..00c08fd1b1d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/IPropertiesUpdate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/IPropertiesUpdate.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,30 +20,30 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; /** * Context sensitive properties update request for an element. - * + * * @since 1.0 */ public interface IPropertiesUpdate extends IViewerUpdate { - /** - * Returns the set of element properties that the provider should update. - */ - public Set<String> getProperties(); - - /** - * Sets the given property to update. - * - * @param property Property ID. - * @param value Property value. - */ - public void setProperty(String property, Object value); - - /** - * Sets the given map as the complete property map for this update. - * If other properties were already set to this update, the properties - * given here will be added. If properties are added later, the properties - * map given here will not be modified, instead it will be copied. - * - * @param properties Full properties map. - */ - public void setAllProperties(Map<String, Object> properties); + /** + * Returns the set of element properties that the provider should update. + */ + public Set<String> getProperties(); + + /** + * Sets the given property to update. + * + * @param property Property ID. + * @param value Property value. + */ + public void setProperty(String property, Object value); + + /** + * Sets the given map as the complete property map for this update. + * If other properties were already set to this update, the properties + * given here will be added. If properties are added later, the properties + * map given here will not be modified, instead it will be copied. + * + * @param properties Full properties map. + */ + public void setAllProperties(Map<String, Object> properties); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/IPropertiesUpdateListener.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/IPropertiesUpdateListener.java index db3c66ac3ff..2ff1d28be71 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/IPropertiesUpdateListener.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/IPropertiesUpdateListener.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -15,19 +15,19 @@ package org.eclipse.cdt.dsf.ui.viewmodel.properties; /** * Listener for properties updates requested by a property based label provider. - * + * * @since 2.2 */ public interface IPropertiesUpdateListener { - - /** - * Indicates that the given updates were requested from a properties provider. - */ - public void propertiesUpdatesStarted(IPropertiesUpdate[] updates); - - /** - * Indicates that the given update has been completed. - */ - public void propertiesUpdateCompleted(IPropertiesUpdate update); + + /** + * Indicates that the given updates were requested from a properties provider. + */ + public void propertiesUpdatesStarted(IPropertiesUpdate[] updates); + + /** + * Indicates that the given update has been completed. + */ + public void propertiesUpdateCompleted(IPropertiesUpdate update); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelAttribute.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelAttribute.java index 7246664a403..bee1a0edc25 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelAttribute.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelAttribute.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -19,105 +19,105 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate; /** - * This is a base class for a label attribute used in generating label - * information based on properties of an element. There are currently - * four types of attributes: text, image, font, and color, and a given - * attribute can be either enabled or disabled based on the element + * This is a base class for a label attribute used in generating label + * information based on properties of an element. There are currently + * four types of attributes: text, image, font, and color, and a given + * attribute can be either enabled or disabled based on the element * properties. * <p/> - * Clients are intended to override this class and its extensions to - * implement the {@link LabelAttribute#isEnabled(Map)} and - * {@link LabelAttribute#getPropertyNames()} methods as needed. Clients can - * also override how the attribute settings are stored, for example in - * order to use a preference. - * + * Clients are intended to override this class and its extensions to + * implement the {@link LabelAttribute#isEnabled(Map)} and + * {@link LabelAttribute#getPropertyNames()} methods as needed. Clients can + * also override how the attribute settings are stored, for example in + * order to use a preference. + * * @see PropertiesBasedLabelProvider - * @see LabelColumnInfo - * + * @see LabelColumnInfo + * * @since 1.0 */ abstract public class LabelAttribute { - public static final String[] EMPTY_PROPERTY_NAMES_ARRAY = new String[0]; - - /** - * @since 2.0 - */ - private String[] fPropertyNames = EMPTY_PROPERTY_NAMES_ARRAY; - - public LabelAttribute() { - this(EMPTY_PROPERTY_NAMES_ARRAY); - } - - /** - * @since 2.0 - */ - public LabelAttribute(String[] propertyNames) { - setPropertyNames(propertyNames); - } - - protected void setPropertyNames(String[] propertyNames) { - fPropertyNames = propertyNames; - } - - /** - * Returns the properties that are needed by this attribute in order to - * determine whether this attribute is enabled and/or for the actual - * attribute itself. - * @return Array of names of properties for the element properties provider. - */ - public String[] getPropertyNames() { - return fPropertyNames; - } - - /** - * Returns whether this attribute is enabled for an element which has - * the given properties. The default implementation checks if all the - * label's attributes are present in the properties map. - * - * @param status Result of the properties update. - * @param properties Properties supplied by a property update. - * @return true if this attribute is enabled. - * - * @since 2.0 - */ - public boolean isEnabled(IStatus status, Map<String, Object> properties) { - for (String propertyName : getPropertyNames()) { - if (!checkProperty(propertyName, status, properties)) { - return false; - } - } - return true; - } + public static final String[] EMPTY_PROPERTY_NAMES_ARRAY = new String[0]; + + /** + * @since 2.0 + */ + private String[] fPropertyNames = EMPTY_PROPERTY_NAMES_ARRAY; + + public LabelAttribute() { + this(EMPTY_PROPERTY_NAMES_ARRAY); + } + + /** + * @since 2.0 + */ + public LabelAttribute(String[] propertyNames) { + setPropertyNames(propertyNames); + } + + protected void setPropertyNames(String[] propertyNames) { + fPropertyNames = propertyNames; + } + + /** + * Returns the properties that are needed by this attribute in order to + * determine whether this attribute is enabled and/or for the actual + * attribute itself. + * @return Array of names of properties for the element properties provider. + */ + public String[] getPropertyNames() { + return fPropertyNames; + } + /** + * Returns whether this attribute is enabled for an element which has + * the given properties. The default implementation checks if all the + * label's attributes are present in the properties map. + * + * @param status Result of the properties update. + * @param properties Properties supplied by a property update. + * @return true if this attribute is enabled. + * + * @since 2.0 + */ + public boolean isEnabled(IStatus status, Map<String, Object> properties) { + for (String propertyName : getPropertyNames()) { + if (!checkProperty(propertyName, status, properties)) { + return false; + } + } + return true; + } - /** - * Checks the status of the given property in the given properties map. The - * default implementation returns <code>true</code> if the given property - * exists and is not null. - * - * @param propertyName Name of the property to check. - * @param status Result of the properties update. - * @param properties Properties map following an update. - * @return <code>true</code> if the property exists in the given map and - * its value is not null. - * - * @since 2.0 - */ - protected boolean checkProperty(String propertyName, IStatus status, Map<String, Object> properties) { - return properties.get(propertyName) != null; - } + /** + * Checks the status of the given property in the given properties map. The + * default implementation returns <code>true</code> if the given property + * exists and is not null. + * + * @param propertyName Name of the property to check. + * @param status Result of the properties update. + * @param properties Properties map following an update. + * @return <code>true</code> if the property exists in the given map and + * its value is not null. + * + * @since 2.0 + */ + protected boolean checkProperty(String propertyName, IStatus status, Map<String, Object> properties) { + return properties.get(propertyName) != null; + } - /** - * Updates the label with this attribute. - * - * @param update Label update object to write to. - * @param columnIndex Column index to write at. - * @param status Result of the property update. - * @param properties Property values map. It is guaranteed to contain all - * the properties that this attribute requested through - * {@link getPropertyNames()}. - * - * @since 2.0 - */ - abstract public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties); + /** + * Updates the label with this attribute. + * + * @param update Label update object to write to. + * @param columnIndex Column index to write at. + * @param status Result of the property update. + * @param properties Property values map. It is guaranteed to contain all + * the properties that this attribute requested through + * {@link getPropertyNames()}. + * + * @since 2.0 + */ + abstract public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, + Map<String, Object> properties); }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelBackground.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelBackground.java index 6988038cc5c..fd2aa3e7226 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelBackground.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelBackground.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,36 +20,36 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate; import org.eclipse.swt.graphics.RGB; /** - * The color attribute of a label. It determines what background color to use + * The color attribute of a label. It determines what background color to use * for the given label. - * + * * @see LabelAttribute * @see LabelColumnInfo * @see PropertiesBasedLabelProvider - * + * * @since 2.0 */ public class LabelBackground extends LabelAttribute { - private RGB fBackground; - - public LabelBackground(RGB background) { - fBackground = background; - } - - public RGB getBackground() { - return fBackground; - } - - public void setBackground(RGB background) { - fBackground = background; - } - - @Override - public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { - RGB background = getBackground(); - if (background != null) { - update.setBackground(background, columnIndex); - } - } + private RGB fBackground; + + public LabelBackground(RGB background) { + fBackground = background; + } + + public RGB getBackground() { + return fBackground; + } + + public void setBackground(RGB background) { + fBackground = background; + } + + @Override + public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { + RGB background = getBackground(); + if (background != null) { + update.setBackground(background, columnIndex); + } + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelColumnInfo.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelColumnInfo.java index af7c1788dec..e17ee6343be 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelColumnInfo.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelColumnInfo.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -22,131 +22,130 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate; /** - * Class used by the PropertiesBasedLabelProvider to generate store - * label attributes related to a single column. Each column info is + * Class used by the PropertiesBasedLabelProvider to generate store + * label attributes related to a single column. Each column info is * configured with an array of attributes (there are currently four - * types of attributes: text, image, font, and color), which are - * evaluated in order to generate the label. + * types of attributes: text, image, font, and color), which are + * evaluated in order to generate the label. * <p/> * Clients are not intended to extend this class. - * + * * @see PropertiesBasedLabelProvider - * + * * @since 1.0 */ @ThreadSafe -public class LabelColumnInfo { - /** - * Calculated list of property names that need to be retrieved to - * generate the label for this column. - */ - private String[] fPropertyNames; - - /** - * Array of label attribute objects. - */ - private LabelAttribute[] fLabelAttributes; - - /** - * Creates the column info object with given array of attributes. - * @param attributeInfos Attributes for the label. - */ - public LabelColumnInfo(LabelAttribute[] attributes) - { - fLabelAttributes = attributes; - - List<String> names = new LinkedList<String>(); - for (LabelAttribute attr : attributes) { - for (String name : attr.getPropertyNames()) { - names.add(name); - } - } - - fPropertyNames = names.toArray(new String[names.size()]); - } - - /** - * Returns the property names that need to be retrieved in order - * to generate the label for this column. - */ - public String[] getPropertyNames() { return fPropertyNames; } - - /** - * Returns the list of configured label attributes for this column. - */ - public LabelAttribute[] getLabelAttributes() { return fLabelAttributes; } - - /** - * Returns the list of configured label attributes for this column. - * - * @since 2.1 - */ - protected void setLabelAttributes(LabelAttribute[] attributes) { - fLabelAttributes = attributes; - - List<String> names = new LinkedList<String>(); - for (LabelAttribute attr : attributes) { - for (String name : attr.getPropertyNames()) { - names.add(name); - } - } - - fPropertyNames = names.toArray(new String[names.size()]); - } - - /** - * Inserts an attribute in front of all the other existing attributes. - * - * @since 2.1 - */ - public void insertAttribute(LabelAttribute attribute) { - LabelAttribute[] newAttributeList = new LabelAttribute[fLabelAttributes.length+1]; - - for ( int idx = 0 ; idx < fLabelAttributes.length; idx ++ ) { - newAttributeList[ idx + 1 ] = fLabelAttributes[ idx ]; - } - - newAttributeList[ 0 ] = attribute; - - setLabelAttributes( newAttributeList ); - } - - /** - * Updates the label parameters for this column based on the provided - * properties. The label information is written to the givne label - * update under the given column index. - * - * @param update Update to write to. - * @param columnIndex Column to write label information under. - * @param status Result of the properties update - * @param properties Map of properties to use to generate the label. - * - * @since 2.0 - */ - public void updateColumn(ILabelUpdate update, int columnIndex, IStatus status, Map<String,Object> properties) { - boolean textSet = false; - boolean imageSet = false; - boolean fontSet = false; - boolean foregroundSet = false; - boolean backgroundSet = false; - - LabelAttribute[] labelAttributes = getLabelAttributes(); - for (LabelAttribute info : labelAttributes) { - - if (!(info instanceof LabelText && textSet) && - !(info instanceof LabelImage && imageSet) && - !(info instanceof LabelFont && fontSet) && - !(info instanceof LabelForeground && foregroundSet) && - !(info instanceof LabelBackground && backgroundSet) && - info.isEnabled(status, properties)) - { - info.updateAttribute(update, columnIndex, status, properties); - textSet = textSet || info instanceof LabelText; - imageSet = imageSet || info instanceof LabelImage; - fontSet = fontSet || info instanceof LabelFont; - foregroundSet = foregroundSet || info instanceof LabelForeground; - backgroundSet = backgroundSet || info instanceof LabelBackground; - } - } - } +public class LabelColumnInfo { + /** + * Calculated list of property names that need to be retrieved to + * generate the label for this column. + */ + private String[] fPropertyNames; + + /** + * Array of label attribute objects. + */ + private LabelAttribute[] fLabelAttributes; + + /** + * Creates the column info object with given array of attributes. + * @param attributeInfos Attributes for the label. + */ + public LabelColumnInfo(LabelAttribute[] attributes) { + fLabelAttributes = attributes; + + List<String> names = new LinkedList<String>(); + for (LabelAttribute attr : attributes) { + for (String name : attr.getPropertyNames()) { + names.add(name); + } + } + + fPropertyNames = names.toArray(new String[names.size()]); + } + + /** + * Returns the property names that need to be retrieved in order + * to generate the label for this column. + */ + public String[] getPropertyNames() { + return fPropertyNames; + } + + /** + * Returns the list of configured label attributes for this column. + */ + public LabelAttribute[] getLabelAttributes() { + return fLabelAttributes; + } + + /** + * Returns the list of configured label attributes for this column. + * + * @since 2.1 + */ + protected void setLabelAttributes(LabelAttribute[] attributes) { + fLabelAttributes = attributes; + + List<String> names = new LinkedList<String>(); + for (LabelAttribute attr : attributes) { + for (String name : attr.getPropertyNames()) { + names.add(name); + } + } + + fPropertyNames = names.toArray(new String[names.size()]); + } + + /** + * Inserts an attribute in front of all the other existing attributes. + * + * @since 2.1 + */ + public void insertAttribute(LabelAttribute attribute) { + LabelAttribute[] newAttributeList = new LabelAttribute[fLabelAttributes.length + 1]; + + for (int idx = 0; idx < fLabelAttributes.length; idx++) { + newAttributeList[idx + 1] = fLabelAttributes[idx]; + } + + newAttributeList[0] = attribute; + + setLabelAttributes(newAttributeList); + } + + /** + * Updates the label parameters for this column based on the provided + * properties. The label information is written to the givne label + * update under the given column index. + * + * @param update Update to write to. + * @param columnIndex Column to write label information under. + * @param status Result of the properties update + * @param properties Map of properties to use to generate the label. + * + * @since 2.0 + */ + public void updateColumn(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { + boolean textSet = false; + boolean imageSet = false; + boolean fontSet = false; + boolean foregroundSet = false; + boolean backgroundSet = false; + + LabelAttribute[] labelAttributes = getLabelAttributes(); + for (LabelAttribute info : labelAttributes) { + + if (!(info instanceof LabelText && textSet) && !(info instanceof LabelImage && imageSet) + && !(info instanceof LabelFont && fontSet) && !(info instanceof LabelForeground && foregroundSet) + && !(info instanceof LabelBackground && backgroundSet) && info.isEnabled(status, properties)) { + info.updateAttribute(update, columnIndex, status, properties); + textSet = textSet || info instanceof LabelText; + imageSet = imageSet || info instanceof LabelImage; + fontSet = fontSet || info instanceof LabelFont; + foregroundSet = foregroundSet || info instanceof LabelForeground; + backgroundSet = backgroundSet || info instanceof LabelBackground; + } + } + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelFont.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelFont.java index b8e1379e4a6..d360ba7eb3b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelFont.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelFont.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -22,40 +22,40 @@ import org.eclipse.swt.graphics.FontData; /** * The font attribute of a label. - * + * * @see LabelAttribute * @see LabelColumnInfo * @see PropertiesBasedLabelProvider - * + * * @since 1.0 */ public class LabelFont extends LabelAttribute { - private static final FontData DEFAULT_FONT = JFaceResources.getDefaultFontDescriptor().getFontData()[0]; - - /** - * The font data of this attribute. - */ - private FontData fFontData; - - public LabelFont() { - this(DEFAULT_FONT); - } - - public LabelFont(FontData fontData) { - fFontData = fontData; - } - - public FontData getFontData() { - return fFontData; - } - - public void setFontData(FontData fontData) { - fFontData = fontData; - } - - @Override - public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { - update.setFontData(getFontData(), columnIndex); - } + private static final FontData DEFAULT_FONT = JFaceResources.getDefaultFontDescriptor().getFontData()[0]; + + /** + * The font data of this attribute. + */ + private FontData fFontData; + + public LabelFont() { + this(DEFAULT_FONT); + } + + public LabelFont(FontData fontData) { + fFontData = fontData; + } + + public FontData getFontData() { + return fFontData; + } + + public void setFontData(FontData fontData) { + fFontData = fontData; + } + + @Override + public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { + update.setFontData(getFontData(), columnIndex); + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelForeground.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelForeground.java index 9f8cdb5500b..54f324ac12b 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelForeground.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelForeground.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,36 +20,36 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate; import org.eclipse.swt.graphics.RGB; /** - * The color attribute of a label. It determines what foreground color to use + * The color attribute of a label. It determines what foreground color to use * for the given label. - * + * * @see LabelAttribute * @see LabelColumnInfo * @see PropertiesBasedLabelProvider - * + * * @since 2.0 */ public class LabelForeground extends LabelAttribute { - private RGB fForeground; - - public LabelForeground(RGB foreground) { - fForeground = foreground; - } - - public RGB getForeground() { - return fForeground; - } - - public void setForeground(RGB foreground) { - fForeground = foreground; - } - - @Override - public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { - RGB foreground = getForeground(); - if (foreground != null) { - update.setForeground(foreground, columnIndex); - } - } + private RGB fForeground; + + public LabelForeground(RGB foreground) { + fForeground = foreground; + } + + public RGB getForeground() { + return fForeground; + } + + public void setForeground(RGB foreground) { + fForeground = foreground; + } + + @Override + public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { + RGB foreground = getForeground(); + if (foreground != null) { + update.setForeground(foreground, columnIndex); + } + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelImage.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelImage.java index ee74b4e06dc..e316bc7304e 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelImage.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelImage.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -21,37 +21,37 @@ import org.eclipse.jface.resource.ImageDescriptor; /** * The image attribute of a label. - * + * * @see LabelAttribute * @see LabelColumnInfo * @see PropertiesBasedLabelProvider - * + * * @since 1.0 */ public class LabelImage extends LabelAttribute { - private ImageDescriptor fImageDescriptor; - - public LabelImage() { - this(null); - } - - public LabelImage(ImageDescriptor image) { - fImageDescriptor = image; - } - - public ImageDescriptor getImageDescriptor() { - return fImageDescriptor; - } - - public void setImageDescriptor(ImageDescriptor image) { - fImageDescriptor = image; - } - - @Override - public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { - ImageDescriptor descriptor = getImageDescriptor(); - if (descriptor != null) { - update.setImageDescriptor(descriptor, columnIndex); - } - } + private ImageDescriptor fImageDescriptor; + + public LabelImage() { + this(null); + } + + public LabelImage(ImageDescriptor image) { + fImageDescriptor = image; + } + + public ImageDescriptor getImageDescriptor() { + return fImageDescriptor; + } + + public void setImageDescriptor(ImageDescriptor image) { + fImageDescriptor = image; + } + + @Override + public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { + ImageDescriptor descriptor = getImageDescriptor(); + if (descriptor != null) { + update.setImageDescriptor(descriptor, columnIndex); + } + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelText.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelText.java index 977a8b496f1..7b48d36cc2f 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelText.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/LabelText.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -22,81 +22,84 @@ import org.eclipse.core.runtime.Status; import org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate; /** - * The text attribute of a label. It uses a message format string in order to + * The text attribute of a label. It uses a message format string in order to * compose the text string. The parameter names determine the array of objects - * given to the message format. - * + * given to the message format. + * * @see MessageFormat#format(Object[], StringBuffer, java.text.FieldPosition) * @see LabelAttribute * @see LabelColumnInfo * @see PropertiesBasedLabelProvider - * + * * @since 1.0 */ public class LabelText extends LabelAttribute { - - public static final MessageFormat DEFAULT_MESSAGE = new MessageFormat(MessagesForProperties.DefaultLabelMessage_label); - - /** - * Message format used to generate the label text. - * - */ - private MessageFormat fMessageFormat; - - /** - * The property names needed for the message format. The property values - * corresponding to these names are given the the {@link MessageFormat#format(Object[], StringBuffer, java.text.FieldPosition)} - * method. - */ - private String[] fPropertyNames; - public LabelText() { - this(DEFAULT_MESSAGE, EMPTY_PROPERTY_NAMES_ARRAY); - } + public static final MessageFormat DEFAULT_MESSAGE = new MessageFormat( + MessagesForProperties.DefaultLabelMessage_label); + + /** + * Message format used to generate the label text. + * + */ + private MessageFormat fMessageFormat; + + /** + * The property names needed for the message format. The property values + * corresponding to these names are given the the {@link MessageFormat#format(Object[], StringBuffer, java.text.FieldPosition)} + * method. + */ + private String[] fPropertyNames; + + public LabelText() { + this(DEFAULT_MESSAGE, EMPTY_PROPERTY_NAMES_ARRAY); + } + + /** + * @since 2.0 + * @param formatPattern + * @param propertyNames + */ + public LabelText(String formatPattern, String[] propertyNames) { + this(new MessageFormat(formatPattern), propertyNames); + } + + public LabelText(MessageFormat format, String[] propertyNames) { + fMessageFormat = format; + fPropertyNames = propertyNames; + } + + @Override + public String[] getPropertyNames() { + return fPropertyNames; + } + + public MessageFormat getMessageFormat() { + return fMessageFormat; + } - /** - * @since 2.0 - * @param formatPattern - * @param propertyNames - */ - public LabelText(String formatPattern, String[] propertyNames) { - this (new MessageFormat(formatPattern), propertyNames); - } + public void setMessageFormat(MessageFormat messageFormat) { + fMessageFormat = messageFormat; + } - public LabelText(MessageFormat format, String[] propertyNames) { - fMessageFormat = format; - fPropertyNames = propertyNames; - } - - @Override - public String[] getPropertyNames() { - return fPropertyNames; - } - - public MessageFormat getMessageFormat() { - return fMessageFormat; - } + @Override + public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { + String[] propertyNames = getPropertyNames(); + Object[] propertyValues = new Object[propertyNames.length]; + for (int i = 0; i < propertyNames.length; i++) { + propertyValues[i] = getPropertyValue(propertyNames[i], status, properties); + } - public void setMessageFormat(MessageFormat messageFormat) { - fMessageFormat = messageFormat; - } + try { + update.setLabel(getMessageFormat().format(propertyValues, new StringBuffer(), null).toString(), + columnIndex); + } catch (IllegalArgumentException e) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, 0, + "Failed formatting a message for column " + columnIndex + ", for update " + update, e)); //$NON-NLS-1$ //$NON-NLS-2$ + } + } - @Override - public void updateAttribute(ILabelUpdate update, int columnIndex, IStatus status, Map<String, Object> properties) { - String[] propertyNames = getPropertyNames(); - Object[] propertyValues = new Object[propertyNames.length]; - for (int i = 0; i < propertyNames.length; i++) { - propertyValues[i] = getPropertyValue(propertyNames[i], status, properties); - } - - try { - update.setLabel(getMessageFormat().format(propertyValues, new StringBuffer(), null).toString(), columnIndex); - } catch (IllegalArgumentException e) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, 0, "Failed formatting a message for column " + columnIndex + ", for update " + update, e)); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - protected Object getPropertyValue(String propertyName, IStatus status, Map<String, Object> properties) { - return properties.get(propertyName); - } + protected Object getPropertyValue(String propertyName, IStatus status, Map<String, Object> properties) { + return properties.get(propertyName); + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/MessagesForProperties.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/MessagesForProperties.java index 30a764f450b..d7ad7d618bf 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/MessagesForProperties.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/MessagesForProperties.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -16,14 +16,14 @@ package org.eclipse.cdt.dsf.ui.viewmodel.properties; import org.eclipse.osgi.util.NLS; class MessagesForProperties extends NLS { - public static String DefaultLabelMessage_label; - public static String PropertiesUpdateStatus_message; - - static { - // initialize resource bundle - NLS.initializeMessages(MessagesForProperties.class.getName(), MessagesForProperties.class); - } + public static String DefaultLabelMessage_label; + public static String PropertiesUpdateStatus_message; + + static { + // initialize resource bundle + NLS.initializeMessages(MessagesForProperties.class.getName(), MessagesForProperties.class); + } - private MessagesForProperties() { - } + private MessagesForProperties() { + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/PropertiesBasedLabelProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/PropertiesBasedLabelProvider.java index d9aece18722..fa5cb57a35d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/PropertiesBasedLabelProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/PropertiesBasedLabelProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -31,224 +31,227 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IElementLabelProv import org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate; /** - * A configurable label provider which uses element's property label provider + * A configurable label provider which uses element's property label provider * to set element's label attributes. * <p> * When this provider is registered for an element it calculates the properties * that need to be retrieved based on view's active columns, and then it calls the * element's property provider to retrieve those properties. After the property - * values are retrieved, they are processed in order to produce correct label text, + * values are retrieved, they are processed in order to produce correct label text, * images, fonts, and colors, for the given element. - * - * @since 2.0 - Renamed from PropertyBasedLabelProvider + * + * @since 2.0 - Renamed from PropertyBasedLabelProvider */ @ThreadSafe -public class PropertiesBasedLabelProvider - implements IElementLabelProvider -{ - public static final String ID_COLUMN_NO_COLUMNS = "ID_COLUMN_NO_COLUMNS"; //$NON-NLS-1$ - - /** - * Attribute information for each column by column ID. - */ - private Map<String, LabelColumnInfo> fColumnInfos = Collections.synchronizedMap(new HashMap<String,LabelColumnInfo>()); - - private IPropertiesUpdateListener[] fListeners = new IPropertiesUpdateListener[0]; - - /** - * Standard constructor. A property based label constructor does not - * initialize column attribute information {@link #setColumnInfo(String, LabelColumnInfo)} - * must be called to configure each column. - */ - public PropertiesBasedLabelProvider() { - } - - /** - * Sets the given column info object for the given column ID. This column - * info will be used to generate the label when the given column is visibile. - * - * @param columnId Column ID that the given column info is being registered for. - * @param info Column 'info' object containing column attributes. - * @return The previous column info object configured for this ID. - */ - public LabelColumnInfo setColumnInfo(String columnId, LabelColumnInfo info) { - LabelColumnInfo oldInfo = fColumnInfos.put(columnId, info); - return oldInfo; - } - - /** - * Returns the given column info object for the given column ID. - * @param columnId Column ID to retrieve the column info for. - * - * @param columnId Column ID that the given column info is being registered for. - * @@return Column 'info' object containing column attributes. - */ - public LabelColumnInfo getColumnInfo(String columnId) { - return fColumnInfos.get(columnId); - } - - /** - * Adds a listener for properties updates generated by this label provider. - * - * @since 2.2 - */ - public void addPropertiesUpdateListener(IPropertiesUpdateListener listener) { - synchronized(this) { - if (!Arrays.asList(fListeners).contains(listener)) { - IPropertiesUpdateListener[] newListeners = new IPropertiesUpdateListener[fListeners.length + 1]; - System.arraycopy(fListeners, 0, newListeners, 0, fListeners.length); - newListeners[fListeners.length] = listener; - fListeners = newListeners; - } - } - } - - /** - * Removes a listener for properties updates generated by this label provider. - * - * @since 2.2 - */ - public void removePropertiesUpdateListener(IPropertiesUpdateListener listener) { - synchronized(this) { - int listenerIdx = Arrays.asList(fListeners).indexOf(listener); - - if (listenerIdx != -1) { - IPropertiesUpdateListener[] newListeners = new IPropertiesUpdateListener[fListeners.length - 1]; - System.arraycopy(fListeners, 0, newListeners, 0, listenerIdx); - System.arraycopy(fListeners, listenerIdx + 1, newListeners, listenerIdx, newListeners.length - listenerIdx); - fListeners = newListeners; - } - } - } +public class PropertiesBasedLabelProvider implements IElementLabelProvider { + public static final String ID_COLUMN_NO_COLUMNS = "ID_COLUMN_NO_COLUMNS"; //$NON-NLS-1$ + + /** + * Attribute information for each column by column ID. + */ + private Map<String, LabelColumnInfo> fColumnInfos = Collections + .synchronizedMap(new HashMap<String, LabelColumnInfo>()); + + private IPropertiesUpdateListener[] fListeners = new IPropertiesUpdateListener[0]; + + /** + * Standard constructor. A property based label constructor does not + * initialize column attribute information {@link #setColumnInfo(String, LabelColumnInfo)} + * must be called to configure each column. + */ + public PropertiesBasedLabelProvider() { + } + + /** + * Sets the given column info object for the given column ID. This column + * info will be used to generate the label when the given column is visibile. + * + * @param columnId Column ID that the given column info is being registered for. + * @param info Column 'info' object containing column attributes. + * @return The previous column info object configured for this ID. + */ + public LabelColumnInfo setColumnInfo(String columnId, LabelColumnInfo info) { + LabelColumnInfo oldInfo = fColumnInfos.put(columnId, info); + return oldInfo; + } + + /** + * Returns the given column info object for the given column ID. + * @param columnId Column ID to retrieve the column info for. + * + * @param columnId Column ID that the given column info is being registered for. + * @@return Column 'info' object containing column attributes. + */ + public LabelColumnInfo getColumnInfo(String columnId) { + return fColumnInfos.get(columnId); + } + + /** + * Adds a listener for properties updates generated by this label provider. + * + * @since 2.2 + */ + public void addPropertiesUpdateListener(IPropertiesUpdateListener listener) { + synchronized (this) { + if (!Arrays.asList(fListeners).contains(listener)) { + IPropertiesUpdateListener[] newListeners = new IPropertiesUpdateListener[fListeners.length + 1]; + System.arraycopy(fListeners, 0, newListeners, 0, fListeners.length); + newListeners[fListeners.length] = listener; + fListeners = newListeners; + } + } + } + + /** + * Removes a listener for properties updates generated by this label provider. + * + * @since 2.2 + */ + public void removePropertiesUpdateListener(IPropertiesUpdateListener listener) { + synchronized (this) { + int listenerIdx = Arrays.asList(fListeners).indexOf(listener); + + if (listenerIdx != -1) { + IPropertiesUpdateListener[] newListeners = new IPropertiesUpdateListener[fListeners.length - 1]; + System.arraycopy(fListeners, 0, newListeners, 0, listenerIdx); + System.arraycopy(fListeners, listenerIdx + 1, newListeners, listenerIdx, + newListeners.length - listenerIdx); + fListeners = newListeners; + } + } + } /** * In addition to guarantees on [labelUpdates] declared by * {@link IElementLabelProvider}, we further require/assume that all the * model elements referenced by [labelUpdates] adapt to the same * {@link IElementPropertiesProvider}. - * + * * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IElementLabelProvider#update(org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate[]) */ - @Override + @Override public void update(final ILabelUpdate[] labelUpdates) { - IElementPropertiesProvider propertiesProvider = getElementPropertiesProvider(labelUpdates[0].getElement()); - if (propertiesProvider == null) { - for (ILabelUpdate update : labelUpdates) { - update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, "Properties-based label provider " + this + " failed to generate a label, no properties provider registered for element: " + labelUpdates[0].getElement())); //$NON-NLS-1$ //$NON-NLS-2$ - update.done(); - } - return; - } - + IElementPropertiesProvider propertiesProvider = getElementPropertiesProvider(labelUpdates[0].getElement()); + if (propertiesProvider == null) { + for (ILabelUpdate update : labelUpdates) { + update.setStatus(new Status(IStatus.ERROR, DsfUIPlugin.PLUGIN_ID, + "Properties-based label provider " + this //$NON-NLS-1$ + + " failed to generate a label, no properties provider registered for element: " //$NON-NLS-1$ + + labelUpdates[0].getElement())); + update.done(); + } + return; + } + // We are guaranteed that all the provided updates are for the same // presentation context. Thus we can safely assume they request the same // columns - String[] columnIds = labelUpdates[0].getColumnIds(); - - Set<String> propertyNames = calcPropertyNamesForColumns(columnIds); - - // Call the properties provider. Create a request monitor for each label update. - // We can use an immediate executor for the request monitor because the label provider - // is thread safe. - final IPropertiesUpdate[] propertiesUpdates = new IPropertiesUpdate[labelUpdates.length]; - for (int i = 0; i < labelUpdates.length; i++) { - final int idx = i; - propertiesUpdates[idx] = new VMPropertiesUpdate( - propertyNames, labelUpdates[idx], - new ViewerDataRequestMonitor<Map<String, Object>>(ImmediateExecutor.getInstance(), labelUpdates[idx]) { - @Override - protected void handleCompleted() { - notifyPropertiesUpdateCompleted(propertiesUpdates[idx]); - updateLabel(labelUpdates[idx], getStatus(), getData()); - } - }); - } - notifyPropertiesUpdatesStarted(propertiesUpdates); - propertiesProvider.update(propertiesUpdates); - } - - private void notifyPropertiesUpdatesStarted(IPropertiesUpdate[] updates) { - IPropertiesUpdateListener[] listeners = null; - synchronized(this) { - listeners = fListeners; - } - for (IPropertiesUpdateListener listener : listeners) { - listener.propertiesUpdatesStarted(updates); - } - } - - private void notifyPropertiesUpdateCompleted(IPropertiesUpdate update) { - IPropertiesUpdateListener[] listeners = null; - synchronized(this) { - listeners = fListeners; - } - for (IPropertiesUpdateListener listener : listeners) { - listener.propertiesUpdateCompleted(update); - } - } - - /** - * Calculates the names of properties that have to be retrieved from the property - * provider to generate the labels for given columns. - * @param columnIds Column IDs to check. - * @return Array of property names. - */ - private Set<String> calcPropertyNamesForColumns(String[] columnIds) { - Set<String> propertyNames = new HashSet<String>(); - if (columnIds == null) { - LabelColumnInfo columnInfo = getColumnInfo(ID_COLUMN_NO_COLUMNS); - if (columnInfo != null) { - for (String propertyName : columnInfo.getPropertyNames()) { - propertyNames.add(propertyName); - } - } - } else { - for (String columnId : columnIds) { - LabelColumnInfo info = getColumnInfo(columnId); - if (info != null) { - String[] infoPropertyNames = info.getPropertyNames(); - for (int i = 0; i < infoPropertyNames.length; i++) { - propertyNames.add(infoPropertyNames[i]); - } - } - } - } - return propertyNames; - } - - /** - * Updates the label information based on given map of properties. - * - * @param update Label update to write to. - * @param status Result of the properties update - * @param properties Properties retrieved from the element properties provider. - * - * @since 2.0 - */ - protected void updateLabel(ILabelUpdate update, IStatus status, Map<String, Object> properties) { - if (update.getColumnIds() == null) { - LabelColumnInfo info = getColumnInfo(ID_COLUMN_NO_COLUMNS); - if (info != null) { - info.updateColumn(update, 0, status, properties); - } - } else { - String[] columnIds = update.getColumnIds(); - - for (int i = 0; i < columnIds.length; i++) { - LabelColumnInfo info = getColumnInfo(columnIds[i]); - if (info != null) { - info.updateColumn(update, i, status, properties); - } - } - } - - update.done(); - } - - private IElementPropertiesProvider getElementPropertiesProvider(Object element) { - if (element instanceof IAdaptable) { - return ((IAdaptable)element).getAdapter(IElementPropertiesProvider.class); - } - return null; - } + String[] columnIds = labelUpdates[0].getColumnIds(); + + Set<String> propertyNames = calcPropertyNamesForColumns(columnIds); + + // Call the properties provider. Create a request monitor for each label update. + // We can use an immediate executor for the request monitor because the label provider + // is thread safe. + final IPropertiesUpdate[] propertiesUpdates = new IPropertiesUpdate[labelUpdates.length]; + for (int i = 0; i < labelUpdates.length; i++) { + final int idx = i; + propertiesUpdates[idx] = new VMPropertiesUpdate(propertyNames, labelUpdates[idx], + new ViewerDataRequestMonitor<Map<String, Object>>(ImmediateExecutor.getInstance(), + labelUpdates[idx]) { + @Override + protected void handleCompleted() { + notifyPropertiesUpdateCompleted(propertiesUpdates[idx]); + updateLabel(labelUpdates[idx], getStatus(), getData()); + } + }); + } + notifyPropertiesUpdatesStarted(propertiesUpdates); + propertiesProvider.update(propertiesUpdates); + } + + private void notifyPropertiesUpdatesStarted(IPropertiesUpdate[] updates) { + IPropertiesUpdateListener[] listeners = null; + synchronized (this) { + listeners = fListeners; + } + for (IPropertiesUpdateListener listener : listeners) { + listener.propertiesUpdatesStarted(updates); + } + } + + private void notifyPropertiesUpdateCompleted(IPropertiesUpdate update) { + IPropertiesUpdateListener[] listeners = null; + synchronized (this) { + listeners = fListeners; + } + for (IPropertiesUpdateListener listener : listeners) { + listener.propertiesUpdateCompleted(update); + } + } + + /** + * Calculates the names of properties that have to be retrieved from the property + * provider to generate the labels for given columns. + * @param columnIds Column IDs to check. + * @return Array of property names. + */ + private Set<String> calcPropertyNamesForColumns(String[] columnIds) { + Set<String> propertyNames = new HashSet<String>(); + if (columnIds == null) { + LabelColumnInfo columnInfo = getColumnInfo(ID_COLUMN_NO_COLUMNS); + if (columnInfo != null) { + for (String propertyName : columnInfo.getPropertyNames()) { + propertyNames.add(propertyName); + } + } + } else { + for (String columnId : columnIds) { + LabelColumnInfo info = getColumnInfo(columnId); + if (info != null) { + String[] infoPropertyNames = info.getPropertyNames(); + for (int i = 0; i < infoPropertyNames.length; i++) { + propertyNames.add(infoPropertyNames[i]); + } + } + } + } + return propertyNames; + } + + /** + * Updates the label information based on given map of properties. + * + * @param update Label update to write to. + * @param status Result of the properties update + * @param properties Properties retrieved from the element properties provider. + * + * @since 2.0 + */ + protected void updateLabel(ILabelUpdate update, IStatus status, Map<String, Object> properties) { + if (update.getColumnIds() == null) { + LabelColumnInfo info = getColumnInfo(ID_COLUMN_NO_COLUMNS); + if (info != null) { + info.updateColumn(update, 0, status, properties); + } + } else { + String[] columnIds = update.getColumnIds(); + + for (int i = 0; i < columnIds.length; i++) { + LabelColumnInfo info = getColumnInfo(columnIds[i]); + if (info != null) { + info.updateColumn(update, i, status, properties); + } + } + } + + update.done(); + } + + private IElementPropertiesProvider getElementPropertiesProvider(Object element) { + if (element instanceof IAdaptable) { + return ((IAdaptable) element).getAdapter(IElementPropertiesProvider.class); + } + return null; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/PropertiesUpdateStatus.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/PropertiesUpdateStatus.java index a101e7bc294..f316b24b420 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/PropertiesUpdateStatus.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/PropertiesUpdateStatus.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -28,231 +28,227 @@ import org.eclipse.core.runtime.IStatus; * allows setting a different status result for each property. This allows * for better interpretation of status by the client of the update. * <p> - * This status class derives from MultiStatus class such that the status - * objects for each property can be accessed through the standard - * {@link #getChildren()} method. Also, multiple properties can reference + * This status class derives from MultiStatus class such that the status + * objects for each property can be accessed through the standard + * {@link #getChildren()} method. Also, multiple properties can reference * the same status object, meaning that the number of properties returned - * by {@link #getProperties()} may be greater than the status objects + * by {@link #getProperties()} may be greater than the status objects * returned by <code>getChildren()</code>. * <p> - * The properties status object does not have its own message, severity, - * error status or exception. All these attributes are calculated from - * the child status objects. If the status has more than one status child, + * The properties status object does not have its own message, severity, + * error status or exception. All these attributes are calculated from + * the child status objects. If the status has more than one status child, * the String returned by {@link #getMessage()} is: "Multiple errors reported". - * + * * @since 2.2 */ public class PropertiesUpdateStatus extends DsfMultiStatus { - final private Map<String,IStatus> fPropertiesStatus = new HashMap<String, IStatus>(1); - private boolean fFirstStatusSet; - - public PropertiesUpdateStatus() { - super(DsfUIPlugin.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ - } - - /** - * Returns set of properties that have an additional status specified. - */ - public Set<String> getProperties() { - return fPropertiesStatus.keySet(); - } - - /** - * Returns an additional status for the given property in a property - * update. Returned value may be <code>null</code> if no additional - * status is given. - */ - public IStatus getStatus(String property) { - return fPropertiesStatus.get(property); - } + final private Map<String, IStatus> fPropertiesStatus = new HashMap<String, IStatus>(1); + private boolean fFirstStatusSet; + + public PropertiesUpdateStatus() { + super(DsfUIPlugin.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ + } + + /** + * Returns set of properties that have an additional status specified. + */ + public Set<String> getProperties() { + return fPropertiesStatus.keySet(); + } + + /** + * Returns an additional status for the given property in a property + * update. Returned value may be <code>null</code> if no additional + * status is given. + */ + public IStatus getStatus(String property) { + return fPropertiesStatus.get(property); + } + + /** + * Sets the given status for the given property. + */ + public void setStatus(String property, IStatus status) { + IStatus child = findEquivalentChild(status); + if (child != null) { + status = child; + } else { + add(status); + } + + fPropertiesStatus.put(property, status); + } + + /** + * Sets the given status for the properties array. + */ + public void setStatus(String[] properties, IStatus status) { + IStatus child = findEquivalentChild(status); + if (child != null) { + status = child; + } else { + add(status); + } + + for (String property : properties) { + fPropertiesStatus.put(property, status); + } + } + + /** + * Merges data in the new status into the base status data, and returns the + * resulting status. Only properties specified in the given set are merged. + * <p> + * The new status is considered to be more up to date than the base + * status and its data overrides the base status . If the base status + * holds an error for a given property, which is found in the + * given set, and the new status does not, then the base error status is + * removed. + * + * @param baseStatus Properties into which the new status properties will + * be merged. + * @param newStatus Properties status to merge. + * @param properties The properties to consider in the new status. + * @return Resulting merged status object. + */ + public static PropertiesUpdateStatus mergePropertiesStatus(PropertiesUpdateStatus baseStatus, + PropertiesUpdateStatus newStatus, Set<String> properties) { + PropertiesUpdateStatus mergedStatus = new PropertiesUpdateStatus(); + // Copy the property status map from the base status. + mergedStatus.fPropertiesStatus.putAll(baseStatus.fPropertiesStatus); + + // Add in the property statuses from the new status, but only for the + // specified properties. + for (String property : properties) { + IStatus propertyStatus = newStatus.getStatus(property); + if (propertyStatus != null) { + mergedStatus.fPropertiesStatus.put(property, propertyStatus); + } else { + mergedStatus.fPropertiesStatus.remove(property); + } + } + + // Children of merged status should contain all statuses that are found in the fPropertiesStatus map, but + // without duplicates. + Set<IStatus> children = new HashSet<IStatus>( + (baseStatus.getChildren().length + newStatus.getChildren().length) * 4 / 3); + children.addAll(mergedStatus.fPropertiesStatus.values()); + for (IStatus child : children) { + mergedStatus.add(child); + } + + // Merged status should contain all children statuses that were added without a corresponding property to the + // base status and to the new status. + Collection<IStatus> baseStatusPropertyChildren = baseStatus.fPropertiesStatus.values(); + for (IStatus baseStatusChild : baseStatus.getChildren()) { + if (!baseStatusPropertyChildren.contains(baseStatusChild)) { + mergedStatus.add(baseStatusChild); + } + } + Collection<IStatus> newStatusPropertyChildren = newStatus.fPropertiesStatus.values(); + for (IStatus newStatusChild : newStatus.getChildren()) { + if (!newStatusPropertyChildren.contains(newStatusChild)) { + mergedStatus.add(newStatusChild); + } + } - /** - * Sets the given status for the given property. - */ - public void setStatus(String property, IStatus status) { - IStatus child = findEquivalentChild(status); - if (child != null) { - status = child; - } else { - add(status); - } + return mergedStatus; + } - fPropertiesStatus.put(property, status); - } + /** + * Adds the given status object as a child of this status. If there's an + * equivalent child status already, the new status is ignored. + */ + @Override + public void add(IStatus status) { + if (findEquivalentChild(status) != null) { + return; + } - /** - * Sets the given status for the properties array. - */ - public void setStatus(String[] properties, IStatus status) { - IStatus child = findEquivalentChild(status); - if (child != null) { - status = child; - } else { - add(status); - } + super.add(status); - for (String property : properties) { - fPropertiesStatus.put(property, status); - } - } + boolean firstSet; + synchronized (this) { + firstSet = fFirstStatusSet; + fFirstStatusSet = true; + } - /** - * Merges data in the new status into the base status data, and returns the - * resulting status. Only properties specified in the given set are merged. - * <p> - * The new status is considered to be more up to date than the base - * status and its data overrides the base status . If the base status - * holds an error for a given property, which is found in the - * given set, and the new status does not, then the base error status is - * removed. - * - * @param baseStatus Properties into which the new status properties will - * be merged. - * @param newStatus Properties status to merge. - * @param properties The properties to consider in the new status. - * @return Resulting merged status object. - */ - public static PropertiesUpdateStatus mergePropertiesStatus(PropertiesUpdateStatus baseStatus, - PropertiesUpdateStatus newStatus, Set<String> properties) - { - PropertiesUpdateStatus mergedStatus = new PropertiesUpdateStatus(); - // Copy the property status map from the base status. - mergedStatus.fPropertiesStatus.putAll(baseStatus.fPropertiesStatus); - - // Add in the property statuses from the new status, but only for the - // specified properties. - for (String property : properties) { - IStatus propertyStatus = newStatus.getStatus(property); - if (propertyStatus != null) { - mergedStatus.fPropertiesStatus.put(property, propertyStatus); - } else { - mergedStatus.fPropertiesStatus.remove(property); - } - } + if (!firstSet) { + setMessage(status.getMessage()); + } else { + setMessage(MessagesForProperties.PropertiesUpdateStatus_message); + } + } - // Children of merged status should contain all statuses that are found in the fPropertiesStatus map, but - // without duplicates. - Set<IStatus> children = new HashSet<IStatus>((baseStatus.getChildren().length + newStatus.getChildren().length) * 4/3); - children.addAll(mergedStatus.fPropertiesStatus.values()); - for (IStatus child : children) { - mergedStatus.add(child); - } + /** + * Finds a child status that is equivalent to the given status. + */ + private IStatus findEquivalentChild(IStatus status) { + if (getChildren().length != 0) { + for (IStatus child : getChildren()) { + if (areEquivalent(child, status)) { + return child; + } + } + } + return null; + } - // Merged status should contain all children statuses that were added without a corresponding property to the - // base status and to the new status. - Collection<IStatus> baseStatusPropertyChildren = baseStatus.fPropertiesStatus.values(); - for (IStatus baseStatusChild : baseStatus.getChildren()) { - if (!baseStatusPropertyChildren.contains(baseStatusChild)) { - mergedStatus.add(baseStatusChild); - } - } - Collection<IStatus> newStatusPropertyChildren = newStatus.fPropertiesStatus.values(); - for (IStatus newStatusChild : newStatus.getChildren()) { - if (!newStatusPropertyChildren.contains(newStatusChild)) { - mergedStatus.add(newStatusChild); - } - } - - return mergedStatus; - } - - /** - * Adds the given status object as a child of this status. If there's an - * equivalent child status already, the new status is ignored. - */ - @Override - public void add(IStatus status) { - if (findEquivalentChild(status) != null) { - return; - } - - super.add(status); + /** + * Compares two status objects to determine if they are equivalent. + */ + private boolean areEquivalent(IStatus s1, IStatus s2) { + if ((s1 == null && s2 != null) || (s1 != null && s2 == null)) { + return false; + } + if (s1 == null) { + return true; + } + if ((s1.getSeverity() != s2.getSeverity()) || !s1.getPlugin().equals(s2.getPlugin()) + || (s1.getCode() != s2.getCode())) { + return false; + } + if ((s1.getException() == null && s1.getException() != null) + || (s1.getException() != null && s1.getException() == null) + || (s1.getException() != null && !s1.getException().equals(s2.getException()))) { + return false; + } + return s1.getMessage().equals(s2.getMessage()); + }; - boolean firstSet; - synchronized(this) { - firstSet = fFirstStatusSet; - fFirstStatusSet = true; - } - - if (!firstSet) { - setMessage(status.getMessage()); - } else { - setMessage(MessagesForProperties.PropertiesUpdateStatus_message); - } - } - - /** - * Finds a child status that is equivalent to the given status. - */ - private IStatus findEquivalentChild(IStatus status) { - if (getChildren().length != 0) { - for (IStatus child : getChildren()) { - if (areEquivalent(child, status)) { - return child; - } - } - } - return null; - } - - /** - * Compares two status objects to determine if they are equivalent. - */ - private boolean areEquivalent(IStatus s1, IStatus s2) { - if ( (s1 == null && s2 != null) || (s1 != null && s2 == null) ) - { - return false; - } - if (s1 == null) { - return true; - } - if ( (s1.getSeverity() != s2.getSeverity()) || - !s1.getPlugin().equals(s2.getPlugin()) || - (s1.getCode() != s2.getCode()) ) - { - return false; - } - if ( (s1.getException() == null && s1.getException() != null) || - (s1.getException() != null && s1.getException() == null) || - (s1.getException() != null && !s1.getException().equals(s2.getException())) ) - { - return false; - } - return s1.getMessage().equals(s2.getMessage()); - }; + /** + * Convenience method that returns and optionally creates a properties + * update status object for the given update. + */ + public static PropertiesUpdateStatus getPropertiesStatus(IPropertiesUpdate update) { + IStatus updateStatus = update.getStatus(); + if (updateStatus instanceof PropertiesUpdateStatus) { + return (PropertiesUpdateStatus) updateStatus; + } else { + PropertiesUpdateStatus propertiesStatus = new PropertiesUpdateStatus(); + update.setStatus(propertiesStatus); + if (!updateStatus.isOK()) { + propertiesStatus.add(updateStatus); + } + return propertiesStatus; + } + } - /** - * Convenience method that returns and optionally creates a properties - * update status object for the given update. - */ - public static PropertiesUpdateStatus getPropertiesStatus(IPropertiesUpdate update) { - IStatus updateStatus = update.getStatus(); - if (updateStatus instanceof PropertiesUpdateStatus) { - return (PropertiesUpdateStatus)updateStatus; - } else { - PropertiesUpdateStatus propertiesStatus = new PropertiesUpdateStatus(); - update.setStatus(propertiesStatus); - if (!updateStatus.isOK()) { - propertiesStatus.add(updateStatus); - } - return propertiesStatus; - } - } - - /** - * Convenience method that returns and optionally creates a properties - * update status object for the given update. - */ - public static PropertiesUpdateStatus makePropertiesStatus(IStatus updateStatus) { - if (updateStatus instanceof PropertiesUpdateStatus) { - return (PropertiesUpdateStatus)updateStatus; - } else { - PropertiesUpdateStatus propertiesStatus = new PropertiesUpdateStatus(); - if (!updateStatus.isOK()) { - propertiesStatus.add(updateStatus); - } - return propertiesStatus; - } - } + /** + * Convenience method that returns and optionally creates a properties + * update status object for the given update. + */ + public static PropertiesUpdateStatus makePropertiesStatus(IStatus updateStatus) { + if (updateStatus instanceof PropertiesUpdateStatus) { + return (PropertiesUpdateStatus) updateStatus; + } else { + PropertiesUpdateStatus propertiesStatus = new PropertiesUpdateStatus(); + if (!updateStatus.isOK()) { + propertiesStatus.add(updateStatus); + } + return propertiesStatus; + } + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/VMDelegatingPropertiesUpdate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/VMDelegatingPropertiesUpdate.java index b2d8f6213c6..8e7e42e8eeb 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/VMDelegatingPropertiesUpdate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/VMDelegatingPropertiesUpdate.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -22,54 +22,54 @@ import org.eclipse.core.runtime.IStatus; /** * Properties update used as to collect property data from the provider. - * + * * @since 2.0 */ public class VMDelegatingPropertiesUpdate extends VMViewerUpdate implements IPropertiesUpdate { - /** - * Update to write the properties to. - */ - private final IPropertiesUpdate fParentUpdate; - - public VMDelegatingPropertiesUpdate(IPropertiesUpdate parentUpdate, RequestMonitor rm) { - super(parentUpdate, rm); - fParentUpdate = parentUpdate; - } + /** + * Update to write the properties to. + */ + private final IPropertiesUpdate fParentUpdate; - @Override + public VMDelegatingPropertiesUpdate(IPropertiesUpdate parentUpdate, RequestMonitor rm) { + super(parentUpdate, rm); + fParentUpdate = parentUpdate; + } + + @Override public Set<String> getProperties() { - return fParentUpdate.getProperties(); - } + return fParentUpdate.getProperties(); + } - @Override + @Override public void setProperty(String property, Object value) { - fParentUpdate.setProperty(property, value); - } - - @Override + fParentUpdate.setProperty(property, value); + } + + @Override public void setAllProperties(Map<String, Object> properties) { - fParentUpdate.setAllProperties(properties); - } - - /** - * @since 2.2 - */ - @Override - public IStatus getStatus() { - return fParentUpdate.getStatus(); - } - - /** - * @since 2.2 - */ - @Override - public void setStatus(IStatus status) { - fParentUpdate.setStatus(status); - } - - @Override - public String toString() { - return "VMDelegatingPropertiesUpdate -> " + fParentUpdate; //$NON-NLS-1$ - } + fParentUpdate.setAllProperties(properties); + } + + /** + * @since 2.2 + */ + @Override + public IStatus getStatus() { + return fParentUpdate.getStatus(); + } + + /** + * @since 2.2 + */ + @Override + public void setStatus(IStatus status) { + fParentUpdate.setStatus(status); + } + + @Override + public String toString() { + return "VMDelegatingPropertiesUpdate -> " + fParentUpdate; //$NON-NLS-1$ + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/VMPropertiesUpdate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/VMPropertiesUpdate.java index 4105984811d..3c47a02028c 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/VMPropertiesUpdate.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/properties/VMPropertiesUpdate.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -31,136 +31,139 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; import org.eclipse.jface.viewers.TreePath; /** - * Properties update used as to collect property data from the provider. + * Properties update used as to collect property data from the provider. * <p> * The status returned by the VMPropertiesUpdate is always going to be of type * PropertiesUpdateStatus, which allows for setting status for individual * properties. * </p> - * + * * @see PropertiesUpdateStatus - * + * * @since 2.0 */ public class VMPropertiesUpdate extends VMViewerUpdate implements IPropertiesUpdate { - /** - * Properties that the client has requested to retrieve. - */ - private final Set<String> fProperties; - - /** - * Flag indicating that the update has created a new map, as opposed to - * using directly a map that was created using setAllProperties() call. - */ - private boolean fCreatedOwnMap = false; - - /** - * Map of property values, created on demand. - */ - private Map<String, Object> fValues = Collections.emptyMap(); - - public VMPropertiesUpdate(Set<String> properties, IViewerUpdate parentUpdate, DataRequestMonitor<Map<String,Object>> rm) { - super(parentUpdate, rm); - super.setStatus(new PropertiesUpdateStatus()); - fProperties = properties; - } - - public VMPropertiesUpdate(Set<String> properties, TreePath elementPath, Object viewerInput, IPresentationContext presentationContext, DataRequestMonitor<Map<String,Object>> rm) { - super(elementPath, viewerInput, presentationContext, rm); - super.setStatus(new PropertiesUpdateStatus()); - fProperties = properties; - } - - - @Override + /** + * Properties that the client has requested to retrieve. + */ + private final Set<String> fProperties; + + /** + * Flag indicating that the update has created a new map, as opposed to + * using directly a map that was created using setAllProperties() call. + */ + private boolean fCreatedOwnMap = false; + + /** + * Map of property values, created on demand. + */ + private Map<String, Object> fValues = Collections.emptyMap(); + + public VMPropertiesUpdate(Set<String> properties, IViewerUpdate parentUpdate, + DataRequestMonitor<Map<String, Object>> rm) { + super(parentUpdate, rm); + super.setStatus(new PropertiesUpdateStatus()); + fProperties = properties; + } + + public VMPropertiesUpdate(Set<String> properties, TreePath elementPath, Object viewerInput, + IPresentationContext presentationContext, DataRequestMonitor<Map<String, Object>> rm) { + super(elementPath, viewerInput, presentationContext, rm); + super.setStatus(new PropertiesUpdateStatus()); + fProperties = properties; + } + + @Override public Set<String> getProperties() { - return fProperties; - } - - /** - * @since 2.2 - */ - public Map<String, Object> getValues() { - return fValues; - } - - @Override + return fProperties; + } + + /** + * @since 2.2 + */ + public Map<String, Object> getValues() { + return fValues; + } + + @Override public synchronized void setProperty(String property, Object value) { - if (!fCreatedOwnMap) { - fCreatedOwnMap = true; - Map<String, Object> curValues = fValues; - fValues = new HashMap<String, Object>(fProperties.size() * 4 / 3, 0.75f); - if (curValues != null) { - fValues.putAll(curValues); - } - } - fValues.put(property, value); - } - - @Override + if (!fCreatedOwnMap) { + fCreatedOwnMap = true; + Map<String, Object> curValues = fValues; + fValues = new HashMap<String, Object>(fProperties.size() * 4 / 3, 0.75f); + if (curValues != null) { + fValues.putAll(curValues); + } + } + fValues.put(property, value); + } + + @Override public synchronized void setAllProperties(Map<String, Object> properties) { - if (fCreatedOwnMap) { - fValues.putAll(properties); - } - else { - fValues = properties; - } - } - - /** - * Overrides the base class to implement special handling of - * {@link PropertiesUpdateStatus}. If the given status is an instance of - * properties status, this new status will be set to the update. Otherwise, the - * given status will be merged into the updates existing properties status. - * This way {@link #getStatus()} should always return an instance of - * <code>PropertiesUpdateStatus</code>. - */ - @Override - public void setStatus(IStatus status) { - if (status instanceof PropertiesUpdateStatus) { - super.setStatus(status); - } else if ((getStatus() instanceof PropertiesUpdateStatus)) { - ((PropertiesUpdateStatus)getStatus()).add(status); - } else { - assert getStatus().getSeverity() == IStatus.CANCEL : "VMPropertiesUpdate status should always be a PropertiesUpdateStatus unless update is canceled."; //$NON-NLS-1$ - } - } - - /** - * Overrides the standard done in order to store the retrieved values - * in the client's request monitor. - */ - @Override - public void done() { - @SuppressWarnings("unchecked") - DataRequestMonitor<Map<String,Object>> rm = (DataRequestMonitor<Map<String,Object>>)getRequestMonitor(); - rm.setData(fValues); - - // trace our result - if (VMViewerUpdateTracing.DEBUG_VMUPDATES && !isCanceled() && VMViewerUpdateTracing.matchesFilterRegex(this.getClass())) { - StringBuilder str = new StringBuilder(); - str.append(DsfPlugin.getDebugTime()).append(' ').append(LoggingUtils.toString(this)).append(" marked done; element = ").append(LoggingUtils.toString(getElement())); //$NON-NLS-1$ - if (fValues != null) { - Iterator<String> keyIter = fValues.keySet().iterator(); - while (keyIter.hasNext()) { - String prop = keyIter.next(); - Object val = fValues.get(prop); - if (val instanceof String[]) { - val = LoggingUtils.toString((String[])val); - } - str.append(" ").append(prop).append("=").append(val).append('\n'); //$NON-NLS-1$ //$NON-NLS-2$ - } - str.deleteCharAt(str.length()-1); // remove trailing linefeed - } - DsfUIPlugin.debug(str.toString()); - } - - super.done(); - } - - @Override - public String toString() { - return "VMPropertiesUpdate:" + getElement() + " " + fProperties; //$NON-NLS-1$ //$NON-NLS-2$/ - } + if (fCreatedOwnMap) { + fValues.putAll(properties); + } else { + fValues = properties; + } + } + + /** + * Overrides the base class to implement special handling of + * {@link PropertiesUpdateStatus}. If the given status is an instance of + * properties status, this new status will be set to the update. Otherwise, the + * given status will be merged into the updates existing properties status. + * This way {@link #getStatus()} should always return an instance of + * <code>PropertiesUpdateStatus</code>. + */ + @Override + public void setStatus(IStatus status) { + if (status instanceof PropertiesUpdateStatus) { + super.setStatus(status); + } else if ((getStatus() instanceof PropertiesUpdateStatus)) { + ((PropertiesUpdateStatus) getStatus()).add(status); + } else { + assert getStatus() + .getSeverity() == IStatus.CANCEL : "VMPropertiesUpdate status should always be a PropertiesUpdateStatus unless update is canceled."; //$NON-NLS-1$ + } + } + + /** + * Overrides the standard done in order to store the retrieved values + * in the client's request monitor. + */ + @Override + public void done() { + @SuppressWarnings("unchecked") + DataRequestMonitor<Map<String, Object>> rm = (DataRequestMonitor<Map<String, Object>>) getRequestMonitor(); + rm.setData(fValues); + + // trace our result + if (VMViewerUpdateTracing.DEBUG_VMUPDATES && !isCanceled() + && VMViewerUpdateTracing.matchesFilterRegex(this.getClass())) { + StringBuilder str = new StringBuilder(); + str.append(DsfPlugin.getDebugTime()).append(' ').append(LoggingUtils.toString(this)) + .append(" marked done; element = ").append(LoggingUtils.toString(getElement())); //$NON-NLS-1$ + if (fValues != null) { + Iterator<String> keyIter = fValues.keySet().iterator(); + while (keyIter.hasNext()) { + String prop = keyIter.next(); + Object val = fValues.get(prop); + if (val instanceof String[]) { + val = LoggingUtils.toString((String[]) val); + } + str.append(" ").append(prop).append("=").append(val).append('\n'); //$NON-NLS-1$ //$NON-NLS-2$ + } + str.deleteCharAt(str.length() - 1); // remove trailing linefeed + } + DsfUIPlugin.debug(str.toString()); + } + + super.done(); + } + + @Override + public String toString() { + return "VMPropertiesUpdate:" + getElement() + " " + fProperties; //$NON-NLS-1$ //$NON-NLS-2$/ + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/AbstractCachingVMProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/AbstractCachingVMProvider.java index 4126bfdde63..baa658445b3 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/AbstractCachingVMProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/AbstractCachingVMProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -62,176 +62,174 @@ import org.eclipse.jface.viewers.TreePath; /** * Base implementation of a caching view model provider. - * + * * @since 1.0 */ -public class AbstractCachingVMProvider extends AbstractVMProvider - implements ICachingVMProvider, IElementPropertiesProvider, ICachingVMProviderExtension2 -{ - /** - * @since 2.0 - */ - private final static String PROP_UPDATE_STATUS = "org.eclipse.cdt.dsf.ui.viewmodel.update.update_status"; //$NON-NLS-1$ - - /** - * @since 2.0 - */ - private final static int LENGTH_PROP_IS_CHANGED_PREFIX = PROP_IS_CHANGED_PREFIX.length(); - +public class AbstractCachingVMProvider extends AbstractVMProvider + implements ICachingVMProvider, IElementPropertiesProvider, ICachingVMProviderExtension2 { + /** + * @since 2.0 + */ + private final static String PROP_UPDATE_STATUS = "org.eclipse.cdt.dsf.ui.viewmodel.update.update_status"; //$NON-NLS-1$ + + /** + * @since 2.0 + */ + private final static int LENGTH_PROP_IS_CHANGED_PREFIX = PROP_IS_CHANGED_PREFIX.length(); + private boolean fDelayEventHandleForViewUpdate = false; - + // debug flag - static boolean DEBUG_CACHE = false; + static boolean DEBUG_CACHE = false; + + static { + DEBUG_CACHE = DsfUIPlugin.DEBUG + && Boolean.parseBoolean(Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/vm/cache")); //$NON-NLS-1$ + } + + private static final int MAX_CACHE_SIZE = 1000; + + /** + * Class representing a key to an element's data in the cache. The main + * components of this key are the viewer input and the path, they uniquely + * identify an element. The root element is used to track when a given + * root element is no longer in the cache and can therefore be disposed. + * The node is needed because different nodes have different lists of + * children for the same parent element. + */ + private static class ElementDataKey { + ElementDataKey(Object rootElement, IVMNode node, Object viewerInput, TreePath path) { + fRootElement = rootElement; + fNode = node; + fViewerInput = viewerInput; + fPath = path; + } - static { - DEBUG_CACHE = DsfUIPlugin.DEBUG && Boolean.parseBoolean( - Platform.getDebugOption("org.eclipse.cdt.dsf.ui/debug/vm/cache")); //$NON-NLS-1$ - } + final Object fRootElement; + final IVMNode fNode; + final Object fViewerInput; + final TreePath fPath; - private static final int MAX_CACHE_SIZE = 1000; + @Override + public String toString() { + return fNode.toString() + " " + //$NON-NLS-1$ + (fPath.getSegmentCount() == 0 ? fViewerInput.toString() : fPath.getLastSegment().toString()); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof ElementDataKey)) + return false; + ElementDataKey key = (ElementDataKey) obj; + return (fNode == null && key.fNode == null || (fNode != null && fNode.equals(key.fNode))) + && (fRootElement == null && key.fRootElement == null + || (fRootElement != null && fRootElement.equals(key.fRootElement))) + && (fViewerInput == null && key.fViewerInput == null + || (fViewerInput != null && fViewerInput.equals(key.fViewerInput))) + && (fPath == null && key.fPath == null || (fPath != null && fPath.equals(key.fPath))); + } + + @Override + public int hashCode() { + return (fRootElement != null ? fRootElement.hashCode() : 0) + (fNode != null ? fNode.hashCode() : 0) + + (fViewerInput != null ? fViewerInput.hashCode() : 0) + (fPath != null ? fPath.hashCode() : 0); + } + } /** - * Class representing a key to an element's data in the cache. The main - * components of this key are the viewer input and the path, they uniquely - * identify an element. The root element is used to track when a given - * root element is no longer in the cache and can therefore be disposed. - * The node is needed because different nodes have different lists of - * children for the same parent element. - */ - private static class ElementDataKey { - ElementDataKey(Object rootElement, IVMNode node, Object viewerInput, TreePath path) { - fRootElement = rootElement; - fNode = node; - fViewerInput = viewerInput; - fPath = path; - } - - final Object fRootElement; - final IVMNode fNode; - final Object fViewerInput; - final TreePath fPath; - - @Override - public String toString() { - return fNode.toString() + " " + //$NON-NLS-1$ - (fPath.getSegmentCount() == 0 ? fViewerInput.toString() : fPath.getLastSegment().toString()); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof ElementDataKey)) return false; - ElementDataKey key = (ElementDataKey)obj; - return - (fNode == null && key.fNode == null || (fNode != null && fNode.equals(key.fNode))) && - (fRootElement == null && key.fRootElement == null || (fRootElement != null && fRootElement.equals(key.fRootElement))) && - (fViewerInput == null && key.fViewerInput == null || (fViewerInput != null && fViewerInput.equals(key.fViewerInput))) && - (fPath == null && key.fPath == null || (fPath != null && fPath.equals(key.fPath))); - } - - @Override - public int hashCode() { - return - (fRootElement != null ? fRootElement.hashCode() : 0) + - (fNode != null ? fNode.hashCode() : 0) + - (fViewerInput != null ? fViewerInput.hashCode() : 0) + - (fPath != null ? fPath.hashCode() : 0); - } - } - - /** - * A base class for the entry in the cache. Since the cache maintains - * a double-linked list through all the entries, the linked list references - * are maintained in this class. - */ - private static class Entry { - final Object fKey; - - Entry fNext; - Entry fPrevious; - - Entry(Object key) { - fKey = key; - } - - void insert(Entry nextEntry) { - fNext = nextEntry; - fPrevious = nextEntry.fPrevious; - fPrevious.fNext = this; - fNext.fPrevious = this; - } - - void remove() { - fPrevious.fNext = fNext; - fNext.fPrevious = fPrevious; - } - - void reinsert(Entry nextEntry) { - fPrevious.fNext = fNext; - fNext.fPrevious = fPrevious; - - fNext = nextEntry; - fPrevious = nextEntry.fPrevious; - fPrevious.fNext = this; - fNext.fPrevious = this; - } - } - - /** - * Entry with cached element data. - */ - private static class ElementDataEntry extends Entry implements ICacheEntry { - ElementDataEntry(ElementDataKey key) { - super(key); - } - - /** - * Counter of flush operations performed on this entry. It is used - * by caching update operations to make sure that an update which - * was issued for a given entry is still valid for that entry when - * it is completed by the node. - */ - int fFlushCounter = 0; - - /** - * Indicates that the data in this cache entry is out of date with - * the data on the target. - */ - Boolean fDirty = false; - - /** - * Cached {@link IHasChildrenUpdate} result. - */ - Boolean fHasChildren = null; - - /** - * Cached {@link IChildrenCountUpdate} result. - */ - Integer fChildrenCount = null; - - /** - * Flag indicating that all the children of the given element are - * already cached. - */ - boolean fAllChildrenKnown = false; - - /** - * Map containing children of this element, keyed by child index. - */ - Map<Integer,Object> fChildren = null; - - /** - * Map containing element properties. - * - * @since 2.0 - */ - Map<String, Object> fProperties = null; - - /** - * Previous known element properties. - * - * @since 2.0 - */ - Map<String, Object> fArchiveProperties = null; + * A base class for the entry in the cache. Since the cache maintains + * a double-linked list through all the entries, the linked list references + * are maintained in this class. + */ + private static class Entry { + final Object fKey; + + Entry fNext; + Entry fPrevious; + + Entry(Object key) { + fKey = key; + } + + void insert(Entry nextEntry) { + fNext = nextEntry; + fPrevious = nextEntry.fPrevious; + fPrevious.fNext = this; + fNext.fPrevious = this; + } + + void remove() { + fPrevious.fNext = fNext; + fNext.fPrevious = fPrevious; + } + + void reinsert(Entry nextEntry) { + fPrevious.fNext = fNext; + fNext.fPrevious = fPrevious; + + fNext = nextEntry; + fPrevious = nextEntry.fPrevious; + fPrevious.fNext = this; + fNext.fPrevious = this; + } + } + + /** + * Entry with cached element data. + */ + private static class ElementDataEntry extends Entry implements ICacheEntry { + ElementDataEntry(ElementDataKey key) { + super(key); + } + + /** + * Counter of flush operations performed on this entry. It is used + * by caching update operations to make sure that an update which + * was issued for a given entry is still valid for that entry when + * it is completed by the node. + */ + int fFlushCounter = 0; + + /** + * Indicates that the data in this cache entry is out of date with + * the data on the target. + */ + Boolean fDirty = false; + + /** + * Cached {@link IHasChildrenUpdate} result. + */ + Boolean fHasChildren = null; + + /** + * Cached {@link IChildrenCountUpdate} result. + */ + Integer fChildrenCount = null; + + /** + * Flag indicating that all the children of the given element are + * already cached. + */ + boolean fAllChildrenKnown = false; + + /** + * Map containing children of this element, keyed by child index. + */ + Map<Integer, Object> fChildren = null; + + /** + * Map containing element properties. + * + * @since 2.0 + */ + Map<String, Object> fProperties = null; + + /** + * Previous known element properties. + * + * @since 2.0 + */ + Map<String, Object> fArchiveProperties = null; /** * Ensure this cache entry has a map in which to hold the children @@ -240,720 +238,766 @@ public class AbstractCachingVMProvider extends AbstractVMProvider * has (give it some room to grow). If we don't know the child count, * give the map some nominal initial capacity. */ - void ensureChildrenMap() { - if (fChildren == null) { - Integer childrenCount = fChildrenCount; - childrenCount = childrenCount != null ? childrenCount : 0; - int capacity = Math.max((childrenCount.intValue() * 4)/3, 32); - fChildren = new HashMap<Integer,Object>(capacity); - } - } - - @Override - public String toString() { - return fKey.toString() + " = " + //$NON-NLS-1$ - "[hasChildren=" + fHasChildren + ", " +//$NON-NLS-1$ //$NON-NLS-2$ - "childrenCount=" + fChildrenCount + //$NON-NLS-1$ - ", children=" + fChildren + //$NON-NLS-1$ - ", properties=" + fProperties + //$NON-NLS-1$ - ", oldProperties=" + fArchiveProperties + "]"; //$NON-NLS-1$ //$NON-NLS-2$ - } - - @Override - public IVMNode getNode() { return ((ElementDataKey)fKey).fNode; } - @Override - public Object getViewerInput() { return ((ElementDataKey)fKey).fViewerInput; } - @Override - public TreePath getElementPath() { return ((ElementDataKey)fKey).fPath; } - @Override - public boolean isDirty() { return fDirty; } - @Override - public Boolean getHasChildren() { return fHasChildren; } - @Override - public Integer getChildCount() { return fChildrenCount; } - @Override - public Map<Integer, Object> getChildren() { return fChildren; } - @Override - public Map<String, Object> getProperties() { return fProperties; } - @Override - public java.util.Map<String,Object> getArchiveProperties() { return fArchiveProperties; } - } - - /** - * A key for a special marker entry in the cache. This marker entry is used - * to optimize repeated flushing of the cache. - * @see AbstractCachingVMProvider#flush(List) - */ - private static class FlushMarkerKey { - private Object fRootElement; - private IElementUpdateTester fElementTester; - - FlushMarkerKey(Object rootElement, IElementUpdateTester pathTester) { - fRootElement = rootElement; - fElementTester = pathTester; - } - - boolean includes(FlushMarkerKey key) { - return fRootElement.equals(key.fRootElement) && - fElementTester.includes(key.fElementTester); - } - - int getUpdateFlags(ElementDataKey key) { - if (fRootElement.equals(key.fRootElement)) { - return fElementTester.getUpdateFlags(key.fViewerInput, key.fPath); - } - return 0; - } - - Collection<String> getPropertiesToFlush(ElementDataKey key, boolean isDirty) { - if (fRootElement.equals(key.fRootElement) && fElementTester instanceof IElementUpdateTesterExtension) { - return ((IElementUpdateTesterExtension)fElementTester). - getPropertiesToFlush(key.fViewerInput, key.fPath, isDirty); - } - return null; - } - - @Override - public String toString() { - return fElementTester.toString() + " " + fRootElement.toString(); //$NON-NLS-1$ - } - } - - /** - * Marker used to keep track of whether any entries with the given - * root element are present in the cache. - */ - private static class RootElementMarkerKey { - - private Object fRootElement; - - RootElementMarkerKey(Object rootElement) { - fRootElement = rootElement; - } - - @Override - public boolean equals(Object obj) { - return obj instanceof RootElementMarkerKey && ((RootElementMarkerKey)obj).fRootElement.equals(fRootElement); - } - - @Override - public int hashCode() { - return fRootElement.hashCode(); - } - - @Override - public String toString() { - return fRootElement.toString(); - } - } - - class RootElementMarkerEntry extends Entry { - RootElementMarkerEntry(RootElementMarkerKey key) { - super(key); - } - - @Override - void remove() { - super.remove(); - rootElementRemovedFromCache(((RootElementMarkerKey)fKey).fRootElement); - } - - @Override - public String toString() { - return "ROOT MARKER " + fKey; //$NON-NLS-1$ - } - } - - protected static String SELECTED_UPDATE_MODE = "org.eclipse.cdt.dsf.ui.viewmodel.update.selectedUpdateMode"; //$NON-NLS-1$ - /** - * @since 1.1 - */ - protected static String SELECTED_UPDATE_SCOPE = "org.eclipse.cdt.dsf.ui.viewmodel.update.selectedUpdateScope"; //$NON-NLS-1$ - - private IVMUpdatePolicy[] fAvailableUpdatePolicies; - - public Map<Object, RootElementMarkerKey> fRootMarkers = new HashMap<Object, RootElementMarkerKey>(); - - /** - * Hash map holding cache data. To store the cache information, the cache uses a - * combination of this hash map and a double-linked list running through all - * the entries in the cache. The linked list is used to organize the cache entries - * in least recently used (LRU) order. This ordering is then used to delete least - * recently used entries in the cache and keep the cache from growing indefinitely. - * Also, the ordering is used to optimize the flushing of the cache data (see - * {@link FlushMarkerKey} for more details). - */ - private final Map<Object, Entry> fCacheData = Collections.synchronizedMap(new HashMap<Object, Entry>(200, 0.75f)); - - /** - * Pointer to the first cache entry in the double-linked list of cache entries. - */ - private final Entry fCacheListHead; - - - public AbstractCachingVMProvider(AbstractVMAdapter adapter, IPresentationContext presentationContext) { - super(adapter, presentationContext); - - fCacheListHead = new Entry(null) { - @Override - public String toString() { - return "HEAD"; //$NON-NLS-1$ - } - }; - fCacheListHead.fNext = fCacheListHead; - fCacheListHead.fPrevious = fCacheListHead; - - fAvailableUpdatePolicies = createUpdateModes(); - } - - protected IVMUpdatePolicy[] createUpdateModes() { - return new IVMUpdatePolicy[] { new AutomaticUpdatePolicy() }; - } - - @Override + void ensureChildrenMap() { + if (fChildren == null) { + Integer childrenCount = fChildrenCount; + childrenCount = childrenCount != null ? childrenCount : 0; + int capacity = Math.max((childrenCount.intValue() * 4) / 3, 32); + fChildren = new HashMap<Integer, Object>(capacity); + } + } + + @Override + public String toString() { + return fKey.toString() + " = " + //$NON-NLS-1$ + "[hasChildren=" + fHasChildren + ", " + //$NON-NLS-1$ //$NON-NLS-2$ + "childrenCount=" + fChildrenCount + //$NON-NLS-1$ + ", children=" + fChildren + //$NON-NLS-1$ + ", properties=" + fProperties + //$NON-NLS-1$ + ", oldProperties=" + fArchiveProperties + "]"; //$NON-NLS-1$ //$NON-NLS-2$ + } + + @Override + public IVMNode getNode() { + return ((ElementDataKey) fKey).fNode; + } + + @Override + public Object getViewerInput() { + return ((ElementDataKey) fKey).fViewerInput; + } + + @Override + public TreePath getElementPath() { + return ((ElementDataKey) fKey).fPath; + } + + @Override + public boolean isDirty() { + return fDirty; + } + + @Override + public Boolean getHasChildren() { + return fHasChildren; + } + + @Override + public Integer getChildCount() { + return fChildrenCount; + } + + @Override + public Map<Integer, Object> getChildren() { + return fChildren; + } + + @Override + public Map<String, Object> getProperties() { + return fProperties; + } + + @Override + public java.util.Map<String, Object> getArchiveProperties() { + return fArchiveProperties; + } + } + + /** + * A key for a special marker entry in the cache. This marker entry is used + * to optimize repeated flushing of the cache. + * @see AbstractCachingVMProvider#flush(List) + */ + private static class FlushMarkerKey { + private Object fRootElement; + private IElementUpdateTester fElementTester; + + FlushMarkerKey(Object rootElement, IElementUpdateTester pathTester) { + fRootElement = rootElement; + fElementTester = pathTester; + } + + boolean includes(FlushMarkerKey key) { + return fRootElement.equals(key.fRootElement) && fElementTester.includes(key.fElementTester); + } + + int getUpdateFlags(ElementDataKey key) { + if (fRootElement.equals(key.fRootElement)) { + return fElementTester.getUpdateFlags(key.fViewerInput, key.fPath); + } + return 0; + } + + Collection<String> getPropertiesToFlush(ElementDataKey key, boolean isDirty) { + if (fRootElement.equals(key.fRootElement) && fElementTester instanceof IElementUpdateTesterExtension) { + return ((IElementUpdateTesterExtension) fElementTester).getPropertiesToFlush(key.fViewerInput, + key.fPath, isDirty); + } + return null; + } + + @Override + public String toString() { + return fElementTester.toString() + " " + fRootElement.toString(); //$NON-NLS-1$ + } + } + + /** + * Marker used to keep track of whether any entries with the given + * root element are present in the cache. + */ + private static class RootElementMarkerKey { + + private Object fRootElement; + + RootElementMarkerKey(Object rootElement) { + fRootElement = rootElement; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof RootElementMarkerKey + && ((RootElementMarkerKey) obj).fRootElement.equals(fRootElement); + } + + @Override + public int hashCode() { + return fRootElement.hashCode(); + } + + @Override + public String toString() { + return fRootElement.toString(); + } + } + + class RootElementMarkerEntry extends Entry { + RootElementMarkerEntry(RootElementMarkerKey key) { + super(key); + } + + @Override + void remove() { + super.remove(); + rootElementRemovedFromCache(((RootElementMarkerKey) fKey).fRootElement); + } + + @Override + public String toString() { + return "ROOT MARKER " + fKey; //$NON-NLS-1$ + } + } + + protected static String SELECTED_UPDATE_MODE = "org.eclipse.cdt.dsf.ui.viewmodel.update.selectedUpdateMode"; //$NON-NLS-1$ + /** + * @since 1.1 + */ + protected static String SELECTED_UPDATE_SCOPE = "org.eclipse.cdt.dsf.ui.viewmodel.update.selectedUpdateScope"; //$NON-NLS-1$ + + private IVMUpdatePolicy[] fAvailableUpdatePolicies; + + public Map<Object, RootElementMarkerKey> fRootMarkers = new HashMap<Object, RootElementMarkerKey>(); + + /** + * Hash map holding cache data. To store the cache information, the cache uses a + * combination of this hash map and a double-linked list running through all + * the entries in the cache. The linked list is used to organize the cache entries + * in least recently used (LRU) order. This ordering is then used to delete least + * recently used entries in the cache and keep the cache from growing indefinitely. + * Also, the ordering is used to optimize the flushing of the cache data (see + * {@link FlushMarkerKey} for more details). + */ + private final Map<Object, Entry> fCacheData = Collections.synchronizedMap(new HashMap<Object, Entry>(200, 0.75f)); + + /** + * Pointer to the first cache entry in the double-linked list of cache entries. + */ + private final Entry fCacheListHead; + + public AbstractCachingVMProvider(AbstractVMAdapter adapter, IPresentationContext presentationContext) { + super(adapter, presentationContext); + + fCacheListHead = new Entry(null) { + @Override + public String toString() { + return "HEAD"; //$NON-NLS-1$ + } + }; + fCacheListHead.fNext = fCacheListHead; + fCacheListHead.fPrevious = fCacheListHead; + + fAvailableUpdatePolicies = createUpdateModes(); + } + + protected IVMUpdatePolicy[] createUpdateModes() { + return new IVMUpdatePolicy[] { new AutomaticUpdatePolicy() }; + } + + @Override public IVMUpdatePolicy[] getAvailableUpdatePolicies() { - return fAvailableUpdatePolicies; - } + return fAvailableUpdatePolicies; + } - @Override + @Override public IVMUpdatePolicy getActiveUpdatePolicy() { - String updateModeId = (String)getPresentationContext().getProperty(SELECTED_UPDATE_MODE); - if (updateModeId != null) { - for (IVMUpdatePolicy updateMode : getAvailableUpdatePolicies()) { - if (updateMode.getID().equals(updateModeId)) { - return updateMode; - } - } - } - - // Default to the first one. - return getAvailableUpdatePolicies()[0]; - } - - @Override + String updateModeId = (String) getPresentationContext().getProperty(SELECTED_UPDATE_MODE); + if (updateModeId != null) { + for (IVMUpdatePolicy updateMode : getAvailableUpdatePolicies()) { + if (updateMode.getID().equals(updateModeId)) { + return updateMode; + } + } + } + + // Default to the first one. + return getAvailableUpdatePolicies()[0]; + } + + @Override public void setActiveUpdatePolicy(IVMUpdatePolicy updatePolicy) { - getPresentationContext().setProperty(SELECTED_UPDATE_MODE, updatePolicy.getID()); - - // Repaint the view to allow elements using the PROP_UPDATE_POLICY_ID - // property to repaint themselves. - for (final IVMModelProxy proxyStrategy : getActiveModelProxies()) { - if (!proxyStrategy.isDisposed()) { - proxyStrategy.fireModelChanged(new ModelDelta(proxyStrategy.getRootElement(), IModelDelta.CONTENT)); - } - } - } - - @Override + getPresentationContext().setProperty(SELECTED_UPDATE_MODE, updatePolicy.getID()); + + // Repaint the view to allow elements using the PROP_UPDATE_POLICY_ID + // property to repaint themselves. + for (final IVMModelProxy proxyStrategy : getActiveModelProxies()) { + if (!proxyStrategy.isDisposed()) { + proxyStrategy.fireModelChanged(new ModelDelta(proxyStrategy.getRootElement(), IModelDelta.CONTENT)); + } + } + } + + @Override public void refresh() { - IElementUpdateTester elementTester = getActiveUpdatePolicy().getElementUpdateTester(ManualUpdatePolicy.REFRESH_EVENT); - - for (final IVMModelProxy proxyStrategy : getActiveModelProxies()) { - flush(new FlushMarkerKey(proxyStrategy.getRootElement(), elementTester)); - } - - for (final IVMModelProxy proxyStrategy : getActiveModelProxies()) { - if (!proxyStrategy.isDisposed()) { - proxyStrategy.fireModelChanged(new ModelDelta(proxyStrategy.getRootElement(), IModelDelta.CONTENT)); - } - } - } - - @Override + IElementUpdateTester elementTester = getActiveUpdatePolicy() + .getElementUpdateTester(ManualUpdatePolicy.REFRESH_EVENT); + + for (final IVMModelProxy proxyStrategy : getActiveModelProxies()) { + flush(new FlushMarkerKey(proxyStrategy.getRootElement(), elementTester)); + } + + for (final IVMModelProxy proxyStrategy : getActiveModelProxies()) { + if (!proxyStrategy.isDisposed()) { + proxyStrategy.fireModelChanged(new ModelDelta(proxyStrategy.getRootElement(), IModelDelta.CONTENT)); + } + } + } + + @Override public ICacheEntry getCacheEntry(IVMNode node, Object viewerInput, TreePath path) { - ElementDataKey key = makeEntryKey(node, viewerInput, path); - return getElementDataEntry(key, false); - } - - @Override - public void updateNode(final IVMNode node, IHasChildrenUpdate[] updates) { - LinkedList <IHasChildrenUpdate> missUpdates = new LinkedList<IHasChildrenUpdate>(); - for(final IHasChildrenUpdate update : updates) { - // Find or create the cache entry for the element of this update. - ElementDataKey key = makeEntryKey(node, update); - final ElementDataEntry entry = getElementDataEntry(key, true); - updateRootElementMarker(key.fRootElement, node, update); - - // Check if the cache entry has this request result cached. - if (entry.fHasChildren != null) { - // Cache Hit! Just return the value. - if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("cacheHitHasChildren(node = " + node + ", update = " + update + ", " + entry.fHasChildren + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - update.setHasChilren(entry.fHasChildren.booleanValue()); - update.done(); - } else { - // Cache miss! Save the flush counter of the entry and create a proxy update. - final int flushCounter = entry.fFlushCounter; - missUpdates.add( - new VMHasChildrenUpdate( - update, - new ViewerDataRequestMonitor<Boolean>(getExecutor(), update) { - @Override - protected void handleCompleted() { - // Update completed. Write value to cache only if update succeeded - // and the cache entry wasn't flushed in the mean time. - if(isSuccess()) { - if (flushCounter == entry.fFlushCounter) { - if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("cacheSavedHasChildren(node = " + node + ", update = " + update + ", " + getData() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - entry.fHasChildren = this.getData(); - } - update.setHasChilren(getData()); - } else { - update.setStatus(getStatus()); - } - update.done(); - } - })); - } - } - - // Issue all the update proxies with one call. - if (!missUpdates.isEmpty()) { - super.updateNode(node, missUpdates.toArray(new IHasChildrenUpdate[missUpdates.size()])); - } - } - - @Override - public void updateNode(final IVMNode node, final IChildrenCountUpdate update) { - // Find or create the cache entry for the element of this update. - ElementDataKey key = makeEntryKey(node, update); - final ElementDataEntry entry = getElementDataEntry(key, true); - updateRootElementMarker(key.fRootElement, node, update); - - // Check if the cache entry has this request result cached. - if(entry.fChildrenCount != null) { - // Cache Hit! Just return the value. - if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("cacheHitChildrenCount(node = " + node + ", update = " + update + ", " + entry.fChildrenCount + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - update.setChildCount(entry.fChildrenCount.intValue()); - update.done(); - } else { - // Cache miss! Save the flush counter of the entry and create a proxy update. - final int flushCounter = entry.fFlushCounter; - IChildrenCountUpdate updateProxy = new VMChildrenCountUpdate( - update, - new ViewerDataRequestMonitor<Integer>(getExecutor(), update) { - @Override - protected void handleCompleted() { - // Update completed. Write value to cache only if update succeeded - // and the cache entry wasn't flushed in the mean time. - if(isSuccess()) { - if (flushCounter == entry.fFlushCounter) { - if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("cacheSavedChildrenCount(node = " + node + ", update = " + update + ", " + getData() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - entry.fChildrenCount = this.getData(); - } - update.setChildCount(getData()); - } else { - update.setStatus(getStatus()); - } - update.done(); - } - }); - super.updateNode(node, updateProxy); - } - } - - @Override - public void updateNode(final IVMNode node, final IChildrenUpdate update) { - // Find or create the cache entry for the element of this update. - ElementDataKey key = makeEntryKey(node, update); - final ElementDataEntry entry = getElementDataEntry(key, true); - updateRootElementMarker(key.fRootElement, node, update); - - final int flushCounter = entry.fFlushCounter; - if (entry.fChildren == null || (update.getOffset() < 0 && !entry.fAllChildrenKnown)) { - // Need to retrieve all the children if there is no children information yet. - // Or if the client requested all children (offset = -1, length -1) and all - // the children are not yet known. - IChildrenUpdate updateProxy = new VMChildrenUpdate( - update, update.getOffset(), update.getLength(), - new ViewerDataRequestMonitor<List<Object>>(getExecutor(), update){ - @Override - protected void handleSuccess() { - // Check if the update retrieved all children by specifying "offset = -1, length = -1" - int updateOffset = update.getOffset(); - if (updateOffset < 0) - { - updateOffset = 0; - if (entry.fFlushCounter == flushCounter) { - entry.fAllChildrenKnown = true; - } - } - - if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("cacheSavedChildren(node = " + node + ", update = " + update + ", children = {" + updateOffset + "->" + (updateOffset + getData().size()) + "})"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ - } - - if (flushCounter == entry.fFlushCounter) { - entry.ensureChildrenMap(); - } - - // Set the children to map and update. - for(int j = 0; j < getData().size(); j++) { - int offset = updateOffset + j; - Object child = getData().get(j); - if (child != null) { - if (flushCounter == entry.fFlushCounter) { - entry.fChildren.put(offset, child); - } - update.setChild(child, offset); - } - } - update.done(); - } - - @Override - protected void handleCancel() { - if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("cacheCanceledChildren(node = " + node + ", update = " + update + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - super.handleCancel(); - } - }); - super.updateNode(node, updateProxy); - } else if (update.getOffset() < 0 ) { - // The update requested all children. Fill in all children assuming that - // the children array is complete. - - if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("cacheHitChildren(node = " + node + ", update = " + update + ", children = " + entry.fChildren.keySet() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - - // The following assert should never fail given the first if statement. - assert entry.fAllChildrenKnown; - - // we have all of the children in cache; return from cache - for(int position = 0; position < entry.fChildren.size(); position++) { - update.setChild(entry.fChildren.get(position), position); - } - update.done(); - } else { - // Update for a partial list of children was requested. - // Iterate through the known children and make a list of missing - // indexes. - List<Integer> childrenMissingFromCache = new LinkedList<Integer>(); - for (int i = update.getOffset(); i < update.getOffset() + update.getLength(); i++) { - childrenMissingFromCache.add(i); - } - - // Write known children from cache into the update. - for(Integer position = update.getOffset(); position < update.getOffset() + update.getLength(); position++) { - Object child = entry.fChildren.get(position); - if (child != null) { - update.setChild(entry.fChildren.get(position), position); - childrenMissingFromCache.remove(position); - } - } - - if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("cachePartialHitChildren(node = " + node + ", update = " + update + ", missing = " + childrenMissingFromCache + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - - if (!childrenMissingFromCache.isEmpty()) { - // Note: it is possible that entry.fAllChildrenKnown == true at this point. - // This can happen if the node's has children implementation returns true - // while the actual children update returns with no elements. A node - // may do this for optimization reasons. I.e. sometimes it may be more - // efficient to ask the user to expand a node to see if it has any - // children. - - // Some children were not found in the cache, create separate - // proxy updates for the continuous ranges of missing children. - List<IChildrenUpdate> partialUpdates = new ArrayList<IChildrenUpdate>(2); - final CountingRequestMonitor multiRm = new ViewerCountingRequestMonitor(getExecutor(), update); - while(!childrenMissingFromCache.isEmpty()) - { - final int offset = childrenMissingFromCache.get(0); - childrenMissingFromCache.remove(0); - int length = 1; - while(!childrenMissingFromCache.isEmpty() && childrenMissingFromCache.get(0) == offset + length) - { - length++; - childrenMissingFromCache.remove(0); - } - - partialUpdates.add(new VMChildrenUpdate( - update, offset, length, - new DataRequestMonitor<List<Object>>(getExecutor(), multiRm) { - @Override - protected void handleSuccess() { - // Only save the children to the cahce if the entry wasn't flushed. - if (flushCounter == entry.fFlushCounter) { - if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("cachePartialSaveChildren(node = " + node + ", update = " + update + ", saved = {" + offset + "->" + (offset + getData().size()) + "})"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ - } - entry.ensureChildrenMap(); - } - - for (int i = 0; i < getData().size(); i++) { - if (getData().get(i) != null) { - update.setChild(getData().get(i), offset + i); - if (flushCounter == entry.fFlushCounter) { - // Only save the children to the cahce if the entry wasn't flushed. - entry.fChildren.put(offset + i, getData().get(i)); - } - } - } - multiRm.done(); - } - })); - } - - for (IChildrenUpdate partialUpdate : partialUpdates) { - super.updateNode(node, partialUpdate); - } - multiRm.setDoneCount(partialUpdates.size()); - } else { - // All children were found in cache. Complete the update. - update.done(); - } - } - - } - - /** - * Flushes the cache with given DMC as the root element. - * @param dmcToFlush DM Context which is the root of the flush operation. Entries - * for all DMCs that have this DMC as their ancestor will be flushed. If this - * parameter is null, then all entries are flushed. - * @param archive - */ - private void flush(FlushMarkerKey flushKey) { - if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("cacheFlushing(" + flushKey + ")"); //$NON-NLS-1$ //$NON-NLS-2$ - } - // For each entry that has the given context as a parent, perform the flush. - // Iterate through the cache entries backwards. This means that we will be - // iterating in order of most-recently-used to least-recently-used. - Entry entry = fCacheListHead.fPrevious; - while (entry != fCacheListHead) { - if (entry.fKey instanceof FlushMarkerKey) { - FlushMarkerKey entryFlushKey = (FlushMarkerKey)entry.fKey; - // If the context currently being flushed includes the flush - // context in current entry, remove the current entry since it will - // be replaced with one at the end of the list. - // Use special handling for null contexts, which we treat like it's an - // ancestor of all other contexts. - if (flushKey.includes(entryFlushKey)) { - fCacheData.remove(entryFlushKey); - entry.remove(); - } - - // If the flush context in current entry includes the current context - // being flushed, we can stop iterating through the cache entries - // now. - if (entryFlushKey.includes(flushKey)) { - break; - - } - } - else if (entry instanceof ElementDataEntry) { - ElementDataEntry elementDataEntry = (ElementDataEntry)entry; - ElementDataKey elementDataKey = (ElementDataKey)elementDataEntry.fKey; - int updateFlags = flushKey.getUpdateFlags(elementDataKey); - if ((updateFlags & IVMUpdatePolicy.FLUSH) != 0) { - if ((updateFlags & IVMUpdatePolicy.ARCHIVE) == IVMUpdatePolicy.ARCHIVE) { - // We are saving current data for change history, check if the data is valid. - // If it valid, save it for archive, if it's not valid old archive data will be used - // if there is any. And if there is no old archive data, just remove the cache entry. - if (elementDataEntry.fProperties != null) { - elementDataEntry.fArchiveProperties = elementDataEntry.fProperties; - } - elementDataEntry.fProperties = null; - - // There is no archived data, which means that this entry is empty, so remove it from cache - // completely. - if (elementDataEntry.fArchiveProperties == null) { - fCacheData.remove(entry.fKey); - entry.remove(); - } - } else { - // We are not changing the archived data. If archive data exists in the entry, leave it. - // Otherwise remove the whole entry. - if (elementDataEntry.fArchiveProperties != null) { - elementDataEntry.fProperties = null; - } else { - fCacheData.remove(entry.fKey); - entry.remove(); - } - } - elementDataEntry.fFlushCounter++; - elementDataEntry.fHasChildren = null; - elementDataEntry.fChildrenCount = null; - elementDataEntry.fChildren = null; - elementDataEntry.fAllChildrenKnown = false; - elementDataEntry.fDirty = false; - } else if ((updateFlags & IVMUpdatePolicy.FLUSH_ALL_PROPERTIES) != 0) { - elementDataEntry.fProperties = null; - } else if ((updateFlags & IVMUpdatePolicy.FLUSH_PARTIAL_PROPERTIES) != 0) { - Collection<String> propertiesToFlush = flushKey.getPropertiesToFlush(elementDataKey, elementDataEntry.fDirty); - if (propertiesToFlush != null && elementDataEntry.fProperties != null) { - elementDataEntry.fProperties.keySet().removeAll(propertiesToFlush); - } - } else if ((updateFlags & IVMUpdatePolicy.DIRTY) != 0) { - elementDataEntry.fDirty = true; - if (elementDataEntry.fProperties != null) { - elementDataEntry.fProperties.put(PROP_CACHE_ENTRY_DIRTY, Boolean.TRUE); - } - } - } - entry = entry.fPrevious; - } - - // Insert a marker for this flush operation. - Entry flushMarkerEntry = new Entry(flushKey); - fCacheData.put(flushKey, flushMarkerEntry); - flushMarkerEntry.insert(fCacheListHead); - } - - /** - * Listener used to detect when the viewer is finished updating itself - * after a model event. The - */ - // Warnings for use of ITreeModelViewer. ITreeModelViewer is an internal - // interface in platform, but it is more generic than the public TreeModelViewer. - // Using ITreeModelViewer will allow us to write unit tests using the - // VirtualTreeModelViewer. - private class ViewUpdateFinishedListener implements IViewerUpdateListener, IModelChangedListener { - private final ITreeModelViewer fViewer; - private boolean fViewerChangeStarted = false; - private RequestMonitor fRm; - - ViewUpdateFinishedListener(ITreeModelViewer viewer) { - fViewer = viewer; - } - - private void start(RequestMonitor rm) { - synchronized(this) { - fViewer.addModelChangedListener(this); - fViewer.addViewerUpdateListener(this); - fRm = rm; - } - } - - @Override + ElementDataKey key = makeEntryKey(node, viewerInput, path); + return getElementDataEntry(key, false); + } + + @Override + public void updateNode(final IVMNode node, IHasChildrenUpdate[] updates) { + LinkedList<IHasChildrenUpdate> missUpdates = new LinkedList<IHasChildrenUpdate>(); + for (final IHasChildrenUpdate update : updates) { + // Find or create the cache entry for the element of this update. + ElementDataKey key = makeEntryKey(node, update); + final ElementDataEntry entry = getElementDataEntry(key, true); + updateRootElementMarker(key.fRootElement, node, update); + + // Check if the cache entry has this request result cached. + if (entry.fHasChildren != null) { + // Cache Hit! Just return the value. + if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("cacheHitHasChildren(node = " + node + ", update = " + update + ", " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + + entry.fHasChildren + ")"); //$NON-NLS-1$ + } + update.setHasChilren(entry.fHasChildren.booleanValue()); + update.done(); + } else { + // Cache miss! Save the flush counter of the entry and create a proxy update. + final int flushCounter = entry.fFlushCounter; + missUpdates.add( + new VMHasChildrenUpdate(update, new ViewerDataRequestMonitor<Boolean>(getExecutor(), update) { + @Override + protected void handleCompleted() { + // Update completed. Write value to cache only if update succeeded + // and the cache entry wasn't flushed in the mean time. + if (isSuccess()) { + if (flushCounter == entry.fFlushCounter) { + if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("cacheSavedHasChildren(node = " + node + ", update = " //$NON-NLS-1$//$NON-NLS-2$ + + update + ", " + getData() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ + } + entry.fHasChildren = this.getData(); + } + update.setHasChilren(getData()); + } else { + update.setStatus(getStatus()); + } + update.done(); + } + })); + } + } + + // Issue all the update proxies with one call. + if (!missUpdates.isEmpty()) { + super.updateNode(node, missUpdates.toArray(new IHasChildrenUpdate[missUpdates.size()])); + } + } + + @Override + public void updateNode(final IVMNode node, final IChildrenCountUpdate update) { + // Find or create the cache entry for the element of this update. + ElementDataKey key = makeEntryKey(node, update); + final ElementDataEntry entry = getElementDataEntry(key, true); + updateRootElementMarker(key.fRootElement, node, update); + + // Check if the cache entry has this request result cached. + if (entry.fChildrenCount != null) { + // Cache Hit! Just return the value. + if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("cacheHitChildrenCount(node = " + node + ", update = " + update + ", " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + + entry.fChildrenCount + ")"); //$NON-NLS-1$ + } + update.setChildCount(entry.fChildrenCount.intValue()); + update.done(); + } else { + // Cache miss! Save the flush counter of the entry and create a proxy update. + final int flushCounter = entry.fFlushCounter; + IChildrenCountUpdate updateProxy = new VMChildrenCountUpdate(update, + new ViewerDataRequestMonitor<Integer>(getExecutor(), update) { + @Override + protected void handleCompleted() { + // Update completed. Write value to cache only if update succeeded + // and the cache entry wasn't flushed in the mean time. + if (isSuccess()) { + if (flushCounter == entry.fFlushCounter) { + if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("cacheSavedChildrenCount(node = " + node + ", update = " //$NON-NLS-1$//$NON-NLS-2$ + + update + ", " + getData() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ + } + entry.fChildrenCount = this.getData(); + } + update.setChildCount(getData()); + } else { + update.setStatus(getStatus()); + } + update.done(); + } + }); + super.updateNode(node, updateProxy); + } + } + + @Override + public void updateNode(final IVMNode node, final IChildrenUpdate update) { + // Find or create the cache entry for the element of this update. + ElementDataKey key = makeEntryKey(node, update); + final ElementDataEntry entry = getElementDataEntry(key, true); + updateRootElementMarker(key.fRootElement, node, update); + + final int flushCounter = entry.fFlushCounter; + if (entry.fChildren == null || (update.getOffset() < 0 && !entry.fAllChildrenKnown)) { + // Need to retrieve all the children if there is no children information yet. + // Or if the client requested all children (offset = -1, length -1) and all + // the children are not yet known. + IChildrenUpdate updateProxy = new VMChildrenUpdate(update, update.getOffset(), update.getLength(), + new ViewerDataRequestMonitor<List<Object>>(getExecutor(), update) { + @Override + protected void handleSuccess() { + // Check if the update retrieved all children by specifying "offset = -1, length = -1" + int updateOffset = update.getOffset(); + if (updateOffset < 0) { + updateOffset = 0; + if (entry.fFlushCounter == flushCounter) { + entry.fAllChildrenKnown = true; + } + } + + if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug( + "cacheSavedChildren(node = " + node + ", update = " + update + ", children = {" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + + updateOffset + "->" + (updateOffset + getData().size()) + "})"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + if (flushCounter == entry.fFlushCounter) { + entry.ensureChildrenMap(); + } + + // Set the children to map and update. + for (int j = 0; j < getData().size(); j++) { + int offset = updateOffset + j; + Object child = getData().get(j); + if (child != null) { + if (flushCounter == entry.fFlushCounter) { + entry.fChildren.put(offset, child); + } + update.setChild(child, offset); + } + } + update.done(); + } + + @Override + protected void handleCancel() { + if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin + .debug("cacheCanceledChildren(node = " + node + ", update = " + update + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + super.handleCancel(); + } + }); + super.updateNode(node, updateProxy); + } else if (update.getOffset() < 0) { + // The update requested all children. Fill in all children assuming that + // the children array is complete. + + if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("cacheHitChildren(node = " + node + ", update = " + update + ", children = " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + + entry.fChildren.keySet() + ")"); //$NON-NLS-1$ + } + + // The following assert should never fail given the first if statement. + assert entry.fAllChildrenKnown; + + // we have all of the children in cache; return from cache + for (int position = 0; position < entry.fChildren.size(); position++) { + update.setChild(entry.fChildren.get(position), position); + } + update.done(); + } else { + // Update for a partial list of children was requested. + // Iterate through the known children and make a list of missing + // indexes. + List<Integer> childrenMissingFromCache = new LinkedList<Integer>(); + for (int i = update.getOffset(); i < update.getOffset() + update.getLength(); i++) { + childrenMissingFromCache.add(i); + } + + // Write known children from cache into the update. + for (Integer position = update.getOffset(); position < update.getOffset() + + update.getLength(); position++) { + Object child = entry.fChildren.get(position); + if (child != null) { + update.setChild(entry.fChildren.get(position), position); + childrenMissingFromCache.remove(position); + } + } + + if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("cachePartialHitChildren(node = " + node + ", update = " + update + ", missing = " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + + childrenMissingFromCache + ")"); //$NON-NLS-1$ + } + + if (!childrenMissingFromCache.isEmpty()) { + // Note: it is possible that entry.fAllChildrenKnown == true at this point. + // This can happen if the node's has children implementation returns true + // while the actual children update returns with no elements. A node + // may do this for optimization reasons. I.e. sometimes it may be more + // efficient to ask the user to expand a node to see if it has any + // children. + + // Some children were not found in the cache, create separate + // proxy updates for the continuous ranges of missing children. + List<IChildrenUpdate> partialUpdates = new ArrayList<IChildrenUpdate>(2); + final CountingRequestMonitor multiRm = new ViewerCountingRequestMonitor(getExecutor(), update); + while (!childrenMissingFromCache.isEmpty()) { + final int offset = childrenMissingFromCache.get(0); + childrenMissingFromCache.remove(0); + int length = 1; + while (!childrenMissingFromCache.isEmpty() && childrenMissingFromCache.get(0) == offset + length) { + length++; + childrenMissingFromCache.remove(0); + } + + partialUpdates.add(new VMChildrenUpdate(update, offset, length, + new DataRequestMonitor<List<Object>>(getExecutor(), multiRm) { + @Override + protected void handleSuccess() { + // Only save the children to the cahce if the entry wasn't flushed. + if (flushCounter == entry.fFlushCounter) { + if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("cachePartialSaveChildren(node = " + node + ", update = " //$NON-NLS-1$//$NON-NLS-2$ + + update + ", saved = {" + offset + "->" //$NON-NLS-1$//$NON-NLS-2$ + + (offset + getData().size()) + "})"); //$NON-NLS-1$ + } + entry.ensureChildrenMap(); + } + + for (int i = 0; i < getData().size(); i++) { + if (getData().get(i) != null) { + update.setChild(getData().get(i), offset + i); + if (flushCounter == entry.fFlushCounter) { + // Only save the children to the cahce if the entry wasn't flushed. + entry.fChildren.put(offset + i, getData().get(i)); + } + } + } + multiRm.done(); + } + })); + } + + for (IChildrenUpdate partialUpdate : partialUpdates) { + super.updateNode(node, partialUpdate); + } + multiRm.setDoneCount(partialUpdates.size()); + } else { + // All children were found in cache. Complete the update. + update.done(); + } + } + + } + + /** + * Flushes the cache with given DMC as the root element. + * @param dmcToFlush DM Context which is the root of the flush operation. Entries + * for all DMCs that have this DMC as their ancestor will be flushed. If this + * parameter is null, then all entries are flushed. + * @param archive + */ + private void flush(FlushMarkerKey flushKey) { + if (DEBUG_CACHE + && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("cacheFlushing(" + flushKey + ")"); //$NON-NLS-1$ //$NON-NLS-2$ + } + // For each entry that has the given context as a parent, perform the flush. + // Iterate through the cache entries backwards. This means that we will be + // iterating in order of most-recently-used to least-recently-used. + Entry entry = fCacheListHead.fPrevious; + while (entry != fCacheListHead) { + if (entry.fKey instanceof FlushMarkerKey) { + FlushMarkerKey entryFlushKey = (FlushMarkerKey) entry.fKey; + // If the context currently being flushed includes the flush + // context in current entry, remove the current entry since it will + // be replaced with one at the end of the list. + // Use special handling for null contexts, which we treat like it's an + // ancestor of all other contexts. + if (flushKey.includes(entryFlushKey)) { + fCacheData.remove(entryFlushKey); + entry.remove(); + } + + // If the flush context in current entry includes the current context + // being flushed, we can stop iterating through the cache entries + // now. + if (entryFlushKey.includes(flushKey)) { + break; + + } + } else if (entry instanceof ElementDataEntry) { + ElementDataEntry elementDataEntry = (ElementDataEntry) entry; + ElementDataKey elementDataKey = (ElementDataKey) elementDataEntry.fKey; + int updateFlags = flushKey.getUpdateFlags(elementDataKey); + if ((updateFlags & IVMUpdatePolicy.FLUSH) != 0) { + if ((updateFlags & IVMUpdatePolicy.ARCHIVE) == IVMUpdatePolicy.ARCHIVE) { + // We are saving current data for change history, check if the data is valid. + // If it valid, save it for archive, if it's not valid old archive data will be used + // if there is any. And if there is no old archive data, just remove the cache entry. + if (elementDataEntry.fProperties != null) { + elementDataEntry.fArchiveProperties = elementDataEntry.fProperties; + } + elementDataEntry.fProperties = null; + + // There is no archived data, which means that this entry is empty, so remove it from cache + // completely. + if (elementDataEntry.fArchiveProperties == null) { + fCacheData.remove(entry.fKey); + entry.remove(); + } + } else { + // We are not changing the archived data. If archive data exists in the entry, leave it. + // Otherwise remove the whole entry. + if (elementDataEntry.fArchiveProperties != null) { + elementDataEntry.fProperties = null; + } else { + fCacheData.remove(entry.fKey); + entry.remove(); + } + } + elementDataEntry.fFlushCounter++; + elementDataEntry.fHasChildren = null; + elementDataEntry.fChildrenCount = null; + elementDataEntry.fChildren = null; + elementDataEntry.fAllChildrenKnown = false; + elementDataEntry.fDirty = false; + } else if ((updateFlags & IVMUpdatePolicy.FLUSH_ALL_PROPERTIES) != 0) { + elementDataEntry.fProperties = null; + } else if ((updateFlags & IVMUpdatePolicy.FLUSH_PARTIAL_PROPERTIES) != 0) { + Collection<String> propertiesToFlush = flushKey.getPropertiesToFlush(elementDataKey, + elementDataEntry.fDirty); + if (propertiesToFlush != null && elementDataEntry.fProperties != null) { + elementDataEntry.fProperties.keySet().removeAll(propertiesToFlush); + } + } else if ((updateFlags & IVMUpdatePolicy.DIRTY) != 0) { + elementDataEntry.fDirty = true; + if (elementDataEntry.fProperties != null) { + elementDataEntry.fProperties.put(PROP_CACHE_ENTRY_DIRTY, Boolean.TRUE); + } + } + } + entry = entry.fPrevious; + } + + // Insert a marker for this flush operation. + Entry flushMarkerEntry = new Entry(flushKey); + fCacheData.put(flushKey, flushMarkerEntry); + flushMarkerEntry.insert(fCacheListHead); + } + + /** + * Listener used to detect when the viewer is finished updating itself + * after a model event. The + */ + // Warnings for use of ITreeModelViewer. ITreeModelViewer is an internal + // interface in platform, but it is more generic than the public TreeModelViewer. + // Using ITreeModelViewer will allow us to write unit tests using the + // VirtualTreeModelViewer. + private class ViewUpdateFinishedListener implements IViewerUpdateListener, IModelChangedListener { + private final ITreeModelViewer fViewer; + private boolean fViewerChangeStarted = false; + private RequestMonitor fRm; + + ViewUpdateFinishedListener(ITreeModelViewer viewer) { + fViewer = viewer; + } + + private void start(RequestMonitor rm) { + synchronized (this) { + fViewer.addModelChangedListener(this); + fViewer.addViewerUpdateListener(this); + fRm = rm; + } + } + + @Override public synchronized void viewerUpdatesComplete() { - done(); - } + done(); + } - @Override + @Override public void modelChanged(IModelDelta delta, IModelProxy proxy) { - synchronized (this) { - if (!fViewerChangeStarted) { - done(); - } - } - } - - @Override + synchronized (this) { + if (!fViewerChangeStarted) { + done(); + } + } + } + + @Override public void viewerUpdatesBegin() { - synchronized(this) { - fViewerChangeStarted = true; - } - } - - private synchronized void done() { - if (fRm != null) { - fRm.done(); - fViewer.removeViewerUpdateListener(this); - fViewer.removeModelChangedListener(this); - } - } - - @Override - public void updateStarted(IViewerUpdate update) {} - @Override - public void updateComplete(IViewerUpdate update) {} - - } - - @Override - protected void handleEvent(final IVMModelProxy proxyStrategy, final Object event, final RequestMonitor rm) { - IElementUpdateTester elementTester = getActiveUpdatePolicy().getElementUpdateTester(event); - - flush(new FlushMarkerKey(proxyStrategy.getRootElement(), elementTester)); - - if (!proxyStrategy.isDisposed()) { - if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - trace(event, null, proxyStrategy, EventHandlerAction.processing); - } - proxyStrategy.createDelta( - event, - new DataRequestMonitor<IModelDelta>(getExecutor(), rm) { - @Override - public void handleSuccess() { - if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - trace(event, null, proxyStrategy, EventHandlerAction.firedDeltaFor); - } - - // If we need to wait for the view to finish updating, then before posting the delta to the - // viewer install a listener, which will in turn call rm.done(). - if (fDelayEventHandleForViewUpdate) { - ITreeModelViewer viewer = (ITreeModelViewer) proxyStrategy.getViewer(); - new ViewUpdateFinishedListener(viewer).start(rm); - } - - proxyStrategy.fireModelChanged(getData()); - - if (!fDelayEventHandleForViewUpdate) { - rm.done(); - } - } - @Override public String toString() { - return "Result of a delta for event: '" + event.toString() + "' in VMP: '" + AbstractCachingVMProvider.this + "'" + "\n" + getData().toString(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - }); - } else { - rm.done(); - } - } - - /** - * Override default implementation to avoid automatically removing disposed proxies from - * list of active proxies. The caching provider only removes a proxy after its root element - * is no longer in the cache. - */ - @Override - public IModelProxy createModelProxy(Object element, IPresentationContext context) { - // Iterate through the current active proxies to try to find a proxy with the same - // element and re-use it if found. Only disposed proxies can be re-used because - // multiple viewers cannot use the same proxy. - // - // Unlike in the base class, do not remove proxies just because they were disposed - // by the viewer. These proxies can contain modification history for variables in - // their cache. The proxies will be removed once their cache entries are emptied. - // See rootElementRemovedFromCache(). - IVMModelProxy proxy = null; - for (Iterator<IVMModelProxy> itr = getActiveModelProxies().iterator(); itr.hasNext();) { - IVMModelProxy next = itr.next(); - if (next != null && next.getRootElement().equals(element) && next.isDisposed()) { - proxy = next; - break; - } - } - if (proxy == null) { - proxy = createModelProxyStrategy(element); - getActiveModelProxies().add(proxy); - } else if (proxy.isDisposed()) { - // DSF is capable of re-using old proxies which were previously - // disposed. However, the viewer which installs a proxy using - // a background job to install the proxy calls - // IModelProxy.isDisposed(), to check whether the proxy was disposed - // before it could be installed. We need to clear the disposed flag - // of the re-used proxy here, otherwise the proxy will never get used. - // Calling init here will cause the init() method to be called twice - // so the IVMModelProxy needs to be prepared for that. - // See bug 241024. - proxy.init(context); - } - - return proxy; - } + synchronized (this) { + fViewerChangeStarted = true; + } + } + + private synchronized void done() { + if (fRm != null) { + fRm.done(); + fViewer.removeViewerUpdateListener(this); + fViewer.removeModelChangedListener(this); + } + } + + @Override + public void updateStarted(IViewerUpdate update) { + } + + @Override + public void updateComplete(IViewerUpdate update) { + } + + } + + @Override + protected void handleEvent(final IVMModelProxy proxyStrategy, final Object event, final RequestMonitor rm) { + IElementUpdateTester elementTester = getActiveUpdatePolicy().getElementUpdateTester(event); + + flush(new FlushMarkerKey(proxyStrategy.getRootElement(), elementTester)); + + if (!proxyStrategy.isDisposed()) { + if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + trace(event, null, proxyStrategy, EventHandlerAction.processing); + } + proxyStrategy.createDelta(event, new DataRequestMonitor<IModelDelta>(getExecutor(), rm) { + @Override + public void handleSuccess() { + if (DEBUG_DELTA && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + trace(event, null, proxyStrategy, EventHandlerAction.firedDeltaFor); + } + + // If we need to wait for the view to finish updating, then before posting the delta to the + // viewer install a listener, which will in turn call rm.done(). + if (fDelayEventHandleForViewUpdate) { + ITreeModelViewer viewer = (ITreeModelViewer) proxyStrategy.getViewer(); + new ViewUpdateFinishedListener(viewer).start(rm); + } + + proxyStrategy.fireModelChanged(getData()); + + if (!fDelayEventHandleForViewUpdate) { + rm.done(); + } + } + + @Override + public String toString() { + return "Result of a delta for event: '" + event.toString() + "' in VMP: '" //$NON-NLS-1$//$NON-NLS-2$ + + AbstractCachingVMProvider.this + "'" + "\n" + getData().toString(); //$NON-NLS-1$ //$NON-NLS-2$ + } + }); + } else { + rm.done(); + } + } + + /** + * Override default implementation to avoid automatically removing disposed proxies from + * list of active proxies. The caching provider only removes a proxy after its root element + * is no longer in the cache. + */ + @Override + public IModelProxy createModelProxy(Object element, IPresentationContext context) { + // Iterate through the current active proxies to try to find a proxy with the same + // element and re-use it if found. Only disposed proxies can be re-used because + // multiple viewers cannot use the same proxy. + // + // Unlike in the base class, do not remove proxies just because they were disposed + // by the viewer. These proxies can contain modification history for variables in + // their cache. The proxies will be removed once their cache entries are emptied. + // See rootElementRemovedFromCache(). + IVMModelProxy proxy = null; + for (Iterator<IVMModelProxy> itr = getActiveModelProxies().iterator(); itr.hasNext();) { + IVMModelProxy next = itr.next(); + if (next != null && next.getRootElement().equals(element) && next.isDisposed()) { + proxy = next; + break; + } + } + if (proxy == null) { + proxy = createModelProxyStrategy(element); + getActiveModelProxies().add(proxy); + } else if (proxy.isDisposed()) { + // DSF is capable of re-using old proxies which were previously + // disposed. However, the viewer which installs a proxy using + // a background job to install the proxy calls + // IModelProxy.isDisposed(), to check whether the proxy was disposed + // before it could be installed. We need to clear the disposed flag + // of the re-used proxy here, otherwise the proxy will never get used. + // Calling init here will cause the init() method to be called twice + // so the IVMModelProxy needs to be prepared for that. + // See bug 241024. + proxy.init(context); + } + + return proxy; + } /** * Called when all cache entries for the given root element have been @@ -963,433 +1007,439 @@ public class AbstractCachingVMProvider extends AbstractVMProvider * on to the proxy and keeps processing deltas for that root element until * the cache entries for this element are gone. */ - protected void rootElementRemovedFromCache(Object rootElement) { - fRootMarkers.remove(rootElement); - - for (Iterator<IVMModelProxy> proxiesItr = getActiveModelProxies().iterator(); proxiesItr.hasNext();) { - IVMModelProxy proxy = proxiesItr.next(); - if (proxy.isDisposed() && proxy.getRootElement().equals(rootElement) ) { - proxiesItr.remove(); - } - } - } - - /** - * Convenience class that searches for the root element for the given - * update and creates an element cache entry key. - */ - private ElementDataKey makeEntryKey(IVMNode node, IViewerUpdate update) { - return makeEntryKey(node, update.getViewerInput(), update.getElementPath()); - } - - /** - * Convenience class that searches for the root element for the given - * update and creates an element cache entry key. - */ - private ElementDataKey makeEntryKey(IVMNode node, Object viewerInput, TreePath path) { - Object rootElement = viewerInput; // Default - outer: for (IVMModelProxy proxy : getActiveModelProxies()) { - Object proxyRoot = proxy.getRootElement(); - if (proxyRoot.equals(viewerInput)) { - rootElement = proxyRoot; - break; - } - for (int i = 0; i < path.getSegmentCount(); i++) { - if (proxyRoot.equals(path.getSegment(i))) { - rootElement = proxyRoot; - break outer; - } - } - } - - return new ElementDataKey(rootElement, node, viewerInput, path); - } - - - /** - * This is the only method that should be used to access a cache entry. - * It creates a new entry if needed and it maintains the ordering in - * the least-recently-used linked list. - * @param create Create the entry if needed. - * @return cache element entry, may be <code>null</code> if entry does - * not exist and the create parameter is <code>false</code> - */ - private ElementDataEntry getElementDataEntry(ElementDataKey key, boolean create) { - assert key != null; - ElementDataEntry entry = (ElementDataEntry)fCacheData.get(key); - if (entry != null) { - // Entry exists, move it to the end of the list. - entry.reinsert(fCacheListHead); - } else if (create) { - // Create a new entry and add it to the end of the list. - entry = new ElementDataEntry(key); - addEntry(key, entry); - } - return entry; - } - - private void updateRootElementMarker(Object rootElement, IVMNode node, IViewerUpdate update) { - boolean created = false; - // Update the root element marker: - // - ensure that the root marker is root markers' map, - // - ensure that the root marker is in the cache map, - // - and ensure that it's at the end of the cache. - RootElementMarkerKey rootMarker = fRootMarkers.get(rootElement); - if (rootMarker == null) { - rootMarker = new RootElementMarkerKey(rootElement); - fRootMarkers.put(rootElement, rootMarker); - created = true; - } - Entry rootMarkerEntry = fCacheData.get(rootMarker); - if (rootMarkerEntry == null) { - rootMarkerEntry = new RootElementMarkerEntry(rootMarker); - addEntry(rootMarker, rootMarkerEntry); - } else if (rootMarkerEntry.fNext != fCacheListHead) { - rootMarkerEntry.reinsert(fCacheListHead); - } - - if (created) { - ElementDataKey rootElementDataKey = - new ElementDataKey(rootElement, node, update.getViewerInput(), update.getElementPath()); - ElementDataEntry entry = getElementDataEntry(rootElementDataKey, false); - - Object[] rootElementChildren = getActiveUpdatePolicy().getInitialRootElementChildren(rootElement); - if (rootElementChildren != null) { - entry.fHasChildren = rootElementChildren.length > 0; - entry.fChildrenCount = rootElementChildren.length; - entry.fChildren = new HashMap<Integer, Object>(entry.fChildrenCount * 4/3); - for (int i = 0; i < rootElementChildren.length; i++) { - entry.fChildren.put(i, rootElementChildren[i]); - } - entry.fAllChildrenKnown = true; - entry.fDirty = true; - } - - Map<String, Object> rootElementProperties = getActiveUpdatePolicy().getInitialRootElementProperties(rootElement); - - if (rootElementProperties != null) { - entry.fProperties = new HashMap<String, Object>((rootElementProperties.size() + 1) * 4/3); - entry.fProperties.putAll(rootElementProperties); - entry.fProperties.put(PROP_CACHE_ENTRY_DIRTY, true); - entry.fDirty = true; - } - } - } - - /** - * Convenience method used by {@link #getElementDataEntry(ElementDataKey)} - */ - private void addEntry(Object key, Entry entry) { - fCacheData.put(key, entry); - entry.insert(fCacheListHead); - // If we are at capacity in the cache, remove the entry from head. - if (fCacheData.size() > MAX_CACHE_SIZE) { - fCacheData.remove(fCacheListHead.fNext.fKey); - fCacheListHead.fNext.remove(); - } - } - - /** - * @since 2.0 - */ - @Override + protected void rootElementRemovedFromCache(Object rootElement) { + fRootMarkers.remove(rootElement); + + for (Iterator<IVMModelProxy> proxiesItr = getActiveModelProxies().iterator(); proxiesItr.hasNext();) { + IVMModelProxy proxy = proxiesItr.next(); + if (proxy.isDisposed() && proxy.getRootElement().equals(rootElement)) { + proxiesItr.remove(); + } + } + } + + /** + * Convenience class that searches for the root element for the given + * update and creates an element cache entry key. + */ + private ElementDataKey makeEntryKey(IVMNode node, IViewerUpdate update) { + return makeEntryKey(node, update.getViewerInput(), update.getElementPath()); + } + + /** + * Convenience class that searches for the root element for the given + * update and creates an element cache entry key. + */ + private ElementDataKey makeEntryKey(IVMNode node, Object viewerInput, TreePath path) { + Object rootElement = viewerInput; // Default + outer: for (IVMModelProxy proxy : getActiveModelProxies()) { + Object proxyRoot = proxy.getRootElement(); + if (proxyRoot.equals(viewerInput)) { + rootElement = proxyRoot; + break; + } + for (int i = 0; i < path.getSegmentCount(); i++) { + if (proxyRoot.equals(path.getSegment(i))) { + rootElement = proxyRoot; + break outer; + } + } + } + + return new ElementDataKey(rootElement, node, viewerInput, path); + } + + /** + * This is the only method that should be used to access a cache entry. + * It creates a new entry if needed and it maintains the ordering in + * the least-recently-used linked list. + * @param create Create the entry if needed. + * @return cache element entry, may be <code>null</code> if entry does + * not exist and the create parameter is <code>false</code> + */ + private ElementDataEntry getElementDataEntry(ElementDataKey key, boolean create) { + assert key != null; + ElementDataEntry entry = (ElementDataEntry) fCacheData.get(key); + if (entry != null) { + // Entry exists, move it to the end of the list. + entry.reinsert(fCacheListHead); + } else if (create) { + // Create a new entry and add it to the end of the list. + entry = new ElementDataEntry(key); + addEntry(key, entry); + } + return entry; + } + + private void updateRootElementMarker(Object rootElement, IVMNode node, IViewerUpdate update) { + boolean created = false; + // Update the root element marker: + // - ensure that the root marker is root markers' map, + // - ensure that the root marker is in the cache map, + // - and ensure that it's at the end of the cache. + RootElementMarkerKey rootMarker = fRootMarkers.get(rootElement); + if (rootMarker == null) { + rootMarker = new RootElementMarkerKey(rootElement); + fRootMarkers.put(rootElement, rootMarker); + created = true; + } + Entry rootMarkerEntry = fCacheData.get(rootMarker); + if (rootMarkerEntry == null) { + rootMarkerEntry = new RootElementMarkerEntry(rootMarker); + addEntry(rootMarker, rootMarkerEntry); + } else if (rootMarkerEntry.fNext != fCacheListHead) { + rootMarkerEntry.reinsert(fCacheListHead); + } + + if (created) { + ElementDataKey rootElementDataKey = new ElementDataKey(rootElement, node, update.getViewerInput(), + update.getElementPath()); + ElementDataEntry entry = getElementDataEntry(rootElementDataKey, false); + + Object[] rootElementChildren = getActiveUpdatePolicy().getInitialRootElementChildren(rootElement); + if (rootElementChildren != null) { + entry.fHasChildren = rootElementChildren.length > 0; + entry.fChildrenCount = rootElementChildren.length; + entry.fChildren = new HashMap<Integer, Object>(entry.fChildrenCount * 4 / 3); + for (int i = 0; i < rootElementChildren.length; i++) { + entry.fChildren.put(i, rootElementChildren[i]); + } + entry.fAllChildrenKnown = true; + entry.fDirty = true; + } + + Map<String, Object> rootElementProperties = getActiveUpdatePolicy() + .getInitialRootElementProperties(rootElement); + + if (rootElementProperties != null) { + entry.fProperties = new HashMap<String, Object>((rootElementProperties.size() + 1) * 4 / 3); + entry.fProperties.putAll(rootElementProperties); + entry.fProperties.put(PROP_CACHE_ENTRY_DIRTY, true); + entry.fDirty = true; + } + } + } + + /** + * Convenience method used by {@link #getElementDataEntry(ElementDataKey)} + */ + private void addEntry(Object key, Entry entry) { + fCacheData.put(key, entry); + entry.insert(fCacheListHead); + // If we are at capacity in the cache, remove the entry from head. + if (fCacheData.size() > MAX_CACHE_SIZE) { + fCacheData.remove(fCacheListHead.fNext.fKey); + fCacheListHead.fNext.remove(); + } + } + + /** + * @since 2.0 + */ + @Override public void update(IPropertiesUpdate[] updates) { - if (updates.length == 0) - return; - - // Optimization: if all the updates belong to the same node, avoid - // creating any new lists/arrays. - boolean allNodesTheSame = true; - IVMNode firstNode = getNodeForElement(updates[0].getElement()); - for (int i = 1; i < updates.length; i++) { - if (firstNode != getNodeForElement(updates[i].getElement())) { - allNodesTheSame = false; - break; - } - } - - if (allNodesTheSame) { - if ( !(firstNode instanceof IElementPropertiesProvider) ) { - for (IPropertiesUpdate update : updates) { - update.setStatus(DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_HANDLE, "Element is not a VM Context or its node is not a properties provider.", null)); //$NON-NLS-1$ - update.done(); - } - } else { - updateNode(firstNode, updates); - } - } else { - // Sort the updates by the node. - Map<IVMNode, List<IPropertiesUpdate>> nodeUpdatesMap = new HashMap<IVMNode, List<IPropertiesUpdate>>(); - for (IPropertiesUpdate update : updates) { - // Get the VM Context for last element in path. - IVMNode node = getNodeForElement(update.getElement()); - if ( node == null || !(node instanceof IElementPropertiesProvider) ) { - // Misdirected update. - update.setStatus(DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_HANDLE, "Element is not a VM Context or its node is not a properties provider.", null)); //$NON-NLS-1$ - update.done(); - continue; - } - if (!nodeUpdatesMap.containsKey(node)) { - nodeUpdatesMap.put(node, new ArrayList<IPropertiesUpdate>()); - } - nodeUpdatesMap.get(node).add(update); - } - - // Iterate through the nodes in the sorted map. - for (IVMNode node : nodeUpdatesMap.keySet()) { - updateNode(node, nodeUpdatesMap.get(node).toArray( - new IPropertiesUpdate[nodeUpdatesMap.get(node).size()])); - } - } - } - - /** - * Convenience method that finds the VM node corresponding to given element. - * It returns <code>null</code> if the element is not a VM context. - * - * @param element Element to find the VM Node for. - * @return View Model Node that this element was created by, or <code>null</code>. - * - * @since 2.0 - */ - private IVMNode getNodeForElement(Object element) { - if (element instanceof IVMContext) { - return ((IVMContext) element).getVMNode(); - } - return null; - } - - - protected void updateNode(final IVMNode node, IPropertiesUpdate[] updates) { - LinkedList <IPropertiesUpdate> missUpdates = new LinkedList<IPropertiesUpdate>(); - for(final IPropertiesUpdate update : updates) { - // Find or create the cache entry for the element of this update. - ElementDataKey key = makeEntryKey(node, update); - final ElementDataEntry entry = getElementDataEntry(key, true); - updateRootElementMarker(key.fRootElement, node, update); - - // The request can be retrieved from cache if all the properties that were requested in the update are - // found in the map. - if (entry.fProperties != null && entry.fProperties.keySet().containsAll(update.getProperties())) { - // Cache Hit! Just return the value. - if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("cacheHitProperties(node = " + node + ", update = " + update + ", " + entry.fProperties + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - if (entry.fProperties.containsKey(PROP_UPDATE_POLICY_ID)) { - entry.fProperties.put(PROP_UPDATE_POLICY_ID, getActiveUpdatePolicy().getID()); - } - update.setAllProperties(entry.fProperties); - update.setStatus((IStatus)entry.fProperties.get(PROP_UPDATE_STATUS)); - update.done(); - } else { - // Cache miss! Check if already cached properties can be re-used. - Set<String> missingProperties = null; - if (entry.fProperties != null) { - missingProperties = new HashSet<String>(update.getProperties().size() * 4/3); - missingProperties.addAll(update.getProperties()); - missingProperties.removeAll(entry.fProperties.keySet()); - - if (entry.fDirty) { - // Cache miss, BUT the entry is dirty already. Determine which properties can still be updated - // (if any), then request the missing properties from node, or return an error. - if (getActiveUpdatePolicy() instanceof IVMUpdatePolicyExtension) { - IVMUpdatePolicyExtension updatePolicyExt = (IVMUpdatePolicyExtension)getActiveUpdatePolicy(); - for (Iterator<String> itr = missingProperties.iterator(); itr.hasNext();) { - String missingProperty = itr.next(); - if ( !updatePolicyExt.canUpdateDirtyProperty(entry, missingProperty) ) { - itr.remove(); - PropertiesUpdateStatus.getPropertiesStatus(update).setStatus( - missingProperty, - DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_STATE, "Cache contains stale data. Refresh view.", null ));//$NON-NLS-1$ - } - } - } else { - PropertiesUpdateStatus.getPropertiesStatus(update).setStatus( - missingProperties.toArray(new String[missingProperties.size()]), - DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_STATE, "Cache contains stale data. Refresh view.", null ));//$NON-NLS-1$ - missingProperties.clear(); - } - if (missingProperties.isEmpty()) { - if (entry.fProperties.containsKey(PROP_UPDATE_POLICY_ID)) { - entry.fProperties.put(PROP_UPDATE_POLICY_ID, getActiveUpdatePolicy().getID()); - } - update.setAllProperties(entry.fProperties); - update.done(); - return; - } - } - } else { - missingProperties = update.getProperties(); - } - - final Set<String> _missingProperties = missingProperties; - // Save the flush counter of the entry and create a proxy update. - final int flushCounter = entry.fFlushCounter; - missUpdates.add(new VMPropertiesUpdate( - missingProperties, - update, - new ViewerDataRequestMonitor<Map<String, Object>>(getExecutor(), update) { - @Override - protected void handleCompleted() { - PropertiesUpdateStatus missUpdateStatus = PropertiesUpdateStatus.makePropertiesStatus(getStatus()); - Map<String, Object> cachedProperties; - PropertiesUpdateStatus cachedStatus; - if (!isCanceled() && flushCounter == entry.fFlushCounter) { - // We are caching the result of this update. Copy the properties from the update - // to the cached properties map. - if (entry.fProperties == null) { - entry.fProperties = new HashMap<String, Object>((getData().size() + 3) * 4/3); - if (update.getProperties().contains(PROP_CACHE_ENTRY_DIRTY)) { - entry.fProperties.put(PROP_CACHE_ENTRY_DIRTY, entry.fDirty); - } - entry.fProperties.put(PROP_UPDATE_STATUS, new PropertiesUpdateStatus()); - } - cachedProperties = entry.fProperties; - cachedProperties.putAll(getData()); - - // Make sure that all the properties that were requested by the update object are in - // the cache entry's properties map. It's possible he ViewerDataRequestMonitor was able - // to provide us only a subset of the requested ones. We want to prevent that from - // causing future cache misses, since a cache hit requires the cache entry to contain - // all requested properties. Use a null value for the missing items. - for (String property : _missingProperties) { - if (!getData().containsKey(property)) { - cachedProperties.put(property, null); - } - } - - // Merge status from properties that came back from the node into the status that's in - // the cache. - cachedStatus = (PropertiesUpdateStatus)cachedProperties.get(PROP_UPDATE_STATUS); - cachedStatus = PropertiesUpdateStatus.mergePropertiesStatus( - cachedStatus, missUpdateStatus, _missingProperties); - cachedProperties.put(PROP_UPDATE_STATUS, cachedStatus); - } else { - // We are not caching the result of this update, but we should still return valid data - // to the client. In case the update was canceled we can also return valid data to the - // client even if the client is likely to ignore it since the cost of doing so is - // relatively low. - // Create a temporary cached properties map and add existing cache and node update - // properties to it. - if (entry.fProperties != null) { - cachedProperties = new HashMap<String, Object>((entry.fProperties.size() + getData().size() + 3) * 4/3); - cachedProperties.putAll(entry.fProperties); - cachedStatus = PropertiesUpdateStatus.mergePropertiesStatus( - (PropertiesUpdateStatus)cachedProperties.get(PROP_UPDATE_STATUS), - missUpdateStatus, _missingProperties); - } else { - cachedProperties = new HashMap<String, Object>((getData().size() + 3) * 4/3); - cachedStatus = missUpdateStatus; - } - cachedProperties.putAll(getData()); - cachedProperties.put(PROP_UPDATE_STATUS, missUpdateStatus); - if (update.getProperties().contains(PROP_CACHE_ENTRY_DIRTY)) { - cachedProperties.put(PROP_CACHE_ENTRY_DIRTY, Boolean.TRUE); - } - } - - // Refresh the update policy property. - if (update.getProperties().contains(PROP_UPDATE_POLICY_ID)) { - cachedProperties.put(PROP_UPDATE_POLICY_ID, getActiveUpdatePolicy().getID()); - } - - // If there is archive data available, calculate the requested changed value properties. - // Do not calculate the changed flags if the entry has been flushed. - if (entry.fArchiveProperties != null && flushCounter == entry.fFlushCounter) { - for (String updateProperty : update.getProperties()) { - if (updateProperty.startsWith(PROP_IS_CHANGED_PREFIX)) { - String changedPropertyName = updateProperty.substring(LENGTH_PROP_IS_CHANGED_PREFIX); - Object newValue = cachedProperties.get(changedPropertyName); - Object oldValue = entry.fArchiveProperties.get(changedPropertyName); - if (oldValue != null) { - cachedProperties.put(updateProperty, !oldValue.equals(newValue)); - } - } - } - } - - if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { - DsfUIPlugin.debug("cacheSavedProperties(node = " + node + ", update = " + update + ", " + getData() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - - // Fill in requested properties and status into the update. - for (String property : update.getProperties()) { - update.setProperty(property, cachedProperties.get(property)); - } - PropertiesUpdateStatus updateStatus = PropertiesUpdateStatus.makePropertiesStatus(update.getStatus()); - updateStatus = PropertiesUpdateStatus.mergePropertiesStatus( - updateStatus, cachedStatus, update.getProperties()); - update.setStatus(updateStatus); - update.done(); - } - })); - } - } - - // Issue all the update proxies with one call. - if (!missUpdates.isEmpty()) { - ((IElementPropertiesProvider)node).update(missUpdates.toArray(new IPropertiesUpdate[missUpdates.size()])); - } - } - - @Override - public boolean shouldWaitHandleEventToComplete() { - return fDelayEventHandleForViewUpdate; - } - - /** - * @since 1.1 - */ + if (updates.length == 0) + return; + + // Optimization: if all the updates belong to the same node, avoid + // creating any new lists/arrays. + boolean allNodesTheSame = true; + IVMNode firstNode = getNodeForElement(updates[0].getElement()); + for (int i = 1; i < updates.length; i++) { + if (firstNode != getNodeForElement(updates[i].getElement())) { + allNodesTheSame = false; + break; + } + } + + if (allNodesTheSame) { + if (!(firstNode instanceof IElementPropertiesProvider)) { + for (IPropertiesUpdate update : updates) { + update.setStatus(DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_HANDLE, + "Element is not a VM Context or its node is not a properties provider.", null)); //$NON-NLS-1$ + update.done(); + } + } else { + updateNode(firstNode, updates); + } + } else { + // Sort the updates by the node. + Map<IVMNode, List<IPropertiesUpdate>> nodeUpdatesMap = new HashMap<IVMNode, List<IPropertiesUpdate>>(); + for (IPropertiesUpdate update : updates) { + // Get the VM Context for last element in path. + IVMNode node = getNodeForElement(update.getElement()); + if (node == null || !(node instanceof IElementPropertiesProvider)) { + // Misdirected update. + update.setStatus(DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_HANDLE, + "Element is not a VM Context or its node is not a properties provider.", null)); //$NON-NLS-1$ + update.done(); + continue; + } + if (!nodeUpdatesMap.containsKey(node)) { + nodeUpdatesMap.put(node, new ArrayList<IPropertiesUpdate>()); + } + nodeUpdatesMap.get(node).add(update); + } + + // Iterate through the nodes in the sorted map. + for (IVMNode node : nodeUpdatesMap.keySet()) { + updateNode(node, + nodeUpdatesMap.get(node).toArray(new IPropertiesUpdate[nodeUpdatesMap.get(node).size()])); + } + } + } + + /** + * Convenience method that finds the VM node corresponding to given element. + * It returns <code>null</code> if the element is not a VM context. + * + * @param element Element to find the VM Node for. + * @return View Model Node that this element was created by, or <code>null</code>. + * + * @since 2.0 + */ + private IVMNode getNodeForElement(Object element) { + if (element instanceof IVMContext) { + return ((IVMContext) element).getVMNode(); + } + return null; + } + + protected void updateNode(final IVMNode node, IPropertiesUpdate[] updates) { + LinkedList<IPropertiesUpdate> missUpdates = new LinkedList<IPropertiesUpdate>(); + for (final IPropertiesUpdate update : updates) { + // Find or create the cache entry for the element of this update. + ElementDataKey key = makeEntryKey(node, update); + final ElementDataEntry entry = getElementDataEntry(key, true); + updateRootElementMarker(key.fRootElement, node, update); + + // The request can be retrieved from cache if all the properties that were requested in the update are + // found in the map. + if (entry.fProperties != null && entry.fProperties.keySet().containsAll(update.getProperties())) { + // Cache Hit! Just return the value. + if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("cacheHitProperties(node = " + node + ", update = " + update + ", " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + + entry.fProperties + ")"); //$NON-NLS-1$ + } + if (entry.fProperties.containsKey(PROP_UPDATE_POLICY_ID)) { + entry.fProperties.put(PROP_UPDATE_POLICY_ID, getActiveUpdatePolicy().getID()); + } + update.setAllProperties(entry.fProperties); + update.setStatus((IStatus) entry.fProperties.get(PROP_UPDATE_STATUS)); + update.done(); + } else { + // Cache miss! Check if already cached properties can be re-used. + Set<String> missingProperties = null; + if (entry.fProperties != null) { + missingProperties = new HashSet<String>(update.getProperties().size() * 4 / 3); + missingProperties.addAll(update.getProperties()); + missingProperties.removeAll(entry.fProperties.keySet()); + + if (entry.fDirty) { + // Cache miss, BUT the entry is dirty already. Determine which properties can still be updated + // (if any), then request the missing properties from node, or return an error. + if (getActiveUpdatePolicy() instanceof IVMUpdatePolicyExtension) { + IVMUpdatePolicyExtension updatePolicyExt = (IVMUpdatePolicyExtension) getActiveUpdatePolicy(); + for (Iterator<String> itr = missingProperties.iterator(); itr.hasNext();) { + String missingProperty = itr.next(); + if (!updatePolicyExt.canUpdateDirtyProperty(entry, missingProperty)) { + itr.remove(); + PropertiesUpdateStatus.getPropertiesStatus(update).setStatus(missingProperty, + DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_STATE, + "Cache contains stale data. Refresh view.", null));//$NON-NLS-1$ + } + } + } else { + PropertiesUpdateStatus.getPropertiesStatus(update).setStatus( + missingProperties.toArray(new String[missingProperties.size()]), + DsfUIPlugin.newErrorStatus(IDsfStatusConstants.INVALID_STATE, + "Cache contains stale data. Refresh view.", null));//$NON-NLS-1$ + missingProperties.clear(); + } + if (missingProperties.isEmpty()) { + if (entry.fProperties.containsKey(PROP_UPDATE_POLICY_ID)) { + entry.fProperties.put(PROP_UPDATE_POLICY_ID, getActiveUpdatePolicy().getID()); + } + update.setAllProperties(entry.fProperties); + update.done(); + return; + } + } + } else { + missingProperties = update.getProperties(); + } + + final Set<String> _missingProperties = missingProperties; + // Save the flush counter of the entry and create a proxy update. + final int flushCounter = entry.fFlushCounter; + missUpdates.add(new VMPropertiesUpdate(missingProperties, update, + new ViewerDataRequestMonitor<Map<String, Object>>(getExecutor(), update) { + @Override + protected void handleCompleted() { + PropertiesUpdateStatus missUpdateStatus = PropertiesUpdateStatus + .makePropertiesStatus(getStatus()); + Map<String, Object> cachedProperties; + PropertiesUpdateStatus cachedStatus; + if (!isCanceled() && flushCounter == entry.fFlushCounter) { + // We are caching the result of this update. Copy the properties from the update + // to the cached properties map. + if (entry.fProperties == null) { + entry.fProperties = new HashMap<String, Object>((getData().size() + 3) * 4 / 3); + if (update.getProperties().contains(PROP_CACHE_ENTRY_DIRTY)) { + entry.fProperties.put(PROP_CACHE_ENTRY_DIRTY, entry.fDirty); + } + entry.fProperties.put(PROP_UPDATE_STATUS, new PropertiesUpdateStatus()); + } + cachedProperties = entry.fProperties; + cachedProperties.putAll(getData()); + + // Make sure that all the properties that were requested by the update object are in + // the cache entry's properties map. It's possible he ViewerDataRequestMonitor was able + // to provide us only a subset of the requested ones. We want to prevent that from + // causing future cache misses, since a cache hit requires the cache entry to contain + // all requested properties. Use a null value for the missing items. + for (String property : _missingProperties) { + if (!getData().containsKey(property)) { + cachedProperties.put(property, null); + } + } + + // Merge status from properties that came back from the node into the status that's in + // the cache. + cachedStatus = (PropertiesUpdateStatus) cachedProperties.get(PROP_UPDATE_STATUS); + cachedStatus = PropertiesUpdateStatus.mergePropertiesStatus(cachedStatus, + missUpdateStatus, _missingProperties); + cachedProperties.put(PROP_UPDATE_STATUS, cachedStatus); + } else { + // We are not caching the result of this update, but we should still return valid data + // to the client. In case the update was canceled we can also return valid data to the + // client even if the client is likely to ignore it since the cost of doing so is + // relatively low. + // Create a temporary cached properties map and add existing cache and node update + // properties to it. + if (entry.fProperties != null) { + cachedProperties = new HashMap<String, Object>( + (entry.fProperties.size() + getData().size() + 3) * 4 / 3); + cachedProperties.putAll(entry.fProperties); + cachedStatus = PropertiesUpdateStatus.mergePropertiesStatus( + (PropertiesUpdateStatus) cachedProperties.get(PROP_UPDATE_STATUS), + missUpdateStatus, _missingProperties); + } else { + cachedProperties = new HashMap<String, Object>((getData().size() + 3) * 4 / 3); + cachedStatus = missUpdateStatus; + } + cachedProperties.putAll(getData()); + cachedProperties.put(PROP_UPDATE_STATUS, missUpdateStatus); + if (update.getProperties().contains(PROP_CACHE_ENTRY_DIRTY)) { + cachedProperties.put(PROP_CACHE_ENTRY_DIRTY, Boolean.TRUE); + } + } + + // Refresh the update policy property. + if (update.getProperties().contains(PROP_UPDATE_POLICY_ID)) { + cachedProperties.put(PROP_UPDATE_POLICY_ID, getActiveUpdatePolicy().getID()); + } + + // If there is archive data available, calculate the requested changed value properties. + // Do not calculate the changed flags if the entry has been flushed. + if (entry.fArchiveProperties != null && flushCounter == entry.fFlushCounter) { + for (String updateProperty : update.getProperties()) { + if (updateProperty.startsWith(PROP_IS_CHANGED_PREFIX)) { + String changedPropertyName = updateProperty + .substring(LENGTH_PROP_IS_CHANGED_PREFIX); + Object newValue = cachedProperties.get(changedPropertyName); + Object oldValue = entry.fArchiveProperties.get(changedPropertyName); + if (oldValue != null) { + cachedProperties.put(updateProperty, !oldValue.equals(newValue)); + } + } + } + } + + if (DEBUG_CACHE && (DEBUG_PRESENTATION_ID == null + || getPresentationContext().getId().equals(DEBUG_PRESENTATION_ID))) { + DsfUIPlugin.debug("cacheSavedProperties(node = " + node + ", update = " + update //$NON-NLS-1$//$NON-NLS-2$ + + ", " + getData() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + // Fill in requested properties and status into the update. + for (String property : update.getProperties()) { + update.setProperty(property, cachedProperties.get(property)); + } + PropertiesUpdateStatus updateStatus = PropertiesUpdateStatus + .makePropertiesStatus(update.getStatus()); + updateStatus = PropertiesUpdateStatus.mergePropertiesStatus(updateStatus, cachedStatus, + update.getProperties()); + update.setStatus(updateStatus); + update.done(); + } + })); + } + } + + // Issue all the update proxies with one call. + if (!missUpdates.isEmpty()) { + ((IElementPropertiesProvider) node).update(missUpdates.toArray(new IPropertiesUpdate[missUpdates.size()])); + } + } + + @Override + public boolean shouldWaitHandleEventToComplete() { + return fDelayEventHandleForViewUpdate; + } + + /** + * @since 1.1 + */ protected void setDelayEventHandleForViewUpdate(boolean on) { fDelayEventHandleForViewUpdate = on; } - /** - * Used for tracing event handling - * <p> - * Note: this enum is duplicated from AbstractVMProvider. - */ - private enum EventHandlerAction { - received, - queued, - processing, - firedDeltaFor, - skipped, - canceled - } - - /** - * Trace that we've reached a particular phase of the handling of an event - * for a particular proxy. - * <p> - * Note: this method is duplicated from AbstractVMProvider. - * - * @param event - * the event being handled - * @param skippedOrCanceledEvent - * for a 'skip' or 'cancel' action, this is the event that is - * being dismissed. Otherwise null - * @param proxy - * the target proxy; n/a (null) for a 'received' action. - * @param action - * what phased of the event handling has beeb reached - */ - private void trace(Object event, Object skippedOrCanceledEvent, IVMModelProxy proxy, EventHandlerAction action) { - assert DEBUG_DELTA; - StringBuilder str = new StringBuilder(); - str.append(DsfPlugin.getDebugTime()); - str.append(' '); - if (action == EventHandlerAction.skipped || action == EventHandlerAction.canceled) { - str.append(LoggingUtils.toString(this)).append(' ').append(action).append(" event ").append(LoggingUtils.toString(skippedOrCanceledEvent)).append(" because of event ").append(LoggingUtils.toString(event)); //$NON-NLS-1$ //$NON-NLS-2$ - } - else { - str.append(LoggingUtils.toString(this)).append(' ').append(action).append(" event ").append(LoggingUtils.toString(event)); //$NON-NLS-1$ - } - - if (action != EventHandlerAction.received) { - str.append(" for proxy ").append(LoggingUtils.toString(proxy)).append( ", whose root is ").append(LoggingUtils.toString(proxy.getRootElement())); //$NON-NLS-1$ //$NON-NLS-2$ - } - DsfUIPlugin.debug(str.toString()); - } + /** + * Used for tracing event handling + * <p> + * Note: this enum is duplicated from AbstractVMProvider. + */ + private enum EventHandlerAction { + received, queued, processing, firedDeltaFor, skipped, canceled + } + + /** + * Trace that we've reached a particular phase of the handling of an event + * for a particular proxy. + * <p> + * Note: this method is duplicated from AbstractVMProvider. + * + * @param event + * the event being handled + * @param skippedOrCanceledEvent + * for a 'skip' or 'cancel' action, this is the event that is + * being dismissed. Otherwise null + * @param proxy + * the target proxy; n/a (null) for a 'received' action. + * @param action + * what phased of the event handling has beeb reached + */ + private void trace(Object event, Object skippedOrCanceledEvent, IVMModelProxy proxy, EventHandlerAction action) { + assert DEBUG_DELTA; + StringBuilder str = new StringBuilder(); + str.append(DsfPlugin.getDebugTime()); + str.append(' '); + if (action == EventHandlerAction.skipped || action == EventHandlerAction.canceled) { + str.append(LoggingUtils.toString(this)).append(' ').append(action).append(" event ") //$NON-NLS-1$ + .append(LoggingUtils.toString(skippedOrCanceledEvent)).append(" because of event ") //$NON-NLS-1$ + .append(LoggingUtils.toString(event)); + } else { + str.append(LoggingUtils.toString(this)).append(' ').append(action).append(" event ") //$NON-NLS-1$ + .append(LoggingUtils.toString(event)); + } + + if (action != EventHandlerAction.received) { + str.append(" for proxy ").append(LoggingUtils.toString(proxy)).append(", whose root is ") //$NON-NLS-1$//$NON-NLS-2$ + .append(LoggingUtils.toString(proxy.getRootElement())); + } + DsfUIPlugin.debug(str.toString()); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/AutomaticUpdatePolicy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/AutomaticUpdatePolicy.java index 621770b235e..5b3392fa1b4 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/AutomaticUpdatePolicy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/AutomaticUpdatePolicy.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -18,55 +18,55 @@ import java.util.Map; import org.eclipse.jface.viewers.TreePath; /** - * An "automatic" update policy which causes the view model provider cache to - * be flushed whenever an event causes a delta to be generated in the given + * An "automatic" update policy which causes the view model provider cache to + * be flushed whenever an event causes a delta to be generated in the given * model. - * + * * @since 1.0 */ public class AutomaticUpdatePolicy implements IVMUpdatePolicy { - public static String AUTOMATIC_UPDATE_POLICY_ID = "org.eclipse.cdt.dsf.ui.viewmodel.update.defaultUpdatePolicy"; //$NON-NLS-1$ - - public static IElementUpdateTester fgUpdateTester = new IElementUpdateTester() { - @Override + public static String AUTOMATIC_UPDATE_POLICY_ID = "org.eclipse.cdt.dsf.ui.viewmodel.update.defaultUpdatePolicy"; //$NON-NLS-1$ + + public static IElementUpdateTester fgUpdateTester = new IElementUpdateTester() { + @Override public int getUpdateFlags(Object viewerInput, TreePath path) { - return FLUSH | ARCHIVE; - } - - @Override + return FLUSH | ARCHIVE; + } + + @Override public boolean includes(IElementUpdateTester tester) { - return tester.equals(this); - } + return tester.equals(this); + } + + @Override + public String toString() { + return "Automatic update tester"; //$NON-NLS-1$ + } + }; - @Override - public String toString() { - return "Automatic update tester"; //$NON-NLS-1$ - } - }; - - @Override + @Override public String getID() { - return AUTOMATIC_UPDATE_POLICY_ID; - } + return AUTOMATIC_UPDATE_POLICY_ID; + } - @Override + @Override public String getName() { - return ViewModelUpdateMessages.AutomaticUpdatePolicy_name; - } + return ViewModelUpdateMessages.AutomaticUpdatePolicy_name; + } - @Override + @Override public IElementUpdateTester getElementUpdateTester(Object event) { - return fgUpdateTester; - } + return fgUpdateTester; + } - @Override + @Override public Object[] getInitialRootElementChildren(Object rootElement) { - return null; - } - - @Override + return null; + } + + @Override public Map<String, Object> getInitialRootElementProperties(Object rootElement) { - return null; - } + return null; + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ICacheEntry.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ICacheEntry.java index af12cac4f24..efa6d55216a 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ICacheEntry.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ICacheEntry.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -21,73 +21,73 @@ import org.eclipse.jface.viewers.TreePath; /** * Cache entry in a caching VM provider. - * - * @see ICachingVMProvider + * + * @see ICachingVMProvider * @see ICachingVMProviderExtension2 - * + * * @since 2.2 */ @ConfinedToDsfExecutor("") public interface ICacheEntry { - - /** - * The VM node that this cache entry is for. This parameter is part of the - * key to finding the cache entry. - */ - public IVMNode getNode(); - - /** - * The viewer input object that this cache entry is for. This parameter - * is part of the key to finding the cache entry. - */ - public Object getViewerInput(); - - /** - * The element path that this cache entry is for. This parameter is part - * of the key to finding the cache entry. - */ - public TreePath getElementPath(); - - /** - * Says whether this cache entry is currently marked as dirty. If a cache - * entry is dirty, it means that it contains stale data which has not been - * flushed as indicated by the cache's update policy. - * @return - */ - public boolean isDirty(); - - /** - * Returns the a flag indicating whether the element pointing to this entry - * has children. Returns <code>null</code> if this value is not known by - * cache. - */ - public Boolean getHasChildren(); - - /** - * Returns the count of children for the element belonging to this entry. - * Returns <code>null</code> if this value is not known by cache. - */ - public Integer getChildCount(); - - /** - * Returns a map of children of the element belonging to this entry. - * The returned map contains integer keys which are indexes of the - * element's children. The values in the map are the child element. - * Returns <code>null</code> if this value is not known by cache. - */ - public Map<Integer, Object> getChildren(); - - /** - * Returns map of properties of the element belonging to this entry. - * Returns <code>null</code> if this value is not known by cache. - */ - public Map<String, Object> getProperties(); - - /** - * Returns the archived map of properties of the element belong to this - * entry. The archived properties are properties which were saved when - * the cache was last flushed, as indicated by the cache's active update - * policy. Returns <code>null</code> if this value is not known by cache. - */ - public Map<String, Object> getArchiveProperties(); + + /** + * The VM node that this cache entry is for. This parameter is part of the + * key to finding the cache entry. + */ + public IVMNode getNode(); + + /** + * The viewer input object that this cache entry is for. This parameter + * is part of the key to finding the cache entry. + */ + public Object getViewerInput(); + + /** + * The element path that this cache entry is for. This parameter is part + * of the key to finding the cache entry. + */ + public TreePath getElementPath(); + + /** + * Says whether this cache entry is currently marked as dirty. If a cache + * entry is dirty, it means that it contains stale data which has not been + * flushed as indicated by the cache's update policy. + * @return + */ + public boolean isDirty(); + + /** + * Returns the a flag indicating whether the element pointing to this entry + * has children. Returns <code>null</code> if this value is not known by + * cache. + */ + public Boolean getHasChildren(); + + /** + * Returns the count of children for the element belonging to this entry. + * Returns <code>null</code> if this value is not known by cache. + */ + public Integer getChildCount(); + + /** + * Returns a map of children of the element belonging to this entry. + * The returned map contains integer keys which are indexes of the + * element's children. The values in the map are the child element. + * Returns <code>null</code> if this value is not known by cache. + */ + public Map<Integer, Object> getChildren(); + + /** + * Returns map of properties of the element belonging to this entry. + * Returns <code>null</code> if this value is not known by cache. + */ + public Map<String, Object> getProperties(); + + /** + * Returns the archived map of properties of the element belong to this + * entry. The archived properties are properties which were saved when + * the cache was last flushed, as indicated by the cache's active update + * policy. Returns <code>null</code> if this value is not known by cache. + */ + public Map<String, Object> getArchiveProperties(); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ICachingVMProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ICachingVMProvider.java index 434f241d71d..f3fba282dc5 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ICachingVMProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ICachingVMProvider.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -18,67 +18,67 @@ import org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider; /** * A view model provider which supports caching of data returned by view model - * nodes. The methods in this interface allow clients to configure how the + * nodes. The methods in this interface allow clients to configure how the * cache should be updated in response to different events. - * + * * @since 1.0 */ public interface ICachingVMProvider extends IVMProvider, IElementPropertiesProvider { - /** - * A prefix used to create a property to indicate whether a given property - * has changed since the last cache update with the {@link IVMUpdatePolicy#ARCHIVE} - * flag. The caching VM provider appends these properties to an element's set of - * properties as they are retrieved through the cache. - * - * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider - * @see IVMUpdatePolicy#ARCHIVE - * - * @since 2.0 - */ - public static final String PROP_IS_CHANGED_PREFIX = "is_changed."; //$NON-NLS-1$ - - /** - * A property used to indicate whether a given cache entry is currently dirty. - * The caching VM provider appends this property to an - * element's set of properties as they are retrieved through the cache. - * - * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider - * @see IVMUpdatePolicy#DIRTY - * - * @since 2.0 - */ - public static final String PROP_CACHE_ENTRY_DIRTY = "cache_entry_dirty"; //$NON-NLS-1$ - - /** - * Property name for the current update policy in view. - * - * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider - * - * @since 2.1 - */ - public static final String PROP_UPDATE_POLICY_ID = "update_policy_id"; //$NON-NLS-1$ - - /** - * Returns the update policies that the given provider supports. - */ - public IVMUpdatePolicy[] getAvailableUpdatePolicies(); + /** + * A prefix used to create a property to indicate whether a given property + * has changed since the last cache update with the {@link IVMUpdatePolicy#ARCHIVE} + * flag. The caching VM provider appends these properties to an element's set of + * properties as they are retrieved through the cache. + * + * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider + * @see IVMUpdatePolicy#ARCHIVE + * + * @since 2.0 + */ + public static final String PROP_IS_CHANGED_PREFIX = "is_changed."; //$NON-NLS-1$ + + /** + * A property used to indicate whether a given cache entry is currently dirty. + * The caching VM provider appends this property to an + * element's set of properties as they are retrieved through the cache. + * + * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider + * @see IVMUpdatePolicy#DIRTY + * + * @since 2.0 + */ + public static final String PROP_CACHE_ENTRY_DIRTY = "cache_entry_dirty"; //$NON-NLS-1$ + + /** + * Property name for the current update policy in view. + * + * @see org.eclipse.cdt.dsf.ui.viewmodel.properties.IElementPropertiesProvider + * + * @since 2.1 + */ + public static final String PROP_UPDATE_POLICY_ID = "update_policy_id"; //$NON-NLS-1$ + + /** + * Returns the update policies that the given provider supports. + */ + public IVMUpdatePolicy[] getAvailableUpdatePolicies(); + + /** + * Returns the active update policy. + */ + public IVMUpdatePolicy getActiveUpdatePolicy(); + + /** + * Sets the active update policy. This has to be one of the update + * policies supported by the provider. + */ + public void setActiveUpdatePolicy(IVMUpdatePolicy mode); - /** - * Returns the active update policy. - */ - public IVMUpdatePolicy getActiveUpdatePolicy(); + /** + * Forces the view to flush its cache and re-fetch data from the view + * model nodes. + */ + public void refresh(); - /** - * Sets the active update policy. This has to be one of the update - * policies supported by the provider. - */ - public void setActiveUpdatePolicy(IVMUpdatePolicy mode); - - /** - * Forces the view to flush its cache and re-fetch data from the view - * model nodes. - */ - public void refresh(); - } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ICachingVMProviderExtension2.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ICachingVMProviderExtension2.java index fb855b6f0b9..f67776be560 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ICachingVMProviderExtension2.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ICachingVMProviderExtension2.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -16,18 +16,17 @@ package org.eclipse.cdt.dsf.ui.viewmodel.update; import org.eclipse.cdt.dsf.ui.viewmodel.IVMNode; import org.eclipse.jface.viewers.TreePath; - /** * Extension allowing access to the caching VM provider cache entries. - * + * * @since 2.2 */ public interface ICachingVMProviderExtension2 extends ICachingVMProvider { - - /** - * Returns the cache entry for the given parameters. May return <code>null</code> - * if the cache entry does not exist in the cache. - */ - public ICacheEntry getCacheEntry(IVMNode node, Object viewerInput, TreePath path); - + + /** + * Returns the cache entry for the given parameters. May return <code>null</code> + * if the cache entry does not exist in the cache. + */ + public ICacheEntry getCacheEntry(IVMNode node, Object viewerInput, TreePath path); + } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IElementUpdateTester.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IElementUpdateTester.java index 82ad8e0c204..22d57d63fb9 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IElementUpdateTester.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IElementUpdateTester.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -17,33 +17,33 @@ import org.eclipse.jface.viewers.TreePath; /** * Tester object used to determine how individual update cache - * entries should be updated during a flush operation. - * + * entries should be updated during a flush operation. + * * @see IVMUpdatePolicy - * + * * @since 1.0 */ public interface IElementUpdateTester { - /** - * Returns the flags indicating what updates should be performed on the - * cache entry of the given element. - * - * @param viewerInput The input to the viewer for the given cache entry. - * @param path The viewer tree path for the given cache entry. - */ - public int getUpdateFlags(Object viewerInput, TreePath path); + /** + * Returns the flags indicating what updates should be performed on the + * cache entry of the given element. + * + * @param viewerInput The input to the viewer for the given cache entry. + * @param path The viewer tree path for the given cache entry. + */ + public int getUpdateFlags(Object viewerInput, TreePath path); + + /** + * Returns whether update represented by this tester includes another + * update. For example if update A was created as a result of an element X, + * and update B was created for an element Y, and element X is a parent of + * element Y, then tester A should include tester B. Also a tester should + * always include itself. + * <p/> + * This method is used to optimize the repeated flushing of the cache as + * it allows the cache to avoid needlessly updating the same cache entries. + */ + public boolean includes(IElementUpdateTester tester); - /** - * Returns whether update represented by this tester includes another - * update. For example if update A was created as a result of an element X, - * and update B was created for an element Y, and element X is a parent of - * element Y, then tester A should include tester B. Also a tester should - * always include itself. - * <p/> - * This method is used to optimize the repeated flushing of the cache as - * it allows the cache to avoid needlessly updating the same cache entries. - */ - public boolean includes(IElementUpdateTester tester); - }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IElementUpdateTesterExtension.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IElementUpdateTesterExtension.java index f12ac77baae..764d861c2ef 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IElementUpdateTesterExtension.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IElementUpdateTesterExtension.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -21,19 +21,19 @@ import org.eclipse.jface.viewers.TreePath; * Element update tester extension which allows an update policy to selectively * flush properties of elements. This can be useful if the update tester's event * only affects a certain aspect of the element's presentation. - * + * * @since 2.1 */ public interface IElementUpdateTesterExtension extends IElementUpdateTester { - - /** - * Returns the properties that should be flushed for the element. - * - * @param viewerInput The input to the viewer for the given cache entry. - * @param path The viewer tree path for the given cache entry. - * @param isDirty <code>true</code> if the given cache entry is already dirty - * @return Collection of properties which should be flushed, or - * <code>null</code> if none. - */ - Collection<String> getPropertiesToFlush(Object viewerInput, TreePath path, boolean isDirty); + + /** + * Returns the properties that should be flushed for the element. + * + * @param viewerInput The input to the viewer for the given cache entry. + * @param path The viewer tree path for the given cache entry. + * @param isDirty <code>true</code> if the given cache entry is already dirty + * @return Collection of properties which should be flushed, or + * <code>null</code> if none. + */ + Collection<String> getPropertiesToFlush(Object viewerInput, TreePath path, boolean isDirty); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IVMUpdatePolicy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IVMUpdatePolicy.java index 79ac9f60d1a..0e9f03af2f8 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IVMUpdatePolicy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IVMUpdatePolicy.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -15,98 +15,96 @@ package org.eclipse.cdt.dsf.ui.viewmodel.update; import java.util.Map; - - /** - * Interface for an update policy. The main function of an update policy is + * Interface for an update policy. The main function of an update policy is * to create an element tester for each given event. The element tester - * is then used to update the viewer cache. - * + * is then used to update the viewer cache. + * * @since 1.0 */ public interface IVMUpdatePolicy { - /** - * Flag indicating that a given entry in the cache should be cleared. - */ - public static int FLUSH = 0x1; - - /** - * Flag indicating that a given entry in the cache should be cleared - * and saved for purpose of change tracking. - */ - public static int ARCHIVE = FLUSH | 0x2; // Flush is required when archiving. - - /** - * Flag indicating that the a given cache entry should be marked as dirty. - * A dirty cache entry is one that is known not to be consistent with - * target data. - */ - public static int DIRTY = 0x4; - - /** - * Flag indicating that the cache should flush only selected properties of - * an element. The list of properties to clear can be accessed using - * {@link IElementUpdateTesterExtension#getPropertiesToFlush(Object, org.eclipse.jface.viewers.TreePath, boolean)}. - * - * @since 2.1 - */ - public static int FLUSH_PARTIAL_PROPERTIES = 0x8; + /** + * Flag indicating that a given entry in the cache should be cleared. + */ + public static int FLUSH = 0x1; + + /** + * Flag indicating that a given entry in the cache should be cleared + * and saved for purpose of change tracking. + */ + public static int ARCHIVE = FLUSH | 0x2; // Flush is required when archiving. + + /** + * Flag indicating that the a given cache entry should be marked as dirty. + * A dirty cache entry is one that is known not to be consistent with + * target data. + */ + public static int DIRTY = 0x4; + + /** + * Flag indicating that the cache should flush only selected properties of + * an element. The list of properties to clear can be accessed using + * {@link IElementUpdateTesterExtension#getPropertiesToFlush(Object, org.eclipse.jface.viewers.TreePath, boolean)}. + * + * @since 2.1 + */ + public static int FLUSH_PARTIAL_PROPERTIES = 0x8; + + /** + * Flag indicating that the cache should flush all properties of + * an element. + * + * @since 2.2 + */ + public static int FLUSH_ALL_PROPERTIES = 0x10; + + /** + * Returns unique ID of this update policy. + */ + public String getID(); - /** - * Flag indicating that the cache should flush all properties of - * an element. - * - * @since 2.2 - */ - public static int FLUSH_ALL_PROPERTIES = 0x10; + /** + * Returns the user-presentable name of this update policy. + */ + public String getName(); - /** - * Returns unique ID of this update policy. - */ - public String getID(); - - /** - * Returns the user-presentable name of this update policy. - */ - public String getName(); + /** + * Creates an element tester for the given event. + */ + public IElementUpdateTester getElementUpdateTester(Object event); - /** - * Creates an element tester for the given event. - */ - public IElementUpdateTester getElementUpdateTester(Object event); - - /** - * Returns the array of elements that should be used to initially populate - * the cache, or <code>null</code> if this update policy does not need to - * pre-populate the cache. These elements will be shown as children - * of the root element in the view. - * <p/> - * This method allows an update policy to prevent the UI from reading the - * model when the UI first appears and the cache has not been populated yet. - * - * @param rootElement The rootElement for which the cache is being - * pre-populated. - * - * @since 2.0 - */ - public Object[] getInitialRootElementChildren(Object rootElement); + /** + * Returns the array of elements that should be used to initially populate + * the cache, or <code>null</code> if this update policy does not need to + * pre-populate the cache. These elements will be shown as children + * of the root element in the view. + * <p/> + * This method allows an update policy to prevent the UI from reading the + * model when the UI first appears and the cache has not been populated yet. + * + * @param rootElement The rootElement for which the cache is being + * pre-populated. + * + * @since 2.0 + */ + public Object[] getInitialRootElementChildren(Object rootElement); - /** - * Returns the properties that should be used to initially populate - * the cache, or <code>null</code> if the cache should not be pre-populated - * for this update policy. These properties may be used by the - * view model to generate the label for the root element. - * <p/> - * This method allows an update policy to prevent the UI from reading the - * model when the UI first appears and the cache has not been populated - * yet. Note however that if the root element is the view input it is - * not shown in the view. - * - * @param rootElement The rootElement for which the cache is being - * pre-populated. - * - * @since 2.0 - */ - public Map<String, Object> getInitialRootElementProperties(Object rootElement); + /** + * Returns the properties that should be used to initially populate + * the cache, or <code>null</code> if the cache should not be pre-populated + * for this update policy. These properties may be used by the + * view model to generate the label for the root element. + * <p/> + * This method allows an update policy to prevent the UI from reading the + * model when the UI first appears and the cache has not been populated + * yet. Note however that if the root element is the view input it is + * not shown in the view. + * + * @param rootElement The rootElement for which the cache is being + * pre-populated. + * + * @since 2.0 + */ + public Map<String, Object> getInitialRootElementProperties(Object rootElement); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IVMUpdatePolicyExtension.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IVMUpdatePolicyExtension.java index 34b71a4a532..7eaeb6a5c4d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IVMUpdatePolicyExtension.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/IVMUpdatePolicyExtension.java @@ -7,30 +7,29 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.dsf.ui.viewmodel.update; - -/** - * Extension to the VM Update policy which allows the policy to control how to +/** + * Extension to the VM Update policy which allows the policy to control how to * update missing property values in a dirty cache entry. - * + * * @since 2.2 */ public interface IVMUpdatePolicyExtension extends IVMUpdatePolicy { - /** - * Determines whether the given dirty cache entry should have the given - * missing property updated. - * - * @param entry The dirty cache entry that is missing the given requested - * property. - * @param property Property missing from cache. - * @return If <code>true</code> cache can update the given missing property - * in the dirty cache entry with data from the VM node. - */ - public boolean canUpdateDirtyProperty(ICacheEntry entry, String property); + /** + * Determines whether the given dirty cache entry should have the given + * missing property updated. + * + * @param entry The dirty cache entry that is missing the given requested + * property. + * @param property Property missing from cache. + * @return If <code>true</code> cache can update the given missing property + * in the dirty cache entry with data from the VM node. + */ + public boolean canUpdateDirtyProperty(ICacheEntry entry, String property); } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ManualUpdatePolicy.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ManualUpdatePolicy.java index 645217cf425..b8bb7351f8c 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ManualUpdatePolicy.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ManualUpdatePolicy.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -28,162 +28,160 @@ import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.TreePath; import org.eclipse.swt.graphics.RGB; - /** - * An "manual" update policy which causes the view model provider cache to be - * flushed only as a result of an explicit user action. - * + * An "manual" update policy which causes the view model provider cache to be + * flushed only as a result of an explicit user action. + * * @since 1.0 */ public class ManualUpdatePolicy implements IVMUpdatePolicy { - public static String MANUAL_UPDATE_POLICY_ID = "org.eclipse.cdt.dsf.ui.viewmodel.update.manualUpdatePolicy"; //$NON-NLS-1$ - - public static Object REFRESH_EVENT = new Object(); + public static String MANUAL_UPDATE_POLICY_ID = "org.eclipse.cdt.dsf.ui.viewmodel.update.manualUpdatePolicy"; //$NON-NLS-1$ - private static class BlankDataElement implements IElementContentProvider, IElementLabelProvider { - - @Override + public static Object REFRESH_EVENT = new Object(); + + private static class BlankDataElement implements IElementContentProvider, IElementLabelProvider { + + @Override public void update(IHasChildrenUpdate[] updates) { - for (IHasChildrenUpdate update : updates) { - update.setHasChilren(false); - update.done(); - } - } - - @Override + for (IHasChildrenUpdate update : updates) { + update.setHasChilren(false); + update.done(); + } + } + + @Override public void update(IChildrenCountUpdate[] updates) { - for (IChildrenCountUpdate update : updates) { - update.setChildCount(0); - update.done(); - } - } - - @Override + for (IChildrenCountUpdate update : updates) { + update.setChildCount(0); + update.done(); + } + } + + @Override public void update(IChildrenUpdate[] updates) { - for (IChildrenUpdate update : updates) { - update.done(); - } - } - - @Override + for (IChildrenUpdate update : updates) { + update.done(); + } + } + + @Override public void update(ILabelUpdate[] updates) { - RGB staleDataForeground = JFaceResources.getColorRegistry().getRGB( - IDsfDebugUIConstants.PREF_COLOR_STALE_DATA_FOREGROUND); - RGB staleDataBackground = JFaceResources.getColorRegistry().getRGB( - IDsfDebugUIConstants.PREF_COLOR_STALE_DATA_BACKGROUND); - for (ILabelUpdate update : updates) { - update.setLabel(ViewModelUpdateMessages.ManualUpdatePolicy_InitialDataElement__label, 0); - // Set the stale data color to the label. Use foreground color if column modes are enabled, and - // background color when there are no columns. - if (update.getColumnIds() != null) { - update.setForeground(staleDataForeground, 0); - } else { - update.setBackground(staleDataBackground, 0); - } - update.done(); - } - } - } - - private static class UserEditEventUpdateTester implements IElementUpdateTester { - private final Set<Object> fElements; - - public UserEditEventUpdateTester(Set<Object> elements) { - fElements = elements; - } - - @Override + RGB staleDataForeground = JFaceResources.getColorRegistry() + .getRGB(IDsfDebugUIConstants.PREF_COLOR_STALE_DATA_FOREGROUND); + RGB staleDataBackground = JFaceResources.getColorRegistry() + .getRGB(IDsfDebugUIConstants.PREF_COLOR_STALE_DATA_BACKGROUND); + for (ILabelUpdate update : updates) { + update.setLabel(ViewModelUpdateMessages.ManualUpdatePolicy_InitialDataElement__label, 0); + // Set the stale data color to the label. Use foreground color if column modes are enabled, and + // background color when there are no columns. + if (update.getColumnIds() != null) { + update.setForeground(staleDataForeground, 0); + } else { + update.setBackground(staleDataBackground, 0); + } + update.done(); + } + } + } + + private static class UserEditEventUpdateTester implements IElementUpdateTester { + private final Set<Object> fElements; + + public UserEditEventUpdateTester(Set<Object> elements) { + fElements = elements; + } + + @Override public int getUpdateFlags(Object viewerInput, TreePath path) { - if (fElements.contains(viewerInput)) { - return FLUSH; - } - for (int i = 0; i < path.getSegmentCount(); i++) { - if (fElements.contains(path.getSegment(i))) { - return FLUSH; - } - } - return 0; - } - - @Override + if (fElements.contains(viewerInput)) { + return FLUSH; + } + for (int i = 0; i < path.getSegmentCount(); i++) { + if (fElements.contains(path.getSegment(i))) { + return FLUSH; + } + } + return 0; + } + + @Override public boolean includes(IElementUpdateTester tester) { - return - tester instanceof UserEditEventUpdateTester && - fElements.equals(((UserEditEventUpdateTester)tester).fElements); - } - - @Override - public String toString() { - return "Edit (" + fElements + ") update tester"; //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - private static IElementUpdateTester fgUpdateTester = new IElementUpdateTester() { - @Override + return tester instanceof UserEditEventUpdateTester + && fElements.equals(((UserEditEventUpdateTester) tester).fElements); + } + + @Override + public String toString() { + return "Edit (" + fElements + ") update tester"; //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + private static IElementUpdateTester fgUpdateTester = new IElementUpdateTester() { + @Override public int getUpdateFlags(Object viewerInput, TreePath path) { - return DIRTY; - } - - @Override + return DIRTY; + } + + @Override public boolean includes(IElementUpdateTester tester) { - return tester.equals(this); - } - - @Override - public String toString() { - return "Manual (refresh = false) update tester"; //$NON-NLS-1$ - } - }; - - private static IElementUpdateTester fgRefreshUpdateTester = new IElementUpdateTester() { - @Override + return tester.equals(this); + } + + @Override + public String toString() { + return "Manual (refresh = false) update tester"; //$NON-NLS-1$ + } + }; + + private static IElementUpdateTester fgRefreshUpdateTester = new IElementUpdateTester() { + @Override public int getUpdateFlags(Object viewerInput, TreePath path) { - return FLUSH | ARCHIVE; - } - - @Override + return FLUSH | ARCHIVE; + } + + @Override public boolean includes(IElementUpdateTester tester) { - return tester.equals(this) || tester.equals(fgUpdateTester) || tester instanceof UserEditEventUpdateTester; - } - - @Override - public String toString() { - return "Manual (refresh = true) update tester"; //$NON-NLS-1$ - } - }; - - @Override + return tester.equals(this) || tester.equals(fgUpdateTester) || tester instanceof UserEditEventUpdateTester; + } + + @Override + public String toString() { + return "Manual (refresh = true) update tester"; //$NON-NLS-1$ + } + }; + + @Override public String getID() { - return MANUAL_UPDATE_POLICY_ID; - } + return MANUAL_UPDATE_POLICY_ID; + } - @Override + @Override public String getName() { - return ViewModelUpdateMessages.ManualUpdatePolicy_name; - } + return ViewModelUpdateMessages.ManualUpdatePolicy_name; + } - @Override + @Override public IElementUpdateTester getElementUpdateTester(Object event) { - if (event.equals(REFRESH_EVENT)) { - return fgRefreshUpdateTester; - } else if (event instanceof UserEditEvent) { - return new UserEditEventUpdateTester(((UserEditEvent)event).getElements()); - } - return fgUpdateTester; - } - - @Override + if (event.equals(REFRESH_EVENT)) { + return fgRefreshUpdateTester; + } else if (event instanceof UserEditEvent) { + return new UserEditEventUpdateTester(((UserEditEvent) event).getElements()); + } + return fgUpdateTester; + } + + @Override public Object[] getInitialRootElementChildren(Object rootElement) { - // Return an dummy element to show in the view. The user will - // need to refresh the view to retrieve this data from the model. - return new Object[] { new BlankDataElement() }; - } + // Return an dummy element to show in the view. The user will + // need to refresh the view to retrieve this data from the model. + return new Object[] { new BlankDataElement() }; + } - @Override + @Override public Map<String, Object> getInitialRootElementProperties(Object rootElement) { - // Return an empty set of properties for the root element. The user will - // need to refresh the view to retrieve this data from the model. - return Collections.emptyMap(); - } + // Return an empty set of properties for the root element. The user will + // need to refresh the view to retrieve this data from the model. + return Collections.emptyMap(); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/StaleDataLabelBackground.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/StaleDataLabelBackground.java index 259a8f7c923..68ccf402e0f 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/StaleDataLabelBackground.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/StaleDataLabelBackground.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,31 +20,29 @@ import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.graphics.RGB; /** - * Stale data backgroun color label attribute to use with the - * PropertyBasedLabelProvider. The background color should only be - * used when the view is in no-columns mode. - * + * Stale data backgroun color label attribute to use with the + * PropertyBasedLabelProvider. The background color should only be + * used when the view is in no-columns mode. + * * @since 2.0 */ public class StaleDataLabelBackground extends LabelBackground { - public StaleDataLabelBackground() { - super(null); - setPropertyNames( - new String[] { ICachingVMProvider.PROP_CACHE_ENTRY_DIRTY, ICachingVMProvider.PROP_UPDATE_POLICY_ID }); - } - - @Override - public RGB getBackground() { - return JFaceResources.getColorRegistry().getRGB( - IDsfDebugUIConstants.PREF_COLOR_STALE_DATA_BACKGROUND); - } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - return - Boolean.TRUE.equals(properties.get(ICachingVMProvider.PROP_CACHE_ENTRY_DIRTY)) && - !AutomaticUpdatePolicy.AUTOMATIC_UPDATE_POLICY_ID.equals( - properties.get(ICachingVMProvider.PROP_UPDATE_POLICY_ID)); - } + public StaleDataLabelBackground() { + super(null); + setPropertyNames( + new String[] { ICachingVMProvider.PROP_CACHE_ENTRY_DIRTY, ICachingVMProvider.PROP_UPDATE_POLICY_ID }); + } + + @Override + public RGB getBackground() { + return JFaceResources.getColorRegistry().getRGB(IDsfDebugUIConstants.PREF_COLOR_STALE_DATA_BACKGROUND); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + return Boolean.TRUE.equals(properties.get(ICachingVMProvider.PROP_CACHE_ENTRY_DIRTY)) + && !AutomaticUpdatePolicy.AUTOMATIC_UPDATE_POLICY_ID + .equals(properties.get(ICachingVMProvider.PROP_UPDATE_POLICY_ID)); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/StaleDataLabelForeground.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/StaleDataLabelForeground.java index d736ad83896..834250e1b97 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/StaleDataLabelForeground.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/StaleDataLabelForeground.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -20,31 +20,29 @@ import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.graphics.RGB; /** - * Stale data foreground color label attribute to use with the - * PropertyBasedLabelProvider. The foreground color should only be - * used when the view is in column mode. - * + * Stale data foreground color label attribute to use with the + * PropertyBasedLabelProvider. The foreground color should only be + * used when the view is in column mode. + * * @since 2.0 */ public class StaleDataLabelForeground extends LabelForeground { - public StaleDataLabelForeground() { - super(null); - setPropertyNames( - new String[] { ICachingVMProvider.PROP_CACHE_ENTRY_DIRTY, ICachingVMProvider.PROP_UPDATE_POLICY_ID }); - } - - @Override - public RGB getForeground() { - return JFaceResources.getColorRegistry().getRGB( - IDsfDebugUIConstants.PREF_COLOR_STALE_DATA_FOREGROUND); - } - - @Override - public boolean isEnabled(IStatus status, java.util.Map<String,Object> properties) { - return - Boolean.TRUE.equals(properties.get(ICachingVMProvider.PROP_CACHE_ENTRY_DIRTY)) && - !AutomaticUpdatePolicy.AUTOMATIC_UPDATE_POLICY_ID.equals( - properties.get(ICachingVMProvider.PROP_UPDATE_POLICY_ID)); - } + public StaleDataLabelForeground() { + super(null); + setPropertyNames( + new String[] { ICachingVMProvider.PROP_CACHE_ENTRY_DIRTY, ICachingVMProvider.PROP_UPDATE_POLICY_ID }); + } + + @Override + public RGB getForeground() { + return JFaceResources.getColorRegistry().getRGB(IDsfDebugUIConstants.PREF_COLOR_STALE_DATA_FOREGROUND); + } + + @Override + public boolean isEnabled(IStatus status, java.util.Map<String, Object> properties) { + return Boolean.TRUE.equals(properties.get(ICachingVMProvider.PROP_CACHE_ENTRY_DIRTY)) + && !AutomaticUpdatePolicy.AUTOMATIC_UPDATE_POLICY_ID + .equals(properties.get(ICachingVMProvider.PROP_UPDATE_POLICY_ID)); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/UpdatePolicyDecorator.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/UpdatePolicyDecorator.java index 3b688aabca0..27375328209 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/UpdatePolicyDecorator.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/UpdatePolicyDecorator.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -15,33 +15,33 @@ package org.eclipse.cdt.dsf.ui.viewmodel.update; /** * An update policy decorator which can override behaviour of an underlying update policy. - * + * * @since 1.1 */ public abstract class UpdatePolicyDecorator implements IVMUpdatePolicy { private final IVMUpdatePolicy fBasePolicy; - - protected UpdatePolicyDecorator(IVMUpdatePolicy base) { - fBasePolicy= base; - } - - protected final IVMUpdatePolicy getBaseUpdatePolicy() { - return fBasePolicy; - } - - @Override + + protected UpdatePolicyDecorator(IVMUpdatePolicy base) { + fBasePolicy = base; + } + + protected final IVMUpdatePolicy getBaseUpdatePolicy() { + return fBasePolicy; + } + + @Override public final String getID() { - return fBasePolicy.getID(); - } + return fBasePolicy.getID(); + } - @Override + @Override public String getName() { - return fBasePolicy.getName(); - } + return fBasePolicy.getName(); + } - @Override + @Override public IElementUpdateTester getElementUpdateTester(Object event) { - return fBasePolicy.getElementUpdateTester(event); - } + return fBasePolicy.getElementUpdateTester(event); + } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/UserEditEvent.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/UserEditEvent.java index 7768526b7ff..db5238b452d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/UserEditEvent.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/UserEditEvent.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -21,22 +21,22 @@ import java.util.Set; * viewer is configured to be in a manual update mode, the modification of an * element by the user should at least cause an update of the modified element. * This event is used to accomplish that behavior. - * + * * @since 1.0 */ public class UserEditEvent { - private final Set<Object> fElements; - - public UserEditEvent(Object element) { - fElements = new HashSet<Object>(); - fElements.add(element); - } + private final Set<Object> fElements; + + public UserEditEvent(Object element) { + fElements = new HashSet<Object>(); + fElements.add(element); + } + + public UserEditEvent(Set<Object> elements) { + fElements = elements; + } - public UserEditEvent(Set<Object> elements) { - fElements = elements; - } - - public Set<Object> getElements() { - return fElements; - } + public Set<Object> getElements() { + return fElements; + } }
\ No newline at end of file diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ViewModelUpdateMessages.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ViewModelUpdateMessages.java index b36ea6521cb..31afcb9d86d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ViewModelUpdateMessages.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/update/ViewModelUpdateMessages.java @@ -7,7 +7,7 @@ * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 - * + * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ @@ -16,23 +16,23 @@ package org.eclipse.cdt.dsf.ui.viewmodel.update; import org.eclipse.osgi.util.NLS; public class ViewModelUpdateMessages extends NLS { - public static String AutomaticUpdatePolicy_name; - public static String ManualUpdatePolicy_InitialDataElement__label; - public static String ManualUpdatePolicy_name; - /** - * @since 1.1 - */ - public static String AllUpdateScope_name; - /** - * @since 1.1 - */ - public static String VisibleUpdateScope_name; - - static { - // load message values from bundle file - NLS.initializeMessages(ViewModelUpdateMessages.class.getName(), ViewModelUpdateMessages.class); - } + public static String AutomaticUpdatePolicy_name; + public static String ManualUpdatePolicy_InitialDataElement__label; + public static String ManualUpdatePolicy_name; + /** + * @since 1.1 + */ + public static String AllUpdateScope_name; + /** + * @since 1.1 + */ + public static String VisibleUpdateScope_name; + + static { + // load message values from bundle file + NLS.initializeMessages(ViewModelUpdateMessages.class.getName(), ViewModelUpdateMessages.class); + } - private ViewModelUpdateMessages() { - } + private ViewModelUpdateMessages() { + } } |