diff --git a/build/org.eclipse.cdt.autotools-feature/feature.xml b/build/org.eclipse.cdt.autotools-feature/feature.xml index cb3d48ad844..4cf9823fcc7 100644 --- a/build/org.eclipse.cdt.autotools-feature/feature.xml +++ b/build/org.eclipse.cdt.autotools-feature/feature.xml @@ -63,5 +63,12 @@ download-size="0" install-size="0" version="0.0.0"/> + + diff --git a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/core/MakeBuilder.java b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/core/MakeBuilder.java index 79a7880705b..87465d3896a 100644 --- a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/core/MakeBuilder.java +++ b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/core/MakeBuilder.java @@ -15,30 +15,24 @@ package org.eclipse.cdt.make.core; import java.io.IOException; -import java.io.OutputStream; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.CommandLauncher; import org.eclipse.cdt.core.ErrorParserManager; import org.eclipse.cdt.core.ICommandLauncher; -import org.eclipse.cdt.core.model.ICModelMarker; +import org.eclipse.cdt.core.IConsoleParser; import org.eclipse.cdt.core.resources.ACBuilder; import org.eclipse.cdt.core.resources.IConsole; -import org.eclipse.cdt.core.resources.RefreshScopeManager; -import org.eclipse.cdt.internal.core.ConsoleOutputSniffer; +import org.eclipse.cdt.internal.core.BuildRunnerHelper; +import org.eclipse.cdt.make.core.scannerconfig.IScannerInfoConsoleParser; import org.eclipse.cdt.make.internal.core.MakeMessages; -import org.eclipse.cdt.make.internal.core.StreamMonitor; import org.eclipse.cdt.make.internal.core.scannerconfig.ScannerInfoConsoleParserFactory; import org.eclipse.cdt.utils.CommandLineUtil; -import org.eclipse.cdt.utils.EFSExtensionManager; -import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; @@ -53,8 +47,6 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.jobs.ISchedulingRule; @@ -65,8 +57,10 @@ import org.eclipse.core.runtime.jobs.Job; * @noinstantiate This class is not intended to be instantiated by clients. */ public class MakeBuilder extends ACBuilder { - public final static String BUILDER_ID = MakeCorePlugin.getUniqueIdentifier() + ".makeBuilder"; //$NON-NLS-1$ + private static final int MONITOR_SCALE = 100; + + private BuildRunnerHelper buildRunnerHelper = null; public MakeBuilder() { } @@ -146,132 +140,112 @@ public class MakeBuilder extends ACBuilder { } } + /** + * Run build command. + * + * @param kind - kind of build, constant defined by {@link IncrementalProjectBuilder} + * @param info - builder info + * @param monitor - progress monitor in the initial state where {@link IProgressMonitor#beginTask(String, int)} + * has not been called yet. + * @return {@code true} if the build purpose is to clean, {@code false} otherwise. + */ protected boolean invokeMake(int kind, IMakeBuilderInfo info, IProgressMonitor monitor) { boolean isClean = false; - IProject currProject = getProject(); - - if (monitor == null) { - monitor = new NullProgressMonitor(); - } - monitor.beginTask(MakeMessages.getString("MakeBuilder.Invoking_Make_Builder") + currProject.getName(), 100); //$NON-NLS-1$ + IProject project = getProject(); + buildRunnerHelper = new BuildRunnerHelper(project); try { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + monitor.beginTask(MakeMessages.getString("MakeBuilder.Invoking_Make_Builder") + project.getName(), 3 * MONITOR_SCALE); //$NON-NLS-1$ + IPath buildCommand = info.getBuildCommand(); if (buildCommand != null) { IConsole console = CCorePlugin.getDefault().getConsole(); - console.start(currProject); + console.start(project); - OutputStream cos = console.getOutputStream(); - - // remove all markers for this project - removeAllMarkers(currProject); - - URI workingDirectoryURI = MakeBuilderUtil.getBuildDirectoryURI(currProject, info); - final String pathFromURI = EFSExtensionManager.getDefault().getPathFromURI(workingDirectoryURI); - if(pathFromURI == null) { - throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.PLUGIN_ID, MakeMessages.getString("MakeBuilder.ErrorWorkingDirectory"), null)); //$NON-NLS-1$ - } - - IPath workingDirectory = new Path(pathFromURI); + // Prepare launch parameters for BuildRunnerHelper + ICommandLauncher launcher = new CommandLauncher(); String[] targets = getTargets(kind, info); if (targets.length != 0 && targets[targets.length - 1].equals(info.getCleanBuildTarget())) isClean = true; - String errMsg = null; - ICommandLauncher launcher = new CommandLauncher(); - launcher.setProject(currProject); - // Print the command for visual interaction. - launcher.showCommand(true); + String[] args = getCommandArguments(info, targets); - // Set the environment - HashMap envMap = new HashMap(); - if (info.appendEnvironment()) { - @SuppressWarnings({"unchecked", "rawtypes"}) - Map env = (Map)launcher.getEnvironment(); - envMap.putAll(env); - } - // Add variables from build info - envMap.putAll(info.getExpandedEnvironment()); - List strings= new ArrayList(envMap.size()); - Set> entrySet = envMap.entrySet(); - for (Entry entry : entrySet) { - StringBuffer buffer= new StringBuffer(entry.getKey()); - buffer.append('=').append(entry.getValue()); - strings.add(buffer.toString()); - } - String[] env = strings.toArray(new String[strings.size()]); - String[] buildArguments = targets; - if (info.isDefaultBuildCmd()) { - if (!info.isStopOnError()) { - buildArguments = new String[targets.length + 1]; - buildArguments[0] = "-k"; //$NON-NLS-1$ - System.arraycopy(targets, 0, buildArguments, 1, targets.length); - } - } else { - String args = info.getBuildArguments(); - if (args != null && !args.equals("")) { //$NON-NLS-1$ - String[] newArgs = makeArray(args); - buildArguments = new String[targets.length + newArgs.length]; - System.arraycopy(newArgs, 0, buildArguments, 0, newArgs.length); - System.arraycopy(targets, 0, buildArguments, newArgs.length, targets.length); - } - } -// MakeRecon recon = new MakeRecon(buildCommand, buildArguments, env, workingDirectory, makeMonitor, cos); -// recon.invokeMakeRecon(); -// cos = recon; - QualifiedName qName = new QualifiedName(MakeCorePlugin.getUniqueIdentifier(), "progressMonitor"); //$NON-NLS-1$ - Integer last = (Integer)getProject().getSessionProperty(qName); - if (last == null) { - last = new Integer(100); - } - ErrorParserManager epm = new ErrorParserManager(getProject(), workingDirectoryURI, this, info.getErrorParsers()); - epm.setOutputStream(cos); - StreamMonitor streamMon = new StreamMonitor(new SubProgressMonitor(monitor, 100), epm, last.intValue()); - OutputStream stdout = streamMon; - OutputStream stderr = streamMon; - // Sniff console output for scanner info - ConsoleOutputSniffer sniffer = ScannerInfoConsoleParserFactory.getMakeBuilderOutputSniffer( - stdout, stderr, getProject(), workingDirectory, null, this, null); - OutputStream consoleOut = (sniffer == null ? stdout : sniffer.getOutputStream()); - OutputStream consoleErr = (sniffer == null ? stderr : sniffer.getErrorStream()); - Process p = launcher.execute(buildCommand, buildArguments, env, workingDirectory, monitor); - if (p != null) { - try { - // Close the input of the Process explicitly. - // We will never write to it. - p.getOutputStream().close(); - } catch (IOException e) { - } - // Before launching give visual cues via the monitor - monitor.subTask(MakeMessages.getString("MakeBuilder.Invoking_Command") + launcher.getCommandLine()); //$NON-NLS-1$ - if (launcher.waitAndRead(consoleOut, consoleErr, new SubProgressMonitor(monitor, 0)) - != ICommandLauncher.OK) - errMsg = launcher.getErrorMessage(); - monitor.subTask(MakeMessages.getString("MakeBuilder.Updating_project")); //$NON-NLS-1$ - refreshProject(currProject); - } else { - errMsg = launcher.getErrorMessage(); - } - getProject().setSessionProperty(qName, !monitor.isCanceled() && !isClean ? new Integer(streamMon.getWorkDone()) : null); + URI workingDirectoryURI = MakeBuilderUtil.getBuildDirectoryURI(project, info); - if (errMsg != null) { - consoleErr.write((errMsg + '\n').getBytes()); + HashMap envMap = getEnvironment(launcher, info); + String[] envp = BuildRunnerHelper.envMapToEnvp(envMap); + + String[] errorParsers = info.getErrorParsers(); + ErrorParserManager epm = new ErrorParserManager(getProject(), workingDirectoryURI, this, errorParsers); + + List parsers = new ArrayList(); + IScannerInfoConsoleParser parserSD = ScannerInfoConsoleParserFactory.getScannerInfoConsoleParser(project, workingDirectoryURI, this); + parsers.add(parserSD); + + buildRunnerHelper.setLaunchParameters(launcher, buildCommand, args, workingDirectoryURI, envp); + buildRunnerHelper.prepareStreams(epm, parsers, console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); + + buildRunnerHelper.removeOldMarkers(project, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); + + buildRunnerHelper.greeting(kind); + int state = buildRunnerHelper.build(new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); + + if (state != ICommandLauncher.ILLEGAL_COMMAND) { + refreshProject(project); } - - stdout.close(); - stderr.close(); - - consoleOut.close(); - consoleErr.close(); - cos.close(); + } else { + String msg = MakeMessages.getFormattedString("MakeBuilder.message.undefined.build.command", project.getName()); //$NON-NLS-1$ + throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.PLUGIN_ID, msg, new Exception())); } } catch (Exception e) { MakeCorePlugin.log(e); } finally { + try { + buildRunnerHelper.close(); + } catch (IOException e) { + MakeCorePlugin.log(e); + } monitor.done(); } - return (isClean); + return isClean; + } + + private HashMap getEnvironment(ICommandLauncher launcher, IMakeBuilderInfo info) + throws CoreException { + HashMap envMap = new HashMap(); + if (info.appendEnvironment()) { + @SuppressWarnings({"unchecked", "rawtypes"}) + Map env = (Map)launcher.getEnvironment(); + envMap.putAll(env); + } + envMap.putAll(info.getExpandedEnvironment()); + return envMap; + } + + private String[] getCommandArguments(IMakeBuilderInfo info, String[] targets) { + String[] args = targets; + if (info.isDefaultBuildCmd()) { + if (!info.isStopOnError()) { + args = new String[targets.length + 1]; + args[0] = "-k"; //$NON-NLS-1$ + System.arraycopy(targets, 0, args, 1, targets.length); + } + } else { + String argsStr = info.getBuildArguments(); + if (argsStr != null && !argsStr.equals("")) { //$NON-NLS-1$ + String[] newArgs = makeArray(argsStr); + args = new String[targets.length + newArgs.length]; + System.arraycopy(newArgs, 0, args, 0, newArgs.length); + System.arraycopy(targets, 0, args, newArgs.length, targets.length); + } + } + return args; } /** @@ -281,18 +255,8 @@ public class MakeBuilder extends ACBuilder { * @since 6.0 */ protected void refreshProject(IProject project) { - try { - // Do not allow the cancel of the refresh, since the builder is external - // to Eclipse, files may have been created/modified and we will be out-of-sync. - // The caveat is for huge projects, it may take sometimes at every build. - // project.refreshLocal(IResource.DEPTH_INFINITE, null); - - // use the refresh scope manager to refresh - RefreshScopeManager refreshManager = RefreshScopeManager.getInstance(); - IWorkspaceRunnable runnable = refreshManager.getRefreshRunnable(project); - ResourcesPlugin.getWorkspace().run(runnable, null, IWorkspace.AVOID_UPDATE, null); - } catch (CoreException e) { - MakeCorePlugin.log(e); + if (buildRunnerHelper != null) { + buildRunnerHelper.refreshProject(null); } } @@ -339,14 +303,4 @@ public class MakeBuilder extends ACBuilder { private String[] makeArray(String string) { return CommandLineUtil.argumentsToArray(string); } - - private void removeAllMarkers(IProject currProject) throws CoreException { - IWorkspace workspace = currProject.getWorkspace(); - - // remove all markers - IMarker[] markers = currProject.findMarkers(ICModelMarker.C_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE); - if (markers != null) { - workspace.deleteMarkers(markers); - } - } } diff --git a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/MakeMessages.properties b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/MakeMessages.properties index 7509f90aa47..5673ce0ea8e 100644 --- a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/MakeMessages.properties +++ b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/MakeMessages.properties @@ -14,10 +14,8 @@ AbstractGCCBOPConsoleParser_EnteringDirectory=Entering directory AbstractGCCBOPConsoleParser_LeavingDirectory=Leaving directory MakeBuilder.Invoking_Make_Builder=Invoking Make Builder... -MakeBuilder.Invoking_Command=Invoking Command: -MakeBuilder.Updating_project=Updating project... -MakeBuilder.Creating_Markers=Generating markers... -MakeBuilder.ErrorWorkingDirectory=Error determining working directory. +MakeBuilder.message.error.build = Internal error building project {0} +MakeBuilder.message.undefined.build.command = Build command is null for project {0} BuildInfoFactory.Missing_Builder=Missing Builder: @@ -37,12 +35,7 @@ ScannerConfigInfoFactory.Missing_Builder=Missing Builder: ExternalScannerInfoProvider.Console_Name=CDT Built-in Specs Console, {0} ExternalScannerInfoProvider.Reading_Specs=Reading specs ... -ExternalScannerInfoProvider.Invoking_Command=Invoking Command: -ExternalScannerInfoProvider.Parsing_Output=Parsing output ... -ExternalScannerInfoProvider.Creating_Markers=Generating markers ... -ExternalScannerInfoProvider.Provider_Error=Warning: Error launching external scanner info generator ({0}) -ExternalScannerInfoProvider.Working_Directory=Working directory: {0} -ExternalScannerInfoProvider.Program_Not_In_Path=Program ''{0}'' is not found in $PATH +ExternalScannerInfoProvider.Greeting=Scanner Discovery of compiler built-in settings for project {0} ScannerInfoCollector.Processing=Processing discovered scanner configuration ... ScannerInfoCollector.Updating=Updating Scanner Configuration for project diff --git a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/StreamMonitor.java b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/StreamMonitor.java index ef7363695bb..dde487ec6b9 100644 --- a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/StreamMonitor.java +++ b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/StreamMonitor.java @@ -10,97 +10,18 @@ *******************************************************************************/ package org.eclipse.cdt.make.internal.core; -import java.io.IOException; import java.io.OutputStream; import org.eclipse.core.runtime.IProgressMonitor; -public class StreamMonitor extends OutputStream { - - IProgressMonitor monitor; - OutputStream console; - public final int fTotalWork; - private int halfWay; - private int currentIncrement = 2; - private int nextProgress = currentIncrement; - private int worked = 0; - +/** + * + * @deprecated as of CDT 8.1. Use org.eclipse.cdt.internal.core.StreamMonitor + * + */ +@Deprecated +public class StreamMonitor extends org.eclipse.cdt.internal.core.StreamMonitor { public StreamMonitor(IProgressMonitor mon, OutputStream cos, int totalWork) { - monitor = mon; - console = cos; - fTotalWork = totalWork; - halfWay = fTotalWork / 2; - monitor.beginTask("", fTotalWork); //$NON-NLS-1$ - } - - private void progressUpdate() { - if (--nextProgress <= 0) { - //we have exhausted the current increment, so report progress - if (fTotalWork > worked) { - monitor.worked(1); - } - worked++; - if (worked >= halfWay) { - //we have passed the current halfway point, so double the - //increment and reset the halfway point. - currentIncrement *= 2; - halfWay += (fTotalWork - halfWay) / 2; - } - //reset the progress counter to another full increment - nextProgress = currentIncrement; - } - } - /** - * @see java.io.OutputStream#close() - */ - @Override - public void close() throws IOException { - if (console != null) { - console.close(); - } - monitor.done(); - } - - /** - * @see java.io.OutputStream#flush() - */ - @Override - public void flush() throws IOException { - if (console != null) { - console.flush(); - } - } - - /** - * @see java.io.OutputStream#write(int) - */ - @Override - public synchronized void write(int b) throws IOException { - if (console != null) { - console.write(b); - } - progressUpdate(); - } - - /** - * @see java.io.OutputStream#write(byte[], int, int) - */ - @Override - public synchronized void write(byte[] b, int off, int len) throws IOException { - if (b == null) { - throw new NullPointerException(); - } else if (off != 0 || (len < 0) || (len > b.length)) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) { - return; - } - if (console != null) { - console.write(b, off, len); - } - progressUpdate(); - } - - public int getWorkDone() { - return worked; + super(mon, cos, totalWork); } } diff --git a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/ScannerInfoConsoleParserFactory.java b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/ScannerInfoConsoleParserFactory.java index 1b568a53a8e..f1f2b9ddd4e 100644 --- a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/ScannerInfoConsoleParserFactory.java +++ b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/ScannerInfoConsoleParserFactory.java @@ -4,7 +4,7 @@ * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM - Initial API and implementation * Tianchao Li (tianchao.li@gmail.com) - arbitrary build directory (bug #136136) @@ -12,12 +12,9 @@ package org.eclipse.cdt.make.internal.core.scannerconfig; import java.io.OutputStream; +import java.net.URI; import org.eclipse.cdt.core.IMarkerGenerator; -import org.eclipse.cdt.core.language.settings.providers.ScannerDiscoveryLegacySupport; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; -import org.eclipse.cdt.core.settings.model.ICProjectDescription; import org.eclipse.cdt.internal.core.ConsoleOutputSniffer; import org.eclipse.cdt.make.core.MakeBuilder; import org.eclipse.cdt.make.core.MakeBuilderUtil; @@ -27,15 +24,18 @@ import org.eclipse.cdt.make.core.scannerconfig.IScannerInfoCollector; import org.eclipse.cdt.make.core.scannerconfig.IScannerInfoConsoleParser; import org.eclipse.cdt.make.core.scannerconfig.InfoContext; import org.eclipse.cdt.make.internal.core.scannerconfig2.SCProfileInstance; +import org.eclipse.cdt.make.internal.core.scannerconfig2.ScannerConfigProfile; import org.eclipse.cdt.make.internal.core.scannerconfig2.ScannerConfigProfileManager; +import org.eclipse.cdt.utils.EFSExtensionManager; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; /** * A factory that creates a ConsoleOutputStreamSniffer, * ScannerInfoConsoleParser and optionally a ScannerInfoConsoleParserUtility. - * + * * @author vhirsl */ public class ScannerInfoConsoleParserFactory { @@ -68,14 +68,14 @@ public class ScannerInfoConsoleParserFactory { IScannerInfoCollector collector, IMarkerGenerator markerGenerator) { if (scBuildInfo.isProviderOutputParserEnabled(providerId)) { - // get the ESIProvider console parser + // get the ESIProvider console parser SCProfileInstance profileInstance = ScannerConfigProfileManager.getInstance(). getSCProfileInstance(currentProject, context, scBuildInfo.getSelectedProfileId()); IScannerInfoConsoleParser clParser = profileInstance.createExternalScannerInfoParser(providerId); IPath buildDirectory = MakeBuilderUtil.getBuildDirectory(currentProject, MakeBuilder.BUILDER_ID); clParser.startup(currentProject, buildDirectory, collector, markerGenerator); // create an output stream sniffer - return new ConsoleOutputSniffer(outputStream, errorStream, new + return new ConsoleOutputSniffer(outputStream, errorStream, new IScannerInfoConsoleParser[] {clParser}); } return null; @@ -90,9 +90,9 @@ public class ScannerInfoConsoleParserFactory { OutputStream errorStream, IProject currentProject, IPath workingDirectory, - IScannerConfigBuilderInfo2 scBuildInfo, + IScannerConfigBuilderInfo2 scBuildInfo, IMarkerGenerator markerGenerator, - IScannerInfoCollector collector) { + IScannerInfoCollector collector) { return getMakeBuilderOutputSniffer(outputStream, errorStream, currentProject, new InfoContext(currentProject), workingDirectory, scBuildInfo, markerGenerator, collector); } @@ -103,54 +103,90 @@ public class ScannerInfoConsoleParserFactory { public static ConsoleOutputSniffer getMakeBuilderOutputSniffer( OutputStream outputStream, OutputStream errorStream, - IProject currentProject, - InfoContext context, + IProject project, + InfoContext infoContext, IPath workingDirectory, - IScannerConfigBuilderInfo2 scBuildInfo, + IScannerConfigBuilderInfo2 info2, IMarkerGenerator markerGenerator, - IScannerInfoCollector collector) { + IScannerInfoCollector collector) { + + IScannerInfoConsoleParser parser = getScannerInfoConsoleParserInternal(project, infoContext, workingDirectory, info2, markerGenerator, collector); + if (parser != null) { + // create an output stream sniffer + return new ConsoleOutputSniffer(outputStream, errorStream, new IScannerInfoConsoleParser[] {parser}); + + } + return null; + } + + private static IScannerInfoConsoleParser getScannerInfoConsoleParserInternal(IProject project, InfoContext infoContext, IPath workingDirectory, + IScannerConfigBuilderInfo2 info2, IMarkerGenerator markerGenerator, IScannerInfoCollector collector) { + + IScannerInfoConsoleParser parser = null; // try { // get the SC builder settings /*if (currentProject.hasNature(ScannerConfigNature.NATURE_ID))*/ { - if (scBuildInfo == null) { - try { - IScannerConfigBuilderInfo2Set container = ScannerConfigProfileManager. - createScannerConfigBuildInfo2Set(currentProject); - scBuildInfo = container.getInfo(context); - } - catch (CoreException e) { - // builder not installed or disabled - } - } - if (scBuildInfo != null) { - boolean autodiscoveryEnabled2 = scBuildInfo.isAutoDiscoveryEnabled(); - if (autodiscoveryEnabled2) { - ICProjectDescription projDesc = CoreModel.getDefault().getProjectDescription(currentProject); - ICConfigurationDescription cfgDescription = projDesc.getActiveConfiguration(); - autodiscoveryEnabled2 = ScannerDiscoveryLegacySupport.isLegacyScannerDiscoveryOn(cfgDescription); + if (info2 == null) { + try { + IScannerConfigBuilderInfo2Set container = ScannerConfigProfileManager.createScannerConfigBuildInfo2Set(project); + info2 = container.getInfo(infoContext); + } catch (CoreException e) { + // builder not installed or disabled } - if (autodiscoveryEnabled2 && scBuildInfo.isBuildOutputParserEnabled()) { - // get the make builder console parser - SCProfileInstance profileInstance = ScannerConfigProfileManager.getInstance(). - getSCProfileInstance(currentProject, context, scBuildInfo.getSelectedProfileId()); - IScannerInfoConsoleParser clParser = profileInstance.createBuildOutputParser(); + } + if (info2 != null && info2.isAutoDiscoveryEnabled() && info2.isBuildOutputParserEnabled()) { + String id = info2.getSelectedProfileId(); + + // get the make builder console parser + SCProfileInstance profileInstance = ScannerConfigProfileManager.getInstance().getSCProfileInstance(project, infoContext, id); + parser = profileInstance.createBuildOutputParser(); + if (parser != null){ if (collector == null) { collector = profileInstance.getScannerInfoCollector(); } - if(clParser != null){ - clParser.startup(currentProject, workingDirectory, collector, - scBuildInfo.isProblemReportingEnabled() ? markerGenerator : null); - // create an output stream sniffer - return new ConsoleOutputSniffer(outputStream, errorStream, new - IScannerInfoConsoleParser[] {clParser}); - } + parser.startup(project, workingDirectory, collector, info2.isProblemReportingEnabled() ? markerGenerator : null); } } } -// } +// } // catch (CoreException e) { // MakeCorePlugin.log(e.getStatus()); // } - return null; + + return parser; + } + + public static IScannerInfoConsoleParser getScannerInfoConsoleParser(IProject project, URI workingDirectoryURI, IMarkerGenerator markerGenerator) { + String pathFromURI = EFSExtensionManager.getDefault().getPathFromURI(workingDirectoryURI); + if(pathFromURI == null) { + // fallback to CWD + pathFromURI = System.getProperty("user.dir"); //$NON-NLS-1$ + } + return getScannerInfoConsoleParserInternal(project, new InfoContext(project), new Path(pathFromURI), null, markerGenerator, null); + } + + // TODO - perhaps this be unified with the other one? + public static IScannerInfoConsoleParser getScannerInfoConsoleParser(IProject project, InfoContext infoContext, IPath workingDirectory, + IScannerConfigBuilderInfo2 info2, IMarkerGenerator markerGenerator, IScannerInfoCollector collector) { + + IScannerInfoConsoleParser parser = null; + if (info2 != null && info2.isAutoDiscoveryEnabled() && info2.isBuildOutputParserEnabled()) { + String id = info2.getSelectedProfileId(); + ScannerConfigProfile profile = ScannerConfigProfileManager.getInstance().getSCProfileConfiguration(id); + if(profile.getBuildOutputProviderElement() != null){ + // get the make builder console parser + SCProfileInstance profileInstance = ScannerConfigProfileManager.getInstance().getSCProfileInstance(project, infoContext, id); + parser = profileInstance.createBuildOutputParser(); + if(parser != null){ + if (collector == null) { + collector = profileInstance.getScannerInfoCollector(); + } + parser.startup(project, workingDirectory, collector, info2.isProblemReportingEnabled() ? markerGenerator : null); + } + + } + } + + return parser; } } diff --git a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/gnu/GCCSpecsConsoleParser.java b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/gnu/GCCSpecsConsoleParser.java index bd42c16fd97..30ea92422bf 100644 --- a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/gnu/GCCSpecsConsoleParser.java +++ b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/gnu/GCCSpecsConsoleParser.java @@ -44,10 +44,7 @@ public class GCCSpecsConsoleParser implements IScannerInfoConsoleParser { protected List symbols = new ArrayList(); protected List includes = new ArrayList(); - /* (non-Javadoc) - * @see org.eclipse.cdt.make.core.scannerconfig.IScannerInfoConsoleParser#startup(org.eclipse.core.resources.IProject, org.eclipse.core.runtime.IPath, org.eclipse.cdt.make.core.scannerconfig.IScannerInfoCollector, org.eclipse.cdt.core.IMarkerGenerator) - */ - @Override + @Override public void startup(IProject project, IPath workingDirectory, IScannerInfoCollector collector, IMarkerGenerator markerGenerator) { this.fProject = project; this.fCollector = collector; @@ -58,21 +55,24 @@ public class GCCSpecsConsoleParser implements IScannerInfoConsoleParser { */ @Override public boolean processLine(String line) { - boolean rc = false; - line= line.trim(); TraceUtil.outputTrace("GCCSpecsConsoleParser parsing line: [", line, "]"); //$NON-NLS-1$ //$NON-NLS-2$ + line= line.trim(); + if (line.length() == 0) { + return false; + } + // contribution of -dD option if (line.startsWith(DEFINE)) { String[] defineParts = line.split("\\s+", 3); //$NON-NLS-1$ if (defineParts[0].equals(DEFINE)) { - if (defineParts[1].indexOf('(') >= 0) { - // #define __X__(P1, P2) __Y__(P1, P2) - // Enclose matching parentheses pairs - // in the macro name if they are present - int i = line.indexOf(')'); // macro definition itself can have only one pair of brackets + if (defineParts[1].indexOf('(') >= 0) { + // #define __X__(P1, P2) __Y__(P1, P2) + // Enclose matching parentheses pairs + // in the macro name if they are present + int i = line.indexOf(')'); // macro definition itself can have only one pair of brackets - // i now marks the space between the name and definition + // i now marks the space between the name and definition if (i > 0) { int start = line.indexOf(defineParts[1]); // start of definition defineParts[1] = line.substring(start, i + 1); @@ -82,18 +82,18 @@ public class GCCSpecsConsoleParser implements IScannerInfoConsoleParser { } else { MakeCorePlugin.log(new Exception("GCCSpecsConsoleParser ERROR: Unmatched brackets: ["+ line+ "]")); //$NON-NLS-1$ //$NON-NLS-2$ } - } + } - // Now defineParts[1] is the symbol name, and [2] is the definition - String symbol = null; - if (defineParts.length > 1) { - symbol = defineParts[1] + "="; //$NON-NLS-1$ - if (defineParts.length > 2) { - symbol += defineParts[2]; - } - if (!symbols.contains(symbol)) { - symbols.add(symbol); - } + // Now defineParts[1] is the symbol name, and [2] is the definition + String symbol = null; + if (defineParts.length > 1) { + symbol = defineParts[1] + "="; //$NON-NLS-1$ + if (defineParts.length > 2) { + symbol += defineParts[2]; + } + if (!symbols.contains(symbol)) { + symbols.add(symbol); + } } } } @@ -109,7 +109,7 @@ public class GCCSpecsConsoleParser implements IScannerInfoConsoleParser { includes.add(line); } - return rc; + return false; } /* (non-Javadoc) diff --git a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig2/DefaultRunSIProvider.java b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig2/DefaultRunSIProvider.java index 19123121aa0..a88e64bb236 100644 --- a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig2/DefaultRunSIProvider.java +++ b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig2/DefaultRunSIProvider.java @@ -12,7 +12,6 @@ package org.eclipse.cdt.make.internal.core.scannerconfig2; import java.io.IOException; -import java.io.OutputStream; import java.net.URI; import java.util.ArrayList; import java.util.Enumeration; @@ -24,7 +23,7 @@ import org.eclipse.cdt.core.ErrorParserManager; import org.eclipse.cdt.core.ICommandLauncher; import org.eclipse.cdt.core.model.ILanguage; import org.eclipse.cdt.core.resources.IConsole; -import org.eclipse.cdt.internal.core.ConsoleOutputSniffer; +import org.eclipse.cdt.internal.core.BuildRunnerHelper; import org.eclipse.cdt.make.core.MakeBuilder; import org.eclipse.cdt.make.core.MakeBuilderUtil; import org.eclipse.cdt.make.core.MakeCorePlugin; @@ -33,9 +32,7 @@ import org.eclipse.cdt.make.core.scannerconfig.IScannerConfigBuilderInfo2; import org.eclipse.cdt.make.core.scannerconfig.IScannerInfoCollector; import org.eclipse.cdt.make.core.scannerconfig.InfoContext; import org.eclipse.cdt.make.internal.core.MakeMessages; -import org.eclipse.cdt.make.internal.core.StreamMonitor; import org.eclipse.cdt.make.internal.core.scannerconfig.ScannerConfigUtil; -import org.eclipse.cdt.make.internal.core.scannerconfig.ScannerInfoConsoleParserFactory; import org.eclipse.cdt.utils.EFSExtensionManager; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; @@ -56,7 +53,7 @@ import org.osgi.service.prefs.BackingStoreException; public class DefaultRunSIProvider implements IExternalScannerInfoProvider { private static final String GMAKE_ERROR_PARSER_ID = "org.eclipse.cdt.core.GmakeErrorParser"; //$NON-NLS-1$ private static final String PREF_CONSOLE_ENABLED = "org.eclipse.cdt.make.core.scanner.discovery.console.enabled"; //$NON-NLS-1$ - private static final String NEWLINE = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + private static final int MONITOR_SCALE = 100; protected IResource resource; protected String providerId; @@ -90,17 +87,20 @@ public class DefaultRunSIProvider implements IExternalScannerInfoProvider { this.buildInfo = buildInfo; this.collector = collector; - IProject currentProject = resource.getProject(); - // call a subclass to initialize protected fields - if (!initialize()) { - return false; - } - if (monitor == null) { - monitor = new NullProgressMonitor(); - } - monitor.beginTask(MakeMessages.getString("ExternalScannerInfoProvider.Reading_Specs"), 100); //$NON-NLS-1$ + IProject project = resource.getProject(); + BuildRunnerHelper buildRunnerHelper = new BuildRunnerHelper(project); try { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + monitor.beginTask(MakeMessages.getString("ExternalScannerInfoProvider.Reading_Specs"), 2 * MONITOR_SCALE); //$NON-NLS-1$ + + // call a subclass to initialize protected fields + if (!initialize()) { + return false; + } + ILanguage language = context.getLanguage(); IConsole console; if (language!=null && isConsoleEnabled()) { @@ -111,64 +111,34 @@ public class DefaultRunSIProvider implements IExternalScannerInfoProvider { // that looks in extension points registry and won't find the id console = CCorePlugin.getDefault().getConsole(MakeCorePlugin.PLUGIN_ID + ".console.hidden"); //$NON-NLS-1$ } - console.start(currentProject); - OutputStream cos = console.getOutputStream(); + console.start(project); - // Before launching give visual cues via the monitor - monitor.subTask(MakeMessages.getString("ExternalScannerInfoProvider.Reading_Specs")); //$NON-NLS-1$ - - String errMsg = null; ICommandLauncher launcher = new CommandLauncher(); - launcher.setProject(currentProject); - // Print the command for visual interaction. - launcher.showCommand(true); + launcher.setProject(project); String[] comandLineOptions = getCommandLineOptions(); IPath program = getCommandToLaunch(); - String params = coligate(comandLineOptions); + URI workingDirectoryURI = MakeBuilderUtil.getBuildDirectoryURI(project, MakeBuilder.BUILDER_ID); + String[] envp = setEnvironment(launcher, env); - monitor.subTask(MakeMessages.getString("ExternalScannerInfoProvider.Invoking_Command") //$NON-NLS-1$ - + program + params); + ErrorParserManager epm = new ErrorParserManager(project, markerGenerator, new String[] {GMAKE_ERROR_PARSER_ID}); - ErrorParserManager epm = new ErrorParserManager(currentProject, markerGenerator, new String[] {GMAKE_ERROR_PARSER_ID}); - epm.setOutputStream(cos); - StreamMonitor streamMon = new StreamMonitor(new SubProgressMonitor(monitor, 70), epm, 100); - OutputStream stdout = streamMon; - OutputStream stderr = streamMon; + buildRunnerHelper.setLaunchParameters(launcher, program, comandLineOptions, workingDirectoryURI, envp ); + buildRunnerHelper.prepareStreams(epm, null, console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); - ConsoleOutputSniffer sniffer = ScannerInfoConsoleParserFactory.getESIProviderOutputSniffer( - stdout, stderr, currentProject, context, providerId, buildInfo, collector, markerGenerator); - OutputStream consoleOut = (sniffer == null ? cos : sniffer.getOutputStream()); - OutputStream consoleErr = (sniffer == null ? cos : sniffer.getErrorStream()); - Process p = launcher.execute(program, comandLineOptions, setEnvironment(launcher, env), fWorkingDirectory, monitor); - if (p != null) { - try { - // Close the input of the Process explicitly. - // We will never write to it. - p.getOutputStream().close(); - } catch (IOException e) { - } - if (launcher.waitAndRead(consoleOut, consoleErr, new SubProgressMonitor(monitor, 0)) != ICommandLauncher.OK) { - errMsg = launcher.getErrorMessage(); - } - monitor.subTask(MakeMessages.getString("ExternalScannerInfoProvider.Parsing_Output")); //$NON-NLS-1$ - } else { - errMsg = launcher.getErrorMessage(); - } + buildRunnerHelper.greeting(MakeMessages.getFormattedString("ExternalScannerInfoProvider.Greeting", project.getName())); //$NON-NLS-1$ + buildRunnerHelper.build(new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); - if (errMsg != null) { - printLine(consoleErr, errMsg); - printLine(consoleErr, MakeMessages.getFormattedString("ExternalScannerInfoProvider.Provider_Error", program + params) + NEWLINE); //$NON-NLS-1$ - } - - consoleOut.close(); - consoleErr.close(); - cos.close(); - } - catch (Exception e) { + } catch (Exception e) { MakeCorePlugin.log(e); - } - finally { + } finally { + try { + buildRunnerHelper.close(); + } catch (IOException e) { + MakeCorePlugin.log(e); + } monitor.done(); } return true; @@ -185,11 +155,6 @@ public class DefaultRunSIProvider implements IExternalScannerInfoProvider { buildInfo.isUseDefaultProviderCommand(providerId)); } - private void printLine(OutputStream stream, String msg) throws IOException { - stream.write((msg + NEWLINE).getBytes()); - stream.flush(); - } - /** * Initialization of protected fields. * Subclasses are most likely to override default implementation. @@ -223,16 +188,6 @@ public class DefaultRunSIProvider implements IExternalScannerInfoProvider { return fCompileArguments; } - private String coligate(String[] array) { - StringBuffer sb = new StringBuffer(128); - for (int i = 0; i < array.length; ++i) { - sb.append(' '); - sb.append(array[i]); - } - String ca = sb.toString(); - return ca; - } - private Properties getEnvMap(ICommandLauncher launcher, Properties initialEnv) { // Set the environmennt, some scripts may need the CWD var to be set. Properties props = initialEnv != null ? initialEnv : launcher.getEnvironment(); diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/AbstractBuildRunner.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/AbstractBuildRunner.java index d387f1ee47b..d3ae5ce2ef8 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/AbstractBuildRunner.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/AbstractBuildRunner.java @@ -20,7 +20,7 @@ import org.eclipse.core.runtime.IProgressMonitor; /** * Interface implemented by toolchain integrators to perform the actual build. - * + * * @author Doug Schaefer * @since 8.0 */ @@ -29,12 +29,13 @@ public abstract class AbstractBuildRunner { /** * Perform the build. * - * @param kind kind from the IncrementalProjectBuilder - * @param project project being built - * @param configuration configuration being built - * @param console console to use for build output - * @param markerGenerator generator to add markers for build problems - * @param monitor progress monitor + * @param kind - kind from the IncrementalProjectBuilder + * @param project - project being built + * @param configuration - configuration being built + * @param console - console to use for build output + * @param markerGenerator - generator to add markers for build problems + * @param monitor - progress monitor in the initial state where {@link IProgressMonitor#beginTask(String, int)} + * has not been called yet. * @throws CoreException standard core exception if something goes wrong */ public abstract boolean invokeBuild(int kind, IProject project, IConfiguration configuration, diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/ExternalBuildRunner.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/ExternalBuildRunner.java index ad406199f85..af21781a20b 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/ExternalBuildRunner.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/ExternalBuildRunner.java @@ -1,18 +1,18 @@ /******************************************************************************* - * Copyright (c) 2010, 2011 Wind River Systems and others. + * Copyright (c) 2010, 2012 Wind River Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Wind River Systems - Initial API and implementation - * James Blackburn (Broadcom Corp.) + * Wind River Systems - Initial API and implementation + * James Blackburn (Broadcom Corp.) + * Andrew Gvozdev *******************************************************************************/ package org.eclipse.cdt.managedbuilder.core; import java.io.IOException; -import java.io.OutputStream; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; @@ -25,48 +25,31 @@ import org.eclipse.cdt.build.core.scannerconfig.ICfgScannerConfigBuilderInfo2Set import org.eclipse.cdt.build.internal.core.scannerconfig2.CfgScannerConfigProfileManager; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.ErrorParserManager; -import org.eclipse.cdt.core.ICConsoleParser; import org.eclipse.cdt.core.ICommandLauncher; import org.eclipse.cdt.core.IConsoleParser; import org.eclipse.cdt.core.IMarkerGenerator; import org.eclipse.cdt.core.envvar.IEnvironmentVariable; import org.eclipse.cdt.core.envvar.IEnvironmentVariableManager; -import org.eclipse.cdt.core.language.settings.providers.ILanguageSettingsProvider; -import org.eclipse.cdt.core.language.settings.providers.ILanguageSettingsProvidersKeeper; -import org.eclipse.cdt.core.language.settings.providers.LanguageSettingsManager; import org.eclipse.cdt.core.language.settings.providers.ScannerDiscoveryLegacySupport; -import org.eclipse.cdt.core.model.ICModelMarker; import org.eclipse.cdt.core.resources.IConsole; -import org.eclipse.cdt.core.resources.RefreshScopeManager; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; -import org.eclipse.cdt.internal.core.ConsoleOutputSniffer; +import org.eclipse.cdt.internal.core.BuildRunnerHelper; import org.eclipse.cdt.make.core.scannerconfig.IScannerConfigBuilderInfo2; -import org.eclipse.cdt.make.core.scannerconfig.IScannerInfoCollector; import org.eclipse.cdt.make.core.scannerconfig.IScannerInfoConsoleParser; -import org.eclipse.cdt.make.core.scannerconfig.InfoContext; -import org.eclipse.cdt.make.internal.core.scannerconfig2.SCProfileInstance; -import org.eclipse.cdt.make.internal.core.scannerconfig2.ScannerConfigProfile; -import org.eclipse.cdt.make.internal.core.scannerconfig2.ScannerConfigProfileManager; +import org.eclipse.cdt.make.internal.core.scannerconfig.ScannerInfoConsoleParserFactory; import org.eclipse.cdt.managedbuilder.internal.core.ManagedMakeMessages; import org.eclipse.cdt.managedbuilder.macros.BuildMacroException; import org.eclipse.cdt.managedbuilder.macros.IBuildMacroProvider; -import org.eclipse.cdt.newmake.internal.core.StreamMonitor; import org.eclipse.cdt.utils.CommandLineUtil; import org.eclipse.cdt.utils.EFSExtensionManager; -import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.IncrementalProjectBuilder; -import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; @@ -75,13 +58,7 @@ import org.eclipse.core.runtime.SubProgressMonitor; * @since 8.0 */ public class ExternalBuildRunner extends AbstractBuildRunner { - - private static final String TYPE_CLEAN = "ManagedMakeBuilder.type.clean"; //$NON-NLS-1$ - private static final String TYPE_INC = "ManagedMakeBuider.type.incremental"; //$NON-NLS-1$ - private static final String CONSOLE_HEADER = "ManagedMakeBuilder.message.console.header"; //$NON-NLS-1$ - private static final String WARNING_UNSUPPORTED_CONFIGURATION = "ManagedMakeBuilder.warning.unsupported.configuration"; //$NON-NLS-1$ - private static final String NEWLINE = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - private static final String PATH_ENV = "PATH"; //$NON-NLS-1$ + private static final int MONITOR_SCALE = 100; @Override public boolean invokeBuild(int kind, IProject project, IConfiguration configuration, @@ -94,163 +71,86 @@ public class ExternalBuildRunner extends AbstractBuildRunner { protected boolean invokeExternalBuild(int kind, IProject project, IConfiguration configuration, IBuilder builder, IConsole console, IMarkerGenerator markerGenerator, IncrementalProjectBuilder projectBuilder, IProgressMonitor monitor) throws CoreException { + boolean isClean = false; - if (monitor == null) { - monitor = new NullProgressMonitor(); - } - monitor.beginTask(ManagedMakeMessages.getResourceString("MakeBuilder.Invoking_Make_Builder") + project.getName(), 100); //$NON-NLS-1$ - + BuildRunnerHelper buildRunnerHelper = new BuildRunnerHelper(project); try { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + monitor.beginTask(ManagedMakeMessages.getResourceString("MakeBuilder.Invoking_Make_Builder") + project.getName(), 4 * MONITOR_SCALE); //$NON-NLS-1$ + IPath buildCommand = builder.getBuildCommand(); if (buildCommand != null) { - OutputStream cos = console.getOutputStream(); - StringBuffer buf = new StringBuffer(); + ICConfigurationDescription cfgDescription = ManagedBuildManager.getDescriptionForConfiguration(configuration); - String[] consoleHeader = new String[3]; - switch (kind) { - case IncrementalProjectBuilder.FULL_BUILD: - case IncrementalProjectBuilder.INCREMENTAL_BUILD: - case IncrementalProjectBuilder.AUTO_BUILD: - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_INC); - break; - case IncrementalProjectBuilder.CLEAN_BUILD: - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_CLEAN); - break; - } + String cfgName = configuration.getName(); + String toolchainName = configuration.getToolChain().getName(); + boolean isSupported = configuration.isSupported(); - URI workingDirectoryURI = ManagedBuildManager.getBuildLocationURI(configuration, builder); - final String pathFromURI = EFSExtensionManager.getDefault().getPathFromURI(workingDirectoryURI); - if(pathFromURI == null) { - throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, ManagedMakeMessages.getString("ManagedMakeBuilder.message.error"), null)); //$NON-NLS-1$ - } - - IPath workingDirectory = new Path(pathFromURI); - - // Set the environment - Map envMap = getEnvironment(builder); - String[] env = getEnvStrings(envMap); - - consoleHeader[1] = configuration.getName(); - consoleHeader[2] = project.getName(); - buf.append(NEWLINE); - buf.append(ManagedMakeMessages.getFormattedString(CONSOLE_HEADER, consoleHeader)).append(NEWLINE); - buf.append(NEWLINE); - - if(!configuration.isSupported()){ - String unsupportedToolchainMsg = ManagedMakeMessages.getFormattedString(WARNING_UNSUPPORTED_CONFIGURATION, - new String[] { configuration.getName(), configuration.getToolChain().getName() }); - buf.append(unsupportedToolchainMsg).append(NEWLINE); - buf.append(NEWLINE); - } - cos.write(buf.toString().getBytes()); - cos.flush(); - - // remove all markers for this project - IWorkspace workspace = project.getWorkspace(); - IMarker[] markers = project.findMarkers(ICModelMarker.C_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE); - if (markers != null) - workspace.deleteMarkers(markers); + ICommandLauncher launcher = builder.getCommandLauncher(); String[] targets = getTargets(kind, builder); if (targets.length != 0 && targets[targets.length - 1].equals(builder.getCleanBuildTarget())) isClean = true; - String errMsg = null; - ICommandLauncher launcher = builder.getCommandLauncher(); - launcher.setProject(project); - // Print the command for visual interaction. - launcher.showCommand(true); + String[] args = getCommandArguments(builder, targets); - String[] buildArguments = targets; + URI workingDirectoryURI = ManagedBuildManager.getBuildLocationURI(configuration, builder); - String[] newArgs = CommandLineUtil.argumentsToArray(builder.getBuildArguments()); - buildArguments = new String[targets.length + newArgs.length]; - System.arraycopy(newArgs, 0, buildArguments, 0, newArgs.length); - System.arraycopy(targets, 0, buildArguments, newArgs.length, targets.length); + Map envMap = getEnvironment(builder); + String[] envp = BuildRunnerHelper.envMapToEnvp(envMap); - QualifiedName qName = new QualifiedName(ManagedBuilderCorePlugin.getUniqueIdentifier(), "progressMonitor"); //$NON-NLS-1$ - Integer last = (Integer)project.getSessionProperty(qName); - if (last == null) { - last = new Integer(100); - } - ErrorParserManager epm = new ErrorParserManager(project, workingDirectoryURI, markerGenerator, builder.getErrorParsers()); - epm.setOutputStream(cos); - StreamMonitor streamMon = new StreamMonitor(new SubProgressMonitor(monitor, 100), epm, last.intValue()); - OutputStream stdout = streamMon; - OutputStream stderr = streamMon; + String[] errorParsers = builder.getErrorParsers(); + ErrorParserManager epm = new ErrorParserManager(project, workingDirectoryURI, markerGenerator, errorParsers); - // Sniff console output for scanner info - OutputStream consoleOut = stdout; - OutputStream consoleErr = stderr; - if (kind!=IncrementalProjectBuilder.CLEAN_BUILD) { - ConsoleOutputSniffer sniffer = createBuildOutputSniffer(stdout, stderr, project, configuration, workingDirectory, markerGenerator, null, epm); - if (sniffer!=null) { - consoleOut = sniffer.getOutputStream(); - consoleErr = sniffer.getErrorStream(); + List parsers = new ArrayList(); + if (!isClean) { + ManagedBuildManager.collectLanguageSettingsConsoleParsers(cfgDescription, parsers); + if (ScannerDiscoveryLegacySupport.isLegacyScannerDiscoveryOn(cfgDescription)) { + collectScannerInfoConsoleParsers(project, configuration, workingDirectoryURI, markerGenerator, parsers); } } - Process p = launcher.execute(buildCommand, buildArguments, env, workingDirectory, monitor); - if (p != null) { - try { - // Close the input of the Process explicitly. - // We will never write to it. - p.getOutputStream().close(); - } catch (IOException e) { - } - // Before launching give visual cues via the monitor - monitor.subTask(ManagedMakeMessages.getResourceString("MakeBuilder.Invoking_Command") + launcher.getCommandLine()); //$NON-NLS-1$ - if (launcher.waitAndRead(consoleOut, consoleErr, new SubProgressMonitor(monitor, 0)) - != ICommandLauncher.OK) - errMsg = launcher.getErrorMessage(); - monitor.subTask(ManagedMakeMessages.getResourceString("MakeBuilder.Updating_project")); //$NON-NLS-1$ - try { - // Do not allow the cancel of the refresh, since the builder is external - // to Eclipse, files may have been created/modified and we will be out-of-sync. - // The caveat is for huge projects, it may take sometimes at every build. + buildRunnerHelper.setLaunchParameters(launcher, buildCommand, args, workingDirectoryURI, envp); + buildRunnerHelper.prepareStreams(epm, parsers, console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); - // TODO should only refresh output folders - //project.refreshLocal(IResource.DEPTH_INFINITE, null); + buildRunnerHelper.removeOldMarkers(project, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); - // use the refresh scope manager to refresh - RefreshScopeManager refreshManager = RefreshScopeManager.getInstance(); - IWorkspaceRunnable runnable = refreshManager.getRefreshRunnable(project); - ResourcesPlugin.getWorkspace().run(runnable, null, IWorkspace.AVOID_UPDATE, null); - } catch (CoreException e) { - } - } else { - errMsg = launcher.getErrorMessage(); + buildRunnerHelper.greeting(kind, cfgName, toolchainName, isSupported); + int state = buildRunnerHelper.build(new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); + + if (state != ICommandLauncher.ILLEGAL_COMMAND) { + buildRunnerHelper.refreshProject(new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); } - project.setSessionProperty(qName, !monitor.isCanceled() && !isClean ? new Integer(streamMon.getWorkDone()) : null); - - if (errMsg != null) { - consoleErr.write(errMsg.getBytes()); - consoleErr.flush(); - } - - buf = new StringBuffer(NEWLINE); - buf.append(ManagedMakeMessages.getResourceString("ManagedMakeBuilder.message.build.finished")).append(NEWLINE); //$NON-NLS-1$ - consoleOut.write(buf.toString().getBytes()); - - stdout.close(); - stderr.close(); - - monitor.subTask(ManagedMakeMessages.getResourceString("MakeBuilder.Creating_Markers")); //$NON-NLS-1$ - consoleOut.close(); - consoleErr.close(); - cos.close(); + } else { + String msg = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.undefined.build.command", builder.getId()); //$NON-NLS-1$ + throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, msg, new Exception())); } } catch (Exception e) { - ManagedBuilderCorePlugin.log(e); - throw new CoreException(new Status(IStatus.ERROR, - ManagedBuilderCorePlugin.getUniqueIdentifier(), - e.getLocalizedMessage(), - e)); + String msg = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.error.build", //$NON-NLS-1$ + new String[] { project.getName(), configuration.getName() }); + throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, msg, e)); } finally { + try { + buildRunnerHelper.close(); + } catch (IOException e) { + ManagedBuilderCorePlugin.log(e); + } monitor.done(); } - return (isClean); + return isClean; + } + + private String[] getCommandArguments(IBuilder builder, String[] targets) { + String[] builderArgs = CommandLineUtil.argumentsToArray(builder.getBuildArguments()); + String[] args = new String[targets.length + builderArgs.length]; + System.arraycopy(builderArgs, 0, args, 0, builderArgs.length); + System.arraycopy(targets, 0, args, builderArgs.length, targets.length); + return args; } protected String[] getTargets(int kind, IBuilder builder) { @@ -314,6 +214,7 @@ public class ExternalBuildRunner extends AbstractBuildRunner { return envMap; } + @Deprecated protected static String[] getEnvStrings(Map env) { // Convert into env strings List strings= new ArrayList(env.size()); @@ -326,17 +227,19 @@ public class ExternalBuildRunner extends AbstractBuildRunner { return strings.toArray(new String[strings.size()]); } - private ConsoleOutputSniffer createBuildOutputSniffer(OutputStream outputStream, - OutputStream errorStream, - IProject project, - IConfiguration cfg, - IPath workingDirectory, - IMarkerGenerator markerGenerator, - IScannerInfoCollector collector, - ErrorParserManager epm){ + private static void collectScannerInfoConsoleParsers(IProject project, IConfiguration cfg, URI workingDirectoryURI, + IMarkerGenerator markerGenerator, List parsers) { ICfgScannerConfigBuilderInfo2Set container = CfgScannerConfigProfileManager.getCfgScannerConfigBuildInfo(cfg); Map map = container.getInfoMap(); - List clParserList = new ArrayList(); + + String pathFromURI = EFSExtensionManager.getDefault().getPathFromURI(workingDirectoryURI); + if(pathFromURI == null) { + // fallback to CWD + pathFromURI = System.getProperty("user.dir"); //$NON-NLS-1$ + } + IPath workingDirectory = new Path(pathFromURI); + + int oldSize = parsers.size(); if(container.isPerRcTypeDiscovery()){ for (IResourceInfo rcInfo : cfg.getResourceInfos()) { @@ -351,89 +254,35 @@ public class ExternalBuildRunner extends AbstractBuildRunner { if(types.length != 0){ for (IInputType type : types) { - CfgInfoContext c = new CfgInfoContext(rcInfo, tool, type); - contributeToConsoleParserList(project, map, c, workingDirectory, markerGenerator, collector, clParserList); + CfgInfoContext context = new CfgInfoContext(rcInfo, tool, type); + IScannerInfoConsoleParser parser = getScannerInfoConsoleParser(project, map, context, workingDirectory, markerGenerator); + if (parser != null) { + parsers.add(parser); + } } } else { - CfgInfoContext c = new CfgInfoContext(rcInfo, tool, null); - contributeToConsoleParserList(project, map, c, workingDirectory, markerGenerator, collector, clParserList); + CfgInfoContext context = new CfgInfoContext(rcInfo, tool, null); + IScannerInfoConsoleParser parser = getScannerInfoConsoleParser(project, map, context, workingDirectory, markerGenerator); + if (parser != null) { + parsers.add(parser); + } } } } } - if(clParserList.size() == 0){ - contributeToConsoleParserList(project, map, new CfgInfoContext(cfg), workingDirectory, markerGenerator, collector, clParserList); - } - - ICConfigurationDescription cfgDescription = ManagedBuildManager.getDescriptionForConfiguration(cfg); - if (cfgDescription instanceof ILanguageSettingsProvidersKeeper) { - List lsProviders = ((ILanguageSettingsProvidersKeeper) cfgDescription).getLanguageSettingProviders(); - for (ILanguageSettingsProvider lsProvider : lsProviders) { - ILanguageSettingsProvider rawProvider = LanguageSettingsManager.getRawProvider(lsProvider); - if (rawProvider instanceof ICConsoleParser) { - ICConsoleParser consoleParser = (ICConsoleParser) rawProvider; - try { - consoleParser.startup(cfgDescription); - clParserList.add(consoleParser); - } catch (CoreException e) { - ManagedBuilderCorePlugin.log(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, - "Language Settings Provider failed to start up", e)); //$NON-NLS-1$ - } - } + if(parsers.size() == oldSize){ + CfgInfoContext context = new CfgInfoContext(cfg); + IScannerInfoConsoleParser parser = getScannerInfoConsoleParser(project, map, context, workingDirectory, markerGenerator); + if (parser != null) { + parsers.add(parser); } } - - if(clParserList.size() != 0){ - IConsoleParser[] parsers = clParserList.toArray(new IConsoleParser[clParserList.size()]); - return new ConsoleOutputSniffer(outputStream, errorStream, parsers, epm); - } - - return null; } - private boolean contributeToConsoleParserList( - IProject project, - Map map, - CfgInfoContext context, - IPath workingDirectory, - IMarkerGenerator markerGenerator, - IScannerInfoCollector collector, - List parserList){ - IScannerConfigBuilderInfo2 info = map.get(context); - InfoContext ic = context.toInfoContext(); - boolean added = false; - if (info != null) { - boolean autodiscoveryEnabled2 = info.isAutoDiscoveryEnabled(); - if (autodiscoveryEnabled2) { - IConfiguration cfg = context.getConfiguration(); - ICConfigurationDescription cfgDescription = ManagedBuildManager.getDescriptionForConfiguration(cfg); - autodiscoveryEnabled2 = ScannerDiscoveryLegacySupport.isLegacyScannerDiscoveryOn(cfgDescription); - } - if (autodiscoveryEnabled2 && info.isBuildOutputParserEnabled()) { - - String id = info.getSelectedProfileId(); - ScannerConfigProfile profile = ScannerConfigProfileManager.getInstance().getSCProfileConfiguration(id); - if(profile.getBuildOutputProviderElement() != null){ - // get the make builder console parser - SCProfileInstance profileInstance = ScannerConfigProfileManager.getInstance(). - getSCProfileInstance(project, ic, id); - - IScannerInfoConsoleParser clParser = profileInstance.createBuildOutputParser(); - if (collector == null) { - collector = profileInstance.getScannerInfoCollector(); - } - if(clParser != null){ - clParser.startup(project, workingDirectory, collector, - info.isProblemReportingEnabled() ? markerGenerator : null); - parserList.add(clParser); - added = true; - } - - } - } - } - - return added; + private static IScannerInfoConsoleParser getScannerInfoConsoleParser(IProject project, Map map, + CfgInfoContext context, IPath workingDirectory, IMarkerGenerator markerGenerator) { + return ScannerInfoConsoleParserFactory.getScannerInfoConsoleParser(project, context.toInfoContext(), workingDirectory, map.get(context), markerGenerator, null); } + } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/InternalBuildRunner.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/InternalBuildRunner.java index eadd2f30b9a..344c654f4fe 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/InternalBuildRunner.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/InternalBuildRunner.java @@ -13,40 +13,34 @@ package org.eclipse.cdt.managedbuilder.core; import java.io.IOException; import java.io.OutputStream; +import java.net.URI; import java.util.ArrayList; import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import org.eclipse.cdt.core.ConsoleOutputStream; import org.eclipse.cdt.core.ErrorParserManager; +import org.eclipse.cdt.core.ICommandLauncher; +import org.eclipse.cdt.core.IConsoleParser; import org.eclipse.cdt.core.IMarkerGenerator; -import org.eclipse.cdt.core.language.settings.providers.ILanguageSettingsProvider; -import org.eclipse.cdt.core.language.settings.providers.ILanguageSettingsProvidersKeeper; -import org.eclipse.cdt.core.model.ICModelMarker; import org.eclipse.cdt.core.resources.IConsole; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; -import org.eclipse.cdt.make.core.language.settings.providers.AbstractBuildCommandParser; +import org.eclipse.cdt.internal.core.BuildRunnerHelper; import org.eclipse.cdt.managedbuilder.buildmodel.BuildDescriptionManager; import org.eclipse.cdt.managedbuilder.buildmodel.IBuildDescription; -import org.eclipse.cdt.managedbuilder.internal.buildmodel.BuildDescription; import org.eclipse.cdt.managedbuilder.internal.buildmodel.BuildStateManager; import org.eclipse.cdt.managedbuilder.internal.buildmodel.DescriptionBuilder; -import org.eclipse.cdt.managedbuilder.internal.buildmodel.IBuildModelBuilder; import org.eclipse.cdt.managedbuilder.internal.buildmodel.IConfigurationBuildState; import org.eclipse.cdt.managedbuilder.internal.buildmodel.IProjectBuildState; import org.eclipse.cdt.managedbuilder.internal.buildmodel.ParallelBuilder; import org.eclipse.cdt.managedbuilder.internal.core.ManagedMakeMessages; -import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.SubProgressMonitor; /** * The build runner for the internal builder. @@ -55,57 +49,24 @@ import org.eclipse.core.runtime.NullProgressMonitor; * @since 8.0 */ public class InternalBuildRunner extends AbstractBuildRunner { - - private static final String INTERNAL_BUILDER = "ManagedMakeBuilder.message.internal.builder"; //$NON-NLS-1$ - private static final String TYPE_INC = "ManagedMakeBuider.type.incremental"; //$NON-NLS-1$ - private static final String TYPE_REBUILD = "ManagedMakeBuider.type.rebuild"; //$NON-NLS-1$ - private static final String CONSOLE_HEADER = "ManagedMakeBuilder.message.console.header"; //$NON-NLS-1$ - private static final String INTERNAL_BUILDER_HEADER_NOTE = "ManagedMakeBuilder.message.internal.builder.header.note"; //$NON-NLS-1$ - private static final String WARNING_UNSUPPORTED_CONFIGURATION = "ManagedMakeBuilder.warning.unsupported.configuration"; //$NON-NLS-1$ - private static final String BUILD_FINISHED = "ManagedMakeBuilder.message.finished"; //$NON-NLS-1$ - private static final String BUILD_CANCELLED = "ManagedMakeBuilder.message.cancelled"; //$NON-NLS-1$ - private static final String BUILD_FINISHED_WITH_ERRS = "ManagedMakeBuilder.message.finished.with.errs"; //$NON-NLS-1$ - private static final String BUILD_STOPPED_ERR = "ManagedMakeBuilder.message.stopped.error"; //$NON-NLS-1$ - private static final String BUILD_FAILED_ERR = "ManagedMakeBuilder.message.internal.builder.error"; //$NON-NLS-1$ - private static final String MARKERS = "ManagedMakeBuilder.message.creating.markers"; //$NON-NLS-1$ - private static final String NOTHING_BUILT = "ManagedMakeBuilder.message.no.build"; //$NON-NLS-1$ - private static final String BUILD_ERROR = "ManagedMakeBuilder.message.error"; //$NON-NLS-1$ - - - // TODO: same function is present in CommandBuilder and BuildProcessManager - private String[] mapToStringArray(Map map){ - if(map == null) - return null; - - List list = new ArrayList(); - - for (Entry entry : map.entrySet()) { - list.add(entry.getKey() + '=' + entry.getValue()); - } - - return list.toArray(new String[list.size()]); - } + private static final int MONITOR_SCALE = 100; @Override public boolean invokeBuild(int kind, IProject project, IConfiguration configuration, IBuilder builder, IConsole console, IMarkerGenerator markerGenerator, IncrementalProjectBuilder projectBuilder, IProgressMonitor monitor) throws CoreException { - boolean isParallel = builder.getParallelizationNum() > 1; -// boolean buildIncrementaly = true; - boolean resumeOnErr = !builder.isStopOnError(); - // Get the project and make sure there's a monitor to cancel the build - if (monitor == null) { - monitor = new NullProgressMonitor(); - } + BuildRunnerHelper buildRunnerHelper = new BuildRunnerHelper(project); - String[] msgs = new String[2]; - msgs[0] = ManagedMakeMessages.getResourceString(INTERNAL_BUILDER); - msgs[1] = project.getName(); - - ConsoleOutputStream consoleOutStream = null; - OutputStream epmOutputStream = null; try { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + monitor.beginTask("", 3 * MONITOR_SCALE); //$NON-NLS-1$ + + boolean isParallel = builder.getParallelizationNum() > 1; + boolean resumeOnErr = !builder.isStopOnError(); + int flags = 0; IResourceDelta delta = projectBuilder.getDelta(project); BuildStateManager bsMngr = BuildStateManager.getInstance(); @@ -113,183 +74,82 @@ public class InternalBuildRunner extends AbstractBuildRunner { IConfigurationBuildState cBS = pBS.getConfigurationBuildState(configuration.getId(), true); // if(delta != null){ - flags = BuildDescriptionManager.REBUILD | BuildDescriptionManager.REMOVED | BuildDescriptionManager.DEPS; + flags = BuildDescriptionManager.REBUILD | BuildDescriptionManager.REMOVED | BuildDescriptionManager.DEPS; // delta = getDelta(currentProject); // } - boolean buildIncrementaly = delta != null; - // Get a build console for the project - StringBuffer buf = new StringBuffer(); + ICConfigurationDescription cfgDescription = ManagedBuildManager.getDescriptionForConfiguration(configuration); + + // Prepare launch parameters for BuildRunnerHelper + String cfgName = configuration.getName(); + String toolchainName = configuration.getToolChain().getName(); + boolean isConfigurationSupported = configuration.isSupported(); + + URI workingDirectoryURI = ManagedBuildManager.getBuildLocationURI(configuration, builder); + + String[] errorParsers = builder.getErrorParsers(); + ErrorParserManager epm = new ErrorParserManager(project, workingDirectoryURI, markerGenerator, errorParsers); + + List parsers = new ArrayList(); + ManagedBuildManager.collectLanguageSettingsConsoleParsers(cfgDescription, parsers); + + buildRunnerHelper.prepareStreams(epm, parsers, console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); IBuildDescription des = BuildDescriptionManager.createBuildDescription(configuration, cBS, delta, flags); - - IPath workingDirectory = des.getDefaultBuildDirLocation(); - String[] env = null; - if (des instanceof BuildDescription) { - Map envMap = ((BuildDescription)des).getEnvironment(); - env = mapToStringArray(envMap); - } - - consoleOutStream = console.getOutputStream(); - String[] consoleHeader = new String[3]; - if(buildIncrementaly) - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_INC); - else - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_REBUILD); - - consoleHeader[1] = configuration.getName(); - consoleHeader[2] = project.getName(); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append(ManagedMakeMessages.getFormattedString(CONSOLE_HEADER, consoleHeader)); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - - buf.append(ManagedMakeMessages.getResourceString(INTERNAL_BUILDER_HEADER_NOTE)); - buf.append("\n"); //$NON-NLS-1$ - - if(!configuration.isSupported()){ - buf.append(ManagedMakeMessages.getFormattedString(WARNING_UNSUPPORTED_CONFIGURATION, - new String[] { configuration.getName(), configuration.getToolChain().getName()})); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - } - - if (kind!=IncrementalProjectBuilder.CLEAN_BUILD) { - // TODO - AG - sanity check? elaborate - ICConfigurationDescription cfgDescription = ManagedBuildManager.getDescriptionForConfiguration(configuration); - if (cfgDescription instanceof ILanguageSettingsProvidersKeeper) { - List providers = ((ILanguageSettingsProvidersKeeper) cfgDescription).getLanguageSettingProviders(); - for (ILanguageSettingsProvider provider : providers) { - if (provider instanceof AbstractBuildCommandParser) { - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - String msg = ManagedMakeMessages.getFormattedString("BOP Language Settings Provider [{0}] is not supported by Internal Builder.", provider.getName()); - buf.append("**** "+msg+" ****"); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - - ManagedBuilderCorePlugin.error(msg); - } - } - } - } - - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - DescriptionBuilder dBuilder = null; - if (!isParallel) + if (!isParallel) { dBuilder = new DescriptionBuilder(des, buildIncrementaly, resumeOnErr, cBS); - - if(isParallel || dBuilder.getNumCommands() > 0) { - // Remove all markers for this project - IWorkspace workspace = project.getWorkspace(); - IMarker[] markers = project.findMarkers(ICModelMarker.C_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE); - if (markers != null) - workspace.deleteMarkers(markers); - - // Hook up an error parser manager - String[] errorParsers = builder.getErrorParsers(); - ErrorParserManager epm = new ErrorParserManager(project, des.getDefaultBuildDirLocationURI(), markerGenerator, errorParsers); - epm.setOutputStream(consoleOutStream); - // This variable is necessary to ensure that the EPM stream stay open - // until we explicitly close it. See bug#123302. - epmOutputStream = epm.getOutputStream(); - - int status = 0; - - long t1 = System.currentTimeMillis(); - if (isParallel) - status = ParallelBuilder.build(des, null, null, epmOutputStream, epmOutputStream, monitor, resumeOnErr, buildIncrementaly); - else - status = dBuilder.build(epmOutputStream, epmOutputStream, monitor); - long t2 = System.currentTimeMillis(); - - // Report either the success or failure of our mission - buf = new StringBuffer(); - - switch(status){ - case IBuildModelBuilder.STATUS_OK: - buf.append(ManagedMakeMessages - .getFormattedString(BUILD_FINISHED, - project.getName())); - break; - case IBuildModelBuilder.STATUS_CANCELLED: - buf.append(ManagedMakeMessages - .getResourceString(BUILD_CANCELLED)); - break; - case IBuildModelBuilder.STATUS_ERROR_BUILD: - String msg = resumeOnErr ? - ManagedMakeMessages.getResourceString(BUILD_FINISHED_WITH_ERRS) : - ManagedMakeMessages.getResourceString(BUILD_STOPPED_ERR); - buf.append(msg); - break; - case IBuildModelBuilder.STATUS_ERROR_LAUNCH: - default: - buf.append(ManagedMakeMessages.getResourceString(BUILD_FAILED_ERR)); - break; + if (dBuilder.getNumCommands() <= 0) { + buildRunnerHelper.printLine(ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.no.build", project.getName())); //$NON-NLS-1$ + return false; } - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$//$NON-NLS-2$ + } - // Report time and number of threads used - buf.append(ManagedMakeMessages.getFormattedString("CommonBuilder.6", Integer.toString((int)(t2 - t1)))); //$NON-NLS-1$ -// buf.append(t2 - t1); -// buf.append(" ms. "); - if (isParallel) { - buf.append(ManagedMakeMessages.getFormattedString("CommonBuilder.7", Integer.toString(ParallelBuilder.lastThreadsUsed))); //$NON-NLS-1$ -// buf.append(ParallelBuilder.lastThreadsUsed); - } - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - // Write message on the console - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - epmOutputStream.close(); - epmOutputStream = null; + buildRunnerHelper.removeOldMarkers(project, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); - // Generate any error markers that the build has discovered - monitor.subTask(ManagedMakeMessages.getResourceString(MARKERS)); - - bsMngr.setProjectBuildState(project, pBS); + if (buildIncrementaly) { + buildRunnerHelper.greeting(IncrementalProjectBuilder.INCREMENTAL_BUILD, cfgName, toolchainName, isConfigurationSupported); } else { - buf = new StringBuffer(); - buf.append(ManagedMakeMessages.getFormattedString(NOTHING_BUILT, project.getName())); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$//$NON-NLS-2$ - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); + buildRunnerHelper.greeting(ManagedMakeMessages.getResourceString("ManagedMakeBuider.type.rebuild"), cfgName, toolchainName, isConfigurationSupported); //$NON-NLS-1$ + } + buildRunnerHelper.printLine(ManagedMakeMessages.getResourceString("ManagedMakeBuilder.message.internal.builder.header.note")); //$NON-NLS-1$ + + OutputStream stdout = buildRunnerHelper.getOutputStream(); + OutputStream stderr = buildRunnerHelper.getErrorStream(); + + int status; + if (dBuilder != null) { + status = dBuilder.build(stdout, stderr, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); + } else { + status = ParallelBuilder.build(des, null, null, stdout, stderr, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK), resumeOnErr, buildIncrementaly); + buildRunnerHelper.printLine(ManagedMakeMessages.getFormattedString("CommonBuilder.7", Integer.toString(ParallelBuilder.lastThreadsUsed))); //$NON-NLS-1$ + } + + bsMngr.setProjectBuildState(project, pBS); + + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); + + if (status != ICommandLauncher.ILLEGAL_COMMAND) { + buildRunnerHelper.refreshProject(monitor); } } catch (Exception e) { - if(consoleOutStream != null){ - StringBuffer buf = new StringBuffer(); - String errorDesc = ManagedMakeMessages - .getResourceString(BUILD_ERROR); - buf.append(errorDesc); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$//$NON-NLS-2$ - buf.append(e.getLocalizedMessage()); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$//$NON-NLS-2$ - - try { - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - } catch (IOException e1) { - } - } projectBuilder.forgetLastBuiltState(); + + String msg = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.error.build", //$NON-NLS-1$ + new String[] { project.getName(), configuration.getName() }); + throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, msg, e)); } finally { - if(epmOutputStream != null){ - try { - epmOutputStream.close(); - } catch (IOException e) { - } - } - if(consoleOutStream != null){ - try { - consoleOutStream.close(); - } catch (IOException e) { - } + try { + buildRunnerHelper.close(); + } catch (IOException e) { + ManagedBuilderCorePlugin.log(e); } monitor.done(); } + return false; } } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/ManagedBuildManager.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/ManagedBuildManager.java index 12ad3f2750a..955e07858e7 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/ManagedBuildManager.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/ManagedBuildManager.java @@ -49,6 +49,11 @@ import javax.xml.transform.stream.StreamResult; import org.eclipse.cdt.core.AbstractCExtension; import org.eclipse.cdt.core.CCorePlugin; +import org.eclipse.cdt.core.ICConsoleParser; +import org.eclipse.cdt.core.IConsoleParser; +import org.eclipse.cdt.core.language.settings.providers.ILanguageSettingsProvider; +import org.eclipse.cdt.core.language.settings.providers.ILanguageSettingsProvidersKeeper; +import org.eclipse.cdt.core.language.settings.providers.LanguageSettingsManager; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.CoreModelUtil; import org.eclipse.cdt.core.parser.IScannerInfo; @@ -4720,4 +4725,24 @@ public class ManagedBuildManager extends AbstractCExtension { return true; // no target platform - nothing to check. } + /*package*/ static void collectLanguageSettingsConsoleParsers(ICConfigurationDescription cfgDescription, List parsers) { + if (cfgDescription instanceof ILanguageSettingsProvidersKeeper) { + List lsProviders = ((ILanguageSettingsProvidersKeeper) cfgDescription).getLanguageSettingProviders(); + for (ILanguageSettingsProvider lsProvider : lsProviders) { + ILanguageSettingsProvider rawProvider = LanguageSettingsManager.getRawProvider(lsProvider); + if (rawProvider instanceof ICConsoleParser) { + ICConsoleParser consoleParser = (ICConsoleParser) rawProvider; + try { + consoleParser.startup(cfgDescription); + parsers.add(consoleParser); + } catch (CoreException e) { + ManagedBuilderCorePlugin.log(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, + "Language Settings Provider failed to start up", e)); //$NON-NLS-1$ + } + } + } + } + + } + } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/buildmodel/CommandBuilder.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/buildmodel/CommandBuilder.java index f4fbfd0244a..712027a2a1d 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/buildmodel/CommandBuilder.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/buildmodel/CommandBuilder.java @@ -21,8 +21,13 @@ import java.util.Set; import org.eclipse.cdt.core.CommandLauncher; import org.eclipse.cdt.core.ICommandLauncher; import org.eclipse.cdt.managedbuilder.buildmodel.IBuildCommand; +import org.eclipse.cdt.managedbuilder.core.ManagedBuilderCorePlugin; +import org.eclipse.cdt.managedbuilder.internal.core.ManagedMakeMessages; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; /** @@ -36,7 +41,6 @@ import org.eclipse.core.runtime.SubProgressMonitor; * */ public class CommandBuilder implements IBuildModelBuilder { - private static final String PATH_ENV = "PATH"; //$NON-NLS-1$ private static final String NEWLINE = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ private IBuildCommand fCmd; @@ -84,67 +88,57 @@ public class CommandBuilder implements IBuildModelBuilder { return new OutputStreamWrapper(out); } - /* (non-Javadoc) - * @see org.eclipse.cdt.managedbuilder.internal.builddescription.IBuildDescriptionBuilder#build(java.io.OutputStream, java.io.OutputStream, org.eclipse.core.runtime.IProgressMonitor) - */ @Override - public int build(OutputStream out, OutputStream err, IProgressMonitor monitor){ - //TODO: should we display the command line here? - monitor.beginTask("", getNumCommands()); //$NON-NLS-1$ - monitor.subTask(""/*getCommandLine()*/); //$NON-NLS-1$ - - ICommandLauncher launcher = createLauncher(); - int status = STATUS_OK; - - launcher.showCommand(true); + public int build(OutputStream out, OutputStream err, IProgressMonitor monitor) { + int status = STATUS_ERROR_LAUNCH; try { - fProcess = launcher.execute(fCmd.getCommand(), fCmd.getArgs(), mapToStringArray(fCmd.getEnvironment()), fCmd.getCWD(), monitor); - } catch (CoreException e1) { - // TODO Auto-generated catch block - if(DbgUtil.DEBUG) - DbgUtil.trace("Error launching command: " + e1.getMessage()); //$NON-NLS-1$ - monitor.done(); - return STATUS_ERROR_LAUNCH; - } - - int st = ICommandLauncher.ILLEGAL_COMMAND; - if (fProcess != null) { - try { - // Close the input of the process since we will never write to it - fProcess.getOutputStream().close(); - } catch (IOException e) { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + monitor.beginTask("", getNumCommands()); //$NON-NLS-1$ + monitor.subTask(ManagedMakeMessages.getResourceString("MakeBuilder.Invoking_Command") + getCommandLine()); //$NON-NLS-1$ + + ICommandLauncher launcher = createLauncher(); + launcher.showCommand(true); + + fProcess = launcher.execute(fCmd.getCommand(), fCmd.getArgs(), mapToStringArray(fCmd.getEnvironment()), fCmd.getCWD(), monitor); + if (fProcess != null) { + try { + // Close the input of the process since we will never write to it + fProcess.getOutputStream().close(); + } catch (IOException e) { + } + + // Wrapping out and err streams to avoid their closure + int st = launcher.waitAndRead(wrap(out), wrap(err), new SubProgressMonitor(monitor, getNumCommands())); + switch (st) { + case ICommandLauncher.OK: + // assuming that compiler returns error code after compilation errors + status = fProcess.exitValue() == 0 ? STATUS_OK : STATUS_ERROR_BUILD; + break; + case ICommandLauncher.COMMAND_CANCELED: + status = STATUS_CANCELLED; + break; + case ICommandLauncher.ILLEGAL_COMMAND: + default: + status = STATUS_ERROR_LAUNCH; + break; + } } - //wrapping out and err streams to avoid their closure - st = launcher.waitAndRead(wrap(out), wrap(err), - new SubProgressMonitor(monitor, getNumCommands())); - } - switch(st){ - case ICommandLauncher.OK: - if(fProcess.exitValue() != 0) - status = STATUS_ERROR_BUILD; - break; - case ICommandLauncher.COMMAND_CANCELED: - status = STATUS_CANCELLED; fErrMsg = launcher.getErrorMessage(); - if(DbgUtil.DEBUG) - DbgUtil.trace("command cancelled: " + fErrMsg); //$NON-NLS-1$ - - printMessage(fErrMsg, out); - break; - case ICommandLauncher.ILLEGAL_COMMAND: - default: + if (fErrMsg != null && !fErrMsg.isEmpty()) { + printMessage(fErrMsg, err); + } + } catch (CoreException e) { + ManagedBuilderCorePlugin.log(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, + "Error launching command [" + fCmd.getCommand() + "]", e)); //$NON-NLS-1$ //$NON-NLS-2$ status = STATUS_ERROR_LAUNCH; - fErrMsg = launcher.getErrorMessage(); - if(DbgUtil.DEBUG) - DbgUtil.trace("error launching the command: " + fErrMsg); //$NON-NLS-1$ - - printMessage(fErrMsg, out); - break; + } finally { + monitor.done(); } - monitor.done(); return status; } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/CommonBuilder.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/CommonBuilder.java index df8e4642d52..5de00741f99 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/CommonBuilder.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/CommonBuilder.java @@ -15,6 +15,8 @@ package org.eclipse.cdt.managedbuilder.internal.core; import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -25,12 +27,15 @@ import java.util.Set; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.ConsoleOutputStream; +import org.eclipse.cdt.core.ErrorParserManager; +import org.eclipse.cdt.core.ICommandLauncher; import org.eclipse.cdt.core.ProblemMarkerInfo; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.resources.ACBuilder; import org.eclipse.cdt.core.resources.IConsole; import org.eclipse.cdt.core.settings.model.ICProjectDescription; import org.eclipse.cdt.core.settings.model.util.ListComparator; +import org.eclipse.cdt.internal.core.BuildRunnerHelper; import org.eclipse.cdt.managedbuilder.buildmodel.BuildDescriptionManager; import org.eclipse.cdt.managedbuilder.buildmodel.IBuildDescription; import org.eclipse.cdt.managedbuilder.buildmodel.IBuildStep; @@ -76,14 +81,11 @@ import org.eclipse.core.runtime.jobs.Job; public class CommonBuilder extends ACBuilder { public final static String BUILDER_ID = ManagedBuilderCorePlugin.getUniqueIdentifier() + ".genmakebuilder"; //$NON-NLS-1$ - private static final String BUILD_FINISHED = "ManagedMakeBuilder.message.finished"; //$NON-NLS-1$ - private static final String CONSOLE_HEADER = "ManagedMakeBuilder.message.console.header"; //$NON-NLS-1$ private static final String ERROR_HEADER = "GeneratedmakefileBuilder error ["; //$NON-NLS-1$ private static final String NEWLINE = System.getProperty("line.separator"); //$NON-NLS-1$ private static final String TRACE_FOOTER = "]: "; //$NON-NLS-1$ private static final String TRACE_HEADER = "GeneratedmakefileBuilder trace ["; //$NON-NLS-1$ - private static final String TYPE_CLEAN = "ManagedMakeBuilder.type.clean"; //$NON-NLS-1$ - private static final String TYPE_INC = "ManagedMakeBuider.type.incremental"; //$NON-NLS-1$ + private static final int MONITOR_SCALE = 100; public static boolean VERBOSE = false; private static CfgBuildSet fBuildSet = new CfgBuildSet(); @@ -806,7 +808,7 @@ public class CommonBuilder extends ACBuilder { String configName = bInfo.getConfiguration().getName(); String projName = bInfo.getProject().getName(); if (buildType == FULL_BUILD || buildType == INCREMENTAL_BUILD) { - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_INC); + consoleHeader[0] = ManagedMakeMessages.getResourceString("ManagedMakeBuider.type.incremental"); //$NON-NLS-1$ } else { consoleHeader[0] = new String(); outputError(projName, "The given build type is not supported in this context"); //$NON-NLS-1$ @@ -814,7 +816,7 @@ public class CommonBuilder extends ACBuilder { consoleHeader[1] = configName; consoleHeader[2] = projName; buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append(ManagedMakeMessages.getFormattedString(CONSOLE_HEADER, consoleHeader)); + buf.append(ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.console.header", consoleHeader)); //$NON-NLS-1$ buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ buf.append(status.getMessage()); @@ -1167,73 +1169,82 @@ public class CommonBuilder extends ACBuilder { protected void cleanWithInternalBuilder(CfgBuildInfo bInfo, IProgressMonitor monitor) throws CoreException { // referencedProjects = getProject().getReferencedProjects(); - IProject curProject = bInfo.getProject(); - outputTrace(curProject.getName(), "Clean build with Internal Builder requested"); //$NON-NLS-1$ - IConfiguration cfg = bInfo.getConfiguration(); + IProject project = bInfo.getProject(); + outputTrace(project.getName(), "Clean build with Internal Builder requested"); //$NON-NLS-1$ + IConfiguration configuration = bInfo.getConfiguration(); int flags = BuildDescriptionManager.DEPFILES; - BuildDescription des = (BuildDescription)BuildDescriptionManager.createBuildDescription(cfg, null, null, flags); + BuildDescription des = (BuildDescription)BuildDescriptionManager.createBuildDescription(configuration, null, null, flags); IBuildStep cleanStep = des.getCleanStep(); StepBuilder sBuilder = new StepBuilder(cleanStep, null, null); + BuildRunnerHelper buildRunnerHelper = new BuildRunnerHelper(project); try { - // try the brute force approach first - StringBuffer buf = new StringBuffer(); - // write to the console -// -// IConsole console = CCorePlugin.getDefault().getConsole(); -// console.start(getProject()); - IConsole console = bInfo.getConsole(); - ConsoleOutputStream consoleOutStream = console.getOutputStream(); - String[] consoleHeader = new String[3]; - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_CLEAN); - consoleHeader[1] = cfg.getName(); - consoleHeader[2] = curProject.getName(); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append(ManagedMakeMessages.getFormattedString(CONSOLE_HEADER, consoleHeader)); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - buf = new StringBuffer(); - int result = sBuilder.build(consoleOutStream, consoleOutStream, monitor); - //Throw a core exception indicating that the clean command failed - if(result == IBuildModelBuilder.STATUS_ERROR_LAUNCH) - { - try { - consoleOutStream.close(); - } catch (IOException e) { - } - Status status = new Status(IStatus.INFO, ManagedBuilderCorePlugin.getUniqueIdentifier(), - "Failed to exec delete command"); //$NON-NLS-1$ - throw new CoreException(status); + if (monitor == null) { + monitor = new NullProgressMonitor(); } - // Report a successful clean - String successMsg = ManagedMakeMessages.getFormattedString(BUILD_FINISHED, curProject.getName()); - buf.append(successMsg); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$//$NON-NLS-2$ - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - consoleOutStream.close(); - curProject.refreshLocal(IResource.DEPTH_INFINITE, null); - } catch (IOException io) {} // Ignore console failures... + monitor.beginTask("", 2 * MONITOR_SCALE); //$NON-NLS-1$ + + IConsole console = bInfo.getConsole(); + + IBuilder builder = bInfo.getBuilder(); + String[] errorParsers = builder.getErrorParsers(); + URI workingDirectoryURI = ManagedBuildManager.getBuildLocationURI(configuration, builder); + ErrorParserManager epm = new ErrorParserManager(project, workingDirectoryURI, this, errorParsers); + + buildRunnerHelper.prepareStreams(epm, null, console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); + OutputStream stdout = buildRunnerHelper.getOutputStream(); + OutputStream stderr = buildRunnerHelper.getErrorStream(); + + String cfgName = configuration.getName(); + String toolchainName = configuration.getToolChain().getName(); + boolean isConfigurationSupported = configuration.isSupported(); + + buildRunnerHelper.greeting(CLEAN_BUILD, cfgName, toolchainName, isConfigurationSupported); + int status = sBuilder.build(stdout, stderr, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); + + if (status != ICommandLauncher.ILLEGAL_COMMAND) { + buildRunnerHelper.refreshProject(monitor); + } + + //Throw a core exception indicating that the clean command failed + if(status == IBuildModelBuilder.STATUS_ERROR_LAUNCH) + { + Status st = new Status(IStatus.INFO, ManagedBuilderCorePlugin.PLUGIN_ID, "Failed to execute delete command"); //$NON-NLS-1$ + throw new CoreException(st); + } + } catch (Exception e) { + String msg = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.error.build", //$NON-NLS-1$ + new String[] { project.getName(), configuration.getName() }); + throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, msg, e)); + } finally { + try { + buildRunnerHelper.close(); + } catch (IOException e) { + ManagedBuilderCorePlugin.log(e); + } + monitor.done(); + } } protected void cleanProgrammatically(CfgBuildInfo bInfo, IProgressMonitor monitor) throws CoreException { // referencedProjects = getProject().getReferencedProjects(); - IProject curProject = bInfo.getProject(); - outputTrace(curProject.getName(), "Clean build requested"); //$NON-NLS-1$ + IProject project = bInfo.getProject(); + outputTrace(project.getName(), "Clean build requested"); //$NON-NLS-1$ IBuilder builder = bInfo.getBuilder(); - IConfiguration cfg = bInfo.getConfiguration(); - IPath buildPath = ManagedBuildManager.getBuildFullPath(cfg, builder); + IConfiguration configuration = bInfo.getConfiguration(); + IPath buildPath = ManagedBuildManager.getBuildFullPath(configuration, builder); if(buildPath == null){ throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.getUniqueIdentifier(), ManagedMakeMessages.getResourceString("CommonBuilder.0"))); //$NON-NLS-1$ } - IPath projectFullPath = curProject.getFullPath(); + IPath projectFullPath = project.getFullPath(); if(!projectFullPath.isPrefixOf(buildPath)){ throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.getUniqueIdentifier(), @@ -1256,37 +1267,47 @@ public class CommonBuilder extends ACBuilder { ManagedBuilderCorePlugin.getUniqueIdentifier(), ManagedMakeMessages.getResourceString("CommonBuilder.13"))); //$NON-NLS-1$ } - String status; - try { - // try the brute force approach first - status = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.clean.deleting.output", buildDir.getName()); //$NON-NLS-1$ - monitor.subTask(status); - workspace.delete(new IResource[]{buildDir}, true, monitor); - StringBuffer buf = new StringBuffer(); - // write to the console -// -// IConsole console = CCorePlugin.getDefault().getConsole(); -// console.start(getProject()); - IConsole console = bInfo.getConsole(); - ConsoleOutputStream consoleOutStream = console.getOutputStream(); - String[] consoleHeader = new String[3]; - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_CLEAN); - consoleHeader[1] = cfg.getName(); - consoleHeader[2] = curProject.getName(); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append(ManagedMakeMessages.getFormattedString(CONSOLE_HEADER, consoleHeader)); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - buf = new StringBuffer(); - // Report a successful clean - String successMsg = ManagedMakeMessages.getFormattedString(BUILD_FINISHED, curProject.getName()); - buf.append(successMsg); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$//$NON-NLS-2$ - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - consoleOutStream.close(); - } catch (IOException io) {} // Ignore console failures... + + BuildRunnerHelper buildRunnerHelper = new BuildRunnerHelper(project); + try { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + monitor.beginTask("", 2 * MONITOR_SCALE); //$NON-NLS-1$ + + // try the brute force approach first + String status = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.clean.deleting.output", buildDir.getName()); //$NON-NLS-1$ + monitor.subTask(status); + + IConsole console = bInfo.getConsole(); + + String[] errorParsers = builder.getErrorParsers(); + URI workingDirectoryURI = ManagedBuildManager.getBuildLocationURI(configuration, builder); + ErrorParserManager epm = new ErrorParserManager(project, workingDirectoryURI, this, errorParsers); + + buildRunnerHelper.prepareStreams(epm, null, console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); + + String cfgName = configuration.getName(); + String toolchainName = configuration.getToolChain().getName(); + boolean isConfigurationSupported = configuration.isSupported(); + + buildRunnerHelper.greeting(CLEAN_BUILD, cfgName, toolchainName, isConfigurationSupported); + workspace.delete(new IResource[]{buildDir}, true, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); + + } catch (Exception e) { + String msg = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.error.build", //$NON-NLS-1$ + new String[] { project.getName(), configuration.getName() }); + throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, msg, e)); + } finally { + try { + buildRunnerHelper.close(); + } catch (IOException e) { + ManagedBuilderCorePlugin.log(e); + } + monitor.done(); + } } } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/GeneratedMakefileBuilder.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/GeneratedMakefileBuilder.java index 1650ca25c24..6c55b220bee 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/GeneratedMakefileBuilder.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/GeneratedMakefileBuilder.java @@ -15,6 +15,7 @@ import java.io.OutputStream; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; @@ -31,6 +32,7 @@ import org.eclipse.cdt.core.model.ICModelMarker; import org.eclipse.cdt.core.resources.ACBuilder; import org.eclipse.cdt.core.resources.IConsole; import org.eclipse.cdt.core.resources.RefreshScopeManager; +import org.eclipse.cdt.internal.core.BuildRunnerHelper; import org.eclipse.cdt.managedbuilder.buildmodel.BuildDescriptionManager; import org.eclipse.cdt.managedbuilder.buildmodel.IBuildDescription; import org.eclipse.cdt.managedbuilder.buildmodel.IBuildIOType; @@ -307,6 +309,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { private static final String INTERNAL_BUILDER_HEADER_NOTE = "ManagedMakeBuilder.message.internal.builder.header.note"; //$NON-NLS-1$ private static final String TYPE_REBUILD = "ManagedMakeBuider.type.rebuild"; //$NON-NLS-1$ private static final String INTERNAL_BUILDER = "ManagedMakeBuilder.message.internal.builder"; //$NON-NLS-1$ + private static final int MONITOR_SCALE = 100; public static boolean VERBOSE = false; // Local variables @@ -314,7 +317,6 @@ public class GeneratedMakefileBuilder extends ACBuilder { protected IProject[] referencedProjects; protected List resourcesToBuild; private IConsole console; - private ConsoleOutputStream consoleOutStream; public static void outputTrace(String resourceName, String message) { if (VERBOSE) { System.out.println(TRACE_HEADER + resourceName + TRACE_FOOTER + message + NEWLINE); @@ -864,7 +866,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { */ protected void invokeMake(int buildType, IPath buildDir, IManagedBuildInfo info, IManagedBuilderMakefileGenerator generator, IProgressMonitor monitor) { // Get the project and make sure there's a monitor to cancel the build - IProject currentProject = getProject(); + IProject project = getProject(); if (monitor == null) { monitor = new NullProgressMonitor(); } @@ -879,7 +881,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { IPath workingDirectory = new Path(pathFromURI); - IWorkspace workspace = currentProject.getWorkspace(); + IWorkspace workspace = project.getWorkspace(); if (workspace == null) { return; } @@ -910,13 +912,13 @@ public class GeneratedMakefileBuilder extends ACBuilder { IPath makeCommand = new Path(makeCmd); String[] msgs = new String[2]; msgs[0] = makeCommand.toString(); - msgs[1] = currentProject.getName(); + msgs[1] = project.getName(); monitor.subTask(ManagedMakeMessages.getFormattedString(MAKE, msgs)); // Get a build console for the project StringBuffer buf = new StringBuffer(); IConsole console = CCorePlugin.getDefault().getConsole(); - console.start(currentProject); + console.start(project); ConsoleOutputStream consoleOutStream = console.getOutputStream(); String[] consoleHeader = new String[3]; switch (buildType) { @@ -930,7 +932,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { } consoleHeader[1] = info.getConfigurationName(); - consoleHeader[2] = currentProject.getName(); + consoleHeader[2] = project.getName(); buf.append(NEWLINE); buf.append(ManagedMakeMessages.getFormattedString(CONSOLE_HEADER, consoleHeader)).append(NEWLINE); buf.append(NEWLINE); @@ -945,24 +947,24 @@ public class GeneratedMakefileBuilder extends ACBuilder { consoleOutStream.flush(); // Remove all markers for this project - removeAllMarkers(currentProject); + removeAllMarkers(project); // Get a launcher for the make command String errMsg = null; IBuilder builder = info.getDefaultConfiguration().getBuilder(); ICommandLauncher launcher = builder.getCommandLauncher(); - launcher.setProject(currentProject); + launcher.setProject(project); launcher.showCommand(true); // Set the environmennt IBuildEnvironmentVariable variables[] = ManagedBuildManager.getEnvironmentVariableProvider().getVariables(cfg,true,true); - String[] env = null; + String[] envp = null; ArrayList envList = new ArrayList(); if (variables != null) { for(int i = 0; i < variables.length; i++){ envList.add(variables[i].getName() + "=" + variables[i].getValue()); //$NON-NLS-1$ } - env = envList.toArray(new String[envList.size()]); + envp = envList.toArray(new String[envList.size()]); } // Hook up an error parser manager @@ -1014,7 +1016,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { premakeArgs.add("-q"); //$NON-NLS-1$ premakeArgs.add("main-build"); //$NON-NLS-1$ premakeTargets = premakeArgs.toArray(new String[premakeArgs.size()]); - proc = launcher.execute(makeCommand, premakeTargets, env, workingDirectory, monitor); + proc = launcher.execute(makeCommand, premakeTargets, envp, workingDirectory, monitor); if (proc != null) { try { // Close the input of the process since we will never write to it @@ -1041,7 +1043,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { // If the status value returned from "make -q" is 0, then the build state is up-to-date isuptodate = true; // Report that the build was up to date, and thus nothing needs to be built - String uptodateMsg = ManagedMakeMessages.getFormattedString(NOTHING_BUILT, currentProject.getName()); + String uptodateMsg = ManagedMakeMessages.getFormattedString(NOTHING_BUILT, project.getName()); buf = new StringBuffer(); buf.append(NEWLINE); buf.append(uptodateMsg).append(NEWLINE); @@ -1080,7 +1082,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { // Launch make - main invocation if (!isuptodate) { - proc = launcher.execute(makeCommand, makeTargets, env, workingDirectory, monitor); + proc = launcher.execute(makeCommand, makeTargets, envp, workingDirectory, monitor); if (proc != null) { try { // Close the input of the process since we will never write to it @@ -1112,7 +1114,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { // use the refresh scope manager to refresh RefreshScopeManager refreshManager = RefreshScopeManager.getInstance(); - IWorkspaceRunnable runnable = refreshManager.getRefreshRunnable(currentProject); + IWorkspaceRunnable runnable = refreshManager.getRefreshRunnable(project); ResourcesPlugin.getWorkspace().run(runnable, null, IWorkspace.AVOID_UPDATE, null); } catch (CoreException e) { monitor.subTask(ManagedMakeMessages @@ -1129,7 +1131,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { } else { // Report a successful build String successMsg = ManagedMakeMessages.getFormattedString(BUILD_FINISHED, - currentProject.getName()); + project.getName()); buf.append(successMsg).append(NEWLINE); } @@ -1367,330 +1369,280 @@ public class GeneratedMakefileBuilder extends ACBuilder { } } - /** - * Called to invoke the MBS Internal Builder for building the given resources in - * the given configuration - * - * This method is considered experimental. Clients implementing this API should expect - * possible changes in the API. - * - * @param resourcesToBuild resources to be built - * @param cfg configuration to be built - * @param buildIncrementaly if true, incremental build will be performed, - * only files that need rebuild will be built. - * If false, full rebuild will be performed - * @param resumeOnErr if true, build will continue in case of error while building. - * If false the build will stop on the first error - * @param monitor Progress monitor. For every resource built this monitor will consume one unit of work. - */ - public void invokeInternalBuilder(IResource[] resourcesToBuild, IConfiguration cfg, - boolean buildIncrementaly, - boolean resumeOnErr, - boolean initNewConsole, - boolean printFinishedMessage, - IProgressMonitor monitor) { + private Map> arrangeFilesByProject(List files) { + Map> projectMap = new HashMap>(); + for (IFile file : files) { + IProject project = file.getProject(); + List filesInProject = projectMap.get(project); + if (filesInProject == null) { + filesInProject = new ArrayList(); + projectMap.put(project, filesInProject); + } + filesInProject.add(file); + } + return projectMap; + } - OutputStream epmOutputStream = null; - // Get the project and make sure there's a monitor to cancel the build - IProject currentProject = cfg.getOwner().getProject(); + /** + * Called to invoke the MBS Internal Builder for building the given resources + * + * @param files - list of files to build. + * @param monitor - progress monitor to report progress to user. + * @return status of the operation. Can be {@link Status#OK_STATUS} or + * {@link Status#CANCEL_STATUS}. + */ + public IStatus invokeInternalBuilder(List files, IProgressMonitor monitor) { + // Make sure there's a monitor to cancel the build if (monitor == null) { monitor = new NullProgressMonitor(); } try { - int flags = 0; - IResourceDelta delta = null; + Map> projectMap = arrangeFilesByProject(files); + monitor.beginTask("", projectMap.size() * MONITOR_SCALE); //$NON-NLS-1$ - if(buildIncrementaly){ - flags = BuildDescriptionManager.REBUILD | BuildDescriptionManager.REMOVED | BuildDescriptionManager.DEPS; - delta = getDelta(currentProject); + for (List filesInProject : projectMap.values()) { + IProject project = filesInProject.get(0).getProject(); + monitor.subTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.buildingProject", project.getName())); //$NON-NLS-1$ + invokeInternalBuilderForOneProject(filesInProject, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); } + } finally { + if (monitor.isCanceled()) { + return Status.CANCEL_STATUS; + } + monitor.done(); + } + return Status.OK_STATUS; + } + private void invokeInternalBuilderForOneProject(List files, IProgressMonitor monitor) { + IProject project = files.get(0).getProject(); + BuildRunnerHelper buildRunnerHelper = new BuildRunnerHelper(project); - String[] msgs = new String[2]; - msgs[0] = ManagedMakeMessages.getResourceString(INTERNAL_BUILDER); - msgs[1] = currentProject.getName(); + try { + monitor.beginTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.buildingProject", project.getName()) + ':', files.size() * MONITOR_SCALE); //$NON-NLS-1$ - if(initNewConsole) - initNewBuildConsole(currentProject); + // Get a build console for the project + console = CCorePlugin.getDefault().getConsole(); + console.start(project); - StringBuffer buf = new StringBuffer(); + IManagedBuildInfo buildInfo = ManagedBuildManager.getBuildInfo(project); + IConfiguration configuration = buildInfo.getDefaultConfiguration(); - if (initNewConsole) { - String msg; - if (buildIncrementaly) { - msg = ManagedMakeMessages.getResourceString("GeneratedMakefileBuilder.buildSelectedIncremental"); //$NON-NLS-1$ - } else { - msg = ManagedMakeMessages.getResourceString("GeneratedMakefileBuilder.buildSelectedRebuild"); //$NON-NLS-1$ + String cfgName = configuration.getName(); + String toolchainName = configuration.getToolChain().getName(); + boolean isSupported = configuration.isSupported(); + + IBuildDescription des = BuildDescriptionManager.createBuildDescription(configuration, null, 0); + + String[] errorParsers = configuration.getErrorParserList(); + ErrorParserManager epm = new ErrorParserManager(project, des.getDefaultBuildDirLocationURI(), this, errorParsers); + + buildRunnerHelper.prepareStreams(epm, null, console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); + OutputStream stdout = buildRunnerHelper.getOutputStream(); + OutputStream stderr = buildRunnerHelper.getErrorStream(); + + buildRunnerHelper.greeting(ManagedMakeMessages.getResourceString("BuildFilesAction.buildingSelectedFiles"), cfgName, toolchainName, isSupported); //$NON-NLS-1$ + buildRunnerHelper.printLine(ManagedMakeMessages.getResourceString("ManagedMakeBuilder.message.internal.builder.header.note")); //$NON-NLS-1$ + + // Build artifacts for each file in the project + for (IFile file : files) { + if (monitor.isCanceled()) { + break; } - - buf.append(msg).append(NEWLINE); - buf.append(NEWLINE); - - buf.append(ManagedMakeMessages.getResourceString(INTERNAL_BUILDER_HEADER_NOTE)).append(NEWLINE); - } - - if(!cfg.isSupported()){ - String msg = ManagedMakeMessages.getFormattedString(WARNING_UNSUPPORTED_CONFIGURATION,new String[] {cfg.getName(),cfg.getToolChain().getName()}); - buf.append(msg).append(NEWLINE); - buf.append(NEWLINE); - } - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - - // Remove all markers for this project - // TODO remove only necessary markers - removeAllMarkers(currentProject); - - IBuildDescription des = BuildDescriptionManager.createBuildDescription(cfg, delta, flags); - - // Hook up an error parser manager - String[] errorParsers = cfg.getErrorParserList(); - ErrorParserManager epm = new ErrorParserManager(currentProject, des.getDefaultBuildDirLocationURI(), this, errorParsers); - epm.setOutputStream(consoleOutStream); - // This variable is necessary to ensure that the EPM stream stay open - // until we explicitly close it. See bug#123302. - epmOutputStream = epm.getOutputStream(); - - boolean errorsFound = false; - - doneBuild: for (int k = 0; k < resourcesToBuild.length; k++) { - IBuildResource buildResource = des - .getBuildResource(resourcesToBuild[k]); - -// step collector - Set dependentSteps = new HashSet(); - -// get dependent IO types - IBuildIOType depTypes[] = buildResource.getDependentIOTypes(); - -// iterate through each type and add the step the type belongs to to the collector - for(int j = 0; j < depTypes.length; j++){ - IBuildIOType type = depTypes[j]; - if(type != null && type.getStep() != null) - dependentSteps.add(type.getStep()); - } - - monitor.subTask(ManagedMakeMessages.getResourceString("GeneratedMakefileBuilder.buildingFile") + resourcesToBuild[k].getProjectRelativePath()); //$NON-NLS-1$ - - // iterate through all build steps - Iterator stepIter = dependentSteps.iterator(); - - while(stepIter.hasNext()) - { - IBuildStep step = stepIter.next(); - - StepBuilder stepBuilder = new StepBuilder(step, null); - - int status = stepBuilder.build(epmOutputStream, epmOutputStream, new SubProgressMonitor(monitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); - - // Refresh the output resource without allowing the user to cancel. - // This is probably unkind, but short of this there is no way to ensure - // the UI is up-to-date with the build results - IBuildIOType[] outputIOTypes = step.getOutputIOTypes(); - - for(int j = 0; j < outputIOTypes.length; j++ ) - { - IBuildResource[] resources = outputIOTypes[j].getResources(); - - for(int i = 0; i < resources.length; i++) - { - IFile file = currentProject.getFile(resources[i].getLocation()); - file.refreshLocal(IResource.DEPTH_INFINITE, null); - } - } - - // check status - - switch (status) { - case IBuildModelBuilder.STATUS_OK: - // don't print anything if the step was successful, - // since the build might not be done as a whole - break; - case IBuildModelBuilder.STATUS_CANCELLED: - buf.append(ManagedMakeMessages - .getResourceString(BUILD_CANCELLED)); - break doneBuild; - case IBuildModelBuilder.STATUS_ERROR_BUILD: - errorsFound = true; - if (!resumeOnErr) { - buf.append(ManagedMakeMessages - .getResourceString(BUILD_STOPPED_ERR)); - break doneBuild; - } - break; - case IBuildModelBuilder.STATUS_ERROR_LAUNCH: - default: - buf.append(ManagedMakeMessages - .getResourceString(BUILD_FAILED_ERR)); - break doneBuild; - } - } - - - } - - // check status - // Report either the success or failure of our mission - buf = new StringBuffer(); - - buf.append(NEWLINE); - - if (printFinishedMessage) { - if (errorsFound) { - buf.append(ManagedMakeMessages.getResourceString(BUILD_FAILED_ERR)); - } else { - buf.append(ManagedMakeMessages.getResourceString("GeneratedMakefileBuilder.buildResourcesFinished")); //$NON-NLS-1$ - } - } - - // Write message on the console - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - - // Generate any error markers that the build has discovered - addBuilderMarkers(epm); - } catch (Exception e) { - if(consoleOutStream != null){ - StringBuffer buf = new StringBuffer(); - String errorDesc = ManagedMakeMessages.getResourceString(BUILD_ERROR); - buf.append(errorDesc).append(NEWLINE); - buf.append("(").append(e.getLocalizedMessage()).append(")").append(NEWLINE); //$NON-NLS-1$ //$NON-NLS-2$ + String filePath = file.getProjectRelativePath().toString(); try { - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - } catch (IOException e1) { + IBuildResource buildResource = des.getBuildResource(file); + + Set dependentSteps = new HashSet(); + IBuildIOType depTypes[] = buildResource.getDependentIOTypes(); + for (IBuildIOType btype : depTypes) { + if(btype != null && btype.getStep() != null) + dependentSteps.add(btype.getStep()); + } + + SubProgressMonitor monitor2 = new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); + try { + monitor2.beginTask("", (1 + dependentSteps.size()) * MONITOR_SCALE); //$NON-NLS-1$ + + // Remove problem markers for the file + monitor2.subTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.removingResourceMarkers", filePath)); //$NON-NLS-1$ + buildRunnerHelper.removeOldMarkers(file, new SubProgressMonitor(monitor2, 1 * MONITOR_SCALE, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)); + + // Build dependent steps + for (IBuildStep step : dependentSteps) { + if (monitor2.isCanceled()) { + break; + } + + monitor2.subTask(filePath); + StepBuilder stepBuilder = new StepBuilder(step, null); + stepBuilder.build(stdout, stderr, new SubProgressMonitor(monitor2, 1 * MONITOR_SCALE, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)); + + monitor2.subTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.refreshingArtifacts", filePath)); //$NON-NLS-1$ + IBuildIOType[] outputIOTypes = step.getOutputIOTypes(); + for (IBuildIOType type : outputIOTypes) { + for (IBuildResource outResource : type.getResources()) { + IFile outFile = project.getFile(outResource.getLocation()); + // Refresh the output resource without allowing the user to cancel. + outFile.refreshLocal(IResource.DEPTH_INFINITE, null); + } + } + } + } finally { + monitor2.done(); + } + + } catch (Exception e) { + ManagedBuilderCorePlugin.log(new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "CDT Build Error", e))); //$NON-NLS-1$ } + } + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); + + } catch (Exception e) { + ManagedBuilderCorePlugin.log(new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "CDT Build Error", e))); //$NON-NLS-1$ forgetLastBuiltState(); } finally { - if(epmOutputStream != null){ - try { - epmOutputStream.close(); - } catch (IOException e) { - } - } - if(consoleOutStream != null){ - try { - consoleOutStream.close(); - } catch (IOException e) { - } - } getGenerationProblems().clear(); + try { + buildRunnerHelper.close(); + } catch (IOException e) { + ManagedBuilderCorePlugin.log(new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "CDT Build Error", e))); //$NON-NLS-1$ + } monitor.done(); } } - private void removeAllMarkers(IFile file) { - IMarker[] markers; + public IStatus cleanFiles(List files, IProgressMonitor monitor) { + // Make sure there's a monitor to cancel the build + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + try { - markers = file.findMarkers( - ICModelMarker.C_MODEL_PROBLEM_MARKER, true, - IResource.DEPTH_INFINITE); - } catch (CoreException e) { - // Handled just about every case in the sanity check - return; - } - if (markers != null) { - try { - file.getWorkspace().deleteMarkers(markers); - } catch (CoreException e) { - // The only situation that might cause this is some sort of - // resource change event - return; + Map> projectMap = arrangeFilesByProject(files); + monitor.beginTask("", projectMap.size() * MONITOR_SCALE); //$NON-NLS-1$ + + for (List filesInProject : projectMap.values()) { + IProject project = filesInProject.get(0).getProject(); + monitor.subTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.cleaningProject", project.getName())); //$NON-NLS-1$ + cleanFilesForOneProject(filesInProject, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); } + } finally { + if (monitor.isCanceled()) { + return Status.CANCEL_STATUS; + } + monitor.done(); } + return Status.OK_STATUS; } - public void cleanFile(IFile file, IProgressMonitor monitor) { - - monitor.subTask(ManagedMakeMessages.getResourceString("GeneratedMakefileBuilder.0") //$NON-NLS-1$ - + file.getProjectRelativePath()); - - // remove all markers on the file - removeAllMarkers(file); - - IProject currentProject = file.getProject(); - - IManagedBuildInfo info = ManagedBuildManager - .getBuildInfo(currentProject); - - // if we have no info then don't do anything - if (info == null) { - // monitor.worked(1); - return; - - } - - IConfiguration cfg = info.getDefaultConfiguration(); - - // figure out the output file for this file -// IPath sourcePath = file.getProjectRelativePath(); - - int flags = BuildDescriptionManager.REBUILD | BuildDescriptionManager.REMOVED; - IResourceDelta delta = getDelta(currentProject); + public void cleanFilesForOneProject(List files, IProgressMonitor monitor) { + IProject project = files.get(0).getProject(); + BuildRunnerHelper buildRunnerHelper = new BuildRunnerHelper(project); + int countDeleted = 0; try { - IBuildDescription des = BuildDescriptionManager - .createBuildDescription(cfg, delta, flags); + monitor.beginTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.cleaningProject", project.getName()) + ':', files.size() * MONITOR_SCALE); //$NON-NLS-1$ - IBuildResource buildResource = des.getBuildResource(file); + // Get a build console for the project + console = CCorePlugin.getDefault().getConsole(); + console.start(project); + IManagedBuildInfo buildInfo = ManagedBuildManager.getBuildInfo(project); + IConfiguration configuration = buildInfo.getDefaultConfiguration(); - if (buildResource != null) { + String cfgName = configuration.getName(); + String toolchainName = configuration.getToolChain().getName(); + boolean isSupported = configuration.isSupported(); - // step collector - Set dependentSteps = new HashSet(); + int flags = BuildDescriptionManager.REBUILD | BuildDescriptionManager.REMOVED; + IResourceDelta delta = getDelta(project); - // get dependent IO types - IBuildIOType depTypes[] = buildResource.getDependentIOTypes(); + IBuildDescription des = BuildDescriptionManager.createBuildDescription(configuration, delta, flags); - // iterate through each type and add the step the type belongs - // to to - // the collector - for (int j = 0; j < depTypes.length; j++) { - IBuildIOType type = depTypes[j]; - if (type != null && type.getStep() != null) - dependentSteps.add(type.getStep()); + String[] errorParsers = configuration.getErrorParserList(); + ErrorParserManager epm = new ErrorParserManager(project, des.getDefaultBuildDirLocationURI(), this, errorParsers); + buildRunnerHelper.prepareStreams(epm, null , console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); + + buildRunnerHelper.greeting(ManagedMakeMessages.getResourceString("CleanFilesAction.cleanSelectedFiles"), cfgName, toolchainName, isSupported); //$NON-NLS-1$ + buildRunnerHelper.printLine(ManagedMakeMessages.getResourceString("ManagedMakeBuilder.message.internal.builder.header.note")); //$NON-NLS-1$ + + for (IFile file : files) { + if (monitor.isCanceled()) { + break; } + String filePath = file.getProjectRelativePath().toString(); - // iterate through all build steps - Iterator stepIter = dependentSteps.iterator(); + try { + IBuildResource buildResource = des.getBuildResource(file); + if (buildResource != null) { + Set dependentSteps = new HashSet(); + IBuildIOType depTypes[] = buildResource.getDependentIOTypes(); + for (IBuildIOType btype : depTypes) { + if (btype != null && btype.getStep() != null) + dependentSteps.add(btype.getStep()); + } - while (stepIter.hasNext()) { - IBuildStep step = stepIter.next(); + SubProgressMonitor monitor2 = new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); + try { + monitor2.beginTask("", (1 + dependentSteps.size()) * MONITOR_SCALE); //$NON-NLS-1$ - // Delete the output resources - IBuildIOType[] outputIOTypes = step.getOutputIOTypes(); + // Remove problem markers for the file + monitor2.subTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.removingResourceMarkers", filePath)); //$NON-NLS-1$ + buildRunnerHelper.removeOldMarkers(file, new SubProgressMonitor(monitor2, 1 * MONITOR_SCALE, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)); - for (int j = 0; j < outputIOTypes.length; j++) { - IBuildResource[] resources = outputIOTypes[j].getResources(); + // iterate through all build steps + for (IBuildStep step : dependentSteps) { + if (monitor2.isCanceled()) { + break; + } - for (int i = 0; i < resources.length; i++) { - IResource outputFile = currentProject.findMember(resources[i] - .getFullPath().removeFirstSegments(1)); // strip project name + monitor2.subTask(filePath); + // Delete the output resources + IBuildIOType[] outputIOTypes = step.getOutputIOTypes(); - if (outputFile != null) - outputFile.delete(true, new SubProgressMonitor(monitor, 1)); + for (IBuildIOType ioType : outputIOTypes) { + for (IBuildResource rc : ioType.getResources()) { + IResource outputFile = project.findMember(rc.getFullPath().removeFirstSegments(1)); // strip project name + if (outputFile != null) { + outputFile.delete(true, null); + countDeleted++; + buildRunnerHelper.printLine(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.fileDeleted", //$NON-NLS-1$ + outputFile.getProjectRelativePath().toString())); + } + } + } + + monitor2.worked(1 * MONITOR_SCALE); + } + } finally { + monitor2.done(); } } - + } catch (Exception e) { + ManagedBuilderCorePlugin.log(new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "CDT Build Error", e))); //$NON-NLS-1$ } + } + if (countDeleted == 0) { + buildRunnerHelper.printLine(ManagedMakeMessages.getResourceString("GeneratedMakefileBuilder.nothingToClean")); //$NON-NLS-1$ + } + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + } catch (Exception e) { + ManagedBuilderCorePlugin.log(new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "CDT Build Error", e))); //$NON-NLS-1$ + } finally { + try { + buildRunnerHelper.close(); + } catch (IOException e) { + ManagedBuilderCorePlugin.log(new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "CDT Build Error", e))); //$NON-NLS-1$ + } + monitor.done(); } - - } - - - private void initNewBuildConsole(IProject currentProject) throws CoreException { - // Get a build console for the project - console = CCorePlugin.getDefault().getConsole(); - console.start(currentProject); - consoleOutStream = console.getOutputStream(); } } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/PluginResources.properties b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/PluginResources.properties index abadc94b1c7..83ee8b40fa1 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/PluginResources.properties +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/PluginResources.properties @@ -21,10 +21,11 @@ ManagedMakeBuilder.message.regen.deps = Regenerating dependency files for {0} ManagedMakeBuilder.message.updating.deps = Updating dependency files for {0} ManagedMakeBuilder.message.creating.markers = Generating markers... ManagedMakeBuilder.message.console.header = **** {0} of configuration {1} for project {2} **** -ManagedMakeBuilder.message.internal.builder.header.note = **** Internal Builder is used for build **** -ManagedMakeBuilder.message.no.build = Nothing to build for {0} -ManagedMakeBuilder.message.error = Build error -ManagedMakeBuilder.message.error.refresh = Error refreshing project +ManagedMakeBuilder.message.internal.builder.header.note = Info: Internal Builder is used for build +ManagedMakeBuilder.message.no.build = Info: Nothing to build for {0} +ManagedMakeBuilder.message.error = Internal error during build, see eclipse error log. +ManagedMakeBuilder.message.error.build = Internal error building project {0} configuration {1} +ManagedMakeBuilder.message.undefined.build.command = Build command is null for builder {0} ManagedMakeBuilder.message.finished = Build complete for project {0} ManagedMakeBuilder.message.cancelled = Build cancelled ManagedMakeBuilder.message.finished.with.errs = Build completed with errors @@ -117,7 +118,6 @@ BuildMacroStatus.status.macro.undefined=Macro {0} is undefined BuildFilesAction.buildingSelectedFiles=Building Selected Files BuildDescriptionGnuMakefileGenerator.0=IO exception occurred: BuildDescriptionGnuMakefileGenerator.1=IO exception occurred: -BuildFilesAction.buildSelectedFile=Build the selected file. BuildMacroStatus.status.reference.eachother=Macros {0} and {1} reference each other BuildMacroStatus.status.reference.incorrect=Macro {0} reference is incorrect BuildMacroStatus.status.macro.not.string=Macro {0} is not of String type @@ -130,15 +130,14 @@ BuildInfoFactory.Missing_Builder=Missing Builder: ResourceChangeHandler.buildInfoSerializationJob=Build Info Serialization #ManagedBuilderCorePlugin messages -GeneratedMakefileBuilder.buildResourcesFinished=Build of selected resources is complete. -GeneratedMakefileBuilder.buildSelectedIncremental=Building selected file(s) incrementally -GeneratedMakefileBuilder.buildSelectedRebuild=Rebuilding selected file(s) -GeneratedMakefileBuilder.buildingFile=Building file +GeneratedMakefileBuilder.buildingProject=Building project {0} +GeneratedMakefileBuilder.cleaningProject=Cleaning project {0} +GeneratedMakefileBuilder.removingResourceMarkers=Removing problem markers for {0} +GeneratedMakefileBuilder.refreshingArtifacts=Refreshing build artefacts for {0} +GeneratedMakefileBuilder.fileDeleted={0} deleted. +GeneratedMakefileBuilder.nothingToClean=Nothing to clean. GenerateMakefileWithBuildDescription.0=info is null GenerateMakefileWithBuildDescription.1=cfg is null -GeneratedMakefileBuilder.0=Cleaning output file(s) for -BuildFilesAction.building=Building -BuildFilesAction.buildFiles=Build File(s) ManagedBuilderCorePlugin.resourceChangeHandlingInitializationJob=Initializing Resource Change Handling #Internal Builder messages @@ -146,7 +145,7 @@ InternalBuilder.msg.header=Internal Builder: {0} InternalBuilder.nothing.todo=Nothing to be done for project {0} CfgScannerConfigUtil_ErrorNotSupported=Only type {0} is supported in this method. CleanFilesAction.cleanFiles=Clean File(s) -CleanFilesAction.cleanSelectedFiles=Clean the selected file(s). +CleanFilesAction.cleanSelectedFiles=Cleaning Selected Files CleanFilesAction.cleaningFiles=Cleaning files BuilderFactory.1=can not find builder with the specified id FolderInfo.4=converter invocation failed @@ -156,7 +155,7 @@ GnuLinkOutputNameProvider.0=tool parent must be one of configuration, toolchain, CommonBuilder.1=customized builder created for builder that does not support customization CommonBuilder.2=request for building non active configuration for the builder that does not support this CommonBuilder.6=Time consumed: {0} ms. -CommonBuilder.7=Parallel threads used: {0} +CommonBuilder.7=Info: Parallel threads used: {0} CommonBuilder.0=can not clean programmatically: build workspace path is not specified CommonBuilder.16=can not clean programmatically: build workspace path is not the project path CommonBuilder.12=can not clean programmatically: build workspace path is not folder diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/newmake/internal/core/StreamMonitor.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/newmake/internal/core/StreamMonitor.java index ed578a8a63c..f139d67f758 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/newmake/internal/core/StreamMonitor.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/newmake/internal/core/StreamMonitor.java @@ -10,97 +10,18 @@ *******************************************************************************/ package org.eclipse.cdt.newmake.internal.core; -import java.io.IOException; import java.io.OutputStream; import org.eclipse.core.runtime.IProgressMonitor; -public class StreamMonitor extends OutputStream { - - IProgressMonitor monitor; - OutputStream console; - public final int fTotalWork; - private int halfWay; - private int currentIncrement = 2; - private int nextProgress = currentIncrement; - private int worked = 0; - +/** +* +* @deprecated as of CDT 8.1. Use org.eclipse.cdt.internal.core.StreamMonitor +* +*/ +@Deprecated +public class StreamMonitor extends org.eclipse.cdt.internal.core.StreamMonitor { public StreamMonitor(IProgressMonitor mon, OutputStream cos, int totalWork) { - monitor = mon; - console = cos; - fTotalWork = totalWork; - halfWay = fTotalWork / 2; - monitor.beginTask("", fTotalWork); //$NON-NLS-1$ - } - - private void progressUpdate() { - if (--nextProgress <= 0) { - //we have exhausted the current increment, so report progress - if (fTotalWork > worked) { - monitor.worked(1); - } - worked++; - if (worked >= halfWay) { - //we have passed the current halfway point, so double the - //increment and reset the halfway point. - currentIncrement *= 2; - halfWay += (fTotalWork - halfWay) / 2; - } - //reset the progress counter to another full increment - nextProgress = currentIncrement; - } - } - /** - * @see java.io.OutputStream#close() - */ - @Override - public void close() throws IOException { - if (console != null) { - console.close(); - } - monitor.done(); - } - - /** - * @see java.io.OutputStream#flush() - */ - @Override - public void flush() throws IOException { - if (console != null) { - console.flush(); - } - } - - /** - * @see java.io.OutputStream#write(int) - */ - @Override - public synchronized void write(int b) throws IOException { - if (console != null) { - console.write(b); - } - progressUpdate(); - } - - /** - * @see java.io.OutputStream#write(byte[], int, int) - */ - @Override - public synchronized void write(byte[] b, int off, int len) throws IOException { - if (b == null) { - throw new NullPointerException(); - } else if (off != 0 || (len < 0) || (len > b.length)) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) { - return; - } - if (console != null) { - console.write(b, off, len); - } - progressUpdate(); - } - - public int getWorkDone() { - return worked; + super(mon, cos, totalWork); } } diff --git a/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/actions/BuildFilesAction.java b/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/actions/BuildFilesAction.java index 3da83ce2984..6983bcc43c6 100644 --- a/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/actions/BuildFilesAction.java +++ b/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/actions/BuildFilesAction.java @@ -31,7 +31,6 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Preferences; -import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; @@ -192,10 +191,7 @@ public class BuildFilesAction extends ActionDelegate implements private final List files; BuildFilesJob(List filesToBuild) { - super( - ManagedMakeMessages - .getResourceString("BuildFilesAction.buildingSelectedFiles")); //$NON-NLS-1$ - + super(ManagedMakeMessages.getResourceString("BuildFilesAction.buildingSelectedFiles")); //$NON-NLS-1$ files = filesToBuild; } @@ -204,43 +200,8 @@ public class BuildFilesAction extends ActionDelegate implements */ @Override protected IStatus run(IProgressMonitor monitor) { - - Iterator iterator = files.iterator(); - GeneratedMakefileBuilder builder = new GeneratedMakefileBuilder(); - - monitor - .beginTask( - ManagedMakeMessages - .getResourceString("BuildFilesAction.building"), files.size()); //$NON-NLS-1$ - - boolean isFirstFile = true; - - while (iterator.hasNext()) { - IFile file = iterator.next(); - - IManagedBuildInfo buildInfo = ManagedBuildManager - .getBuildInfo(file.getProject()); - - IResource[] resources = { file }; - - // invoke the internal builder to do the build - builder.invokeInternalBuilder(resources, buildInfo - .getDefaultConfiguration(), false, false, isFirstFile, - !iterator.hasNext(), monitor); - - if (isFirstFile) { - isFirstFile = false; - } - - if (monitor.isCanceled()) { - return Status.CANCEL_STATUS; - } - - } - - monitor.done(); - return Status.OK_STATUS; + return builder.invokeInternalBuilder(files, monitor); } /* (non-Javadoc) @@ -260,9 +221,7 @@ public class BuildFilesAction extends ActionDelegate implements */ @Override public void run(IAction action) { - List selectedFiles = getSelectedBuildableFiles(); - Job buildFilesJob = new BuildFilesJob(selectedFiles); List projects = getProjectsToBuild(selectedFiles); @@ -277,7 +236,7 @@ public class BuildFilesAction extends ActionDelegate implements private boolean shouldBeEnabled() { - // fix for Bugzilla 139663 + // fix for bug 139663 // if build automatically is turned on, then this menu should be turned off as // it will trigger the auto build Preferences preferences = ResourcesPlugin.getPlugin().getPluginPreferences(); diff --git a/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/actions/CleanFilesAction.java b/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/actions/CleanFilesAction.java index 49e3f420d5a..91d33ec1d8b 100644 --- a/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/actions/CleanFilesAction.java +++ b/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/actions/CleanFilesAction.java @@ -13,7 +13,6 @@ package org.eclipse.cdt.managedbuilder.internal.ui.actions; import java.util.Iterator; import java.util.LinkedList; import java.util.List; -import java.util.Vector; import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.managedbuilder.core.IManagedBuildInfo; @@ -26,7 +25,6 @@ import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; @@ -184,10 +182,8 @@ public class CleanFilesAction extends ActionDelegate implements private static final class CleanFilesJob extends Job { private final List files; - protected Vector generationProblems; - - private CleanFilesJob(String name, List filesToBuild) { - super(name); + private CleanFilesJob(List filesToBuild) { + super(ManagedMakeMessages.getResourceString("CleanFilesAction.cleaningFiles")); //$NON-NLS-1$ files = filesToBuild; } @@ -213,36 +209,9 @@ public class CleanFilesAction extends ActionDelegate implements } } } - try { - if (files != null) { - monitor - .beginTask( - ManagedMakeMessages - .getResourceString("CleanFilesAction.cleaningFiles"), files.size()); //$NON-NLS-1$ - Iterator iterator = files.iterator(); - - // clean each file - while (iterator.hasNext() && !monitor.isCanceled()) { - IFile file = iterator.next(); - - GeneratedMakefileBuilder builder = new GeneratedMakefileBuilder(); - builder.cleanFile(file, monitor); - - if (monitor.isCanceled()) { - return Status.CANCEL_STATUS; - } - } - - monitor.done(); - - } - } catch (OperationCanceledException e) { - return Status.CANCEL_STATUS; - } finally { - monitor.done(); - } - return Status.OK_STATUS; + GeneratedMakefileBuilder builder = new GeneratedMakefileBuilder(); + return builder.cleanFiles(files, monitor); } @Override @@ -258,13 +227,8 @@ public class CleanFilesAction extends ActionDelegate implements */ @Override public void run(IAction action) { - List selectedFiles = getSelectedBuildableFiles(); - - CleanFilesJob job = new CleanFilesJob( - ManagedMakeMessages - .getResourceString("CleanFilesAction.cleaningFiles"), selectedFiles); //$NON-NLS-1$ - + CleanFilesJob job = new CleanFilesJob(selectedFiles); job.schedule(); } diff --git a/build/org.eclipse.linuxtools.cdt.autotools.core/META-INF/MANIFEST.MF b/build/org.eclipse.linuxtools.cdt.autotools.core/META-INF/MANIFEST.MF index 69cfd1fb52f..d2f08bafe87 100644 --- a/build/org.eclipse.linuxtools.cdt.autotools.core/META-INF/MANIFEST.MF +++ b/build/org.eclipse.linuxtools.cdt.autotools.core/META-INF/MANIFEST.MF @@ -1,6 +1,6 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 -Bundle-Name: Core +Bundle-Name: %Bundle-Name.0 Bundle-SymbolicName: org.eclipse.linuxtools.cdt.autotools.core;singleton:=true Bundle-Version: 2.0.0.qualifier Bundle-Activator: org.eclipse.linuxtools.cdt.autotools.core.Activator @@ -10,3 +10,4 @@ Require-Bundle: org.eclipse.core.runtime, Bundle-Localization: plugin Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Bundle-Vendor: %provider diff --git a/build/org.eclipse.linuxtools.cdt.autotools.core/plugin.properties b/build/org.eclipse.linuxtools.cdt.autotools.core/plugin.properties index eee053af5e2..846175c02d6 100644 --- a/build/org.eclipse.linuxtools.cdt.autotools.core/plugin.properties +++ b/build/org.eclipse.linuxtools.cdt.autotools.core/plugin.properties @@ -1 +1,13 @@ +################################################################################# +# Copyright (c) 2012 Red Hat, Inc. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Red Hat Incorporated - initial API and implementation +################################################################################# +Bundle-Name.0 = Autotools Core Plug-in (Compatibility) +provider=Eclipse CDT Makefile.builder.name=Autotools Makefile Generator \ No newline at end of file diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/index/IIndexFile.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/index/IIndexFile.java index a8010956196..6e7f3042ae4 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/index/IIndexFile.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/index/IIndexFile.java @@ -77,11 +77,10 @@ public interface IIndexFile extends IFileNomination { int getScannerConfigurationHashcode() throws CoreException; /** - * Returns the hash-code of the file encoding that was used to parse the file. - * 0 will be returned in case the hash-code is unknown. - * @return the hash-code of the file encoding or 0. * @since 5.3 + * @deprecated Returns 0. */ + @Deprecated int getEncodingHashcode() throws CoreException; /** diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/index/IIndexInclude.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/index/IIndexInclude.java index 1cc4cd9f632..0e6d479036f 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/index/IIndexInclude.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/index/IIndexInclude.java @@ -6,9 +6,9 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn - initial API and implementation - * Andrew Ferguson (Symbian) - * Sergey Prigogin (Google) + * Markus Schorn - initial API and implementation + * Andrew Ferguson (Symbian) + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.core.index; @@ -22,7 +22,7 @@ import org.eclipse.core.runtime.CoreException; * @since 4.0 */ public interface IIndexInclude { - IIndexInclude[] EMPTY_INCLUDES_ARRAY = new IIndexInclude[0]; + IIndexInclude[] EMPTY_INCLUDES_ARRAY = {}; /** * Returns the file that contains this directive. diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/AbstractGNUSourceCodeParser.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/AbstractGNUSourceCodeParser.java index ed744344988..44318861942 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/AbstractGNUSourceCodeParser.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/AbstractGNUSourceCodeParser.java @@ -6,10 +6,10 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * John Camelon (IBM Rational Software) - Initial API and implementation - * Markus Schorn (Wind River Systems) - * Ed Swartz (Nokia) - * Mike Kucera (IBM) - bug #206952 + * John Camelon (IBM Rational Software) - Initial API and implementation + * Markus Schorn (Wind River Systems) + * Ed Swartz (Nokia) + * Mike Kucera (IBM) - bug #206952 *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.parser; @@ -252,7 +252,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { // Use to create the completion node protected ASTCompletionNode createCompletionNode(IToken token) { // the preprocessor may deliver tokens for literals or header-names. - if(completionNode == null && token != null && token.getType() == IToken.tCOMPLETION) { + if (completionNode == null && token != null && token.getType() == IToken.tCOMPLETION) { completionNode = new ASTCompletionNode(token, getTranslationUnit()); } return completionNode; @@ -585,14 +585,12 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { return result; } - protected final IASTProblem createProblem(int signal, int offset, int length) { IASTProblem result = nodeFactory.newProblem(signal, CharArrayUtils.EMPTY, true); ((ASTNode) result).setOffsetAndLength(offset, length); return result; } - protected void logThrowable(String methodName, Throwable e) { if (e != null) { if (log.isTracing()) { @@ -604,8 +602,6 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { log.traceException(e); } } - - @Override public String toString() { @@ -656,8 +652,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { startTime = System.currentTimeMillis(); resolveAmbiguities(); log.traceLog("Ambiguity resolution : " //$NON-NLS-1$ - + (System.currentTimeMillis() - startTime) + "ms" //$NON-NLS-1$ - ); + + (System.currentTimeMillis() - startTime) + "ms"); //$NON-NLS-1$ IASTTranslationUnit result = getTranslationUnit(); nullifyTranslationUnit(); result.freeze(); // make the AST immutable @@ -736,7 +731,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { int endOffset; loop: try { endOffset= LA(1).getOffset(); - while(true) { + while (true) { switch (LT(1)) { case IToken.tEOC: endOffset= getEndOffset(); @@ -776,7 +771,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { int depth= 0; int endOffset= offset; loop: try { - while(true) { + while (true) { switch (LT(1)) { case IToken.tEOC: endOffset= getEndOffset(); @@ -827,7 +822,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { int endOffset= consume(IToken.tLBRACE).getOffset(); int stmtOffset= -1; - while(true) { + while (true) { IToken next= LAcatchEOF(1); if (next == null) { ((ASTNode) result).setOffsetAndLength(offset, endOffset-offset); @@ -882,7 +877,6 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { return result; } - private IASTProblemDeclaration buildProblemDeclaration(IASTProblem problem) { IASTProblemDeclaration pd = nodeFactory.newProblemDeclaration(problem); ((ASTNode) pd).setOffsetAndLength(((ASTNode) problem)); @@ -992,7 +986,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { private IASTExpression buildExpression(IASTExpression left, BinaryOperator operator) { int op, unaryOp= 0; final IASTInitializerClause right= operator.fExpression; - switch(operator.fOperatorToken) { + switch (operator.fOperatorToken) { case IToken.tQUESTION: final IASTInitializerClause negative; if (operator.fNext == null || operator.fNext.fOperatorToken != IToken.tCOLON) { @@ -1220,7 +1214,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { consume(); boolean unaryFailed= false; if (ctx == CastExprCtx.eDirectlyInBExpr) { - switch (LT(1)){ + switch (LT(1)) { // ambiguity with unary operator case IToken.tPLUS: case IToken.tMINUS: case IToken.tSTAR: case IToken.tAMPER: @@ -1280,8 +1274,8 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { protected void translationUnit() { try { setupTranslationUnit(); - } catch (Exception e2) { - logException("translationUnit::createCompilationUnit()", e2); //$NON-NLS-1$ + } catch (Exception e) { + logException("translationUnit::createCompilationUnit()", e); //$NON-NLS-1$ return; } parseTranslationUnit(); @@ -1403,7 +1397,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { if (operator == IASTUnaryExpression.op_star && operand instanceof IASTLiteralExpression) { IASTLiteralExpression lit= (IASTLiteralExpression) operand; - switch(lit.getKind()) { + switch (lit.getKind()) { case IASTLiteralExpression.lk_char_constant: case IASTLiteralExpression.lk_float_constant: case IASTLiteralExpression.lk_integer_constant: @@ -1423,7 +1417,6 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { return result; } - protected IASTStatement handleFunctionBody() throws BacktrackException, EndOfFileException { declarationMark= null; if (mode == ParserMode.QUICK_PARSE || mode == ParserMode.STRUCTURAL_PARSE || !isActiveCode()) { @@ -1449,7 +1442,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { /** * Parses a function body. * - * @return TODO + * @return the compound statement representing the function body. * @throws BacktrackException * request a backtrack */ @@ -1579,7 +1572,6 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { return !parsePassed; } - protected abstract IASTDeclaration declaration(DeclarationOptions option) throws BacktrackException, EndOfFileException; /** @@ -1603,7 +1595,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { // support simple declarations without declarators final boolean acceptEmpty = acceptCompoundWithoutDtor && isLegalWithoutDtor(result.fDeclSpec1); if (acceptEmpty) { - switch(lt1) { + switch (lt1) { case 0: case IToken.tEOC: case IToken.tSEMI: @@ -1698,7 +1690,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { if (declarationMark != null) { backup(declarationMark); // avoid creating an empty declaration - switch(LTcatchEOF(1)) { + switch (LTcatchEOF(1)) { case 0: // eof case IToken.tEOC: case IToken.tSEMI: @@ -1751,7 +1743,6 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { return buildASMDirective(offset, buffer.toString(), lastOffset); } - protected IASTDeclaration functionStyleAsmDeclaration() throws BacktrackException, EndOfFileException { final int offset= LA(1).getOffset(); IASTDeclSpecifier declSpec; @@ -1803,7 +1794,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { int open= 1; while (open > 0) { t= consume(); - switch(t.getType()) { + switch (t.getType()) { case IToken.tLPAREN: open++; break; @@ -1948,9 +1939,9 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { * in this case the type defaults to int and is know as "implicit int". */ protected static boolean isImplicitInt(IASTDeclaration declaration) { - if(declaration instanceof IASTSimpleDeclaration) { + if (declaration instanceof IASTSimpleDeclaration) { IASTDeclSpecifier declSpec = ((IASTSimpleDeclaration)declaration).getDeclSpecifier(); - if(declSpec instanceof IASTSimpleDeclSpecifier && + if (declSpec instanceof IASTSimpleDeclSpecifier && ((IASTSimpleDeclSpecifier)declSpec).getType() == IASTSimpleDeclSpecifier.t_unspecified) { return true; } @@ -1966,7 +1957,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { IASTName name = identifier(); // tIDENTIFIER consume(IToken.tCOLON); // tCOLON IASTStatement nestedStatement = statement(); - int lastOffset = calculateEndOffset( nestedStatement ); + int lastOffset = calculateEndOffset(nestedStatement); IASTLabelStatement label_statement = nodeFactory.newLabelStatement(name, nestedStatement); @@ -2208,7 +2199,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { if (!isValidTypeIDForUnaryExpression(unaryExprKind, typeid)) { typeid= null; } else { - switch(LT(1)) { + switch (LT(1)) { case IToken.tRPAREN: case IToken.tEOC: endOffset1= consume().getEndOffset(); @@ -2309,7 +2300,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { protected abstract IASTAmbiguousExpression createAmbiguousCastVsFunctionCallExpression(IASTCastExpression castExpr, IASTFunctionCallExpression funcCall); protected IASTStatement forInitStatement() throws BacktrackException, EndOfFileException { - if( LT(1) == IToken.tSEMI ) + if (LT(1) == IToken.tSEMI) return parseNullStatement(); try { return parseDeclarationOrExpressionStatement(); @@ -2334,7 +2325,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { protected void __attribute_decl_seq(boolean allowAttrib, boolean allowDeclspec) throws BacktrackException, EndOfFileException { while (true) { final int lt = LTcatchEOF(1); - if ( allowAttrib && (lt == IGCCToken.t__attribute__)) { + if (allowAttrib && (lt == IGCCToken.t__attribute__)) { __attribute__(); } else if (allowDeclspec && (lt == IGCCToken.t__declspec)) { __declspec(); @@ -2433,7 +2424,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { if (token.getType() == IToken.tLPAREN) { consume(); int openParen= 1; - while(true) { + while (true) { token = LA(1); consume(); if (token.getType() == IToken.tLPAREN) { @@ -2573,7 +2564,7 @@ public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser { protected void skipBrackets(int left, int right, int terminator) throws EndOfFileException, BacktrackException { consume(left); int nesting= 0; - while(true) { + while (true) { final int lt1= LT(1); if (lt1 == IToken.tEOC || lt1 == terminator) throwBacktrack(LA(1)); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/BuiltinOperators.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/BuiltinOperators.java index c66e750b7a0..8ef3c1de708 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/BuiltinOperators.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/BuiltinOperators.java @@ -6,12 +6,15 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn - initial API and implementation + * Markus Schorn - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.parser.cpp.semantics; import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.typeOrFunctionSet; -import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.*; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.ALLCVQ; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.CVTYPE; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.REF; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.TDEF; import java.util.ArrayList; import java.util.HashSet; @@ -59,7 +62,8 @@ class BuiltinOperators { private static final int SECOND = 1; private static final IType PTR_DIFF = new CPPBasicType(Kind.eInt, 0); - public static ICPPFunction[] create(OverloadableOperator operator, IASTInitializerClause[] args, IASTTranslationUnit tu, Object[] globCandidates) { + public static ICPPFunction[] create(OverloadableOperator operator, IASTInitializerClause[] args, + IASTTranslationUnit tu, Object[] globCandidates) { if (operator == null || args == null || args.length == 0) return EMPTY; @@ -70,14 +74,15 @@ class BuiltinOperators { private final boolean fUnary; private IType fType1; private IType fType2; - private IType[][] fClassConversionTypes= {null, null}; - private boolean[] fIsClass= {false,false}; + private IType[][] fClassConversionTypes= { null, null }; + private boolean[] fIsClass= { false, false }; private IScope fFileScope; private List fResult; private Set fSignatures; private Object[] fGlobalCandidates; - BuiltinOperators(OverloadableOperator operator, IASTInitializerClause[] args, IScope fileScope, Object[] globCandidates) { + BuiltinOperators(OverloadableOperator operator, IASTInitializerClause[] args, IScope fileScope, + Object[] globCandidates) { fFileScope= fileScope; fOperator= operator; fUnary= args.length<2; @@ -97,7 +102,7 @@ class BuiltinOperators { private ICPPFunction[] create() { - switch(fOperator) { + switch (fOperator) { case ARROW: case COMMA: case DELETE: @@ -390,7 +395,7 @@ class BuiltinOperators { for (IType t1 : p1) { for (IType t2 : p2) { IType rt= null; - switch(rstrat) { + switch (rstrat) { case USE_BOOL: rt= CPPBasicType.BOOLEAN; break; @@ -491,7 +496,7 @@ class BuiltinOperators { if (refType instanceof ICPPReferenceType) { IType t= SemanticUtil.getNestedType(((ICPPReferenceType) refType).getType(), TDEF); if (!SemanticUtil.getCVQualifier(t).isConst()) { - switch(assign) { + switch (assign) { case WITHOUT_OPERATION: if (isEnumeration(t) || isPointerToMember(t) || isPointer(t)) { addFunction(refType, refType, SemanticUtil.getNestedType(t, TDEF|ALLCVQ)); @@ -592,7 +597,7 @@ class BuiltinOperators { private boolean isFloatingPoint(IType type) { if (type instanceof IBasicType) { IBasicType.Kind kind= ((IBasicType) type).getKind(); - switch(kind) { + switch (kind) { case eDouble: case eFloat: return true; @@ -613,7 +618,7 @@ class BuiltinOperators { private boolean isArithmetic(IType type) { if (type instanceof IBasicType) { IBasicType.Kind kind= ((IBasicType) type).getKind(); - switch(kind) { + switch (kind) { case eBoolean: case eChar: case eChar16: @@ -634,7 +639,7 @@ class BuiltinOperators { private boolean isIntegral(IType type) { if (type instanceof IBasicType) { IBasicType.Kind kind= ((IBasicType) type).getKind(); - switch(kind) { + switch (kind) { case eBoolean: case eChar: case eChar16: diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPSemantics.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPSemantics.java index b566bd01787..65206c1d7aa 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPSemantics.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPSemantics.java @@ -412,7 +412,7 @@ public class CPPSemantics { } } } - + IASTName name= data.astName; IASTNode nameParent= name.getParent(); if (nameParent instanceof ICPPASTTemplateId) { @@ -421,7 +421,7 @@ public class CPPSemantics { binding = instance.getSpecializedBinding(); name.setBinding(binding); ((ICPPASTTemplateId) nameParent).setBinding(instance); - } + } name= (ICPPASTTemplateId) nameParent; nameParent= name.getParent(); } @@ -431,7 +431,7 @@ public class CPPSemantics { nameParent= name.getParent(); } } - + // if the lookup in base-classes ran into a deferred instance, use the computed unknown binding. final ASTNodeProperty namePropertyInParent = name.getPropertyInParent(); if (binding == null && data.skippedScope != null) { @@ -445,7 +445,7 @@ public class CPPSemantics { } } } - + if (binding != null) { if (namePropertyInParent == IASTNamedTypeSpecifier.NAME) { if (!(binding instanceof IType || binding instanceof ICPPConstructor)) { @@ -461,7 +461,7 @@ public class CPPSemantics { binding = new ProblemBinding(data.astName, IProblemBinding.SEMANTIC_INVALID_TYPE, data.getFoundBindings()); } - } + } } else if (namePropertyInParent == IASTIdExpression.ID_NAME) { if (binding instanceof IType) { final IASTNode idExpr = name.getParent(); @@ -470,7 +470,7 @@ public class CPPSemantics { // Default for template template parameter is a type. } else if (pip == IASTFunctionCallExpression.FUNCTION_NAME) { // Explicit type conversion in functional notation. - } else if (pip == IASTUnaryExpression.OPERAND + } else if (pip == IASTUnaryExpression.OPERAND && ((ICPPASTUnaryExpression) idExpr.getParent()).getOperator() == IASTUnaryExpression.op_sizeofParameterPack) { // Argument of sizeof... can be a type } else { @@ -480,13 +480,13 @@ public class CPPSemantics { } } } - + // Some declarations are found via name resolution (e.g. when using a qualified name), // add name as definition and check the declaration specifier. final IASTDeclaration declaration = data.forDeclaration(); if (declaration != null) { // Functions - if (binding instanceof IFunction) { + if (binding instanceof IFunction) { binding= checkDeclSpecifier(binding, data.astName, declaration); if (!(binding instanceof IProblemBinding)) { if (declaration instanceof ICPPASTFunctionDefinition) { @@ -495,13 +495,13 @@ public class CPPSemantics { } } // Definitions of static fields. - if (binding instanceof ICPPField && data.astName.isDefinition()) { + if (binding instanceof ICPPField && data.astName.isDefinition()) { if (declaration.getPropertyInParent() != IASTCompositeTypeSpecifier.MEMBER_DECLARATION) { ASTInternal.addDefinition(binding, data.astName); } } } - + // If we're still null... if (binding == null) { if (name instanceof ICPPASTQualifiedName && declaration != null) { @@ -521,10 +521,10 @@ public class CPPSemantics { final ASTNodeProperty propertyInParent = name.getPropertyInParent(); if (propertyInParent == CPPSemantics.STRING_LOOKUP_PROPERTY || propertyInParent == null) return false; - + if (propertyInParent == ICPPASTTemplateId.TEMPLATE_NAME) return false; - + IASTNode parent= name.getParent(); if (parent instanceof ICPPASTQualifiedName) { if (((ICPPASTQualifiedName) parent).getLastName() != name) @@ -541,7 +541,7 @@ public class CPPSemantics { if (dtor != null && dtor.getPointerOperators().length == 0) return true; } - } + } return false; } @@ -557,7 +557,7 @@ public class CPPSemantics { } mergeResults(data, friendFns.toArray(), false); } - + static IBinding checkDeclSpecifier(IBinding binding, IASTName name, IASTNode decl) { // check for empty declaration specifiers if (!isCtorOrConversionOperator(binding)) { @@ -577,7 +577,7 @@ public class CPPSemantics { private static boolean isCtorOrConversionOperator(IBinding binding) { if (binding instanceof ICPPConstructor) return true; - + if (binding instanceof ICPPMethod) { ICPPMethod m= (ICPPMethod) binding; if (m.isDestructor()) @@ -590,18 +590,18 @@ public class CPPSemantics { public static LookupData createLookupData(IASTName name) { LookupData data = new LookupData(name); IASTNode parent = name.getParent(); - + if (parent instanceof ICPPASTTemplateId) parent = parent.getParent(); if (parent instanceof ICPPASTQualifiedName) parent = parent.getParent(); - + if (parent instanceof IASTDeclarator && parent.getPropertyInParent() == IASTSimpleDeclaration.DECLARATOR) { IASTSimpleDeclaration simple = (IASTSimpleDeclaration) parent.getParent(); if (simple.getDeclSpecifier().getStorageClass() == IASTDeclSpecifier.sc_typedef) data.forceQualified = true; } - + if (parent instanceof IASTIdExpression) { IASTNode grand= parent.getParent(); while (grand instanceof IASTUnaryExpression @@ -647,14 +647,14 @@ public class CPPSemantics { data.setFunctionArguments(false, (ICPPASTInitializerList) init); } } - + return data; } private static Set getAssociatedScopes(LookupData data, Set friendFns) { if (!data.hasFunctionArguments()) return Collections.emptySet(); - + IType[] ps = data.getFunctionArgumentTypes(); Set namespaces = new HashSet(2); ObjectSet handled = new ObjectSet(2); @@ -664,7 +664,7 @@ public class CPPSemantics { } catch (DOMException e) { } } - + if (data.astName != null) { final char[] simpleID = data.astName.getSimpleID(); if (CharArrayUtils.equals(CPPVisitor.BEGIN, simpleID) || CharArrayUtils.equals(CPPVisitor.END, simpleID)) { @@ -686,7 +686,7 @@ public class CPPSemantics { return namespaces; } - // 3.4.2-2 + // 3.4.2-2 private static void getAssociatedScopes(IType t, Set namespaces, Set friendFns, ObjectSet handled, CPPASTTranslationUnit tu) throws DOMException { t = getNestedType(t, TDEF | CVTYPE | PTR | ARRAY | REF); @@ -694,7 +694,7 @@ public class CPPSemantics { if (handled.containsKey(t)) return; handled.put(t); - + IBinding owner= ((IBinding) t).getOwner(); if (owner instanceof ICPPClassType) { getAssociatedScopes((IType) owner, namespaces, friendFns, handled, tu); @@ -710,10 +710,10 @@ public class CPPSemantics { if (b instanceof IType) getAssociatedScopes((IType) b, namespaces, friendFns, handled, tu); } - // Furthermore, if T is a class template ... - // * ... types of the template arguments for template type parameters - // (excluding template template parameters); - // * ... owners of which any template template arguments are members; + // Furthermore, if T is a class template ... + // * ... types of the template arguments for template type parameters + // (excluding template template parameters); + // * ... owners of which any template template arguments are members; if (ct instanceof ICPPTemplateInstance) { for (IBinding friend : ct.getFriends()) { if (friend instanceof ICPPFunction) { @@ -740,10 +740,10 @@ public class CPPSemantics { getAssociatedScopes(pmt.getType(), namespaces, friendFns, handled, tu); } else if (t instanceof FunctionSetType) { FunctionSetType fst= (FunctionSetType) t; - for (ICPPFunction fn : fst.getFunctionSet()) { + for (ICPPFunction fn : fst.getFunctionSet()) { getAssociatedScopes(fn.getType(), namespaces, friendFns, handled, tu); } - } + } } private static ICPPNamespaceScope getContainingNamespaceScope(IBinding binding, @@ -763,7 +763,7 @@ public class CPPSemantics { public static void getAssociatedNamespaceScopes(ICPPNamespaceScope scope, Set namespaces) { if (scope == null || !namespaces.add(scope)) return; - + if (scope instanceof ICPPInternalNamespaceScope) { final ICPPInternalNamespaceScope internalScope = (ICPPInternalNamespaceScope) scope; for (ICPPNamespaceScope mem : internalScope.getEnclosingNamespaceSet()) { @@ -771,7 +771,7 @@ public class CPPSemantics { } } } - + static ICPPScope getLookupScope(IASTName name, LookupData data) throws DOMException { IASTNode parent = name.getParent(); IScope scope = null; @@ -807,7 +807,7 @@ public class CPPSemantics { data.foundItems = mergePrefixResults(oldItems, results, scoped); } } - + /** * @param dest * @param source : either Object[] or CharArrayObjectMap @@ -815,9 +815,9 @@ public class CPPSemantics { * @return */ static CharArrayObjectMap mergePrefixResults(CharArrayObjectMap dest, Object source, boolean scoped) { - if (source == null) return dest; + if (source == null) return dest; CharArrayObjectMap resultMap = (dest != null) ? dest : new CharArrayObjectMap(2); - + CharArrayObjectMap map = null; Object[] objs = null; int size; @@ -829,10 +829,10 @@ public class CPPSemantics { } else { if (source instanceof Object[]) objs = ArrayUtil.trim(Object.class, (Object[]) source); - else + else objs = new Object[]{ source }; size= objs.length; - } + } int resultInitialSize = resultMap.size(); for (int i = 0; i < size; i ++) { @@ -865,18 +865,18 @@ public class CPPSemantics { temp[0] = obj; obj = ArrayUtil.addAll(Object.class, temp, (Object[]) so); } - } + } resultMap.put(key, obj); } } return resultMap; } - + private static IIndexFileSet getIndexFileSet(LookupData data) { if (data.tu != null) { final IIndexFileSet fs= data.tu.getIndexFileSet(); - if (fs != null) + if (fs != null) return fs; } return IIndexFileSet.EMPTY; @@ -888,13 +888,13 @@ public class CPPSemantics { * @param start either a scope or a name. */ static protected void lookup(LookupData data, IScope start) throws DOMException { - if (data.astName == null) + if (data.astName == null) return; if (start == null && lookupDestructor(data, start)) { return; } - + ICPPScope nextScope= null; ICPPTemplateScope nextTmplScope= null; if (start instanceof ICPPScope) { @@ -938,21 +938,21 @@ public class CPPSemantics { final IASTNode node= ((IASTInternalScope) nextScope).getPhysicalNode(); if (node != null && nextTmplScope.getTemplateDeclaration().contains(node)) { useTemplScope= false; - } + } } } ICPPScope scope= useTemplScope ? nextTmplScope : nextScope; if (scope instanceof IIndexScope && data.tu != null) { scope= (ICPPScope) data.tu.mapToASTScope(((IIndexScope) scope)); } - + if (!data.usingDirectivesOnly && !(data.ignoreMembers && scope instanceof ICPPClassScope)) { mergeResults(data, getBindingsFromScope(scope, fileSet, data), true); // Nominate using-directives found in this block or namespace. if (scope instanceof ICPPNamespaceScope) { final ICPPNamespaceScope blockScope= (ICPPNamespaceScope) scope; - + if (data.qualified() && blockScope.getKind() != EScopeKind.eLocal) { lookupInlineNamespaces(data, fileSet, blockScope); } @@ -969,25 +969,25 @@ public class CPPSemantics { lookupInNominated(data, fileSet, (ICPPNamespaceScope) scope); } } - + if (friendInLocalClass && !(scope instanceof ICPPClassScope)) - return; + return; if (!data.contentAssist && hasReachableResult(data)) return; - + // Lookup in base classes if (!data.usingDirectivesOnly && scope instanceof ICPPClassScope && !data.ignoreMembers) { BaseClassLookup.lookupInBaseClasses(data, (ICPPClassScope) scope, fileSet); - if (!data.contentAssist && data.hasResultOrProblem()) + if (!data.contentAssist && data.hasResultOrProblem()) return; } - + if (data.qualified() && !(scope instanceof ICPPTemplateScope)) { if (data.ignoreUsingDirectives || data.usingDirectives.isEmpty()) return; data.usingDirectivesOnly = true; } - + // Compute next scopes if (useTemplScope && nextTmplScope != null) { nextTmplScope= enclosingTemplateScope(nextTmplScope.getTemplateDeclaration()); @@ -1001,7 +1001,7 @@ public class CPPSemantics { * Checks if lookup data contains result bindings reachable through includes * from the translation unit where lookup started. Any binding is considered reachable * if the lookup is not done in a context of a translation unit. - * + * * @param data the LookupData object. * @return {@code true} if the lookup data contains at least one reachable binding. */ @@ -1053,9 +1053,9 @@ public class CPPSemantics { private static boolean lookupDestructor(LookupData data, IScope start) throws DOMException { IASTName typeDtorName= data.astName; final char[] typeDtorChars= typeDtorName.getSimpleID(); - if (typeDtorChars.length == 0 || typeDtorChars[0] != '~') + if (typeDtorChars.length == 0 || typeDtorChars[0] != '~') return false; - + // Assume class C; typedef C T; // When looking up ~T the strategy is to lookup T::~C in two steps: // * First resolve 'T', then compute '~C' and resolve it. @@ -1093,29 +1093,29 @@ public class CPPSemantics { final CPPASTName classDtorName = new CPPASTName(typeDtorChars); classDtorName.setOffsetAndLength((ASTNode) typeDtorName); syntheticName.addName(classDtorName); - + IBinding type= resolveBinding(typeName); - if (!(type instanceof ITypedef)) + if (!(type instanceof ITypedef)) return false; - + IType t= SemanticUtil.getNestedType((ITypedef) type, TDEF); if (t instanceof ICPPUnknownBinding || t instanceof ISemanticProblem || !(t instanceof ICPPClassType)) { return false; } - + ICPPClassType classType= (ICPPClassType) t; final IScope scope = ((ICPPClassType) t).getCompositeScope(); if (scope == null) { return false; } - + char[] classChars= classType.getNameCharArray(); char[] classDtorChars= new char[classChars.length+1]; classDtorChars[0]= '~'; System.arraycopy(classChars, 0, classDtorChars, 1, classChars.length); classDtorName.setName(classDtorChars); - + data.astName = classDtorName; try { lookup(data, scope); @@ -1129,7 +1129,7 @@ public class CPPSemantics { * Checks whether the name directly or indirectly depends on the this pointer. */ private static boolean dependsOnTemplateFieldReference(IASTName astName) { - if (astName.getPropertyInParent() != IASTFieldReference.FIELD_NAME) + if (astName.getPropertyInParent() != IASTFieldReference.FIELD_NAME) return false; final boolean[] result= {false}; @@ -1243,7 +1243,7 @@ public class CPPSemantics { } } } - } else { + } else { // For index scopes the point of declaration is ignored. bindings= scope.getBindings(data.astName, true, data.prefixLookup, fileSet); } @@ -1253,11 +1253,11 @@ public class CPPSemantics { private static IBinding[] expandUsingDeclarationsAndRemoveObjects(final IBinding[] bindings, LookupData data) { if (bindings == null || bindings.length == 0) return IBinding.EMPTY_BINDING_ARRAY; - + for (IBinding b : bindings) { - if (b == null) + if (b == null) break; - + if (b instanceof ICPPUsingDeclaration || (data.typesOnly && isObject(b))) { List result= new ArrayList(bindings.length); expandUsingDeclarations(bindings, data, result); @@ -1332,7 +1332,7 @@ public class CPPSemantics { * In case of an unqualified lookup the transitive directives are stored, also. This is important because * the members nominated by a transitive directive can appear before those of the original directive. */ - private static void storeUsingDirective(LookupData data, ICPPNamespaceScope container, + private static void storeUsingDirective(LookupData data, ICPPNamespaceScope container, ICPPUsingDirective directive, Set handled) throws DOMException { ICPPNamespaceScope nominated= directive.getNominatedScope(); if (nominated instanceof IIndexScope && data.tu != null) { @@ -1341,7 +1341,7 @@ public class CPPSemantics { if (nominated == null || data.visited.containsKey(nominated) || (handled != null && !handled.add(nominated))) { return; } - // 7.3.4.1 names appear at end of common enclosing scope of container and nominated scope. + // 7.3.4.1 names appear at end of common enclosing scope of container and nominated scope. final IScope appearsIn= getCommonEnclosingScope(nominated, container, data.tu); if (appearsIn instanceof ICPPNamespaceScope) { // store the directive with the scope where it has to be considered @@ -1355,7 +1355,7 @@ public class CPPSemantics { } listOfNominated.add(nominated); } - + // in a non-qualified lookup the transitive directive have to be stored right away, they may overtake the // container. if (!data.qualified() || data.contentAssist) { @@ -1373,7 +1373,7 @@ public class CPPSemantics { /** * Computes the common enclosing scope of s1 and s2. */ - private static ICPPScope getCommonEnclosingScope(IScope s1, IScope s2, CPPASTTranslationUnit tu) throws DOMException { + private static ICPPScope getCommonEnclosingScope(IScope s1, IScope s2, CPPASTTranslationUnit tu) throws DOMException { ObjectSet set = new ObjectSet(2); IScope parent= s1; while (parent != null) { @@ -1390,10 +1390,10 @@ public class CPPSemantics { public static void populateCache(ICPPASTInternalScope scope) { IASTNode[] nodes = null; IASTNode parent= ASTInternal.getPhysicalNodeOfScope(scope); - + IASTName[] namespaceDefs = null; int namespaceIdx = -1; - + if (parent instanceof IASTCompoundStatement) { IASTNode p = parent.getParent(); if (p instanceof IASTFunctionDefinition) { @@ -1460,7 +1460,7 @@ public class CPPSemantics { } return; } - + int idx = -1; IASTNode item = (nodes != null ? (nodes.length > 0 ? nodes[++idx] : null) : parent); IASTNode[][] nodeStack = null; @@ -1478,7 +1478,7 @@ public class CPPSemantics { continue; } } - while (item instanceof IASTLabelStatement) + while (item instanceof IASTLabelStatement) item= ((IASTLabelStatement) item).getNestedStatement(); if (item instanceof IASTDeclarationStatement) item = ((IASTDeclarationStatement) item).getDeclaration(); @@ -1507,7 +1507,7 @@ public class CPPSemantics { } else { populateCache(scope, item); } - + if (nodes != null && ++idx < nodes.length) { item = nodes[idx]; } else { @@ -1521,17 +1521,17 @@ public class CPPSemantics { idx = 0; item = nodes[0]; break; - } + } } } else if (parent instanceof IASTCompoundStatement && nodes instanceof IASTParameterDeclaration[]) { // function body, we were looking at parameters, now check the body itself IASTCompoundStatement compound = (IASTCompoundStatement) parent; - nodes = compound.getStatements(); + nodes = compound.getStatements(); if (nodes.length > 0) { idx = 0; item = nodes[0]; break; - } + } } else if (parent instanceof ICPPASTCatchHandler) { parent = ((ICPPASTCatchHandler) parent).getCatchBody(); if (parent instanceof IASTCompoundStatement) { @@ -1540,7 +1540,7 @@ public class CPPSemantics { idx = 0; item = nodes[0]; break; - } + } } } if (item == null && nodeStack != null && nodeIdxStack != null && nodeStackPos >= 0) { @@ -1549,7 +1549,7 @@ public class CPPSemantics { idx = nodeIdxStack[nodeStackPos--]; if (++idx >= nodes.length) continue; - + item = nodes[idx]; } break; @@ -1562,7 +1562,7 @@ public class CPPSemantics { IASTDeclaration declaration = null; if (node instanceof ICPPASTTemplateDeclaration) { declaration = ((ICPPASTTemplateDeclaration) node).getDeclaration(); - } else if (node instanceof IASTDeclaration) { + } else if (node instanceof IASTDeclaration) { declaration = (IASTDeclaration) node; } else if (node instanceof IASTDeclarationStatement) { declaration = ((IASTDeclarationStatement) node).getDeclaration(); @@ -1619,7 +1619,7 @@ public class CPPSemantics { } } } - + // Declaration specifiers defining or declaring a type IASTName specName = null; final EScopeKind scopeKind = scope.getKind(); @@ -1634,14 +1634,14 @@ public class CPPSemantics { } else if (declSpec instanceof ICPPASTCompositeTypeSpecifier) { ICPPASTCompositeTypeSpecifier compSpec = (ICPPASTCompositeTypeSpecifier) declSpec; specName = compSpec.getName(); - + // Anonymous union or struct (GCC supports anonymous structs too) if (declarators.length == 0 && specName.getLookupKey().length == 0) { IASTDeclaration[] decls = compSpec.getMembers(); for (IASTDeclaration decl : decls) { populateCache(scope, decl); } - } + } } else if (declSpec instanceof ICPPASTEnumerationSpecifier) { ICPPASTEnumerationSpecifier enumeration = (ICPPASTEnumerationSpecifier) declSpec; specName = enumeration.getName(); @@ -1658,7 +1658,7 @@ public class CPPSemantics { ASTInternal.addName(scope, specName); } } - // Collect friends and elaborated type specifiers with declarators + // Collect friends and elaborated type specifiers with declarators // from nested classes if (declarators.length > 0 || declSpec instanceof ICPPASTCompositeTypeSpecifier) { switch (scopeKind) { @@ -1699,7 +1699,7 @@ public class CPPSemantics { IASTName declName = ASTQueries.findInnermostDeclarator(declarator).getName(); ASTInternal.addName(scope, declName); } - // Collect elaborated type specifiers and friends + // Collect elaborated type specifiers and friends final EScopeKind scopeKind = scope.getKind(); switch (scopeKind) { case eLocal: @@ -1721,7 +1721,7 @@ public class CPPSemantics { * lookups the method assumes that transitive directives have been stored in the lookup-data. * For qualified lookups the transitive directives are considered if the lookup of the original * directive returns empty. - * @param fileSet + * @param fileSet */ private static void lookupInNominated(LookupData data, IIndexFileSet fileSet, ICPPNamespaceScope scope) throws DOMException { @@ -1779,18 +1779,18 @@ public class CPPSemantics { } // Bug 238180 - if (candidate instanceof ICPPClassTemplatePartialSpecialization) + if (candidate instanceof ICPPClassTemplatePartialSpecialization) return null; - + // Specialization is selected during instantiation if (candidate instanceof ICPPTemplateInstance) candidate= ((ICPPTemplateInstance) candidate).getSpecializedBinding(); - + if (!(candidate instanceof ICPPFunctionTemplate)) return candidate; } } - + if (name.getPropertyInParent() != STRING_LOOKUP_PROPERTY) { LookupData data = createLookupData(name); data.foundItems = bindings; @@ -1800,7 +1800,7 @@ public class CPPSemantics { return e.getProblem(); } } - + IBinding[] result = null; for (Object binding : bindings) { if (binding instanceof IASTName) { @@ -1811,11 +1811,11 @@ public class CPPSemantics { } return new CPPCompositeBinding(result); } - + public static boolean declaredBefore(Object obj, IASTNode node, boolean indexBased) { - if (node == null) + if (node == null) return true; - + final int pointOfRef= ((ASTNode) node).getOffset(); if (node.getPropertyInParent() == STRING_LOOKUP_PROPERTY && pointOfRef <= 0) { return true; @@ -1825,11 +1825,11 @@ public class CPPSemantics { if (obj instanceof ICPPSpecialization) { obj = ((ICPPSpecialization) obj).getSpecializedBinding(); } - + int pointOfDecl= -1; if (obj instanceof ICPPInternalBinding) { ICPPInternalBinding cpp = (ICPPInternalBinding) obj; - // For bindings in global or namespace scope we don't know whether there is a + // For bindings in global or namespace scope we don't know whether there is a // previous declaration in one of the skipped header files. For bindings that // are likely to be redeclared we need to assume that there is a declaration // in one of the headers. @@ -1845,7 +1845,7 @@ public class CPPSemantics { if (nd == null || def.getOffset() < nd.getOffset()) nd = def; } - if (nd == null) + if (nd == null) return true; } else { if (indexBased && obj instanceof IASTName) { @@ -1861,7 +1861,7 @@ public class CPPSemantics { pointOfDecl= ((ICPPUsingDirective) obj).getPointOfDeclaration(); } } - + if (pointOfDecl < 0 && nd != null) { ASTNodeProperty prop = nd.getPropertyInParent(); if (prop == IASTDeclarator.DECLARATOR_NAME || nd instanceof IASTDeclarator) { @@ -1891,7 +1891,7 @@ public class CPPSemantics { } else if (prop == ICPPASTNamespaceAlias.ALIAS_NAME) { nd = (ASTNode) nd.getParent(); pointOfDecl = nd.getOffset() + nd.getLength(); - } else { + } else { pointOfDecl = nd.getOffset() + nd.getLength(); } } @@ -1918,18 +1918,18 @@ public class CPPSemantics { } return false; } - + private static IBinding resolveAmbiguities(LookupData data, IASTName name) throws DOMException { if (!data.hasResults() || data.contentAssist) return null; - - final boolean indexBased= data.tu != null && data.tu.getIndex() != null; + + final boolean indexBased= data.tu != null && data.tu.getIndex() != null; @SuppressWarnings("unchecked") ObjectSet fns= ObjectSet.EMPTY_SET; IBinding type = null; IBinding obj = null; IBinding temp = null; - + Object[] items = (Object[]) data.foundItems; for (int i = 0; i < items.length && items[i] != null; i++) { Object o = items[i]; @@ -1987,7 +1987,7 @@ public class CPPSemantics { fns.put((ICPPFunction) temp); } else if (temp instanceof IType) { // Specializations are selected during instantiation - if (temp instanceof ICPPClassTemplatePartialSpecialization) + if (temp instanceof ICPPClassTemplatePartialSpecialization) continue; if (temp instanceof ICPPTemplateInstance) { temp= ((ICPPTemplateInstance) temp).getSpecializedBinding(); @@ -2039,7 +2039,7 @@ public class CPPSemantics { if (cmp == 0) { return new ProblemBinding(data.astName, IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.getFoundBindings()); - } + } } } @@ -2053,7 +2053,7 @@ public class CPPSemantics { } bindings = ArrayUtil.trim(IBinding.class, bindings); ICPPUsingDeclaration composite = new CPPUsingDeclaration(data.astName, bindings); - return composite; + return composite; } if (obj != null && type != null) { @@ -2077,8 +2077,8 @@ public class CPPSemantics { final ICPPFunction[] fnArray = fns.keyArray(ICPPFunction.class); if (type != null && overrulesByRelevance(data, type, fnArray)) { return type; - } - + } + if (obj != null) { int cmp= compareByRelevance(data, obj, fnArray); if (cmp == 0) { @@ -2091,7 +2091,7 @@ public class CPPSemantics { } return resolveFunction(data, fnArray, true); } - + if (obj != null) { return obj; } @@ -2130,7 +2130,7 @@ public class CPPSemantics { /** * Compares two bindings for relevance in the context of an AST. Type bindings are - * considered to overrule object bindings when the former is reachable but the + * considered to overrule object bindings when the former is reachable but the * latter is not. */ static boolean overrulesByRelevance(LookupData data, IBinding type, IBinding b2) { @@ -2141,31 +2141,31 @@ public class CPPSemantics { } /** - * Compares a binding with a list of function candidates for relevance in the - * context of an AST. Types are considered to overrule object bindings when + * Compares a binding with a list of function candidates for relevance in the + * context of an AST. Types are considered to overrule object bindings when * the former is reachable but none of the functions are. */ static boolean overrulesByRelevance(LookupData data, IBinding type, IFunction[] fns) { if (data == null || data.tu == null) { return false; } - + for (int i = 0; i < fns.length; i++) { if (!isFromIndex(fns[i])) { return false; // function from ast } } - + if (!isReachableFromAst(data.tu, type)) { return false; } - + for (IFunction fn : fns) { if (isReachableFromAst(data.tu, fn)) { return false; // function from ast } } - return true; + return true; } @@ -2218,7 +2218,7 @@ public class CPPSemantics { // Everything is from the index if (!isReachableFromAst(data.tu, obj)) { return -1; // obj not reachable - } + } for (IFunction fn : fns) { if (isReachableFromAst(data.tu, fn)) { @@ -2226,8 +2226,8 @@ public class CPPSemantics { } } return 1; // no function is reachable - } - + } + // obj is not from the index for (int i = 0; i < fns.length; i++) { if (!isFromIndex(fns[i])) { @@ -2246,7 +2246,7 @@ public class CPPSemantics { } return false; } - + /** * Checks if a binding is an AST binding, or is reachable from the AST through includes. * The binding is assumed to belong to the AST, if it is not an IIndexBinding and not @@ -2310,8 +2310,8 @@ public class CPPSemantics { if (fn != null && !(fn instanceof IProblemBinding)) { if (fn instanceof ICPPUnknownBinding) { return new ICPPFunction[] {fn}; - } - + } + // The index is optimized to provide the function type, try not to use the parameters // as long as possible. final ICPPFunctionType ft = fn.getType(); @@ -2350,16 +2350,16 @@ public class CPPSemantics { } return result; } - + public static IBinding resolveFunction(LookupData data, ICPPFunction[] fns, boolean allowUDC) throws DOMException { fns= ArrayUtil.trim(ICPPFunction.class, fns); if (fns == null || fns.length == 0) return null; - + sortAstBeforeIndex(fns); - - if (data.forUsingDeclaration()) - return new CPPUsingDeclaration(data.astName, fns); + + if (data.forUsingDeclaration()) + return new CPPUsingDeclaration(data.astName, fns); if (data.astName instanceof ICPPASTConversionName) { return resolveUserDefinedConversion(data, fns); @@ -2368,7 +2368,7 @@ public class CPPSemantics { if (data.forDeclaration() != null) { return resolveFunctionDeclaration(data, fns); } - + // No arguments to resolve function if (!data.hasFunctionArguments()) { return createFunctionSet(data.astName, fns); @@ -2377,10 +2377,10 @@ public class CPPSemantics { // Reduce our set of candidate functions to only those who have the right number of parameters final IType[] argTypes = data.getFunctionArgumentTypes(); ICPPFunction[] tmp= selectByArgumentCount(data, fns); - tmp= CPPTemplates.instantiateForFunctionCall(data.astName, tmp, - Arrays.asList(argTypes), + tmp= CPPTemplates.instantiateForFunctionCall(data.astName, tmp, + Arrays.asList(argTypes), Arrays.asList(data.getFunctionArgumentValueCategories()), data.argsContainImpliedObject); - if (tmp.length == 0 || tmp[0] == null) + if (tmp.length == 0 || tmp[0] == null) return new ProblemBinding(data.astName, IProblemBinding.SEMANTIC_NAME_NOT_FOUND, fns); int viableCount= 0; @@ -2389,22 +2389,22 @@ public class CPPSemantics { setTargetedFunctionsToUnknown(argTypes); return f; } - if (f == null) + if (f == null) break; ++viableCount; } - if (viableCount == 0) + if (viableCount == 0) return new ProblemBinding(data.astName, IProblemBinding.SEMANTIC_NAME_NOT_FOUND, fns); // Check for dependent arguments fns= tmp; if (CPPTemplates.containsDependentType(argTypes)) { - if (viableCount == 1) + if (viableCount == 1) return fns[0]; setTargetedFunctionsToUnknown(argTypes); return CPPUnknownFunction.createForSample(fns[0]); } - + IFunction[] ambiguousFunctions= null; // ambiguity, 2 functions are equally good FunctionCost bestFnCost = null; // the cost of the best function @@ -2412,20 +2412,20 @@ public class CPPSemantics { List potentialCosts= null; IFunction unknownFunction= null; for (ICPPFunction fn : fns) { - if (fn == null) + if (fn == null) continue; - + final FunctionCost fnCost= costForFunctionCall(fn, allowUDC, data); if (fnCost == null) continue; - + if (fnCost == CONTAINS_DEPENDENT_TYPES) { - if (viableCount == 1) + if (viableCount == 1) return fn; unknownFunction = fn; continue; } - + if (fnCost.hasDeferredUDC()) { if (potentialCosts == null) { potentialCosts= new ArrayList(); @@ -2441,7 +2441,7 @@ public class CPPSemantics { ambiguousFunctions= ArrayUtil.append(IFunction.class, ambiguousFunctions, fn); } } - + if (potentialCosts != null) { for (FunctionCost fnCost : potentialCosts) { if (!fnCost.mustBeWorse(bestFnCost) && fnCost.performUDC()) { @@ -2457,13 +2457,13 @@ public class CPPSemantics { } if (bestFnCost == null) { - if (unknownFunction == null) + if (unknownFunction == null) return null; - + setTargetedFunctionsToUnknown(argTypes); return CPPUnknownFunction.createForSample(unknownFunction); } - + if (ambiguousFunctions != null) { ambiguousFunctions= ArrayUtil.append(IFunction.class, ambiguousFunctions, bestFnCost.getFunction()); return new ProblemBinding(data.astName, IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, @@ -2473,7 +2473,7 @@ public class CPPSemantics { return new ProblemBinding(data.astName, IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.getFoundBindings()); } - + for (int i = 0; i < argTypes.length; i++) { IType iType = argTypes[i]; if (iType instanceof FunctionSetType) { @@ -2484,7 +2484,7 @@ public class CPPSemantics { if (bestFnCost.isDirectInitWithCopyCtor()) { Cost c0= bestFnCost.getCost(0); IFunction firstConversion= c0.getUserDefinedConversion(); - if (firstConversion instanceof ICPPConstructor) + if (firstConversion instanceof ICPPConstructor) return firstConversion; } return result; @@ -2507,12 +2507,12 @@ public class CPPSemantics { for (ICPPFunction f : fns) { // Use the ast binding final boolean fromIndex = isFromIndex(f); - if (haveASTResult && fromIndex) + if (haveASTResult && fromIndex) break; - + if (f instanceof ICPPFunctionTemplate) { // Works only if there are template arguments - if (!haveTemplateArgs || result != null) + if (!haveTemplateArgs || result != null) return null; result= f; haveASTResult= !fromIndex; @@ -2523,10 +2523,10 @@ public class CPPSemantics { haveASTResult= !fromIndex; } } - - if (result instanceof ICPPFunctionTemplate) + + if (result instanceof ICPPFunctionTemplate) return CPPTemplates.instantiateForAddressOfFunction((ICPPFunctionTemplate) result, null, name); - + return result; } @@ -2539,22 +2539,22 @@ public class CPPSemantics { } /** - * Called for declarations with qualified name or template-id. Also for explicit function + * Called for declarations with qualified name or template-id. Also for explicit function * specializations or instantiations. */ private static IBinding resolveFunctionDeclaration(LookupData data, ICPPFunction[] fns) throws DOMException { final IASTDeclarator dtor= ASTQueries.findTypeRelevantDeclarator(data.getDeclarator()); final IType t = CPPVisitor.createType(dtor); - if (!(t instanceof ICPPFunctionType)) + if (!(t instanceof ICPPFunctionType)) return null; - + final ICPPFunctionType ft= (ICPPFunctionType) t; IASTName templateID= data.astName; if (templateID.getPropertyInParent() == ICPPASTTemplateId.TEMPLATE_NAME) { templateID= (ICPPASTTemplateId) templateID.getParent(); - } - + } + // 14.5.4 Friends with template ids require instantiation boolean isFriend= CPPVisitor.isFriendDeclaration(data.forDeclaration()); if (!data.forExplicitFunctionSpecialization() @@ -2568,12 +2568,12 @@ public class CPPSemantics { } } // 14.5.4 Friends with qualified ids allow for instantiation - if (!data.forExplicitFunctionInstantiation() + if (!data.forExplicitFunctionInstantiation() && !(isFriend && templateID.getParent() instanceof ICPPASTQualifiedName)) { return null; } } - + // Try to instantiate a template IASTTranslationUnit tu= data.tu; ICPPTemplateArgument[] tmplArgs= ICPPTemplateArgument.EMPTY_ARGUMENTS; @@ -2585,13 +2585,13 @@ public class CPPSemantics { ICPPFunction bestInst= null; boolean isAmbiguous= false; for (ICPPFunction fn : fns) { - if (fn instanceof ICPPFunctionTemplate + if (fn instanceof ICPPFunctionTemplate && !(fn instanceof IProblemBinding) && !(fn instanceof ICPPUnknownBinding)) { ICPPFunctionTemplate template= (ICPPFunctionTemplate) fn; ICPPFunction inst= CPPTemplates.instantiateForFunctionDeclaration(template, tmplArgs, ft); if (inst != null) { int cmp= CPPTemplates.orderFunctionTemplates(bestTemplate, template, TypeSelection.PARAMETERS_AND_RETURN_TYPE); - if (cmp == 0) + if (cmp == 0) cmp= compareByRelevance(tu, bestTemplate, template); if (cmp == 0) @@ -2653,12 +2653,12 @@ public class CPPSemantics { result= new FunctionCost(fn, sourceLen); } else { result= new FunctionCost(fn, sourceLen + 1); - + ValueCategory sourceIsLValue= LVALUE; if (impliedObjectType == null) { impliedObjectType= data.getImpliedObjectType(); } - if (fn instanceof ICPPMethod && + if (fn instanceof ICPPMethod && (((ICPPMethod) fn).isDestructor() || ASTInternal.isStatic(fn, false))) { // 13.3.1-4 for static member functions, the implicit object parameter always matches, no cost cost = new Cost(impliedObjectType, implicitParameterType, Rank.IDENTITY); @@ -2678,14 +2678,14 @@ public class CPPSemantics { IType t= getNestedType(implicitParameterType, TDEF|REF|CVTYPE); if (SemanticUtil.calculateInheritanceDepth(s, t) >= 0) return null; - + return CONTAINS_DEPENDENT_TYPES; } } } if (!cost.converts()) return null; - + result.setCost(k++, cost, sourceIsLValue); } @@ -2706,8 +2706,8 @@ public class CPPSemantics { cost = new Cost(argType, null, Rank.ELLIPSIS_CONVERSION); result.setCost(k++, cost, sourceIsLValue); continue; - } - + } + if (argType instanceof FunctionSetType) { cost= ((FunctionSetType) argType).costForTarget(paramType); } else if (argType.isSameType(paramType)) { @@ -2715,7 +2715,7 @@ public class CPPSemantics { } else { if (CPPTemplates.isDependentType(paramType)) return CONTAINS_DEPENDENT_TYPES; - + Context ctx= Context.ORDINARY; if (j == 0 && sourceLen == 1 && fn instanceof ICPPConstructor) { if (paramType instanceof ICPPReferenceType) { @@ -2732,7 +2732,7 @@ public class CPPSemantics { } if (!cost.converts()) return null; - + result.setCost(k++, cost, sourceIsLValue); } return result; @@ -2755,7 +2755,7 @@ public class CPPSemantics { if (t instanceof ISemanticProblem) { return new ProblemBinding(astName, IProblemBinding.SEMANTIC_INVALID_TYPE, data.getFoundBindings()); } - if (data.forDeclaration() == null || + if (data.forDeclaration() == null || data.forExplicitFunctionSpecialization() || data.forExplicitFunctionInstantiation()) { fns= CPPTemplates.instantiateConversionTemplates(fns, t); } @@ -2782,12 +2782,12 @@ public class CPPSemantics { static IBinding resolveTargetedFunction(IASTName name, ICPPFunction[] fns) { boolean addressOf= false; IASTNode node= name.getParent(); - while (node instanceof IASTName) + while (node instanceof IASTName) node= node.getParent(); - - if (!(node instanceof IASTIdExpression)) + + if (!(node instanceof IASTIdExpression)) return new ProblemBinding(name, IProblemBinding.SEMANTIC_INVALID_OVERLOAD); - + ASTNodeProperty prop= node.getPropertyInParent(); IASTNode parent = node.getParent(); while (parent instanceof IASTUnaryExpression) { @@ -2802,7 +2802,7 @@ public class CPPSemantics { prop= node.getPropertyInParent(); parent= node.getParent(); } - + IType targetType= null; if (prop == IASTDeclarator.INITIALIZER) { // Target is an object or reference being initialized @@ -2857,7 +2857,7 @@ public class CPPSemantics { IASTBinaryExpression binaryExp = (IASTBinaryExpression) parent; if (binaryExp.getOperator() == IASTBinaryExpression.op_assign) { targetType= binaryExp.getOperand1().getExpressionType(); - } + } } else if (prop == IASTFunctionCallExpression.ARGUMENT) { // Target is a parameter of a function, need to resolve the function call IASTFunctionCallExpression fnCall = (IASTFunctionCallExpression) parent; @@ -2914,20 +2914,20 @@ public class CPPSemantics { } } } - if (targetType == null && parent instanceof IASTExpression + if (targetType == null && parent instanceof IASTExpression && parent instanceof IASTImplicitNameOwner) { // Trigger resolution of overloaded operator, which may resolve the // function set. - ((IASTImplicitNameOwner) parent).getImplicitNames(); + ((IASTImplicitNameOwner) parent).getImplicitNames(); final IBinding newBinding = name.getPreBinding(); - if (!(newBinding instanceof CPPFunctionSet)) + if (!(newBinding instanceof CPPFunctionSet)) return newBinding; - } + } ICPPFunction function = resolveTargetedFunction(targetType, name, fns); if (function == null) return new ProblemBinding(name, IProblemBinding.SEMANTIC_INVALID_OVERLOAD); - + return function; } @@ -2943,7 +2943,7 @@ public class CPPSemantics { return fn; } } - + // Second pass, consider templates ICPPFunction result= null; ICPPFunctionTemplate resultTemplate= null; @@ -2956,12 +2956,12 @@ public class CPPSemantics { ICPPFunction inst= CPPTemplates.instantiateForAddressOfFunction(template, (ICPPFunctionType) targetType, name); if (inst != null) { int cmp= CPPTemplates.orderFunctionTemplates(resultTemplate, template, TypeSelection.PARAMETERS_AND_RETURN_TYPE); - if (cmp == 0) + if (cmp == 0) cmp= compareByRelevance(tu, resultTemplate, template); if (cmp == 0) isAmbiguous= true; - + if (cmp < 0) { isAmbiguous= false; resultTemplate= template; @@ -2974,10 +2974,10 @@ public class CPPSemantics { } if (isAmbiguous) return null; - + return result; } - + public static ICPPFunction findOverloadedOperator(IASTArraySubscriptExpression exp) { final IASTExpression arrayExpression = exp.getArrayExpression(); IASTInitializerClause[] args = {arrayExpression, exp.getArgument()}; @@ -2994,20 +2994,20 @@ public class CPPSemantics { argsToPass.add(e); } args = argsToPass.toArray(new IASTInitializerClause[argsToPass.size()]); - + return findOverloadedOperator(exp, args, type, OverloadableOperator.PAREN, LookupMode.NO_GLOBALS); } - + public static ICPPFunction findOverloadedOperator(ICPPASTNewExpression expr) { OverloadableOperator op = OverloadableOperator.fromNewExpression(expr); IType type = getTypeOfPointer(expr.getExpressionType()); if (type == null) return null; - + IASTTypeId typeId = expr.getTypeId().copy(); IASTExpression sizeExpression = new CPPASTTypeIdExpression(IASTTypeIdExpression.op_sizeof, typeId); sizeExpression.setParent(expr); - + IASTInitializerClause[] placement = expr.getPlacementArguments(); List args = new ArrayList(); args.add(createArgForType(expr, type)); @@ -3015,8 +3015,8 @@ public class CPPSemantics { if (placement != null) { for (IASTInitializerClause p : placement) { args.add(p); - } - } + } + } IASTInitializerClause[] argArray = args.toArray(new IASTInitializerClause[args.size()]); return findOverloadedOperator(expr, argArray, type, op, LookupMode.GLOBALS_IF_NO_MEMBERS); } @@ -3030,7 +3030,7 @@ public class CPPSemantics { IASTExpression[] args = {createArgForType(expr, type), expr.getOperand()}; return findOverloadedOperator(expr, args, type, op, LookupMode.GLOBALS_IF_NO_MEMBERS); } - + private static IType getTypeOfPointer(IType type) { type = SemanticUtil.getNestedType(type, SemanticUtil.TDEF | SemanticUtil.REF | SemanticUtil.CVTYPE); if (type instanceof IPointerType) { @@ -3087,7 +3087,7 @@ public class CPPSemantics { return null; if (type instanceof ICPPClassTemplate || type instanceof ICPPUnknownClassType || type instanceof ISemanticProblem) return null; - + final ICPPClassType classType = (ICPPClassType) type; if (initializer instanceof IASTEqualsInitializer) { // Copy initialization @@ -3160,7 +3160,7 @@ public class CPPSemantics { IType t = getTypeOfPointer(expr.getOperand().getExpressionType()); if (!(t instanceof ICPPClassType)) return null; - + ICPPClassType cls = (ICPPClassType) t; IScope scope = cls.getCompositeScope(); if (scope == null) @@ -3192,7 +3192,7 @@ public class CPPSemantics { @Override public IType getType() { return type; } - }); + }); final CPPASTIdExpression idExpression = new CPPASTIdExpression(x); idExpression.setParent(node); return idExpression; @@ -3209,16 +3209,16 @@ public class CPPSemantics { IType type = typeOrFunctionSet(operand); type = SemanticUtil.getNestedType(type, TDEF | REF | CVTYPE); - if (!isUserDefined(type)) + if (!isUserDefined(type)) return null; IASTExpression[] args; int operator = exp.getOperator(); - if (operator == IASTUnaryExpression.op_postFixDecr || operator == IASTUnaryExpression.op_postFixIncr) { + if (operator == IASTUnaryExpression.op_postFixDecr || operator == IASTUnaryExpression.op_postFixIncr) { args = new IASTExpression[] { operand, CPPASTLiteralExpression.INT_ZERO }; } else { args = new IASTExpression[] { operand }; - } + } return findOverloadedOperator(exp, args, type, op, LookupMode.LIMITED_GLOBALS); } @@ -3226,7 +3226,7 @@ public class CPPSemantics { OverloadableOperator op = OverloadableOperator.fromBinaryExpression(exp); if (op == null) return null; - + final IASTExpression op1 = exp.getOperand1(); final IASTExpression op2 = exp.getOperand2(); if(op2==null){ @@ -3236,7 +3236,7 @@ public class CPPSemantics { IType op2type = getNestedType(typeOrFunctionSet(op2), TDEF | REF | CVTYPE); if (!isUserDefined(op1type) && !isUserDefined(op2type)) return null; - + final IASTExpression[] args = new IASTExpression[] { op1, op2 }; final LookupMode lookupNonMember; if (exp.getOperator() == IASTBinaryExpression.op_assign) { @@ -3246,19 +3246,19 @@ public class CPPSemantics { } return findOverloadedOperator(exp, args, op1type, op, lookupNonMember); } - + /** - * For simplicity returns an operator of form RT (T, T) rather than RT (boolean, T, T) + * For simplicity returns an operator of form RT (T, T) rather than RT (boolean, T, T) */ public static ICPPFunction findOverloadedConditionalOperator(IASTExpression positive, IASTExpression negative) { final IASTExpression parent = (IASTExpression) positive.getParent(); final IASTExpression[] args = new IASTExpression[] {positive, negative}; - return findOverloadedOperator(parent, args, null, + return findOverloadedOperator(parent, args, null, OverloadableOperator.CONDITIONAL_OPERATOR, LookupMode.NO_GLOBALS); } /** - * Returns the operator,() function that would apply to the two given arguments. + * Returns the operator,() function that would apply to the two given arguments. * The lookup type of the class where the operator,() might be found must also be provided. */ public static ICPPFunction findOverloadedOperatorComma(IASTExpression first, final IType lookupType, final ValueCategory valueCat, IASTExpression second) { @@ -3272,13 +3272,13 @@ public class CPPSemantics { @Override public ValueCategory getValueCategory() { return valueCat; } }; dummy.setParent(first); - + IASTExpression[] args = new IASTExpression[] { dummy , second }; return findOverloadedOperator(dummy, args, op1type, OverloadableOperator.COMMA, LookupMode.LIMITED_GLOBALS); } /** - * Returns the operator->() function + * Returns the operator->() function */ public static ICPPFunction findOverloadedOperator(ICPPASTFieldReference fieldRef, IType cvQualifiedType, ICPPClassType classType) { IASTExpression arg = CPPSemantics.createArgForType(fieldRef, cvQualifiedType); @@ -3286,7 +3286,7 @@ public class CPPSemantics { } private static enum LookupMode {NO_GLOBALS, GLOBALS_IF_NO_MEMBERS, LIMITED_GLOBALS, ALL_GLOBALS} - private static ICPPFunction findOverloadedOperator(IASTExpression parent, IASTInitializerClause[] args, IType methodLookupType, + private static ICPPFunction findOverloadedOperator(IASTExpression parent, IASTInitializerClause[] args, IType methodLookupType, OverloadableOperator operator, LookupMode mode) { ICPPClassType callToObjectOfClassType= null; IType type2= null; @@ -3294,13 +3294,13 @@ public class CPPSemantics { type2 = typeOrFunctionSet((IASTExpression) args[1]); type2= getNestedType(type2, TDEF | REF | CVTYPE); } - + if (methodLookupType instanceof ICPPUnknownType || type2 instanceof ICPPUnknownType) { - if (methodLookupType instanceof FunctionSetType) + if (methodLookupType instanceof FunctionSetType) ((FunctionSetType) methodLookupType).setToUnknown(); - if (type2 instanceof FunctionSetType) + if (type2 instanceof FunctionSetType) ((FunctionSetType) type2).setToUnknown(); - + return new CPPUnknownFunction(null, operator.toCharArray()); } @@ -3318,13 +3318,13 @@ public class CPPSemantics { methodData = new LookupData(methodName); methodData.setFunctionArguments(true, args); methodData.forceQualified = true; // (13.3.1.2.3) - + try { IScope scope = classType.getCompositeScope(); if (scope == null) return null; lookup(methodData, scope); - + if (parent instanceof IASTFunctionCallExpression) { callToObjectOfClassType= classType; } @@ -3332,13 +3332,13 @@ public class CPPSemantics { return null; } } - + // Find a function CPPASTName funcName = new CPPASTName(operator.toCharArray()); funcName.setParent(parent); funcName.setPropertyInParent(STRING_LOOKUP_PROPERTY); LookupData funcData = new LookupData(funcName); - + // Global new and delete operators do not take an argument for the this pointer. switch (operator) { case DELETE: case DELETE_ARRAY: @@ -3384,22 +3384,22 @@ public class CPPSemantics { } catch (DOMException e) { return null; } - + if (operator == OverloadableOperator.NEW || operator == OverloadableOperator.DELETE || operator == OverloadableOperator.NEW_ARRAY || operator == OverloadableOperator.DELETE_ARRAY) { - + // Those operators replace the built-in operator Object[] items= (Object[]) funcData.foundItems; int j= 0; for (Object object : items) { if (object instanceof ICPPFunction) { ICPPFunction func= (ICPPFunction) object; - if (!(func instanceof CPPImplicitFunction)) + if (!(func instanceof CPPImplicitFunction)) items[j++]= func; } } if (j>0) { - while (j < items.length) + while (j < items.length) items[j++]= null; } } @@ -3431,11 +3431,11 @@ public class CPPSemantics { while (j < items.length) { items[j++]= null; } - } + } } - } - - if (callToObjectOfClassType != null) { + } + + if (callToObjectOfClassType != null) { try { // 13.3.1.1.2 call to object of class type ICPPMethod[] ops = SemanticUtil.getConversionOperators(callToObjectOfClassType); @@ -3459,12 +3459,12 @@ public class CPPSemantics { return null; } } - + if (methodLookupType instanceof ICPPClassType || type2 instanceof ICPPClassType) { ICPPFunction[] builtins= BuiltinOperators.create(operator, args, parent.getTranslationUnit(), (Object[]) funcData.foundItems); mergeResults(funcData, builtins, false); } - + try { IBinding binding = null; if (methodData != null && funcData.hasResults()) { @@ -3476,15 +3476,15 @@ public class CPPSemantics { } else if (methodData != null) { binding = resolveAmbiguities(methodData, methodName); } - + if (binding instanceof ICPPFunction) return (ICPPFunction) binding; } catch (DOMException e) { } - + return null; } - + private static IBinding createSurrogateCallFunction(IScope scope, IType returnType, IType rt, IType[] parameterTypes) { IType[] parms = new IType[parameterTypes.length + 1]; ICPPParameter[] theParms = new ICPPParameter[parms.length]; @@ -3503,10 +3503,10 @@ public class CPPSemantics { private static boolean isUserDefined(IType type) { if (type instanceof ISemanticProblem) return false; - + return type instanceof ICPPClassType || type instanceof IEnumeration || type instanceof ICPPUnknownType; } - + public static IBinding[] findBindings(IScope scope, String name, boolean qualified) { return findBindings(scope, name.toCharArray(), qualified, null); } @@ -3523,12 +3523,12 @@ public class CPPSemantics { if (beforeNode instanceof ASTNode) { astName.setOffsetAndLength((ASTNode) beforeNode); } - + LookupData data = new LookupData(astName); data.forceQualified = qualified; return standardLookup(data, scope); } - + public static IBinding[] findBindingsForContentAssist(IASTName name, boolean prefixLookup, String[] additionalNamespaces) { LookupData data = createLookupData(name); @@ -3579,18 +3579,18 @@ public class CPPSemantics { return null; } } - + // Name did not specify a namespace, e.g. "::" if (nsScope == tu.getScope()) return null; - + return nsScope; } - private static IBinding[] contentAssistLookup(LookupData data, List additionalNamespaces) { + private static IBinding[] contentAssistLookup(LookupData data, List additionalNamespaces) { try { lookup(data, null); - + if (additionalNamespaces != null) { data.ignoreUsingDirectives = true; data.forceQualified = true; @@ -3607,7 +3607,7 @@ public class CPPSemantics { IBinding[] result = IBinding.EMPTY_BINDING_ARRAY; if (!map.isEmpty()) { char[] key = null; - int size = map.size(); + int size = map.size(); for (int i = 0; i < size; i++) { key = map.keyAt(i); result = addContentAssistBinding(result, map.get(key)); @@ -3627,7 +3627,7 @@ public class CPPSemantics { if (obj instanceof IASTName) { return addContentAssistBinding(result, ((IASTName) obj).resolveBinding()); } - + if (obj instanceof IBinding && !(obj instanceof IProblemBinding)) { final IBinding binding = (IBinding) obj; if (binding instanceof ICPPFunction) { @@ -3638,7 +3638,7 @@ public class CPPSemantics { } return ArrayUtil.append(result, binding); } - + return result; } @@ -3648,7 +3648,7 @@ public class CPPSemantics { } catch (DOMException e) { return new IBinding[] { e.getProblem() }; } - + Object[] items = (Object[]) data.foundItems; if (items == null) return new IBinding[0]; @@ -3674,16 +3674,16 @@ public class CPPSemantics { } } } - + return set.keyArray(IBinding.class); } - + public static boolean isSameFunction(ICPPFunction function, IASTDeclarator declarator) { final ICPPASTDeclarator innerDtor = (ICPPASTDeclarator) ASTQueries.findInnermostDeclarator(declarator); IASTName name = innerDtor.getName(); ICPPASTTemplateDeclaration templateDecl = CPPTemplates.getTemplateDeclaration(name); if (templateDecl != null) { - + if (templateDecl instanceof ICPPASTTemplateSpecialization) { if (!(function instanceof ICPPTemplateInstance)) return false; @@ -3701,7 +3701,7 @@ public class CPPSemantics { } } else if (function instanceof ICPPTemplateDefinition) { return false; - } + } declarator= ASTQueries.findTypeRelevantDeclarator(declarator); if (declarator instanceof ICPPASTFunctionDeclarator) { @@ -3710,13 +3710,13 @@ public class CPPSemantics { } return false; } - + private static boolean isSameTemplateParameterList(ICPPTemplateParameter[] tplist, ICPPASTTemplateParameter[] tps) { if (tplist.length != tps.length) return false; - + for (int i = 0; i < tps.length; i++) { - if (!isSameTemplateParameter(tplist[i], tps[i])) + if (!isSameTemplateParameter(tplist[i], tps[i])) return false; } return true; @@ -3725,7 +3725,7 @@ public class CPPSemantics { static boolean isSameTemplateParameter(ICPPTemplateParameter tp1, ICPPASTTemplateParameter tp2) { if (tp1.isParameterPack() != tp2.isParameterPack()) return false; - + if (tp1 instanceof ICPPTemplateNonTypeParameter) { if (tp2 instanceof ICPPASTParameterDeclaration) { IType t1= ((ICPPTemplateNonTypeParameter) tp1).getType(); @@ -3748,26 +3748,26 @@ public class CPPSemantics { } return false; } - + return false; } - static protected IBinding resolveUnknownName(IScope scope, ICPPUnknownBinding unknown) { + protected static IBinding resolveUnknownName(IScope scope, ICPPUnknownBinding unknown) { final IASTName unknownName = unknown.getUnknownName(); LookupData data = new LookupData(unknownName); data.checkPointOfDecl= false; data.typesOnly= unknown instanceof IType; - + try { // 2: lookup lookup(data, scope); } catch (DOMException e) { data.problem = (ProblemBinding) e.getProblem(); } - + if (data.problem != null) return data.problem; - + // 3: resolve ambiguities IBinding binding; try { @@ -3778,7 +3778,7 @@ public class CPPSemantics { // 4: Normal post processing is not possible, because the name is not rooted in AST if (binding == null) binding = new ProblemBinding(unknownName, IProblemBinding.SEMANTIC_NAME_NOT_FOUND); - + return binding; } } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java index 1975cd67965..68aee31d1ff 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java @@ -2529,7 +2529,7 @@ public class CPPVisitor extends ASTQueries { * Traverses a chain of nested homogeneous left-to-right-associative binary expressions and * returns a list of their operands in left-to-right order. For example, for the expression * a + b * c + d, it will return a list containing expressions: a, b * c, and d. - * + * * @param binaryExpression the top-level binary expression * @return a list of expression operands from left to right */ diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java index f8a07a9b3e1..3fe59806219 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java @@ -345,8 +345,12 @@ public class ChangeGenerator extends ASTVisitor { int offset = edit.getOffset(); int end = offset + edit.getLength(); int newOffset = document.getLineInformationOfOffset(offset).getOffset(); - int newEnd = endOffset(document.getLineInformationOfOffset(end)); edit = originalEdits[i]; + int originalEnd = edit.getExclusiveEnd(); + // Expand to the end of the line unless the end of the edit region is at + // the beginning of line both, before and after the change. + int newEnd = (originalEnd == 0 || code.charAt(originalEnd - 1) == '\n') && end == newOffset ? + end : endOffset(document.getLineInformationOfOffset(end)); int offsetBefore = edit.getOffset(); int newOffsetBefore = newOffset + offsetBefore - offset; int newEndBefore = newEnd + offsetBefore + edit.getLength() - end; diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/index/IIndexFragmentFile.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/index/IIndexFragmentFile.java index a8c922b561b..f6ca6b05ca2 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/index/IIndexFragmentFile.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/index/IIndexFragmentFile.java @@ -34,10 +34,16 @@ public interface IIndexFragmentFile extends IIndexFile { void setContentsHash(long hash) throws CoreException; /** - * Sets the hash-code of the file encoding. + * Returns the hash-code computed by combining the file size and the file encoding. + * @return hashcode a hash-code or 0 if it is unknown. + */ + int getSizeAndEncodingHashcode() throws CoreException; + + /** + * Sets the hash-code computed by combining the file size and the file encoding. * @param hashcode a hash-code or 0 if it is unknown. */ - void setEncodingHashcode(int hashcode) throws CoreException; + void setSizeAndEncodingHashcode(int hashcode) throws CoreException; /** * Sets the flag that determines whether the file is a header with #pragma once statement diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/indexer/StandaloneIndexerInputAdapter.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/indexer/StandaloneIndexerInputAdapter.java index fc22a1ce3ba..bd018868a36 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/indexer/StandaloneIndexerInputAdapter.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/indexer/StandaloneIndexerInputAdapter.java @@ -6,8 +6,9 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn - initial API and implementation - * IBM Corporation + * Markus Schorn - initial API and implementation + * IBM Corporation + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.internal.core.indexer; @@ -55,7 +56,11 @@ public class StandaloneIndexerInputAdapter extends IndexerInputAdapter { return new File(URIUtil.toPath(location.getURI()).toOSString()).lastModified(); } - + @Override + public long getFileSize(IIndexFileLocation location) { + return new File(URIUtil.toPath(location.getURI()).toOSString()).length(); + } + @Override public String getEncoding(IIndexFileLocation ifl) { String encoding= getFileEncoding(getASTPath(ifl)); @@ -116,7 +121,6 @@ public class StandaloneIndexerInputAdapter extends IndexerInputAdapter { return result; } - @Override public boolean doesIncludeFileExist(String includePath) { return fExistsCache.isFile(includePath); @@ -182,7 +186,7 @@ public class StandaloneIndexerInputAdapter extends IndexerInputAdapter { public AbstractLanguage[] getLanguages(Object tu, UnusedHeaderStrategy strat) { ILanguage language = fIndexer.getLanguageMapper().getLanguage(tu.toString()); if (language instanceof AbstractLanguage) { - return new AbstractLanguage[] {(AbstractLanguage) language}; + return new AbstractLanguage[] { (AbstractLanguage) language }; } return new AbstractLanguage[0]; } @@ -199,5 +203,4 @@ public class StandaloneIndexerInputAdapter extends IndexerInputAdapter { public boolean isCaseInsensitiveFileSystem() { return new File("a").equals(new File("A")); } - } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/indexer/StandaloneIndexerTask.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/indexer/StandaloneIndexerTask.java index 03f23b95d78..48c9980ffc9 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/indexer/StandaloneIndexerTask.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/indexer/StandaloneIndexerTask.java @@ -6,8 +6,8 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn - initial API and implementation - * IBM Corporation + * Markus Schorn - initial API and implementation + * IBM Corporation *******************************************************************************/ package org.eclipse.cdt.internal.core.indexer; @@ -39,7 +39,6 @@ import com.ibm.icu.text.MessageFormat; * @since 4.0 */ public abstract class StandaloneIndexerTask extends AbstractIndexerTask { - protected StandaloneIndexer fIndexer; protected IParserLogService fLogger; @@ -47,7 +46,8 @@ public abstract class StandaloneIndexerTask extends AbstractIndexerTask { ILinkage.CPP_LINKAGE_ID, ILinkage.C_LINKAGE_ID, ILinkage.FORTRAN_LINKAGE_ID }; - protected StandaloneIndexerTask(StandaloneIndexer indexer, Collection added, Collection changed, Collection removed, boolean isFast) { + protected StandaloneIndexerTask(StandaloneIndexer indexer, Collection added, + Collection changed, Collection removed, boolean isFast) { super(concat(added, changed), removed.toArray(), new StandaloneIndexerInputAdapter(indexer), isFast); fIndexer= indexer; setShowActivity(fIndexer.getShowActivity()); @@ -57,8 +57,7 @@ public abstract class StandaloneIndexerTask extends AbstractIndexerTask { if (getIndexAllFiles()) { setIndexFilesWithoutBuildConfiguration(true); setIndexHeadersWithoutContext(UnusedHeaderStrategy.useDefaultLanguage); - } - else { + } else { setIndexFilesWithoutBuildConfiguration(false); setIndexHeadersWithoutContext(UnusedHeaderStrategy.skip); } @@ -104,7 +103,6 @@ public abstract class StandaloneIndexerTask extends AbstractIndexerTask { protected final IWritableIndex createIndex() { return fIndexer.getIndex(); } - public final void run(IProgressMonitor monitor) throws InterruptedException { long start = System.currentTimeMillis(); @@ -160,33 +158,22 @@ public abstract class StandaloneIndexerTask extends AbstractIndexerTask { } } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask#createStatus(java.lang.String) - */ @Override protected IStatus createStatus(String msg) { return new Status(IStatus.ERROR, "org.eclipse.cdt.core", msg, null); //$NON-NLS-1$ } - - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.pdom.PDOMWriter#createStatus(java.lang.String, java.lang.Throwable) - */ @Override protected IStatus createStatus(String msg, Throwable e) { return new Status(IStatus.ERROR, "org.eclipse.cdt.core", msg, e); //$NON-NLS-1$ } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask#getMessage(org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask.MessageKind, java.lang.Object[]) - */ @Override protected String getMessage(MessageKind kind, Object... arguments) { - // unfortunately we don't have OSGi on the remote system so for now we'll just settle for + // Unfortunately we don't have OSGi on the remote system so for now we'll just settle for // English strings // TODO: find a way to do non-OSGi NLS - switch(kind) { + switch (kind) { case parsingFileTask: return MessageFormat.format("parsing {0} ({1})", arguments); //$NON-NLS-1$ @@ -200,9 +187,6 @@ public abstract class StandaloneIndexerTask extends AbstractIndexerTask { return null; } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask#getLogService() - */ @Override protected IParserLogService getLogService() { if (fLogger != null) @@ -214,36 +198,23 @@ public abstract class StandaloneIndexerTask extends AbstractIndexerTask { fLogger = logService; } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask#logError(org.eclipse.core.runtime.IStatus) - */ @Override protected void logError(IStatus s) { trace(s.getMessage()); } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask#logException(java.lang.Throwable) - */ @Override protected void logException(Throwable e) { trace(e.getMessage()); } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask#getLinkagesToParse() - */ @Override protected int[] getLinkagesToParse() { return IDS_FOR_LINKAGES_TO_INDEX; } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.pdom.PDOMWriter#trace(java.lang.String) - */ @Override protected void trace(String message) { getLogService().traceLog(message); } - } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/ASTFilePathResolver.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/ASTFilePathResolver.java index 3215c4013b6..d1a14002d1f 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/ASTFilePathResolver.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/ASTFilePathResolver.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn - initial API and implementation + * Markus Schorn - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.internal.core.pdom; @@ -16,7 +16,6 @@ import org.eclipse.cdt.core.index.IIndexFileLocation; * Abstract class for resolving paths as computed by the parser. */ public abstract class ASTFilePathResolver { - /** * Resolve a path as stored in the AST. * @return an index file location. diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/AbstractIndexerTask.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/AbstractIndexerTask.java index d99c50908ee..9c30c079929 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/AbstractIndexerTask.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/AbstractIndexerTask.java @@ -71,12 +71,11 @@ import org.eclipse.osgi.util.NLS; * @since 5.0 */ public abstract class AbstractIndexerTask extends PDOMWriter { - public static enum UnusedHeaderStrategy { - skip, useC, useCPP, useDefaultLanguage, useBoth - } + public static enum UnusedHeaderStrategy { skip, useC, useCPP, useDefaultLanguage, useBoth } private static final int MAX_ERRORS = 500; - private static enum UpdateKind {REQUIRED_SOURCE, REQUIRED_HEADER, ONE_LINKAGE_HEADER, OTHER_HEADER} + private static enum UpdateKind { REQUIRED_SOURCE, REQUIRED_HEADER, ONE_LINKAGE_HEADER, OTHER_HEADER } + private static class LinkageTask { final int fLinkageID; private final Map fLocationTasks; @@ -687,7 +686,7 @@ public abstract class AbstractIndexerTask extends PDOMWriter { Object tu, IIndexFragmentFile file) throws CoreException { if (checkTimestamps) { if (fResolver.getLastModified(ifl) != file.getTimestamp() || - fResolver.getEncoding(ifl).hashCode() != file.getEncodingHashcode()) { + computeFileSizeAndEncodingHashcode(ifl) != file.getSizeAndEncodingHashcode()) { if (checkFileContentsHash && computeFileContentsHash(tu) == file.getContentsHash()) { return false; } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/IndexerInputAdapter.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/IndexerInputAdapter.java index 7d02e96c2e5..d49d6c13d81 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/IndexerInputAdapter.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/IndexerInputAdapter.java @@ -6,7 +6,8 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn - initial API and implementation + * Markus Schorn - initial API and implementation + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.internal.core.pdom; @@ -22,7 +23,6 @@ import org.eclipse.cdt.core.parser.IScannerInfo; * @since 5.0 */ public abstract class IndexerInputAdapter extends ASTFilePathResolver { - /** * Returns an object representing an input file for the given index location, * or null, if it does not exist. @@ -34,6 +34,16 @@ public abstract class IndexerInputAdapter extends ASTFilePathResolver { */ public abstract long getLastModified(IIndexFileLocation location); + /** + * Returns the size of the file in bytes, or 0 if the file does not exist. + */ + public abstract long getFileSize(IIndexFileLocation ifl); + + /** + * Returns the encoding for the file. + */ + public abstract String getEncoding(IIndexFileLocation ifl); + /** * Create an index location for the given input file. */ @@ -82,8 +92,4 @@ public abstract class IndexerInputAdapter extends ASTFilePathResolver { * Returns a code reader for the given input file. */ public abstract FileContent getCodeReader(Object tu); - /** - * Returns the encoding for the file. - */ - public abstract String getEncoding(IIndexFileLocation ifl); } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOM.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOM.java index 3ea6248527f..c0e9f1fede2 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOM.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOM.java @@ -213,10 +213,11 @@ public class PDOM extends PlatformObject implements IPDOM { * 120.1 - Specializations of using declarations, bug 357293. * 121.0 - Multiple variants of included header file, bug 197989. * 122.0 - Compacting strings + * 123.0 - Combined file size and encoding hash code. */ - private static final int MIN_SUPPORTED_VERSION= version(122, 0); - private static final int MAX_SUPPORTED_VERSION= version(122, Short.MAX_VALUE); - private static final int DEFAULT_VERSION = version(122, 0); + private static final int MIN_SUPPORTED_VERSION= version(123, 0); + private static final int MAX_SUPPORTED_VERSION= version(123, Short.MAX_VALUE); + private static final int DEFAULT_VERSION = version(123, 0); private static int version(int major, int minor) { return (major << 16) + minor; @@ -232,12 +233,15 @@ public class PDOM extends PlatformObject implements IPDOM { public static boolean isSupportedVersion(int vers) { return vers >= MIN_SUPPORTED_VERSION && vers <= MAX_SUPPORTED_VERSION; } + public static int getMinSupportedVersion() { return MIN_SUPPORTED_VERSION; } + public static int getMaxSupportedVersion() { return MAX_SUPPORTED_VERSION; } + public static String versionString(int version) { final int major= version >> 16; final int minor= version & 0xffff; @@ -952,7 +956,8 @@ public class PDOM extends PlatformObject implements IPDOM { CCorePlugin.log(e); } assert lockCount == -1; - lastWriteAccess= System.currentTimeMillis(); + if (!fEvent.isTrivial()) + lastWriteAccess= System.currentTimeMillis(); final ChangeEvent event= fEvent; fEvent= new ChangeEvent(); synchronized (mutex) { diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOMWriter.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOMWriter.java index 7bf753147d3..ed854f09862 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOMWriter.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOMWriter.java @@ -560,7 +560,7 @@ abstract public class PDOMWriter { index.setFileContent(file, linkageID, includeInfoArray, macros, names, fResolver, lock); } file.setTimestamp(fResolver.getLastModified(location)); - file.setEncodingHashcode(fResolver.getEncoding(location).hashCode()); + file.setSizeAndEncodingHashcode(computeFileSizeAndEncodingHashcode(location)); file.setContentsHash(astFile.fContentsHash); file = index.commitUncommittedFile(); } finally { @@ -569,6 +569,10 @@ abstract public class PDOMWriter { return file; } + protected int computeFileSizeAndEncodingHashcode(IIndexFileLocation location) { + return ((int) fResolver.getFileSize(location)) + 31 * fResolver.getEncoding(location).hashCode(); + } + private boolean isContextFor(IIndexFragmentFile oldFile, IASTPreprocessorIncludeStatement stmt) throws CoreException { IIndexFile target= stmt.getImportedIndexFile(); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/db/IBTreeVisitor.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/db/IBTreeVisitor.java index cb3461b0ea6..e22c1895174 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/db/IBTreeVisitor.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/db/IBTreeVisitor.java @@ -6,8 +6,8 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * QNX - Initial API and implementation - * Markus Schorn (Wind River Systems) + * QNX - Initial API and implementation + * Markus Schorn (Wind River Systems) *******************************************************************************/ package org.eclipse.cdt.internal.core.pdom.db; @@ -19,7 +19,6 @@ import org.eclipse.core.runtime.CoreException; * The visitor visits all records where compare returns 0. */ public interface IBTreeVisitor { - /** * Compare the record against an internally held key. The comparison must be * compatible with the one used for the btree. @@ -37,6 +36,5 @@ public interface IBTreeVisitor { * @return true to continue the visit, false to abort it. * @throws CoreException */ - public abstract boolean visit(long record) throws CoreException; - + public abstract boolean visit(long record) throws CoreException; } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/dom/PDOMFile.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/dom/PDOMFile.java index a896f2a3f58..a8692a2927c 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/dom/PDOMFile.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/dom/PDOMFile.java @@ -74,8 +74,8 @@ public class PDOMFile implements IIndexFragmentFile { private static final int FLAGS= LINKAGE_ID + 3; // size 1 private static final int TIME_STAMP = FLAGS + 1; // long private static final int CONTENT_HASH= TIME_STAMP + 8; // long - private static final int ENCODING_HASH= CONTENT_HASH + 8; - private static final int LAST_USING_DIRECTIVE= ENCODING_HASH + 4; + private static final int SIZE_AND_ENCODING_HASH= CONTENT_HASH + 8; + private static final int LAST_USING_DIRECTIVE= SIZE_AND_ENCODING_HASH + 4; private static final int FIRST_MACRO_REFERENCE= LAST_USING_DIRECTIVE + Database.PTR_SIZE; private static final int SIGNIFICANT_MACROS= FIRST_MACRO_REFERENCE + Database.PTR_SIZE; private static final int RECORD_SIZE= SIGNIFICANT_MACROS + Database.PTR_SIZE; // 8*PTR_SIZE + 3+1+8+8+4 = 56 @@ -205,7 +205,7 @@ public class PDOMFile implements IIndexFragmentFile { } setTimestamp(sourceFile.getTimestamp()); - setEncodingHashcode(sourceFile.getEncodingHashcode()); + setSizeAndEncodingHashcode(sourceFile.getSizeAndEncodingHashcode()); setContentsHash(sourceFile.getContentsHash()); // Transfer the flags. @@ -327,15 +327,21 @@ public class PDOMFile implements IIndexFragmentFile { } @Override - public int getEncodingHashcode() throws CoreException { + public int getSizeAndEncodingHashcode() throws CoreException { Database db = fLinkage.getDB(); - return db.getInt(record + ENCODING_HASH); + return db.getInt(record + SIZE_AND_ENCODING_HASH); } @Override - public void setEncodingHashcode(int hashcode) throws CoreException { + @Deprecated + public int getEncodingHashcode() throws CoreException { + return 0; + } + + @Override + public void setSizeAndEncodingHashcode(int hashcode) throws CoreException { Database db= fLinkage.getDB(); - db.putInt(record + ENCODING_HASH, hashcode); + db.putInt(record + SIZE_AND_ENCODING_HASH, hashcode); } @Override diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/ProjectIndexerInputAdapter.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/ProjectIndexerInputAdapter.java index c82b1a90df8..bfb8c6cba4c 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/ProjectIndexerInputAdapter.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/ProjectIndexerInputAdapter.java @@ -6,8 +6,8 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn - initial API and implementation - * Sergey Prigogin (Google) + * Markus Schorn - initial API and implementation + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.internal.core.pdom.indexer; @@ -178,6 +178,24 @@ public class ProjectIndexerInputAdapter extends IndexerInputAdapter { return 0; } + @Override + public long getFileSize(IIndexFileLocation ifl) { + String fullPath= ifl.getFullPath(); + IPath location= null; + if (fullPath != null) { + IResource res= ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(fullPath)); + if (res != null) { + location = res.getLocation(); + } + } else { + location= IndexLocationFactory.getAbsolutePath(ifl); + } + if (location != null) { + return location.toFile().length(); + } + return 0; + } + @Override public String getEncoding(IIndexFileLocation ifl) { String fullPath= ifl.getFullPath(); diff --git a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/core/ErrorParserManager.java b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/core/ErrorParserManager.java index 8b9c0b320b8..37777c8a269 100644 --- a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/core/ErrorParserManager.java +++ b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/core/ErrorParserManager.java @@ -50,7 +50,7 @@ import org.osgi.service.prefs.BackingStoreException; * * @noextend This class is not intended to be subclassed by clients. */ -public class ErrorParserManager extends OutputStream { +public class ErrorParserManager extends OutputStream implements IConsoleParser { /** * The list of error parsers stored in .project for 3.X projects * as key/value pair with key="org.eclipse.cdt.core.errorOutputParser" @@ -306,9 +306,11 @@ public class ErrorParserManager extends OutputStream { } /** - * Parses the input and tries to generate error or warning markers + * Parses one line of output and generates error or warning markers. + * @since 5.4 */ - private void processLine(String line) { + @Override + public boolean processLine(String line) { String lineTrimmed = line.trim(); lineCounter++; @@ -363,6 +365,8 @@ outer: } } outputLine(line, marker); + + return false; } /** @@ -848,4 +852,11 @@ outer: } return result; } + + /** + * @since 5.4 + */ + @Override + public void shutdown() { + } } diff --git a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/core/resources/RefreshScopeManager.java b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/core/resources/RefreshScopeManager.java index 559e3cf5999..d8941f98add 100644 --- a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/core/resources/RefreshScopeManager.java +++ b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/core/resources/RefreshScopeManager.java @@ -485,12 +485,35 @@ public class RefreshScopeManager { String configName = child.getAttribute(CONFIGURATION_ELEMENT_NAME); loadResourceData(workspaceRoot, project, configName, child.getChildren()); } - } + } + // else there are no children, and this is a "new" project. + // so initialize it. + if (children.length == 0) { + initializeConfigMap(project); + } } } } } + private void initializeConfigMap(IProject project) { + getProjectToConfigurationToResourcesMap(); + HashMap>> configMap = fProjToConfToResToExcluMap.get(project); + if (configMap == null) { + configMap = new HashMap>>(); + CProjectDescriptionManager descriptionManager = CProjectDescriptionManager.getInstance(); + ICProjectDescription projectDescription = descriptionManager.getProjectDescription(project, false); + ICConfigurationDescription cfgDescs[] = projectDescription.getConfigurations(); + for (ICConfigurationDescription cfgDesc : cfgDescs) { + String configName = cfgDesc.getName(); + HashMap> resourceMap = new HashMap>(); + resourceMap.put(project, new LinkedList()); + configMap.put(configName, resourceMap); + } + fProjToConfToResToExcluMap.put(project,configMap); + } + } + /** * @since 5.4 */ diff --git a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/BuildRunnerHelper.java b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/BuildRunnerHelper.java new file mode 100644 index 00000000000..d15fa295114 --- /dev/null +++ b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/BuildRunnerHelper.java @@ -0,0 +1,510 @@ +/******************************************************************************* + * Copyright (c) 2012, 2012 Andrew Gvozdev and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Andrew Gvozdev - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.internal.core; + +import java.io.Closeable; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; + +import org.eclipse.cdt.core.CCorePlugin; +import org.eclipse.cdt.core.ErrorParserManager; +import org.eclipse.cdt.core.ICommandLauncher; +import org.eclipse.cdt.core.IConsoleParser; +import org.eclipse.cdt.core.model.ICModelMarker; +import org.eclipse.cdt.core.resources.IConsole; +import org.eclipse.cdt.core.resources.RefreshScopeManager; +import org.eclipse.cdt.utils.EFSExtensionManager; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.IWorkspaceRunnable; +import org.eclipse.core.resources.IncrementalProjectBuilder; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.Assert; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.QualifiedName; +import org.eclipse.core.runtime.SubProgressMonitor; + +/** + * Helper class attempting to unify interactions with build console, + * such as style of console output and handling of console output parsers. + * + * As of CDT 8.1, this class is experimental, internal and work in progress. + * API is unstable and subject to change. + */ +public class BuildRunnerHelper implements Closeable { + private static final String PROGRESS_MONITOR_QUALIFIER = CCorePlugin.PLUGIN_ID + ".progressMonitor"; //$NON-NLS-1$ + private static final int MONITOR_SCALE = 100; + + private IProject project; + + private IConsole console = null; + private ErrorParserManager errorParserManager = null; + private StreamMonitor streamMon = null; + private OutputStream stdout = null; + private OutputStream stderr = null; + private OutputStream consoleOut = null; + private OutputStream consoleInfo = null; + + private long startTime = 0; + private long endTime = 0; + + private QualifiedName progressPropertyName = null; + + private ICommandLauncher launcher; + private IPath buildCommand; + private String[] args; + private URI workingDirectoryURI; + String[] envp; + + private boolean isStreamsOpen = false; + boolean isCancelled = false; + + /** + * Constructor. + */ + public BuildRunnerHelper(IProject project) { + this.project = project; + } + + /** + * Set parameters for the launch. + * @param envp - String[] array of environment variables in format "var=value" suitable for using + * as "envp" with Runtime.exec(String[] cmdarray, String[] envp, File dir) + */ + public void setLaunchParameters(ICommandLauncher launcher, IPath buildCommand, String[] args, URI workingDirectoryURI, String[] envp) { + this.launcher = launcher; + launcher.setProject(project); + // Print the command for visual interaction. + launcher.showCommand(true); + + this.buildCommand = buildCommand; + this.args = args; + this.workingDirectoryURI = workingDirectoryURI; + this.envp = envp; + } + + /** + * Open and set up streams for use by {@link BuildRunnerHelper}. + * This must be followed by {@link #close()} to close the streams. Use try...finally for that. + * + * @param epm - ErrorParserManger for error parsing and coloring errors on the console + * @param buildOutputParsers - list of console output parsers or {@code null}. + * @param con - the console. + * @param monitor - progress monitor in the initial state where {@link IProgressMonitor#beginTask(String, int)} + * has not been called yet. + * @throws CoreException + */ + public void prepareStreams(ErrorParserManager epm, List buildOutputParsers, IConsole con, IProgressMonitor monitor) throws CoreException { + errorParserManager = epm; + console = con; + + // Visualize the flow of the streams: + // + // console <- EPM + // ^ + // IConsoleParsers (includes EPM + other parsers) + // ^ + // null <- StreamMomitor <= Sniffer <= Process (!!! the flow starts here!) + // + + isStreamsOpen = true; + + consoleOut = console.getOutputStream(); + // stdout/stderr get to the console through ErrorParserManager + errorParserManager.setOutputStream(consoleOut); + + List parsers = new ArrayList(); + // Using ErrorParserManager as console parser helps to avoid intermixing buffered streams + // as ConsoleOutputSniffer waits for EOL to send a line to console parsers + // separately for each stream. + parsers.add(errorParserManager); + if (buildOutputParsers != null) { + parsers.addAll(buildOutputParsers); + } + + Integer lastWork = null; + if (buildCommand != null) { + progressPropertyName = getProgressPropertyName(buildCommand, args); + lastWork = (Integer)project.getSessionProperty(progressPropertyName); + } + if (lastWork == null) { + lastWork = MONITOR_SCALE; + } + + streamMon = new StreamMonitor(monitor, null, lastWork.intValue()); + ConsoleOutputSniffer sniffer = new ConsoleOutputSniffer(streamMon, streamMon, parsers.toArray(new IConsoleParser[parsers.size()])); + stdout = sniffer.getOutputStream(); + stderr = sniffer.getErrorStream(); + } + + /** + * @return the output stream to connect stdout of a process + */ + public OutputStream getOutputStream() { + return stdout; + } + + /** + * @return the output stream to connect stderr of a process + */ + public OutputStream getErrorStream() { + return stderr; + } + + /** + * Remove problem markers created for the resource by previous build. + * + * @param rc - resource to remove its markers. + * @param monitor - progress monitor in the initial state where {@link IProgressMonitor#beginTask(String, int)} + * has not been called yet. + * @throws CoreException + */ + public void removeOldMarkers(IResource rc, IProgressMonitor monitor) throws CoreException { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + try { + monitor.beginTask("", IProgressMonitor.UNKNOWN); //$NON-NLS-1$ + monitor.subTask(CCorePlugin.getFormattedString("BuildRunnerHelper.removingMarkers", rc.getFullPath().toString())); //$NON-NLS-1$ + rc.deleteMarkers(ICModelMarker.C_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE); + } finally { + monitor.done(); + } + } + + /** + * Launch build command and process console output. + * + * @param monitor - progress monitor in the initial state where {@link IProgressMonitor#beginTask(String, int)} + * has not been called yet. + * @throws CoreException + * @throws IOException + */ + public int build(IProgressMonitor monitor) throws CoreException, IOException { + Assert.isNotNull(launcher, "Launch parameters must be set before calling this method"); //$NON-NLS-1$ + Assert.isNotNull(errorParserManager, "Streams must be created and connected before calling this method"); //$NON-NLS-1$ + + int status = ICommandLauncher.ILLEGAL_COMMAND; + + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + try { + monitor.beginTask("", 2 * MONITOR_SCALE); //$NON-NLS-1$ + + isCancelled = false; + String pathFromURI = EFSExtensionManager.getDefault().getPathFromURI(workingDirectoryURI); + if(pathFromURI == null) { + // fallback to CWD + pathFromURI = System.getProperty("user.dir"); //$NON-NLS-1$ + } + IPath workingDirectory = new Path(pathFromURI); + + String errMsg = null; + Process p = launcher.execute(buildCommand, args, envp, workingDirectory, monitor); + if (p != null) { + try { + // Close the input of the Process explicitly. + // We will never write to it. + p.getOutputStream().close(); + } catch (IOException e) { + } + // Before launching give visual cues via the monitor + monitor.subTask(CCorePlugin.getFormattedString("BuildRunnerHelper.invokingCommand", launcher.getCommandLine())); //$NON-NLS-1$ + + status = launcher.waitAndRead(stdout, stderr, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); + if (status != ICommandLauncher.OK) { + errMsg = launcher.getErrorMessage(); + } + } else { + errMsg = launcher.getErrorMessage(); + } + + if (errMsg != null && !errMsg.isEmpty()) { + stderr.write(errMsg.getBytes()); + } + + isCancelled = monitor.isCanceled(); + if (!isCancelled) { + project.setSessionProperty(progressPropertyName, new Integer(streamMon.getWorkDone())); + } + } finally { + monitor.done(); + } + return status; + } + + /** + * Close all streams. + */ + @Override + public void close() throws IOException { + if (!isStreamsOpen) + return; + + try { + if (stdout != null) + stdout.close(); + } catch (Exception e) { + CCorePlugin.log(e); + } finally { + try { + if (stderr != null) + stderr.close(); + } catch (Exception e) { + CCorePlugin.log(e); + } finally { + try { + if (streamMon != null) + streamMon.close(); + } catch (Exception e) { + CCorePlugin.log(e); + } finally { + try { + if (consoleOut != null) + consoleOut.close(); + } catch (Exception e) { + CCorePlugin.log(e); + } + } + } + } + isStreamsOpen = false; + } + + /** + * Refresh project in the workspace. + * + * @param monitor - progress monitor in the initial state where {@link IProgressMonitor#beginTask(String, int)} + * has not been called yet. + */ + public void refreshProject(IProgressMonitor monitor) { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + try { + monitor.beginTask(CCorePlugin.getResourceString("BuildRunnerHelper.updatingProject"), IProgressMonitor.UNKNOWN); //$NON-NLS-1$ + + // Do not allow the cancel of the refresh, since the builder is external + // to Eclipse, files may have been created/modified and we will be out-of-sync. + // The caveat is for huge projects, it may take sometimes at every build. + // Use the refresh scope manager to refresh + RefreshScopeManager refreshManager = RefreshScopeManager.getInstance(); + IWorkspaceRunnable runnable = refreshManager.getRefreshRunnable(project); + ResourcesPlugin.getWorkspace().run(runnable, null, IWorkspace.AVOID_UPDATE, null); + } catch (CoreException e) { + // ignore exceptions + } finally { + monitor.done(); + } + } + + /** + * Print a standard greeting to the console. + * Note that start time of the build is recorded by this method. + * + * @param kind - kind of build. {@link IncrementalProjectBuilder} constants such as + * {@link IncrementalProjectBuilder#FULL_BUILD} should be used. + */ + public void greeting(int kind) { + String msg = CCorePlugin.getFormattedString("BuildRunnerHelper.buildProject", //$NON-NLS-1$ + new String[] { buildKindToString(kind), project.getName() }); + greeting(msg); + } + + /** + * Print a standard greeting to the console. + * Note that start time of the build is recorded by this method. + * + * @param kind - kind of build. {@link IncrementalProjectBuilder} constants such as + * {@link IncrementalProjectBuilder#FULL_BUILD} should be used. + * @param cfgName - configuration name. + * @param toolchainName - tool-chain name. + * @param isSupported - flag indicating if tool-chain is supported on the system. + */ + public void greeting(int kind, String cfgName, String toolchainName, boolean isSupported) { + greeting(buildKindToString(kind), cfgName, toolchainName, isSupported); + } + + /** + * Print a standard greeting to the console. + * Note that start time of the build is recorded by this method. + * + * @param kind - kind of build as a String. + * @param cfgName - configuration name. + * @param toolchainName - tool-chain name. + * @param isSupported - flag indicating if tool-chain is supported on the system. + */ + public void greeting(String kind, String cfgName, String toolchainName, boolean isSupported) { + String msg = CCorePlugin.getFormattedString("BuildRunnerHelper.buildProjectConfiguration", //$NON-NLS-1$ + new String[] { kind, cfgName, project.getName() }); + greeting(msg); + + if (!isSupported ){ + String errMsg = CCorePlugin.getFormattedString("BuildRunnerHelper.unsupportedConfiguration", //$NON-NLS-1$ + new String[] { cfgName, toolchainName }); + printLine(errMsg); + } + } + + /** + * Print the specified greeting to the console. + * Note that start time of the build is recorded by this method. + */ + public void greeting(String msg) { + startTime = System.currentTimeMillis(); + toConsole(BuildRunnerHelper.timestamp(startTime) + "**** " + msg + " ****"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Print a standard footer to the console. + * That prints duration of the build determined by start time recorded in {@link #greeting(String)}. + * + *
Important: {@link #close()} the streams BEFORE calling this method to properly flush all outputs + */ + public void goodbye() { + Assert.isTrue(startTime != 0, "Start time must be set before calling this method"); //$NON-NLS-1$ + Assert.isTrue(!isStreamsOpen, "Close streams before calling this method."); //$NON-NLS-1$ + + endTime = System.currentTimeMillis(); + String duration = durationToString(endTime - startTime); + String msg = isCancelled ? CCorePlugin.getFormattedString("BuildRunnerHelper.buildCancelled", duration) //$NON-NLS-1$ + : CCorePlugin.getFormattedString("BuildRunnerHelper.buildFinished", duration); //$NON-NLS-1$ + String goodbye = '\n' + timestamp(endTime) + msg + '\n'; + toConsole(goodbye); + } + + /** + * Print the given message to the console. + * @param msg - message to print. + */ + public void printLine(String msg) { + Assert.isNotNull(errorParserManager, "Streams must be created and connected before calling this method"); //$NON-NLS-1$ + errorParserManager.processLine(msg); + } + + /** + * Print a message to the console info output. Note that this message is colored + * with the color assigned to "Info" stream. + * @param msg - message to print. + */ + private void toConsole(String msg) { + Assert.isNotNull(console, "Streams must be created and connected before calling this method"); //$NON-NLS-1$ + try { + if (consoleInfo == null) { + consoleInfo = console.getInfoStream(); + } + consoleInfo.write((msg+"\n").getBytes()); //$NON-NLS-1$ + } catch (Exception e) { + CCorePlugin.log(e); + } + } + + /** + * Qualified name to keep previous value of build duration in project session properties. + */ + private static QualifiedName getProgressPropertyName(IPath buildCommand, String[] args) { + String name = buildCommand.toString(); + if (args != null) { + for (String arg : args) { + name = name + ' ' + arg; + } + } + return new QualifiedName(PROGRESS_MONITOR_QUALIFIER, name); + } + + /** + * Convert map of environment variables to array of "var=value" + * + * @param envMap - map of environment variables + * @return String array of environment variables in format "var=value" suitable for using + * as "envp" with Runtime.exec(String[] cmdarray, String[] envp, File dir) + */ + public static String[] envMapToEnvp(Map envMap) { + // Convert into env strings + List strings= new ArrayList(envMap.size()); + for (Entry entry : envMap.entrySet()) { + StringBuffer buffer= new StringBuffer(entry.getKey()); + buffer.append('=').append(entry.getValue()); + strings.add(buffer.toString()); + } + + return strings.toArray(new String[strings.size()]); + } + + /** + * Convert duration to human friendly format. + */ + @SuppressWarnings("nls") + private static String durationToString(long duration) { + String result = ""; + long days = TimeUnit.MILLISECONDS.toDays(duration); + if (days > 0) { + result += days + "d,"; + } + long hours = TimeUnit.MILLISECONDS.toHours(duration) % 24; + if (hours > 0) { + result += hours + "h:"; + } + long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) % 60; + if (minutes > 0) { + result += minutes + "m:"; + } + long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) % 60; + if (seconds > 0) { + result += seconds + "s."; + } + long milliseconds = TimeUnit.MILLISECONDS.toMillis(duration) % 1000; + result += milliseconds + "ms"; + + return result; + } + + /** + * Supply timestamp to prefix informational messages. + */ + @SuppressWarnings("nls") + private static String timestamp(long time) { + return new SimpleDateFormat("HH:mm:ss").format(new Date(time)) + " "; + } + + /** + * Convert build kind to human friendly format. + */ + private static String buildKindToString(int kind) { + switch (kind) { + case IncrementalProjectBuilder.FULL_BUILD: + return CCorePlugin.getResourceString("BuildRunnerHelper.build"); //$NON-NLS-1$ + case IncrementalProjectBuilder.INCREMENTAL_BUILD: + return CCorePlugin.getResourceString("BuildRunnerHelper.incrementalBuild"); //$NON-NLS-1$ + case IncrementalProjectBuilder.AUTO_BUILD: + return CCorePlugin.getResourceString("BuildRunnerHelper.autoBuild"); //$NON-NLS-1$ + case IncrementalProjectBuilder.CLEAN_BUILD: + return CCorePlugin.getResourceString("BuildRunnerHelper.cleanBuild"); //$NON-NLS-1$ + default: + return CCorePlugin.getResourceString("BuildRunnerHelper.build"); //$NON-NLS-1$ + } + } +} diff --git a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/CCorePluginResources.properties b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/CCorePluginResources.properties index cfcf1d84e09..36637f2d9e6 100644 --- a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/CCorePluginResources.properties +++ b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/CCorePluginResources.properties @@ -90,3 +90,16 @@ CConfigBasedDescriptorManager.3=Failed to create descriptor CConfigBasedDescriptorManager.4=error: read-only configuration can not be used for CDescriptor CConfigBasedDescriptorManager.5=the project does not contain valid configurations CCorePlugin.startupJob=CDT Startup + +BuildRunnerHelper.unsupportedConfiguration=Info: Configuration "{0}" uses tool-chain "{1}" that is unsupported on this system, attempting to build anyway. +BuildRunnerHelper.removingMarkers=Removing problem markers for {0} +BuildRunnerHelper.invokingCommand=Invoking Command: {0} +BuildRunnerHelper.updatingProject=Updating project... +BuildRunnerHelper.buildProject={0} of project {1} +BuildRunnerHelper.buildProjectConfiguration={0} of configuration {1} for project {2} +BuildRunnerHelper.buildFinished=Build Finished (took {0}) +BuildRunnerHelper.buildCancelled=Build Cancelled (took {0}) +BuildRunnerHelper.build=Build +BuildRunnerHelper.incrementalBuild=Incremental Build +BuildRunnerHelper.autoBuild=Auto Build +BuildRunnerHelper.cleanBuild=Clean-only build diff --git a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/ConsoleOutputSniffer.java b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/ConsoleOutputSniffer.java index 636fe70164e..150b1bb0431 100644 --- a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/ConsoleOutputSniffer.java +++ b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/ConsoleOutputSniffer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2008 IBM Corporation and others. + * Copyright (c) 2004, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,127 +21,116 @@ import org.eclipse.cdt.core.IErrorParser; /** * Intercepts an output to console and forwards it to console parsers for processing - * - * @author vhirsl */ public class ConsoleOutputSniffer { - /* - * Private class to sniffer the output stream for this snifffer. - */ - private class ConsoleOutputStream extends OutputStream { - // Stream's private buffer for the stream's read contents. - private StringBuffer currentLine = new StringBuffer(); - private OutputStream outputStream = null; - + /** + * Private class to sniff the output stream for this sniffer. + */ + private class ConsoleOutputStream extends OutputStream { + // Stream's private buffer for the stream's read contents. + private StringBuffer currentLine = new StringBuffer(); + private OutputStream outputStream = null; + public ConsoleOutputStream(OutputStream outputStream) { this.outputStream = outputStream; } - /* (non-Javadoc) - * @see java.io.OutputStream#write(int) - */ - @Override + @Override public void write(int b) throws IOException { - currentLine.append((char) b); - checkLine(false); + currentLine.append((char) b); + checkLine(false); - // Continue writing the bytes to the console's output. - if (outputStream != null) { - outputStream.write(b); - } - } - - /* (non-Javadoc) - * @see java.io.OutputStream#write(byte[], int, int) - */ - @Override + // Continue writing the bytes to the console's output. + if (outputStream != null) { + outputStream.write(b); + } + } + + @Override public void write(byte[] b, int off, int len) throws IOException { - if (b == null) { - throw new NullPointerException(); - } else if (off != 0 || (len < 0) || (len > b.length)) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) { - return; - } - currentLine.append(new String(b, 0, len)); - checkLine(false); - - // Continue writing the bytes to the console's output. - if (outputStream != null) - outputStream.write(b, off, len); - } - - /* (non-Javadoc) - * @see java.io.OutputStream#close() - */ - @Override + if (b == null) { + throw new NullPointerException(); + } else if (off != 0 || (len < 0) || (len > b.length)) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) { + return; + } + currentLine.append(new String(b, 0, len)); + checkLine(false); + + // Continue writing the bytes to the console's output. + if (outputStream != null) + outputStream.write(b, off, len); + } + + @Override public void close() throws IOException { - checkLine(true); - closeConsoleOutputStream(); - } - - /* (non-Javadoc) - * @see java.io.OutputStream#flush() - */ - @Override + checkLine(true); + closeConsoleOutputStream(); + } + + @Override public void flush() throws IOException { - if (outputStream != null) { - outputStream.flush(); - } - } + if (outputStream != null) { + outputStream.flush(); + } + } - /* - * Checks to see if the already read input constitutes - * a complete line (e.g. does the sniffing). If so, then - * send it to processLine. - * - * @param flush - */ - private void checkLine(boolean flush) { - String buffer = currentLine.toString(); - int i = 0; - while ((i = buffer.indexOf('\n')) != -1) { - // get rid of any trailing whitespace but keep leading whitespaces (bug 199245) - int end= i; - while(end > 0 && buffer.charAt(end-1) <= ' ') { // see String.trim() - end--; - } - if (end > 0) { - String line = buffer.substring(0, end); - processLine(line); - } - buffer = buffer.substring(i + 1); // skip the \n and advance - } - currentLine.setLength(0); - if (flush) { - if (buffer.length() > 0) { - processLine(buffer); - } - } else { - currentLine.append(buffer); - } - } + /** + * Checks to see if the already read input constitutes + * a complete line (e.g. does the sniffing). If so, then + * send it to processLine. + * + * @param flush + */ + private void checkLine(boolean flush) { + if (currentLine.length() == 0) { + return; + } + + String buffer = currentLine.toString(); + int i = 0; + while ((i = buffer.indexOf('\n')) != -1) { + int eol = i; + if (i > 0 && buffer.charAt(i-1) == '\r') { + // also get rid of trailing \r in case of Windows line delimiter "\r\n" + eol = i - 1; + } + String line = buffer.substring(0, eol); + processLine(line); + + buffer = buffer.substring(i + 1); // skip the \n and advance + } + currentLine.setLength(0); + if (flush) { + if (buffer.length() > 0) { + processLine(buffer); + } + } else { + currentLine.append(buffer); + } + } + + } // end ConsoleOutputStream class - } // end ConsoleOutputStream class - private int nOpens = 0; private OutputStream consoleOutputStream; private OutputStream consoleErrorStream; private IConsoleParser[] parsers; - + private ErrorParserManager errorParserManager = null; public ConsoleOutputSniffer(IConsoleParser[] parsers) { this.parsers = parsers; } - + public ConsoleOutputSniffer(OutputStream outputStream, OutputStream errorStream, IConsoleParser[] parsers) { this(parsers); this.consoleOutputStream = outputStream; this.consoleErrorStream = errorStream; } - + public ConsoleOutputSniffer(OutputStream outputStream, OutputStream errorStream, IConsoleParser[] parsers, ErrorParserManager epm) { this(outputStream, errorStream, parsers); this.errorParserManager = epm; @@ -153,24 +142,24 @@ public class ConsoleOutputSniffer { * output stream goes into here. */ public OutputStream getOutputStream() { - incNOpens(); - return new ConsoleOutputStream(consoleOutputStream); + incNOpens(); + return new ConsoleOutputStream(consoleOutputStream); } - + /** * Returns an error stream that will be sniffed. * This stream should be hooked up so the command * error stream goes into here. */ public OutputStream getErrorStream() { - incNOpens(); - return new ConsoleOutputStream(consoleErrorStream); + incNOpens(); + return new ConsoleOutputStream(consoleErrorStream); } - + private synchronized void incNOpens() { - nOpens++; + nOpens++; } - + /* */ public synchronized void closeConsoleOutputStream() throws IOException { @@ -186,10 +175,10 @@ public class ConsoleOutputSniffer { } } } - + /* * Processes the line by passing the line to the parsers. - * + * * @param line */ private synchronized void processLine(String line) { @@ -207,5 +196,5 @@ public class ConsoleOutputSniffer { } } } - + } diff --git a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/StreamMonitor.java b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/StreamMonitor.java new file mode 100644 index 00000000000..26796c8ad91 --- /dev/null +++ b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/StreamMonitor.java @@ -0,0 +1,109 @@ +/******************************************************************************* + * Copyright (c) 2000, 2010 QNX Software Systems and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * QNX Software Systems - Initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.internal.core; + +import java.io.IOException; +import java.io.OutputStream; + +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * Helper class to report progress of the build via {@link IProgressMonitor} + */ +public class StreamMonitor extends OutputStream { + + private IProgressMonitor monitor; + private OutputStream console; + private final int fTotalWork; + private int halfWay; + private int currentIncrement = 2; + private int nextProgress = currentIncrement; + private int worked = 0; + + public StreamMonitor(IProgressMonitor mon, OutputStream cos, int totalWork) { + monitor = mon; + console = cos; + fTotalWork = totalWork; + halfWay = fTotalWork / 2; + monitor.beginTask("", fTotalWork); //$NON-NLS-1$ + } + + private void progressUpdate() { + if (--nextProgress <= 0) { + //we have exhausted the current increment, so report progress + if (fTotalWork > worked) { + monitor.worked(1); + } + worked++; + if (worked >= halfWay) { + //we have passed the current halfway point, so double the + //increment and reset the halfway point. + currentIncrement *= 2; + halfWay += (fTotalWork - halfWay) / 2; + } + //reset the progress counter to another full increment + nextProgress = currentIncrement; + } + } + /** + * @see java.io.OutputStream#close() + */ + @Override + public void close() throws IOException { + if (console != null) { + console.close(); + } + monitor.done(); + } + + /** + * @see java.io.OutputStream#flush() + */ + @Override + public void flush() throws IOException { + if (console != null) { + console.flush(); + } + } + + /** + * @see java.io.OutputStream#write(int) + */ + @Override + public synchronized void write(int b) throws IOException { + if (console != null) { + console.write(b); + } + progressUpdate(); + } + + /** + * @see java.io.OutputStream#write(byte[], int, int) + */ + @Override + public synchronized void write(byte[] b, int off, int len) throws IOException { + if (b == null) { + throw new NullPointerException(); + } else if (off != 0 || (len < 0) || (len > b.length)) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) { + return; + } + if (console != null) { + console.write(b, off, len); + } + progressUpdate(); + } + + public int getWorkDone() { + return worked; + } +} diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/RefactoringTestBase.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/RefactoringTestBase.java index 5ae5b2344fa..9741fc6801e 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/RefactoringTestBase.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/RefactoringTestBase.java @@ -28,6 +28,7 @@ import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.TextSelection; import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringContext; import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; import org.eclipse.ltk.core.refactoring.RefactoringDescriptorProxy; import org.eclipse.ltk.core.refactoring.RefactoringStatus; @@ -50,7 +51,6 @@ import org.eclipse.cdt.ui.testplugin.CTestPlugin; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring; import org.eclipse.cdt.internal.ui.refactoring.CRefactoringContext; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringContext; /** * Common base for refactoring tests. @@ -101,9 +101,11 @@ public abstract class RefactoringTestBase extends BaseTestCase { BufferedReader reader = new BufferedReader(new StringReader(contents.toString())); String line; while ((line = reader.readLine()) != null) { + String trimmedLine = line.trim(); if (testFile == null) { - testFile = new TestSourceFile(line.trim()); - } else if (isResultDelimiter(line.trim())) { + assertTrue("Invalid file name \"" + trimmedLine + "\"", trimmedLine.matches("^(\\w+/)*\\w+\\.\\w+$")); + testFile = new TestSourceFile(trimmedLine); + } else if (isResultDelimiter(trimmedLine)) { expectedResult = true; } else if (expectedResult) { testFile.addLineToExpectedSource(line); @@ -145,8 +147,6 @@ public abstract class RefactoringTestBase extends BaseTestCase { } protected void assertRefactoringSuccess() throws Exception { - if (historyScript != null) - return; // History tests are temporarily disabled. executeRefactoring(true); compareFiles(); } @@ -217,9 +217,9 @@ public abstract class RefactoringTestBase extends BaseTestCase { for (RefactoringDescriptorProxy proxy : history.getDescriptors()) { RefactoringDescriptor descriptor = proxy.requestDescriptor(NULL_PROGRESS_MONITOR); RefactoringStatus status = new RefactoringStatus(); -// RefactoringContext context = descriptor.createRefactoringContext(status); -// assertTrue(status.isOK()); -// executeRefactoring(context.getRefactoring(), context, false, expectedSuccess); + RefactoringContext context = descriptor.createRefactoringContext(status); + assertTrue(status.isOK()); + executeRefactoring(context.getRefactoring(), context, false, expectedSuccess); } } diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java index 471a174916f..10910d20611 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java @@ -274,6 +274,41 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { assertRefactoringSuccess(); } + //main.cpp + //class A { + //public: + // explicit A(const char*); + // void m1() const; + // void m2() const; + //}; + // + //void main() { + // /*$*/A a(""); + // a.m1();/*$$*/ + // A b(a); // nonstandard indent to check that it is preserved + //} + //==================== + //class A { + //public: + // explicit A(const char*); + // void m1() const; + // void m2() const; + //}; + // + //A extracted() { + // A a(""); + // a.m1(); + // return a; + //} + // + //void main() { + // A a = extracted(); + // A b(a); // nonstandard indent to check that it is preserved + //} + public void testLocalVariableDeclaration_3() throws Exception { + assertRefactoringSuccess(); + } + //A.h //#ifndef A_H_ //#define A_H_ diff --git a/core/org.eclipse.cdt.ui/META-INF/MANIFEST.MF b/core/org.eclipse.cdt.ui/META-INF/MANIFEST.MF index a572f20b0e0..9455849653f 100644 --- a/core/org.eclipse.cdt.ui/META-INF/MANIFEST.MF +++ b/core/org.eclipse.cdt.ui/META-INF/MANIFEST.MF @@ -104,8 +104,8 @@ Require-Bundle: org.eclipse.cdt.core;bundle-version="[5.2.0,6.0.0)", org.eclipse.core.variables;bundle-version="[3.1.100,4.0.0)", org.eclipse.help;bundle-version="[3.2.0,4.0.0)", org.eclipse.jface.text;bundle-version="[3.4.0,4.0.0)", - org.eclipse.ltk.core.refactoring;bundle-version="3.4.0", - org.eclipse.ltk.ui.refactoring;bundle-version="3.4.0", + org.eclipse.ltk.core.refactoring;bundle-version="3.6.0", + org.eclipse.ltk.ui.refactoring;bundle-version="3.6.0", org.eclipse.search;bundle-version="[3.2.0,4.0.0)", org.eclipse.ui;bundle-version="[3.3.0,4.0.0)", org.eclipse.ui.console;bundle-version="[3.1.100,4.0.0)", diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/opentype/ElementSelectionDialog.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/opentype/ElementSelectionDialog.java index 196e17a5b75..a99d230af20 100644 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/opentype/ElementSelectionDialog.java +++ b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/opentype/ElementSelectionDialog.java @@ -336,11 +336,6 @@ public class ElementSelectionDialog extends TypeSelectionDialog { return types.toArray(new ITypeInfo[types.size()]); } - @Override - protected final void setListElements(Object[] elements) { - super.setListElements(elements); - } - /** * @deprecated Unsupported */ @@ -350,6 +345,14 @@ public class ElementSelectionDialog extends TypeSelectionDialog { throw new UnsupportedOperationException(); } + /* (non-Javadoc) + * @see org.eclipse.ui.dialogs.AbstractElementListSelectionDialog#handleElementsChanged() + */ + @Override + protected void handleElementsChanged() { + updateOkState(); + } + @Override protected void handleEmptyList() { updateOkState(); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/refactoring/code/flow/FlowAnalyzer.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/refactoring/code/flow/FlowAnalyzer.java index abb635e644b..b5a8f2304af 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/refactoring/code/flow/FlowAnalyzer.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/refactoring/code/flow/FlowAnalyzer.java @@ -911,8 +911,11 @@ abstract class FlowAnalyzer extends ASTGenericVisitor { if (binding instanceof IVariable) { IVariable variable= (IVariable) binding; if (!(variable instanceof IField)) { - int accessMode = CPPVariableReadWriteFlags.getReadWriteFlags(node); - setFlowInfo(node, new LocalFlowInfo(variable, accessMode, fFlowContext)); + int index = fFlowContext.getIndexFromLocal(variable); + if (index >= 0) { + int accessMode = CPPVariableReadWriteFlags.getReadWriteFlags(node); + setFlowInfo(node, new LocalFlowInfo(variable, index, accessMode, fFlowContext)); + } } } return PROCESS_SKIP; @@ -957,7 +960,7 @@ abstract class FlowAnalyzer extends ASTGenericVisitor { return leave((ICASTDesignatedInitializer) node); } else if (node instanceof IASTInitializerList) { return leave((ICPPASTConstructorChainInitializer) node); - } else if (node instanceof IASTInitializerList) { + } else if (node instanceof ICPPASTConstructorInitializer) { return leave((ICPPASTConstructorInitializer) node); } return PROCESS_SKIP; diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/refactoring/code/flow/LocalFlowInfo.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/refactoring/code/flow/LocalFlowInfo.java index 8bbbb4945c6..4cd924edcc9 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/refactoring/code/flow/LocalFlowInfo.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/refactoring/code/flow/LocalFlowInfo.java @@ -16,11 +16,11 @@ import org.eclipse.cdt.core.dom.ast.IVariable; class LocalFlowInfo extends FlowInfo { private final int fVariableIndex; - public LocalFlowInfo(IVariable binding, int localAccessMode, FlowContext context) { + public LocalFlowInfo(IVariable binding, int variableIndex, int localAccessMode, FlowContext context) { super(NO_RETURN); - fVariableIndex= context.getIndexFromLocal(binding); - if (fVariableIndex < 0) - throw new IllegalStateException("Invalid local variable \"" + binding.getName() + "\" for the context."); //$NON-NLS-1$ //$NON-NLS-2$ + if (variableIndex < 0) + throw new IllegalArgumentException("Invalid index for local variable \"" + binding.getName()); //$NON-NLS-1$ + fVariableIndex= variableIndex; if (context.considerAccessMode()) { createAccessModeArray(context); context.manageLocal(binding); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/includebrowser/IBContentProvider.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/includebrowser/IBContentProvider.java index 9d12a633631..a56a15923c7 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/includebrowser/IBContentProvider.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/includebrowser/IBContentProvider.java @@ -172,7 +172,7 @@ public class IBContentProvider extends AsyncTreeContentProvider { } catch (CoreException e) { CUIPlugin.log(e); } - return new IIndexInclude[0]; + return IIndexInclude.EMPTY_INCLUDES_ARRAY; } public IIndexInclude[] findIncludesTo(IIndex index, IIndexFileLocation ifl, IProgressMonitor pm) { @@ -199,6 +199,6 @@ public class IBContentProvider extends AsyncTreeContentProvider { } catch (CoreException e) { CUIPlugin.log(e); } - return new IIndexInclude[0]; + return IIndexInclude.EMPTY_INCLUDES_ARRAY; } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/CRefactoring.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/CRefactoring.java index 798ddf66a29..b93cefc2e78 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/CRefactoring.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/CRefactoring.java @@ -132,16 +132,16 @@ public abstract class CRefactoring extends Refactoring { public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { SubMonitor sm = SubMonitor.convert(pm, 10); - sm.subTask(Messages.Refactoring_PM_LoadTU); - if (isProgressMonitorCanceld(sm, initStatus)) { + if (isProgressMonitorCanceled(sm, initStatus)) { return initStatus; } + sm.subTask(Messages.Refactoring_PM_LoadTU); IASTTranslationUnit ast = getAST(tu, sm); if (ast == null) { initStatus.addError(NLS.bind(Messages.Refactoring_ParsingError, tu.getPath())); return initStatus; } - if (isProgressMonitorCanceld(sm, initStatus)) { + if (isProgressMonitorCanceled(sm, initStatus)) { return initStatus; } sm.subTask(Messages.Refactoring_PM_CheckTU); @@ -152,7 +152,7 @@ public abstract class CRefactoring extends Refactoring { return initStatus; } - protected static boolean isProgressMonitorCanceld(IProgressMonitor sm, RefactoringStatus status) { + protected static boolean isProgressMonitorCanceled(IProgressMonitor sm, RefactoringStatus status) { if (sm.isCanceled()) { status.addFatalError(Messages.Refactoring_CanceledByUser); return true; diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/CRefactoringContext.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/CRefactoringContext.java index 29f4343c884..9dc38f553c1 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/CRefactoringContext.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/CRefactoringContext.java @@ -16,6 +16,7 @@ import java.util.concurrent.ConcurrentHashMap; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.ltk.core.refactoring.RefactoringContext; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/CRefactoringDescriptor.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/CRefactoringDescriptor.java index ddc97b5f9fd..0481355551f 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/CRefactoringDescriptor.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/CRefactoringDescriptor.java @@ -57,13 +57,13 @@ public abstract class CRefactoringDescriptor extends RefactoringDescriptor { @Override public abstract CRefactoring createRefactoring(RefactoringStatus status) throws CoreException; -// @Override -// public CRefactoringContext createRefactoringContext(RefactoringStatus status) throws CoreException { -// CRefactoring refactoring= createRefactoring(status); -// if (refactoring == null) -// return null; -// return new CRefactoringContext(refactoring); -// } + @Override + public CRefactoringContext createRefactoringContext(RefactoringStatus status) throws CoreException { + CRefactoring refactoring= createRefactoring(status); + if (refactoring == null) + return null; + return new CRefactoringContext(refactoring); + } protected ISelection getSelection() throws CoreException { ISelection selection; diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/NameInformation.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/NameInformation.java index 8859680deed..68f2fa4d808 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/NameInformation.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/NameInformation.java @@ -278,6 +278,7 @@ public class NameInformation { if (!isWriteAccess) { indirection = Indirection.REFERENCE; } + // TODO(sprigogin): Verify availability of the copy ctor before passing by value } else { indirection = Indirection.POINTER; } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/RefactoringContext.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/RefactoringContext.java deleted file mode 100644 index c52983f2138..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/RefactoringContext.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 Google, Inc and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Sergey Prigogin - [refactoring] Provide a way to implement refactorings that depend on resources that have to be explicitly released - https://bugs.eclipse.org/347599 - * IBM Corporation - bug fixes - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.ltk.core.refactoring.Refactoring; - -/** - *

- * Refactoring context is a disposable object that can be used by a refactoring to hold resources - * that have to be explicitly released. The refactoring context is guaranteed to receive - * a {@link #dispose()} call after the associated refactoring has finished or produced an error. - * At this point, the refactoring context must release all resources and detach all listeners. - * A refactoring context can only be disposed once; it cannot be reused. - *

- *

- * This class is intended to be subclassed by clients wishing to implement new refactorings that - * depend on resources that have to be explicitly released. - *

- */ -public class RefactoringContext { - private Refactoring fRefactoring; - - /** - * Creates a context for the given refactoring. - * - * @param refactoring The refactoring associated with the context. Cannot be null. - * @throws NullPointerException if refactoring is null. - */ - public RefactoringContext(Refactoring refactoring) { - if (refactoring == null) - throw new NullPointerException(); - fRefactoring= refactoring; - } - - /** - * Returns the refactoring associated with the context. - *

- * The returned refactoring must be in an initialized state, i.e. ready to - * be executed via {@link PerformRefactoringOperation}. - *

- * @return The refactoring associated with the context. - * @nooverride This method is not intended to be re-implemented or extended by clients. - */ - public Refactoring getRefactoring() { - return fRefactoring; - } - - /** - * Disposes of the context. This method will be called exactly once during the life cycle - * of the context after the associated refactoring has finished or produced an error. - *

- * Subclasses may extend this method (must call super). - *

- */ - public void dispose() { - if (fRefactoring == null) - throw new IllegalStateException("dispose() called more than once."); //$NON-NLS-1$ - fRefactoring= null; - } -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractconstant/ExtractConstantRefactoringDescriptor.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractconstant/ExtractConstantRefactoringDescriptor.java index c9e2d31caa2..52f9e12837b 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractconstant/ExtractConstantRefactoringDescriptor.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractconstant/ExtractConstantRefactoringDescriptor.java @@ -40,14 +40,13 @@ public class ExtractConstantRefactoringDescriptor extends CRefactoringDescriptor @Override public CRefactoring createRefactoring(RefactoringStatus status) throws CoreException { - return null; -// ISelection selection = getSelection(); -// ICProject project = getCProject(); -// ExtractConstantRefactoring refactoring = -// new ExtractConstantRefactoring(getTranslationUnit(), selection, project); -// ExtractConstantInfo info = refactoring.getRefactoringInfo(); -// info.setName(arguments.get(NAME)); -// info.setVisibility(VisibilityEnum.getEnumForStringRepresentation(arguments.get(VISIBILITY))); -// return refactoring; + ISelection selection = getSelection(); + ICProject project = getCProject(); + ExtractConstantRefactoring refactoring = + new ExtractConstantRefactoring(getTranslationUnit(), selection, project); + ExtractConstantInfo info = refactoring.getRefactoringInfo(); + info.setName(arguments.get(NAME)); + info.setVisibility(VisibilityEnum.getEnumForStringRepresentation(arguments.get(VISIBILITY))); + return refactoring; } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoring.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoring.java index 6e294bdc6b0..ef15e271284 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoring.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoring.java @@ -173,7 +173,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { nodeFactory = ast.getASTNodeFactory(); container = findExtractableNodes(); - if (isProgressMonitorCanceld(sm, initStatus)) + if (isProgressMonitorCanceled(sm, initStatus)) return initStatus; if (container.isEmpty()) { diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoringDescriptor.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoringDescriptor.java index a0a78c91551..92a03a90c54 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoringDescriptor.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoringDescriptor.java @@ -41,15 +41,14 @@ public class ExtractFunctionRefactoringDescriptor extends CRefactoringDescriptor @Override public CRefactoring createRefactoring(RefactoringStatus status) throws CoreException { - return null; -// ISelection selection = getSelection(); -// ICProject project = getCProject(); -// ExtractFunctionRefactoring refactoring = -// new ExtractFunctionRefactoring(getTranslationUnit(), selection, project); -// ExtractFunctionInformation info = refactoring.getRefactoringInfo(); -// info.setMethodName(arguments.get(NAME)); -// info.setVisibility(VisibilityEnum.getEnumForStringRepresentation(arguments.get(VISIBILITY))); -// info.setReplaceDuplicates(Boolean.parseBoolean(arguments.get(REPLACE_DUPLICATES))); -// return refactoring; + ISelection selection = getSelection(); + ICProject project = getCProject(); + ExtractFunctionRefactoring refactoring = + new ExtractFunctionRefactoring(getTranslationUnit(), selection, project); + ExtractFunctionInformation info = refactoring.getRefactoringInfo(); + info.setMethodName(arguments.get(NAME)); + info.setVisibility(VisibilityEnum.getEnumForStringRepresentation(arguments.get(VISIBILITY))); + info.setReplaceDuplicates(Boolean.parseBoolean(arguments.get(REPLACE_DUPLICATES))); + return refactoring; } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractlocalvariable/ExtractLocalVariableRefactoring.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractlocalvariable/ExtractLocalVariableRefactoring.java index f2fff7c0092..37fd2cb8c18 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractlocalvariable/ExtractLocalVariableRefactoring.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractlocalvariable/ExtractLocalVariableRefactoring.java @@ -114,7 +114,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring { } sm.worked(1); - if (isProgressMonitorCanceld(sm, initStatus)) + if (isProgressMonitorCanceled(sm, initStatus)) return initStatus; boolean oneMarked = selectedRegion != null && isOneMarked(container.getNodesToWrite(), selectedRegion); @@ -125,7 +125,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring { } sm.worked(1); - if (isProgressMonitorCanceld(sm, initStatus)) + if (isProgressMonitorCanceled(sm, initStatus)) return initStatus; sm.worked(1); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractlocalvariable/ExtractLocalVariableRefactoringDescriptor.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractlocalvariable/ExtractLocalVariableRefactoringDescriptor.java index 6cbca133b4c..d4efbd7b831 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractlocalvariable/ExtractLocalVariableRefactoringDescriptor.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractlocalvariable/ExtractLocalVariableRefactoringDescriptor.java @@ -38,12 +38,11 @@ public class ExtractLocalVariableRefactoringDescriptor extends CRefactoringDescr @Override public CRefactoring createRefactoring(RefactoringStatus status) throws CoreException { - return null; -// ISelection selection = getSelection(); -// ICProject proj = getCProject(); -// ExtractLocalVariableRefactoring refactoring = -// new ExtractLocalVariableRefactoring(getTranslationUnit(), selection, proj); -// refactoring.getRefactoringInfo().setName(arguments.get(NAME)); -// return refactoring; + ISelection selection = getSelection(); + ICProject proj = getCProject(); + ExtractLocalVariableRefactoring refactoring = + new ExtractLocalVariableRefactoring(getTranslationUnit(), selection, proj); + refactoring.getRefactoringInfo().setName(arguments.get(NAME)); + return refactoring; } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/hidemethod/HideMethodRefactoring.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/hidemethod/HideMethodRefactoring.java index 18d8d571577..6a588328ed7 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/hidemethod/HideMethodRefactoring.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/hidemethod/HideMethodRefactoring.java @@ -93,7 +93,7 @@ public class HideMethodRefactoring extends CRefactoring { return initStatus; } - if (isProgressMonitorCanceld(sm, initStatus)) + if (isProgressMonitorCanceled(sm, initStatus)) return initStatus; List names = findAllMarkedNames(); @@ -118,7 +118,7 @@ public class HideMethodRefactoring extends CRefactoring { return initStatus; } - if (isProgressMonitorCanceld(sm, initStatus)) + if (isProgressMonitorCanceled(sm, initStatus)) return initStatus; if (methodDeclaration instanceof IASTFunctionDefinition) { IASTDeclarator declarator = ((IASTFunctionDefinition) methodDeclaration).getDeclarator(); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/hidemethod/HideMethodRefactoringDescriptor.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/hidemethod/HideMethodRefactoringDescriptor.java index 48999d0e571..820ba8034f3 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/hidemethod/HideMethodRefactoringDescriptor.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/hidemethod/HideMethodRefactoringDescriptor.java @@ -37,9 +37,8 @@ public class HideMethodRefactoringDescriptor extends CRefactoringDescriptor { @Override public CRefactoring createRefactoring(RefactoringStatus status) throws CoreException { - return null; -// ISelection selection = getSelection(); -// ICProject proj = getCProject(); -// return new HideMethodRefactoring(getTranslationUnit(), selection, proj); + ISelection selection = getSelection(); + ICProject proj = getCProject(); + return new HideMethodRefactoring(getTranslationUnit(), selection, proj); } } diff --git a/debug/org.eclipse.cdt.debug.core/.settings/.api_filters b/debug/org.eclipse.cdt.debug.core/.settings/.api_filters index c528f9e508c..6792bd1faca 100644 --- a/debug/org.eclipse.cdt.debug.core/.settings/.api_filters +++ b/debug/org.eclipse.cdt.debug.core/.settings/.api_filters @@ -1,5 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/CDIDebugModel.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/CDIDebugModel.java index ea88c2b8ef5..43539805dc7 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/CDIDebugModel.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/CDIDebugModel.java @@ -29,11 +29,13 @@ import org.eclipse.cdt.core.settings.model.ICConfigExtensionReference; import org.eclipse.cdt.debug.core.cdi.model.ICDITarget; import org.eclipse.cdt.debug.core.model.ICAddressBreakpoint; import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.cdt.debug.core.model.ICBreakpoint2; import org.eclipse.cdt.debug.core.model.ICBreakpointType; import org.eclipse.cdt.debug.core.model.ICEventBreakpoint; import org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint; import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; import org.eclipse.cdt.debug.core.model.ICLineBreakpoint2; +import org.eclipse.cdt.debug.core.model.ICTracepoint; import org.eclipse.cdt.debug.core.model.ICWatchpoint; import org.eclipse.cdt.debug.core.model.ICWatchpoint2; import org.eclipse.cdt.debug.internal.core.breakpoints.CAddressBreakpoint; @@ -63,6 +65,7 @@ import org.eclipse.debug.core.IBreakpointManager; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.core.model.IDebugTarget; +import org.eclipse.debug.core.model.ILineBreakpoint; import org.eclipse.debug.core.model.IProcess; /** @@ -71,747 +74,1345 @@ import org.eclipse.debug.core.model.IProcess; */ public class CDIDebugModel { - /** - * Returns the identifier for the CDI debug model plug-in - * - * @return plugin identifier - */ - public static String getPluginIdentifier() { - return CDebugCorePlugin.getUniqueIdentifier(); - } + /** + * Returns the identifier for the CDI debug model plug-in + * + * @return plugin identifier + */ + public static String getPluginIdentifier() { + return CDebugCorePlugin.getUniqueIdentifier(); + } - /** - * Creates and returns a debug target for the given CDI target, with the specified name, and associates it with the given process for console I/O. The debug - * target is added to the given launch. - * - * @param launch the launch the new debug target will be contained in - * @param project the project to use to persist breakpoints. - * @param cdiTarget the CDI target to create a debug target for - * @param name the name to associate with this target, which will be returned from IDebugTarget.getName. - * @param debuggeeProcess the process to associate with the debug target, which will be returned from IDebugTarget.getProcess - * @param file the executable to debug. - * @param allowTerminate allow terminate(). - * @param allowDisconnect allow disconnect(). - * @param stopSymbol place temporary breakpoint at stopSymbol, ignore if null or empty. - * @param resumeTarget resume target. - * @return a debug target - * @throws DebugException - * @since 3.1 - */ - public static IDebugTarget newDebugTarget( final ILaunch launch, final IProject project, final ICDITarget cdiTarget, final String name, final IProcess debuggeeProcess, final IBinaryObject file, final boolean allowTerminate, final boolean allowDisconnect, final String stopSymbol, final boolean resumeTarget ) throws DebugException { - final IDebugTarget[] target = new IDebugTarget[1]; - IWorkspaceRunnable r = new IWorkspaceRunnable() { + /** + * Creates and returns a debug target for the given CDI target, with the + * specified name, and associates it with the given process for console I/O. + * The debug target is added to the given launch. + * + * @param launch + * the launch the new debug target will be contained in + * @param project + * the project to use to persist breakpoints. + * @param cdiTarget + * the CDI target to create a debug target for + * @param name + * the name to associate with this target, which will be returned + * from IDebugTarget.getName. + * @param debuggeeProcess + * the process to associate with the debug target, which will be + * returned from IDebugTarget.getProcess + * @param file + * the executable to debug. + * @param allowTerminate + * allow terminate(). + * @param allowDisconnect + * allow disconnect(). + * @param stopSymbol + * place temporary breakpoint at stopSymbol, ignore + * if null or empty. + * @param resumeTarget + * resume target. + * @return a debug target + * @throws DebugException + * @since 3.1 + */ + public static IDebugTarget newDebugTarget(final ILaunch launch, final IProject project, final ICDITarget cdiTarget, + final String name, final IProcess debuggeeProcess, final IBinaryObject file, final boolean allowTerminate, + final boolean allowDisconnect, final String stopSymbol, final boolean resumeTarget) throws DebugException { + final IDebugTarget[] target = new IDebugTarget[1]; + IWorkspaceRunnable r = new IWorkspaceRunnable() { - @Override - public void run( IProgressMonitor m ) throws CoreException { - target[0] = new CDebugTarget( launch, project, cdiTarget, name, debuggeeProcess, file, allowTerminate, allowDisconnect ); - ((CDebugTarget)target[0]).start( stopSymbol, resumeTarget ); - } - }; - try { - ResourcesPlugin.getWorkspace().run( r, null ); - } - catch( CoreException e ) { - CDebugCorePlugin.log( e ); - throw new DebugException( e.getStatus() ); - } - return target[0]; - } - - /** - * Creates and returns a debug target for the given CDI target, with the specified name, and associates it with the given process for console I/O. The debug - * target is added to the given launch. - * - * @param launch the launch the new debug target will be contained in - * @param project the project to use to persist breakpoints. - * @param cdiTarget the CDI target to create a debug target for - * @param name the name to associate with this target, which will be returned from IDebugTarget.getName. - * @param debuggeeProcess the process to associate with the debug target, which will be returned from IDebugTarget.getProcess - * @param file the executable to debug. - * @param allowTerminate allow terminate(). - * @param allowDisconnect allow disconnect(). - * @param stopInMain place temporary breakpoint at main() - * @param resumeTarget resume target. - * @return a debug target - * @throws DebugException - * @deprecated - */ - @Deprecated - public static IDebugTarget newDebugTarget( final ILaunch launch, final IProject project, final ICDITarget cdiTarget, final String name, final IProcess debuggeeProcess, final IBinaryObject file, final boolean allowTerminate, final boolean allowDisconnect, final boolean stopInMain, final boolean resumeTarget ) throws DebugException { - final IDebugTarget[] target = new IDebugTarget[1]; - IWorkspaceRunnable r = new IWorkspaceRunnable() { - - @Override - public void run( IProgressMonitor m ) throws CoreException { - String stopSymbol = null; - if ( stopInMain ) - stopSymbol = launch.getLaunchConfiguration().getAttribute( ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_STOP_AT_MAIN_SYMBOL, ICDTLaunchConfigurationConstants.DEBUGGER_STOP_AT_MAIN_SYMBOL_DEFAULT ); - target[0] = new CDebugTarget( launch, project, cdiTarget, name, debuggeeProcess, file, allowTerminate, allowDisconnect ); - ((CDebugTarget)target[0]).start( stopSymbol, resumeTarget ); - } - }; - try { - ResourcesPlugin.getWorkspace().run( r, null ); - } - catch( CoreException e ) { - CDebugCorePlugin.log( e ); - throw new DebugException( e.getStatus() ); - } - return target[0]; - } - - /** - * Creates and returns a debug target for the given CDI target, with the specified name, and associates it with the given process for console I/O. The debug - * target is added to the given launch. - * - * @param launch the launch the new debug target will be contained in - * @param project the project to use to persist breakpoints. - * @param cdiTarget the CDI target to create a debug target for - * @param name the name to associate with this target, which will be returned from IDebugTarget.getName. - * @param debuggeeProcess the process to associate with the debug target, which will be returned from IDebugTarget.getProcess - * @param file the executable to debug. - * @param allowTerminate allow terminate(). - * @param allowDisconnect allow disconnect(). - * @param resumeTarget resume target. - * @return a debug target - * @throws DebugException - */ - public static IDebugTarget newDebugTarget( ILaunch launch, IProject project, ICDITarget cdiTarget, final String name, IProcess debuggeeProcess, IBinaryObject file, boolean allowTerminate, boolean allowDisconnect, boolean resumeTarget ) throws DebugException { - return newDebugTarget( launch, project, cdiTarget, name, debuggeeProcess, file, allowTerminate, allowDisconnect, null, resumeTarget ); - } - - /** - * Creates and returns a line breakpoint for the source defined by the given source handle, at the given line number. The marker associated with the - * breakpoint will be created on the specified resource. - * - * @param sourceHandle - * the handle to the breakpoint source - * @param resource - * the resource on which to create the associated breakpoint marker - * @param lineNumber - * the line number on which the breakpoint is set - line numbers are 1 based, associated with the source file in which the breakpoint is set - * @param enabled - * whether to enable or disable this breakpoint - * @param ignoreCount - * the number of times this breakpoint will be ignored - * @param condition - * the breakpoint condition - * @param register - * whether to add this breakpoint to the breakpoint manager - * @return a line breakpoint - * @throws CoreException - * if this method fails. Reasons include: - *
    - *
  • Failure creating underlying marker. The exception's status contains the underlying exception responsible for the failure.
  • - *
- * @deprecated as of CDT 5.0 use {@link #createLineBreakpoint(String, IResource, int, int, boolean, int, String, boolean)} - */ - @Deprecated - public static ICLineBreakpoint createLineBreakpoint( String sourceHandle, IResource resource, int lineNumber, boolean enabled, int ignoreCount, String condition, boolean register ) throws CoreException { - return createLineBreakpoint(sourceHandle, resource, ICBreakpointType.REGULAR, lineNumber, enabled, ignoreCount, condition, register); - } - - /** - * Creates and returns a line breakpoint for the source defined by the given source handle, at the given line number. The marker associated with the - * breakpoint will be created on the specified resource. - * - * @param sourceHandle - * the handle to the breakpoint source - * @param resource - * the resource on which to create the associated breakpoint marker - * @param type - * a type constant from ICBreakpointType - * @param lineNumber - * the line number on which the breakpoint is set - line numbers are 1 based, associated with the source file in which the breakpoint is set - * @param enabled - * whether to enable or disable this breakpoint - * @param ignoreCount - * the number of times this breakpoint will be ignored - * @param condition - * the breakpoint condition - * @param register - * whether to add this breakpoint to the breakpoint manager - * @return a line breakpoint - * @throws CoreException - * if this method fails. Reasons include: - *
    - *
  • Failure creating underlying marker. The exception's status contains the underlying exception responsible for the failure.
  • - *
- */ - public static ICLineBreakpoint createLineBreakpoint( String sourceHandle, IResource resource, int type, int lineNumber, boolean enabled, int ignoreCount, String condition, boolean register ) throws CoreException { - HashMap attributes = new HashMap( 10 ); - setLineBreakpointAttributes( attributes, sourceHandle, type, lineNumber, enabled, ignoreCount, condition ); - return new CLineBreakpoint( resource, attributes, register ); - } - - /** - * @since 7.0 - */ - public static ICLineBreakpoint createLineTracepoint( String sourceHandle, IResource resource, int type, int lineNumber, boolean enabled, int ignoreCount, String condition, boolean register ) throws CoreException { - HashMap attributes = new HashMap( 10 ); - setLineBreakpointAttributes( attributes, sourceHandle, type, lineNumber, enabled, ignoreCount, condition ); - return new CLineTracepoint( resource, attributes, register ); - } - - /** - * Helper function for setting common line breakpoint attributes. - */ - private static void setLineBreakpointAttributes( HashMap attributes, - String sourceHandle, - Integer type, - int lineNumber, - boolean enabled, - int ignoreCount, - String condition ) { - attributes.put( IBreakpoint.ID, getPluginIdentifier() ); - attributes.put( IMarker.LINE_NUMBER, new Integer( lineNumber ) ); - attributes.put( IBreakpoint.ENABLED, Boolean.valueOf( enabled ) ); - attributes.put( ICBreakpoint.IGNORE_COUNT, new Integer( ignoreCount ) ); - attributes.put( ICBreakpoint.CONDITION, condition ); - attributes.put( ICBreakpoint.SOURCE_HANDLE, sourceHandle ); - attributes.put( ICBreakpointType.TYPE, type ); - - // Added for source relocated breakpoints. - if (!attributes.containsKey(ICLineBreakpoint2.REQUESTED_SOURCE_HANDLE)) { - attributes.put( ICLineBreakpoint2.REQUESTED_SOURCE_HANDLE, sourceHandle ); - } - if (!attributes.containsKey( ICLineBreakpoint2.REQUESTED_LINE )) { - attributes.put( ICLineBreakpoint2.REQUESTED_LINE, new Integer( lineNumber )); - } - if (attributes.containsKey(IMarker.CHAR_START) && - !attributes.containsKey( ICLineBreakpoint2.REQUESTED_CHAR_START )) - { - attributes.put( ICLineBreakpoint2.REQUESTED_CHAR_START, attributes.get(IMarker.CHAR_START)); + @Override + public void run(IProgressMonitor m) throws CoreException { + target[0] = new CDebugTarget(launch, project, cdiTarget, name, debuggeeProcess, file, allowTerminate, + allowDisconnect); + ((CDebugTarget) target[0]).start(stopSymbol, resumeTarget); + } + }; + try { + ResourcesPlugin.getWorkspace().run(r, null); + } catch (CoreException e) { + CDebugCorePlugin.log(e); + throw new DebugException(e.getStatus()); } - if (attributes.containsKey(IMarker.CHAR_END) && - !attributes.containsKey( ICLineBreakpoint2.REQUESTED_CHAR_END )) - { - attributes.put( ICLineBreakpoint2.REQUESTED_CHAR_END, attributes.get(IMarker.CHAR_END)); + return target[0]; + } + + /** + * Creates and returns a debug target for the given CDI target, with the + * specified name, and associates it with the given process for console I/O. + * The debug target is added to the given launch. + * + * @param launch + * the launch the new debug target will be contained in + * @param project + * the project to use to persist breakpoints. + * @param cdiTarget + * the CDI target to create a debug target for + * @param name + * the name to associate with this target, which will be returned + * from IDebugTarget.getName. + * @param debuggeeProcess + * the process to associate with the debug target, which will be + * returned from IDebugTarget.getProcess + * @param file + * the executable to debug. + * @param allowTerminate + * allow terminate(). + * @param allowDisconnect + * allow disconnect(). + * @param stopInMain + * place temporary breakpoint at main() + * @param resumeTarget + * resume target. + * @return a debug target + * @throws DebugException + * @deprecated + */ + @Deprecated + public static IDebugTarget newDebugTarget(final ILaunch launch, final IProject project, final ICDITarget cdiTarget, + final String name, final IProcess debuggeeProcess, final IBinaryObject file, final boolean allowTerminate, + final boolean allowDisconnect, final boolean stopInMain, final boolean resumeTarget) throws DebugException { + final IDebugTarget[] target = new IDebugTarget[1]; + IWorkspaceRunnable r = new IWorkspaceRunnable() { + + @Override + public void run(IProgressMonitor m) throws CoreException { + String stopSymbol = null; + if (stopInMain) + stopSymbol = launch.getLaunchConfiguration().getAttribute( + ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_STOP_AT_MAIN_SYMBOL, + ICDTLaunchConfigurationConstants.DEBUGGER_STOP_AT_MAIN_SYMBOL_DEFAULT); + target[0] = new CDebugTarget(launch, project, cdiTarget, name, debuggeeProcess, file, allowTerminate, + allowDisconnect); + ((CDebugTarget) target[0]).start(stopSymbol, resumeTarget); + } + }; + try { + ResourcesPlugin.getWorkspace().run(r, null); + } catch (CoreException e) { + CDebugCorePlugin.log(e); + throw new DebugException(e.getStatus()); } - } + return target[0]; + } - /** - * Creates and returns an address breakpoint for the source defined by the - * given source handle, at the given address. The marker associated with the - * breakpoint will be created on the specified resource. - * - * @param module the module name the breakpoint is set in - * @param sourceHandle the handle to the breakpoint source - * @param resource the resource on which to create the associated breakpoint marker - * @param address the address on which the breakpoint is set - * @param enabled whether to enable or disable this breakpoint - * @param ignoreCount the number of times this breakpoint will be ignored - * @param condition the breakpoint condition - * @param register whether to add this breakpoint to the breakpoint manager - * @return an address breakpoint - * @throws CoreException if this method fails. Reasons include: - *
    - *
  • Failure creating underlying marker. The exception's - * status contains the underlying exception responsible for the - * failure.
  • - *
- * @deprecated as of CDT 5.0 use {@link #createAddressBreakpoint(String, String, IResource, int, int, IAddress, boolean, int, String, boolean)} - */ - @Deprecated - public static ICAddressBreakpoint createAddressBreakpoint( String module, String sourceHandle, IResource resource, IAddress address, boolean enabled, int ignoreCount, String condition, boolean register ) throws CoreException { - return createAddressBreakpoint( module, sourceHandle, resource, ICBreakpointType.REGULAR, -1, address, enabled, ignoreCount, condition, register ); - } + /** + * Creates and returns a debug target for the given CDI target, with the + * specified name, and associates it with the given process for console I/O. + * The debug target is added to the given launch. + * + * @param launch + * the launch the new debug target will be contained in + * @param project + * the project to use to persist breakpoints. + * @param cdiTarget + * the CDI target to create a debug target for + * @param name + * the name to associate with this target, which will be returned + * from IDebugTarget.getName. + * @param debuggeeProcess + * the process to associate with the debug target, which will be + * returned from IDebugTarget.getProcess + * @param file + * the executable to debug. + * @param allowTerminate + * allow terminate(). + * @param allowDisconnect + * allow disconnect(). + * @param resumeTarget + * resume target. + * @return a debug target + * @throws DebugException + */ + public static IDebugTarget newDebugTarget(ILaunch launch, IProject project, ICDITarget cdiTarget, + final String name, IProcess debuggeeProcess, IBinaryObject file, boolean allowTerminate, + boolean allowDisconnect, boolean resumeTarget) throws DebugException { + return newDebugTarget(launch, project, cdiTarget, name, debuggeeProcess, file, allowTerminate, allowDisconnect, + null, resumeTarget); + } - /** - * Creates and returns an address breakpoint for the source defined by the - * given source handle, at the given address. The marker associated with the - * breakpoint will be created on the specified resource. - * - * @param module the module name the breakpoint is set in - * @param sourceHandle the handle to the breakpoint source - * @param resource the resource on which to create the associated breakpoint marker - * @param type a type constant from ICBreakpointType - * @param address the address on which the breakpoint is set - * @param enabled whether to enable or disable this breakpoint - * @param ignoreCount the number of times this breakpoint will be ignored - * @param condition the breakpoint condition - * @param register whether to add this breakpoint to the breakpoint manager - * @return an address breakpoint - * @throws CoreException if this method fails. Reasons include: - *
    - *
  • Failure creating underlying marker. The exception's - * status contains the underlying exception responsible for the - * failure.
  • - *
- */ - public static ICAddressBreakpoint createAddressBreakpoint( String module, String sourceHandle, IResource resource, int type, IAddress address, boolean enabled, int ignoreCount, String condition, boolean register ) throws CoreException { - return createAddressBreakpoint( module, sourceHandle, resource, type, -1, address, enabled, ignoreCount, condition, register ); - } + /** + * Calculates breakpoint marker ID based on the breakpoint object type. + * + * @since 7.2 + */ + public static String calculateMarkerType(IBreakpoint bp) { + if (bp instanceof ICBreakpoint2) { + return ((ICBreakpoint2) bp).getMarkerType(); + } + if (bp instanceof ICTracepoint) { + if (bp instanceof ICFunctionBreakpoint) { + return ICTracepoint.C_FUNCTION_TRACEPOINT_MARKER; + } else if (bp instanceof ICAddressBreakpoint) { + return ICTracepoint.C_ADDRESS_TRACEPOINT_MARKER; + } else if (bp instanceof ICLineBreakpoint) { + return ICTracepoint.C_LINE_TRACEPOINT_MARKER; + } else { + return ICTracepoint.C_TRACEPOINT_MARKER; + } + } else if (bp instanceof ICFunctionBreakpoint) { + return ICFunctionBreakpoint.C_FUNCTION_BREAKPOINT_MARKER; + } else if (bp instanceof ICAddressBreakpoint) { + return ICAddressBreakpoint.C_ADDRESS_BREAKPOINT_MARKER; + } else if (bp instanceof ICLineBreakpoint) { + return ICLineBreakpoint.C_LINE_BREAKPOINT_MARKER; + } else if (bp instanceof ICEventBreakpoint) { + return ICEventBreakpoint.C_EVENT_BREAKPOINT_MARKER; + } else if (bp instanceof ICBreakpoint) { + return ICBreakpoint.C_BREAKPOINT_MARKER; + } else if (bp instanceof ILineBreakpoint) { + return IBreakpoint.LINE_BREAKPOINT_MARKER; + } + return IBreakpoint.BREAKPOINT_MARKER; + } - /** - * Creates and returns an address breakpoint for the source defined by the - * given source handle, at the given address. The marker associated with the - * breakpoint will be created on the specified resource. - * - * @param module the module name the breakpoint is set in - * @param sourceHandle the handle to the breakpoint source - * @param resource the resource on which to create the associated breakpoint marker - * @param type a type constant from ICBreakpointType - * @param lineNumber the line number in the source file - * @param address the address on which the breakpoint is set - * @param enabled whether to enable or disable this breakpoint - * @param ignoreCount the number of times this breakpoint will be ignored - * @param condition the breakpoint condition - * @param register whether to add this breakpoint to the breakpoint manager - * @return an address breakpoint - * @throws CoreException if this method fails. Reasons include: - *
    - *
  • Failure creating underlying marker. The exception's - * status contains the underlying exception responsible for the - * failure.
  • - *
- */ - public static ICAddressBreakpoint createAddressBreakpoint( String module, String sourceHandle, IResource resource, int type, int lineNumber, IAddress address, boolean enabled, int ignoreCount, String condition, boolean register ) throws CoreException { - HashMap attributes = new HashMap( 10 ); - setAddressBreakpointAttributes( attributes, module, sourceHandle, type, lineNumber, address, enabled, ignoreCount, condition ); - return new CAddressBreakpoint( resource, attributes, register ); - } + /** + * Creates and returns a line breakpoint for the source defined by the given + * source handle, at the given line number. The marker associated with the + * breakpoint will be created on the specified resource. + * + * @param sourceHandle + * the handle to the breakpoint source + * @param resource + * the resource on which to create the associated breakpoint + * marker + * @param lineNumber + * the line number on which the breakpoint is set - line numbers + * are 1 based, associated with the source file in which the + * breakpoint is set + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * @return a line breakpoint + * @throws CoreException + * if this method fails. Reasons include: + *
    + *
  • Failure creating underlying marker. The exception's + * status contains the underlying exception responsible for the + * failure.
  • + *
+ * @deprecated as of CDT 5.0 use + * {@link #createLineBreakpoint(String, IResource, int, int, boolean, int, String, boolean)} + */ + @Deprecated + public static ICLineBreakpoint createLineBreakpoint(String sourceHandle, IResource resource, int lineNumber, + boolean enabled, int ignoreCount, String condition, boolean register) throws CoreException { + return createLineBreakpoint(sourceHandle, resource, ICBreakpointType.REGULAR, lineNumber, enabled, ignoreCount, + condition, register); + } - /** - * @since 7.0 - */ - public static ICAddressBreakpoint createAddressTracepoint( String module, String sourceHandle, IResource resource, int type, int lineNumber, IAddress address, boolean enabled, int ignoreCount, String condition, boolean register ) throws CoreException { - HashMap attributes = new HashMap( 10 ); - setAddressBreakpointAttributes( attributes, module, sourceHandle, type, lineNumber, address, enabled, ignoreCount, condition ); - return new CAddressTracepoint( resource, attributes, register ); - } + /** + * Creates and returns a line breakpoint for the source defined by the given + * source handle, at the given line number. The marker associated with the + * breakpoint will be created on the specified resource. + * + * @param sourceHandle + * the handle to the breakpoint source + * @param resource + * the resource on which to create the associated breakpoint + * marker + * @param type + * a type constant from ICBreakpointType + * @param lineNumber + * the line number on which the breakpoint is set - line numbers + * are 1 based, associated with the source file in which the + * breakpoint is set + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * @return a line breakpoint + * @throws CoreException + * if this method fails. Reasons include: + *
    + *
  • Failure creating underlying marker. The exception's + * status contains the underlying exception responsible for the + * failure.
  • + *
+ */ + public static ICLineBreakpoint createLineBreakpoint(String sourceHandle, IResource resource, int type, + int lineNumber, boolean enabled, int ignoreCount, String condition, boolean register) throws CoreException { + HashMap attributes = new HashMap(10); + setLineBreakpointAttributes(attributes, sourceHandle, type, lineNumber, enabled, ignoreCount, condition); + return new CLineBreakpoint(resource, attributes, register); + } - /** - * Helper function for setting common address breakpoint attributes. - */ - private static void setAddressBreakpointAttributes( HashMap attributes, - String module, - String sourceHandle, - int type, - int lineNumber, - IAddress address, - boolean enabled, - int ignoreCount, - String condition ) { - setLineBreakpointAttributes(attributes, sourceHandle, type, lineNumber, enabled, ignoreCount, condition); - attributes.put( IMarker.CHAR_START, new Integer( -1 ) ); - attributes.put( IMarker.CHAR_END, new Integer( -1 ) ); - attributes.put( ICLineBreakpoint.ADDRESS, address.toHexAddressString() ); - attributes.put( ICBreakpoint.MODULE, module ); - } - - /** - * Creates and returns a watchpoint for the source defined by the given - * source handle, at the given expression. The marker associated with the - * watchpoint will be created on the specified resource. - * - * @param sourceHandle the handle to the watchpoint source - * @param resource the resource on which to create the associated watchpoint marker - * @param writeAccess whether this is write watchpoint - * @param readAccess whether this is read watchpoint - * @param expression the expression on which the watchpoint is set - * @param enabled whether to enable or disable this breakpoint - * @param ignoreCount the number of times this breakpoint will be ignored - * @param condition the breakpoint condition - * @param register whether to add this breakpoint to the breakpoint manager - * @return a watchpoint - * @throws CoreException if this method fails. Reasons include: - *
    - *
  • Failure creating underlying marker. The exception's - * status contains the underlying exception responsible for the - * failure.
  • - *
- */ - public static ICWatchpoint createWatchpoint( String sourceHandle, IResource resource, boolean writeAccess, boolean readAccess, String expression, boolean enabled, int ignoreCount, String condition, boolean register ) throws CoreException { - HashMap attributes = new HashMap( 10 ); - setWatchPointAttributes( attributes, sourceHandle, resource, writeAccess, readAccess, expression, "", BigInteger.ZERO, enabled, ignoreCount, condition, register ); //$NON-NLS-1$ - return new CWatchpoint( resource, attributes, register ); - } + /** + * Creates a breakpoint without associated marker. + *

+ * Note: Before a breakpoint created using this method can be used, the + * client must first create a marker and register the breakpoint. The former + * is accomplished using {@link IBreakpoint#setMarker(IMarker)}, the latter + * using {@link IBreakpointManager#addBreakpoint(IBreakpoint)}. + * + * @since 7.2 + */ + public static ICLineBreakpoint createBlankLineBreakpoint() { + return new CLineBreakpoint(); + } - /** - * Creates and returns a watchpoint for the source defined by the given - * source handle, at the given expression. The marker associated with the - * watchpoint will be created on the specified resource. - * - * @param sourceHandle the handle to the watchpoint source - * @param resource the resource on which to create the associated watchpoint marker - * @param charStart the first character index associated with the watchpoint, or - * -1 if unspecified, in the source file in which the watchpoint - * is set - * @param charEnd the last character index associated with the watchpoint, or -1 - * if unspecified, in the source file in which the watchpoint is - * set - * @param lineNumber the lineNumber on which the watchpoint is set, or -1 if - * unspecified - line numbers are 1 based, associated with the - * source file in which the watchpoint is set - * @param writeAccess whether this is write watchpoint - * @param readAccess whether this is read watchpoint - * @param expression the expression on which the watchpoint is set - * @param memorySpace the memory space in which the watchpoint is set - * @param range the range of the watchpoint in addressable units - * @param enabled whether to enable or disable this breakpoint - * @param ignoreCount the number of times this breakpoint will be ignored - * @param condition the breakpoint condition - * @param register whether to add this breakpoint to the breakpoint manager - * @return a watchpoint - * @throws CoreException if this method fails. Reasons include: - *

    - *
  • Failure creating underlying marker. The exception's - * status contains the underlying exception responsible for the - * failure.
  • - *
- */ - public static ICWatchpoint createWatchpoint( String sourceHandle, IResource resource, int charStart, int charEnd, int lineNumber, boolean writeAccess, boolean readAccess, String expression, String memorySpace, BigInteger range, boolean enabled, int ignoreCount, String condition, boolean register ) throws CoreException { - HashMap attributes = new HashMap( 10 ); - setWatchPointAttributes( attributes, sourceHandle, resource, writeAccess, readAccess, expression, memorySpace, range, enabled, ignoreCount, condition, register ); - attributes.put( IMarker.CHAR_START, new Integer( charStart ) ); - attributes.put( IMarker.CHAR_END, new Integer( charEnd ) ); - attributes.put( IMarker.LINE_NUMBER, new Integer( lineNumber ) ); - return new CWatchpoint( resource, attributes, register ); - } + /** + * @since 7.0 + */ + public static ICLineBreakpoint createLineTracepoint(String sourceHandle, IResource resource, int type, + int lineNumber, boolean enabled, int ignoreCount, String condition, boolean register) throws CoreException { + HashMap attributes = new HashMap(10); + setLineBreakpointAttributes(attributes, sourceHandle, type, lineNumber, enabled, ignoreCount, condition); + return new CLineTracepoint(resource, attributes, register); + } - /** - * Creates and returns a watchpoint for the source defined by the given - * source handle, at the given expression and over the given range. - * The marker associated with the watchpoint will be created on the - * specified resource. - * - * @param sourceHandle the handle to the watchpoint source - * @param resource the resource on which to create the associated watchpoint marker - * @param writeAccess whether this is write watchpoint - * @param readAccess whether this is read watchpoint - * @param expression the expression on which the watchpoint is set - * @param memorySpace the memory space in which the watchpoint is set - * @param range the range of the watchpoint in addressable units - * @param enabled whether to enable or disable this breakpoint - * @param ignoreCount the number of times this breakpoint will be ignored - * @param condition the breakpoint condition - * @param register whether to add this breakpoint to the breakpoint manager - * @return the watchpoint that was created - * @throws CoreException if this method fails. Reasons include: - *
    - *
  • Failure creating underlying marker. The exception's - * status contains the underlying exception responsible for the - * failure.
  • - *
- */ - public static ICWatchpoint createWatchpoint( String sourceHandle, IResource resource, boolean writeAccess, boolean readAccess, String expression, String memorySpace, BigInteger range, boolean enabled, int ignoreCount, String condition, boolean register ) throws CoreException { - HashMap attributes = new HashMap( 10 ); - setWatchPointAttributes( attributes, sourceHandle, resource, writeAccess, readAccess, expression, memorySpace, range, enabled, ignoreCount, condition, register ); - return new CWatchpoint( resource, attributes, register ); - } - - /** - * Helper function for setting common watchpoint attributes. - */ - private static void setWatchPointAttributes( HashMap attributes, String sourceHandle, IResource resource, boolean writeAccess, boolean readAccess, String expression, String memorySpace, BigInteger range, boolean enabled, int ignoreCount, String condition, boolean register ) { - attributes.put( IBreakpoint.ID, getPluginIdentifier() ); - attributes.put( IBreakpoint.ENABLED, Boolean.valueOf( enabled ) ); - attributes.put( ICBreakpoint.IGNORE_COUNT, new Integer( ignoreCount ) ); - attributes.put( ICBreakpoint.CONDITION, condition ); - attributes.put( ICBreakpoint.SOURCE_HANDLE, sourceHandle ); - attributes.put( ICWatchpoint.EXPRESSION, expression ); - attributes.put( ICWatchpoint2.MEMORYSPACE, memorySpace ); - attributes.put( ICWatchpoint2.RANGE, range.toString() ); - attributes.put( ICWatchpoint.READ, Boolean.valueOf( readAccess ) ); - attributes.put( ICWatchpoint.WRITE, Boolean.valueOf( writeAccess ) ); - } + /** + * Creates a breakpoint without associated marker. + *

+ * Note: Before a breakpoint created using this method can be used, the + * client must first create a marker and register the breakpoint. The former + * is accomplished using {@link IBreakpoint#setMarker(IMarker)}, the latter + * using {@link IBreakpointManager#addBreakpoint(IBreakpoint)}. + * + * @since 7.2 + */ + public static ICLineBreakpoint createBlankLineTracepoint() { + return new CLineTracepoint(); + } - /** - * Creates and returns a breakpoint for the function defined by the given - * name. The marker associated with the breakpoint will be created on the - * specified resource. - * - * @param sourceHandle the handle to the breakpoint source - * @param resource the resource on which to create the associated breakpoint marker - * @param function the name of the function this breakpoint suspends execution in - * @param charStart the first character index associated with the breakpoint, or - * -1 if unspecified, in the source file in which the breakpoint - * is set - * @param charEnd the last character index associated with the breakpoint, or -1 - * if unspecified, in the source file in which the breakpoint is - * set - * @param lineNumber the lineNumber on which the breakpoint is set, or -1 if - * unspecified - line numbers are 1 based, associated with the - * source file in which the breakpoint is set - * @param enabled whether to enable or disable this breakpoint - * @param ignoreCount the number of times this breakpoint will be ignored - * @param condition the breakpoint condition - * @param register whether to add this breakpoint to the breakpoint manager - * @return an address breakpoint - * @throws CoreException if this method fails. Reasons include: - *

    - *
  • Failure creating underlying marker. The exception's - * status contains the underlying exception responsible for the - * failure.
  • - *
- * @deprecated as of CDT 5.0 use {@link #createFunctionBreakpoint(String, IResource, int, String, int, int, int, boolean, int, String, boolean)} - */ - @Deprecated - public static ICFunctionBreakpoint createFunctionBreakpoint( String sourceHandle, IResource resource, String function, int charStart, int charEnd, int lineNumber, boolean enabled, int ignoreCount, String condition, boolean register ) throws CoreException { - return createFunctionBreakpoint(sourceHandle, resource, ICBreakpointType.REGULAR, function, charStart, charEnd, lineNumber, enabled, ignoreCount, condition, register); - } + /** + * Helper function for setting common line breakpoint attributes. + * + * @param attributes + * Map to write the attributes into. + * @param sourceHandle + * The handle to the breakpoint source. + * @param resource + * The resource on which to create the associated breakpoint + * marker. + * @param type + * A type constant from ICBreakpointType. + * @param lineNumber + * The line number on which the breakpoint is set - line numbers + * are 1 based, associated with the source file in which the + * breakpoint is set. + * @param enabled + * Whether to enable or disable this breakpoint. + * @param ignoreCount + * The number of times this breakpoint will be ignored. + * @param condition + * The breakpoint condition. + * @param register + * Whether to add this breakpoint to the breakpoint manager. + * + * @since 7.2 + */ + public static void setLineBreakpointAttributes(Map attributes, String sourceHandle, Integer type, + int lineNumber, boolean enabled, int ignoreCount, String condition) { + attributes.put(IBreakpoint.ID, getPluginIdentifier()); + attributes.put(IMarker.LINE_NUMBER, new Integer(lineNumber)); + attributes.put(IBreakpoint.ENABLED, Boolean.valueOf(enabled)); + attributes.put(ICBreakpoint.IGNORE_COUNT, new Integer(ignoreCount)); + attributes.put(ICBreakpoint.CONDITION, condition); + attributes.put(ICBreakpoint.SOURCE_HANDLE, sourceHandle); + attributes.put(ICBreakpointType.TYPE, type); - /** - * Creates and returns a breakpoint for the function defined by the given - * name. The marker associated with the breakpoint will be created on the - * specified resource. - * - * @param sourceHandle the handle to the breakpoint source - * @param resource the resource on which to create the associated breakpoint marker - * @param type a type constant from ICBreakpointType - * @param function the name of the function this breakpoint suspends execution in - * @param charStart the first character index associated with the breakpoint, or - * -1 if unspecified, in the source file in which the breakpoint - * is set - * @param charEnd the last character index associated with the breakpoint, or -1 - * if unspecified, in the source file in which the breakpoint is - * set - * @param lineNumber the lineNumber on which the breakpoint is set, or -1 if - * unspecified - line numbers are 1 based, associated with the - * source file in which the breakpoint is set - * @param enabled whether to enable or disable this breakpoint - * @param ignoreCount the number of times this breakpoint will be ignored - * @param condition the breakpoint condition - * @param register whether to add this breakpoint to the breakpoint manager - * @return an address breakpoint - * @throws CoreException if this method fails. Reasons include: - *
    - *
  • Failure creating underlying marker. The exception's - * status contains the underlying exception responsible for the - * failure.
  • - *
- */ - public static ICFunctionBreakpoint createFunctionBreakpoint( String sourceHandle, IResource resource, int type, String function, int charStart, int charEnd, int lineNumber, boolean enabled, int ignoreCount, String condition, boolean register ) throws CoreException { - HashMap attributes = new HashMap( 10 ); - setFunctionBreakpointAttributes( attributes, sourceHandle, type, function, charStart, charEnd, lineNumber, enabled, ignoreCount, condition); - return new CFunctionBreakpoint( resource, attributes, register ); - } + // Added for source relocated breakpoints. + if (!attributes.containsKey(ICLineBreakpoint2.REQUESTED_SOURCE_HANDLE)) { + attributes.put(ICLineBreakpoint2.REQUESTED_SOURCE_HANDLE, sourceHandle); + } + if (!attributes.containsKey(ICLineBreakpoint2.REQUESTED_LINE)) { + attributes.put(ICLineBreakpoint2.REQUESTED_LINE, new Integer(lineNumber)); + } + if (attributes.containsKey(IMarker.CHAR_START) + && !attributes.containsKey(ICLineBreakpoint2.REQUESTED_CHAR_START)) { + attributes.put(ICLineBreakpoint2.REQUESTED_CHAR_START, attributes.get(IMarker.CHAR_START)); + } + if (attributes.containsKey(IMarker.CHAR_END) && !attributes.containsKey(ICLineBreakpoint2.REQUESTED_CHAR_END)) { + attributes.put(ICLineBreakpoint2.REQUESTED_CHAR_END, attributes.get(IMarker.CHAR_END)); + } + } - /** - * @since 7.0 - */ - public static ICFunctionBreakpoint createFunctionTracepoint( String sourceHandle, IResource resource, int type, String function, int charStart, int charEnd, int lineNumber, boolean enabled, int ignoreCount, String condition, boolean register ) throws CoreException { - HashMap attributes = new HashMap( 10 ); - setFunctionBreakpointAttributes( attributes, sourceHandle, type, function, charStart, charEnd, lineNumber, enabled, ignoreCount, condition); - return new CFunctionTracepoint( resource, attributes, register ); - } + /** + * Creates and returns an address breakpoint for the source defined by the + * given source handle, at the given address. The marker associated with the + * breakpoint will be created on the specified resource. + * + * @param module + * the module name the breakpoint is set in + * @param sourceHandle + * the handle to the breakpoint source + * @param resource + * the resource on which to create the associated breakpoint + * marker + * @param address + * the address on which the breakpoint is set + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * @return an address breakpoint + * @throws CoreException + * if this method fails. Reasons include: + *
    + *
  • Failure creating underlying marker. The exception's + * status contains the underlying exception responsible for the + * failure.
  • + *
+ * @deprecated as of CDT 5.0 use + * {@link #createAddressBreakpoint(String, String, IResource, int, int, IAddress, boolean, int, String, boolean)} + */ + @Deprecated + public static ICAddressBreakpoint createAddressBreakpoint(String module, String sourceHandle, IResource resource, + IAddress address, boolean enabled, int ignoreCount, String condition, boolean register) throws CoreException { + return createAddressBreakpoint(module, sourceHandle, resource, ICBreakpointType.REGULAR, -1, address, enabled, + ignoreCount, condition, register); + } - /** - * Helper function for setting common address breakpoint attributes. - */ - private static void setFunctionBreakpointAttributes( HashMap attributes, - String sourceHandle, - int type, - String function, - int charStart, - int charEnd, - int lineNumber, - boolean enabled, - int ignoreCount, - String condition ) { - setLineBreakpointAttributes(attributes, sourceHandle, type, lineNumber, enabled, ignoreCount, condition); - attributes.put( IMarker.CHAR_START, new Integer( charStart ) ); - attributes.put( IMarker.CHAR_END, new Integer( charEnd ) ); - attributes.put( ICLineBreakpoint.FUNCTION, function ); - } - - /** - * Returns the line breakpoint that is already registered with the - * breakpoint manager for a source with the given handle and the given - * resource at the given line number. - * - * @param sourceHandle the source handle - * @param resource the breakpoint resource - * @param lineNumber the line number - * @return the line breakpoint that is already registered with the - * breakpoint manager or null if no such breakpoint - * is registered - * @exception CoreException if unable to retrieve the associated marker attributes (line number). - */ - public static ICLineBreakpoint lineBreakpointExists( String sourceHandle, IResource resource, int lineNumber ) throws CoreException { - String modelId = getPluginIdentifier(); - IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager(); - IBreakpoint[] breakpoints = manager.getBreakpoints( modelId ); - for( int i = 0; i < breakpoints.length; i++ ) { - if ( !(breakpoints[i] instanceof ICLineBreakpoint) ) { - continue; - } - ICLineBreakpoint breakpoint = (ICLineBreakpoint)breakpoints[i]; - if ( sameSourceHandle( sourceHandle, breakpoint.getSourceHandle() ) ) { - if ( breakpoint.getLineNumber() == lineNumber ) { - return breakpoint; - } - } - } - return null; - } + /** + * Creates and returns an address breakpoint for the source defined by the + * given source handle, at the given address. The marker associated with the + * breakpoint will be created on the specified resource. + * + * @param module + * the module name the breakpoint is set in + * @param sourceHandle + * the handle to the breakpoint source + * @param resource + * the resource on which to create the associated breakpoint + * marker + * @param type + * a type constant from ICBreakpointType + * @param address + * the address on which the breakpoint is set + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * @return an address breakpoint + * @throws CoreException + * if this method fails. Reasons include: + *
    + *
  • Failure creating underlying marker. The exception's + * status contains the underlying exception responsible for the + * failure.
  • + *
+ */ + public static ICAddressBreakpoint createAddressBreakpoint(String module, String sourceHandle, IResource resource, + int type, IAddress address, boolean enabled, int ignoreCount, String condition, boolean register) + throws CoreException { + return createAddressBreakpoint(module, sourceHandle, resource, type, -1, address, enabled, ignoreCount, + condition, register); + } - /** - * Returns the watchpoint that is already registered with the breakpoint - * manager for a source with the given handle and the given resource at the - * given expression. - * - * @param sourceHandle the source handle - * @param resource the breakpoint resource - * @param expression the expression - * @return the watchpoint that is already registered with the breakpoint - * manager or null if no such watchpoint is - * registered - * @exception CoreException if unable to retrieve the associated marker attributes (line number). - */ - public static ICWatchpoint watchpointExists( String sourceHandle, IResource resource, String expression ) throws CoreException { - String modelId = getPluginIdentifier(); - String markerType = CWatchpoint.getMarkerType(); - IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager(); - IBreakpoint[] breakpoints = manager.getBreakpoints( modelId ); - for( int i = 0; i < breakpoints.length; i++ ) { - if ( !(breakpoints[i] instanceof ICWatchpoint) ) { - continue; - } - ICWatchpoint breakpoint = (ICWatchpoint)breakpoints[i]; - if ( breakpoint.getMarker().getType().equals( markerType ) ) { - if ( sameSourceHandle( sourceHandle, breakpoint.getSourceHandle() ) ) { - if ( breakpoint.getMarker().getResource().equals( resource ) ) { - if ( breakpoint.getExpression().equals( expression ) ) { - return breakpoint; - } - } - } - } - } - return null; - } + /** + * Creates and returns an address breakpoint for the source defined by the + * given source handle, at the given address. The marker associated with the + * breakpoint will be created on the specified resource. + * + * @param module + * the module name the breakpoint is set in + * @param sourceHandle + * the handle to the breakpoint source + * @param resource + * the resource on which to create the associated breakpoint + * marker + * @param type + * a type constant from ICBreakpointType + * @param lineNumber + * the line number in the source file + * @param address + * the address on which the breakpoint is set + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * @return an address breakpoint + * @throws CoreException + * if this method fails. Reasons include: + *
    + *
  • Failure creating underlying marker. The exception's + * status contains the underlying exception responsible for the + * failure.
  • + *
+ */ + public static ICAddressBreakpoint createAddressBreakpoint(String module, String sourceHandle, IResource resource, + int type, int lineNumber, IAddress address, boolean enabled, int ignoreCount, String condition, boolean register) + throws CoreException { + HashMap attributes = new HashMap(10); + setAddressBreakpointAttributes(attributes, module, sourceHandle, type, lineNumber, address, enabled, + ignoreCount, condition); + return new CAddressBreakpoint(resource, attributes, register); + } - /** - * Returns the function breakpoint that is already registered with the - * breakpoint manager for a source with the given handle and the given - * resource with the given function name. - * - * @param sourceHandle the source handle - * @param resource the breakpoint resource - * @param function the fully qualified function name - * @return the breakpoint that is already registered with the breakpoint - * manager or null if no such breakpoint is - * registered - * @exception CoreException if unable to retrieve the associated marker attributes (line number). - */ - public static ICFunctionBreakpoint functionBreakpointExists( String sourceHandle, IResource resource, String function ) throws CoreException { - String modelId = getPluginIdentifier(); - String markerType = CFunctionBreakpoint.getMarkerType(); - IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager(); - IBreakpoint[] breakpoints = manager.getBreakpoints( modelId ); - for( int i = 0; i < breakpoints.length; i++ ) { - if ( !(breakpoints[i] instanceof ICFunctionBreakpoint) ) { - continue; - } - ICFunctionBreakpoint breakpoint = (ICFunctionBreakpoint)breakpoints[i]; - if ( breakpoint.getMarker().getType().equals( markerType ) ) { - if ( sameSourceHandle( sourceHandle, breakpoint.getSourceHandle() ) ) { - if ( breakpoint.getMarker().getResource().equals( resource ) ) { - if ( breakpoint.getFunction() != null && breakpoint.getFunction().equals( function ) ) { - return breakpoint; - } - } - } - } - } - return null; - } + /** + * Creates a breakpoint without associated marker. + *

+ * Note: Before a breakpoint created using this method can be used, the + * client must first create a marker and register the breakpoint. The former + * is accomplished using {@link IBreakpoint#setMarker(IMarker)}, the latter + * using {@link IBreakpointManager#addBreakpoint(IBreakpoint)}. + * + * @since 7.2 + */ + public static ICAddressBreakpoint createBlankAddressBreakpoint() { + return new CAddressBreakpoint(); + } - /** - * @deprecated - */ - @Deprecated - public static IDebugTarget newDebugTarget( ILaunch launch, ICDITarget target, String name, IProcess iprocess, IProcess debuggerProcess, IFile file, boolean allowTerminate, boolean allowDisconnect, boolean stopInMain ) throws CoreException { - IBinaryExecutable exeFile = getBinary( file ); - String stopSymbol = null; - if ( stopInMain ) - stopSymbol = launch.getLaunchConfiguration().getAttribute( ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_STOP_AT_MAIN_SYMBOL, ICDTLaunchConfigurationConstants.DEBUGGER_STOP_AT_MAIN_SYMBOL_DEFAULT ); - return newDebugTarget( launch, file.getProject(), target, name, iprocess, exeFile, allowTerminate, allowDisconnect, stopSymbol, true ); - } + /** + * @since 7.0 + */ + public static ICAddressBreakpoint createAddressTracepoint(String module, String sourceHandle, IResource resource, + int type, int lineNumber, IAddress address, boolean enabled, int ignoreCount, String condition, boolean register) + throws CoreException { + HashMap attributes = new HashMap(10); + setAddressBreakpointAttributes(attributes, module, sourceHandle, type, lineNumber, address, enabled, + ignoreCount, condition); + return new CAddressTracepoint(resource, attributes, register); + } - /** - * @deprecated - */ - @Deprecated - public static IDebugTarget newAttachDebugTarget( ILaunch launch, ICDITarget target, String name, IProcess debuggerProcess, IFile file ) throws CoreException { - IBinaryExecutable exeFile = getBinary( file ); - return newDebugTarget( launch, file.getProject(), target, name, null, exeFile, true, true, false ); - } + /** + * Creates a breakpoint without associated marker. + *

+ * Note: Before a breakpoint created using this method can be used, the + * client must first create a marker and register the breakpoint. The former + * is accomplished using {@link IBreakpoint#setMarker(IMarker)}, the latter + * using {@link IBreakpointManager#addBreakpoint(IBreakpoint)}. + * + * @since 7.2 + */ + public static ICAddressBreakpoint createBlankAddressTracepoint() { + return new CAddressTracepoint(); + } - /** - * @deprecated - */ - @Deprecated - public static IDebugTarget newCoreFileDebugTarget( final ILaunch launch, final ICDITarget target, final String name, final IProcess debuggerProcess, final IFile file ) throws CoreException { - IBinaryExecutable exeFile = getBinary( file ); - return newDebugTarget( launch, file.getProject(), target, name, null, exeFile, true, false, false ); - } + /** + * Helper function for setting common address breakpoint attributes. + * + * @param attributes + * Map to write the attributes into. + * @param module + * the module name the breakpoint is set in + * @param sourceHandle + * the handle to the breakpoint source + * @param resource + * the resource on which to create the associated breakpoint + * marker + * @param type + * a type constant from ICBreakpointType + * @param lineNumber + * the line number in the source file + * @param address + * the address on which the breakpoint is set + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * + * @since 7.2 + */ + public static void setAddressBreakpointAttributes(Map attributes, String module, + String sourceHandle, int type, int lineNumber, IAddress address, boolean enabled, int ignoreCount, + String condition) { + setLineBreakpointAttributes(attributes, sourceHandle, type, lineNumber, enabled, ignoreCount, condition); + attributes.put(IMarker.CHAR_START, new Integer(-1)); + attributes.put(IMarker.CHAR_END, new Integer(-1)); + attributes.put(ICLineBreakpoint.ADDRESS, address.toHexAddressString()); + attributes.put(ICBreakpoint.MODULE, module); + } - private static IBinaryExecutable getBinary( IFile file ) throws CoreException { - IProject project = file.getProject(); - ICConfigExtensionReference[] binaryParsersExt = CCorePlugin.getDefault().getDefaultBinaryParserExtensions( project ); - for( int i = 0; i < binaryParsersExt.length; i++ ) { - IBinaryParser parser = CoreModelUtil.getBinaryParser(binaryParsersExt[i]); - try { - IBinaryFile exe = parser.getBinary( file.getLocation() ); - if ( exe instanceof IBinaryExecutable ) { - return (IBinaryExecutable)exe; - } - } - catch( IOException e ) { - } - } - throw new CoreException( new Status( IStatus.ERROR, CDebugCorePlugin.getUniqueIdentifier(), -1, DebugCoreMessages.getString( "CDIDebugModel.0" ), null ) ); //$NON-NLS-1$ - } + /** + * Creates a breakpoint without associated marker. + *

+ * Note: Before a breakpoint created using this method can be used, the + * client must first create a marker and register the breakpoint. The former + * is accomplished using {@link IBreakpoint#setMarker(IMarker)}, the latter + * using {@link IBreakpointManager#addBreakpoint(IBreakpoint)}. + * + * @since 7.2 + */ + public static ICWatchpoint createBlankWatchpoint() { + return new CWatchpoint(); + } - private static boolean sameSourceHandle( String handle1, String handle2 ) { - if ( handle1 == null || handle2 == null ) - return false; - IPath path1 = new Path( handle1 ); - IPath path2 = new Path( handle2 ); - if ( path1.isValidPath( handle1 ) && path2.isValidPath( handle2 ) ) { - return path1.equals( path2 ); - } - // If handles are not file names ???? - return handle1.equals( handle2 ); - } - - public static ICEventBreakpoint eventBreakpointExists(String type, String arg ) throws CoreException { - String modelId = getPluginIdentifier(); - - IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager(); - IBreakpoint[] breakpoints = manager.getBreakpoints(modelId); - for (int i = 0; i < breakpoints.length; i++) { - if (!(breakpoints[i] instanceof ICEventBreakpoint)) { - continue; - } - ICEventBreakpoint breakpoint = (ICEventBreakpoint) breakpoints[i]; + /** + * Creates and returns a watchpoint for the source defined by the given + * source handle, at the given expression. The marker associated with the + * watchpoint will be created on the specified resource. + * + * @param sourceHandle + * the handle to the watchpoint source + * @param resource + * the resource on which to create the associated watchpoint + * marker + * @param writeAccess + * whether this is write watchpoint + * @param readAccess + * whether this is read watchpoint + * @param expression + * the expression on which the watchpoint is set + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * @return a watchpoint + * @throws CoreException + * if this method fails. Reasons include: + *

    + *
  • Failure creating underlying marker. The exception's + * status contains the underlying exception responsible for the + * failure.
  • + *
+ */ + public static ICWatchpoint createWatchpoint(String sourceHandle, IResource resource, boolean writeAccess, + boolean readAccess, String expression, boolean enabled, int ignoreCount, String condition, boolean register) + throws CoreException { + HashMap attributes = new HashMap(10); + setWatchPointAttributes(attributes, sourceHandle, resource, writeAccess, readAccess, expression, "", //$NON-NLS-1$ + BigInteger.ZERO, enabled, ignoreCount, condition); + return new CWatchpoint(resource, attributes, register); + } - if (breakpoint.getEventType().equals(type)) { - String arg1 = breakpoint.getEventArgument(); - if (arg1 == null) - arg1 = ""; //$NON-NLS-1$ - String arg2 = arg == null ? "" : arg; //$NON-NLS-1$ - if (arg1.equals(arg2)) - return breakpoint; - } + /** + * Creates and returns a watchpoint for the source defined by the given + * source handle, at the given expression. The marker associated with the + * watchpoint will be created on the specified resource. + * + * @param sourceHandle + * the handle to the watchpoint source + * @param resource + * the resource on which to create the associated watchpoint + * marker + * @param charStart + * the first character index associated with the watchpoint, or + * -1 if unspecified, in the source file in which the watchpoint + * is set + * @param charEnd + * the last character index associated with the watchpoint, or -1 + * if unspecified, in the source file in which the watchpoint is + * set + * @param lineNumber + * the lineNumber on which the watchpoint is set, or -1 if + * unspecified - line numbers are 1 based, associated with the + * source file in which the watchpoint is set + * @param writeAccess + * whether this is write watchpoint + * @param readAccess + * whether this is read watchpoint + * @param expression + * the expression on which the watchpoint is set + * @param memorySpace + * the memory space in which the watchpoint is set + * @param range + * the range of the watchpoint in addressable units + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * @return a watchpoint + * @throws CoreException + * if this method fails. Reasons include: + *
    + *
  • Failure creating underlying marker. The exception's + * status contains the underlying exception responsible for the + * failure.
  • + *
+ */ + public static ICWatchpoint createWatchpoint(String sourceHandle, IResource resource, int charStart, int charEnd, + int lineNumber, boolean writeAccess, boolean readAccess, String expression, String memorySpace, + BigInteger range, boolean enabled, int ignoreCount, String condition, boolean register) throws CoreException { + HashMap attributes = new HashMap(10); + setWatchPointAttributes(attributes, sourceHandle, resource, writeAccess, readAccess, expression, memorySpace, + range, enabled, ignoreCount, condition); + attributes.put(IMarker.CHAR_START, new Integer(charStart)); + attributes.put(IMarker.CHAR_END, new Integer(charEnd)); + attributes.put(IMarker.LINE_NUMBER, new Integer(lineNumber)); + return new CWatchpoint(resource, attributes, register); + } - } - return null; - } - public static ICEventBreakpoint createEventBreakpoint(String type, String arg, boolean register) - throws CoreException { - final IResource resource = ResourcesPlugin.getWorkspace().getRoot(); - final Map attributes = new HashMap(); - attributes.put(IBreakpoint.ID, CDIDebugModel.getPluginIdentifier()); - attributes.put(IBreakpoint.ENABLED, true); - attributes.put(ICBreakpoint.IGNORE_COUNT, 0); - attributes.put(ICBreakpoint.CONDITION, ""); //$NON-NLS-1$ - attributes.put(ICEventBreakpoint.EVENT_TYPE_ID, type); - attributes.put(ICEventBreakpoint.EVENT_ARG, arg); - return new CEventBreakpoint(resource, attributes, register); + /** + * Creates and returns a watchpoint for the source defined by the given + * source handle, at the given expression and over the given range. The + * marker associated with the watchpoint will be created on the specified + * resource. + * + * @param sourceHandle + * the handle to the watchpoint source + * @param resource + * the resource on which to create the associated watchpoint + * marker + * @param writeAccess + * whether this is write watchpoint + * @param readAccess + * whether this is read watchpoint + * @param expression + * the expression on which the watchpoint is set + * @param memorySpace + * the memory space in which the watchpoint is set + * @param range + * the range of the watchpoint in addressable units + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * @return the watchpoint that was created + * @throws CoreException + * if this method fails. Reasons include: + *
    + *
  • Failure creating underlying marker. The exception's + * status contains the underlying exception responsible for the + * failure.
  • + *
+ */ + public static ICWatchpoint createWatchpoint(String sourceHandle, IResource resource, boolean writeAccess, + boolean readAccess, String expression, String memorySpace, BigInteger range, boolean enabled, int ignoreCount, + String condition, boolean register) throws CoreException { + HashMap attributes = new HashMap(10); + setWatchPointAttributes(attributes, sourceHandle, resource, writeAccess, readAccess, expression, memorySpace, + range, enabled, ignoreCount, condition); + return new CWatchpoint(resource, attributes, register); + } - } + /** + * Helper function for setting common watchpoint attributes. + * + * @param attributes + * Map to write the attributes into. + * @param sourceHandle + * the handle to the watchpoint source + * @param resource + * the resource on which to create the associated watchpoint + * marker + * @param writeAccess + * whether this is write watchpoint + * @param readAccess + * whether this is read watchpoint + * @param expression + * the expression on which the watchpoint is set + * @param memorySpace + * the memory space in which the watchpoint is set + * @param range + * the range of the watchpoint in addressable units + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * + * @since 7.2 + */ + public static void setWatchPointAttributes(Map attributes, String sourceHandle, IResource resource, + boolean writeAccess, boolean readAccess, String expression, String memorySpace, BigInteger range, + boolean enabled, int ignoreCount, String condition) { + attributes.put(IBreakpoint.ID, getPluginIdentifier()); + attributes.put(IBreakpoint.ENABLED, Boolean.valueOf(enabled)); + attributes.put(ICBreakpoint.IGNORE_COUNT, new Integer(ignoreCount)); + attributes.put(ICBreakpoint.CONDITION, condition); + attributes.put(ICBreakpoint.SOURCE_HANDLE, sourceHandle); + attributes.put(ICWatchpoint.EXPRESSION, expression); + attributes.put(ICWatchpoint2.MEMORYSPACE, memorySpace); + attributes.put(ICWatchpoint2.RANGE, range.toString()); + attributes.put(ICWatchpoint.READ, Boolean.valueOf(readAccess)); + attributes.put(ICWatchpoint.WRITE, Boolean.valueOf(writeAccess)); + } + + /** + * Creates and returns a breakpoint for the function defined by the given + * name. The marker associated with the breakpoint will be created on the + * specified resource. + * + * @param sourceHandle + * the handle to the breakpoint source + * @param resource + * the resource on which to create the associated breakpoint + * marker + * @param function + * the name of the function this breakpoint suspends execution in + * @param charStart + * the first character index associated with the breakpoint, or + * -1 if unspecified, in the source file in which the breakpoint + * is set + * @param charEnd + * the last character index associated with the breakpoint, or -1 + * if unspecified, in the source file in which the breakpoint is + * set + * @param lineNumber + * the lineNumber on which the breakpoint is set, or -1 if + * unspecified - line numbers are 1 based, associated with the + * source file in which the breakpoint is set + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * @return an address breakpoint + * @throws CoreException + * if this method fails. Reasons include: + *
    + *
  • Failure creating underlying marker. The exception's + * status contains the underlying exception responsible for the + * failure.
  • + *
+ * @deprecated as of CDT 5.0 use + * {@link #createFunctionBreakpoint(String, IResource, int, String, int, int, int, boolean, int, String, boolean)} + */ + @Deprecated + public static ICFunctionBreakpoint createFunctionBreakpoint(String sourceHandle, IResource resource, + String function, int charStart, int charEnd, int lineNumber, boolean enabled, int ignoreCount, + String condition, boolean register) throws CoreException { + return createFunctionBreakpoint(sourceHandle, resource, ICBreakpointType.REGULAR, function, charStart, charEnd, + lineNumber, enabled, ignoreCount, condition, register); + } + + /** + * Creates and returns a breakpoint for the function defined by the given + * name. The marker associated with the breakpoint will be created on the + * specified resource. + * + * @param sourceHandle + * the handle to the breakpoint source + * @param resource + * the resource on which to create the associated breakpoint + * marker + * @param type + * a type constant from ICBreakpointType + * @param function + * the name of the function this breakpoint suspends execution in + * @param charStart + * the first character index associated with the breakpoint, or + * -1 if unspecified, in the source file in which the breakpoint + * is set + * @param charEnd + * the last character index associated with the breakpoint, or -1 + * if unspecified, in the source file in which the breakpoint is + * set + * @param lineNumber + * the lineNumber on which the breakpoint is set, or -1 if + * unspecified - line numbers are 1 based, associated with the + * source file in which the breakpoint is set + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * @return an address breakpoint + * @throws CoreException + * if this method fails. Reasons include: + *
    + *
  • Failure creating underlying marker. The exception's + * status contains the underlying exception responsible for the + * failure.
  • + *
+ */ + public static ICFunctionBreakpoint createFunctionBreakpoint(String sourceHandle, IResource resource, int type, + String function, int charStart, int charEnd, int lineNumber, boolean enabled, int ignoreCount, + String condition, boolean register) throws CoreException { + HashMap attributes = new HashMap(10); + setFunctionBreakpointAttributes(attributes, sourceHandle, type, function, charStart, charEnd, lineNumber, + enabled, ignoreCount, condition); + return new CFunctionBreakpoint(resource, attributes, register); + } + + /** + * Creates a breakpoint without associated marker. + *

+ * Note: Before a breakpoint created using this method can be used, the + * client must first create a marker and register the breakpoint. The former + * is accomplished using {@link IBreakpoint#setMarker(IMarker)}, the latter + * using {@link IBreakpointManager#addBreakpoint(IBreakpoint)}. + * + * @since 7.2 + */ + public static ICFunctionBreakpoint createBlankFunctionBreakpoint() { + return new CFunctionBreakpoint(); + } + + /** + * Creates and returns a tracepoint for the function defined by the given + * name. The marker associated with the breakpoint will be created on the + * specified resource. + * + * @param sourceHandle + * the handle to the breakpoint source + * @param resource + * the resource on which to create the associated breakpoint + * marker + * @param type + * a type constant from ICBreakpointType + * @param function + * the name of the function this breakpoint suspends execution in + * @param charStart + * the first character index associated with the breakpoint, or + * -1 if unspecified, in the source file in which the breakpoint + * is set + * @param charEnd + * the last character index associated with the breakpoint, or -1 + * if unspecified, in the source file in which the breakpoint is + * set + * @param lineNumber + * the lineNumber on which the breakpoint is set, or -1 if + * unspecified - line numbers are 1 based, associated with the + * source file in which the breakpoint is set + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * @return an address breakpoint + * @throws CoreException + * if this method fails. Reasons include: + *

    + *
  • Failure creating underlying marker. The exception's + * status contains the underlying exception responsible for the + * failure.
  • + *
+ * @since 7.0 + */ + public static ICFunctionBreakpoint createFunctionTracepoint(String sourceHandle, IResource resource, int type, + String function, int charStart, int charEnd, int lineNumber, boolean enabled, int ignoreCount, + String condition, boolean register) throws CoreException { + HashMap attributes = new HashMap(10); + setFunctionBreakpointAttributes(attributes, sourceHandle, type, function, charStart, charEnd, lineNumber, + enabled, ignoreCount, condition); + return new CFunctionTracepoint(resource, attributes, register); + } + + /** + * Creates a breakpoint without associated marker. + *

+ * Note: Before a breakpoint created using this method can be used, the + * client must first create a marker and register the breakpoint. The former + * is accomplished using {@link IBreakpoint#setMarker(IMarker)}, the latter + * using {@link IBreakpointManager#addBreakpoint(IBreakpoint)}. + * + * @since 7.2 + */ + public static ICFunctionBreakpoint createBlankFunctionTracepoint() { + return new CFunctionTracepoint(); + } + + /** + * Helper function for setting common address breakpoint attributes. + * + * @param attributes + * Map to write the attributes into. + * @param sourceHandle + * the handle to the breakpoint source + * @param resource + * the resource on which to create the associated breakpoint + * marker + * @param type + * a type constant from ICBreakpointType + * @param function + * the name of the function this breakpoint suspends execution in + * @param charStart + * the first character index associated with the breakpoint, or + * -1 if unspecified, in the source file in which the breakpoint + * is set + * @param charEnd + * the last character index associated with the breakpoint, or -1 + * if unspecified, in the source file in which the breakpoint is + * set + * @param lineNumber + * the lineNumber on which the breakpoint is set, or -1 if + * unspecified - line numbers are 1 based, associated with the + * source file in which the breakpoint is set + * @param enabled + * whether to enable or disable this breakpoint + * @param ignoreCount + * the number of times this breakpoint will be ignored + * @param condition + * the breakpoint condition + * @param register + * whether to add this breakpoint to the breakpoint manager + * + * @since 7.2 + */ + public static void setFunctionBreakpointAttributes(Map attributes, String sourceHandle, int type, + String function, int charStart, int charEnd, int lineNumber, boolean enabled, int ignoreCount, String condition) { + setLineBreakpointAttributes(attributes, sourceHandle, type, lineNumber, enabled, ignoreCount, condition); + attributes.put(IMarker.CHAR_START, new Integer(charStart)); + attributes.put(IMarker.CHAR_END, new Integer(charEnd)); + attributes.put(ICLineBreakpoint.FUNCTION, function); + } + + /** + * Returns the line breakpoint that is already registered with the + * breakpoint manager for a source with the given handle and the given + * resource at the given line number. + * + * @param sourceHandle + * the source handle + * @param resource + * the breakpoint resource + * @param lineNumber + * the line number + * @return the line breakpoint that is already registered with the + * breakpoint manager or null if no such breakpoint is + * registered + * @exception CoreException + * if unable to retrieve the associated marker attributes + * (line number). + */ + public static ICLineBreakpoint lineBreakpointExists(String sourceHandle, IResource resource, int lineNumber) + throws CoreException { + String modelId = getPluginIdentifier(); + IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager(); + IBreakpoint[] breakpoints = manager.getBreakpoints(modelId); + for (int i = 0; i < breakpoints.length; i++) { + if (!(breakpoints[i] instanceof ICLineBreakpoint)) { + continue; + } + ICLineBreakpoint breakpoint = (ICLineBreakpoint) breakpoints[i]; + if (sameSourceHandle(sourceHandle, breakpoint.getSourceHandle())) { + if (breakpoint.getLineNumber() == lineNumber) { + return breakpoint; + } + } + } + return null; + } + + /** + * Returns the watchpoint that is already registered with the breakpoint + * manager for a source with the given handle and the given resource at the + * given expression. + * + * @param sourceHandle + * the source handle + * @param resource + * the breakpoint resource + * @param expression + * the expression + * @return the watchpoint that is already registered with the breakpoint + * manager or null if no such watchpoint is registered + * @exception CoreException + * if unable to retrieve the associated marker attributes + * (line number). + */ + public static ICWatchpoint watchpointExists(String sourceHandle, IResource resource, String expression) + throws CoreException { + String modelId = getPluginIdentifier(); + String markerType = ICWatchpoint.C_WATCHPOINT_MARKER; + IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager(); + IBreakpoint[] breakpoints = manager.getBreakpoints(modelId); + for (int i = 0; i < breakpoints.length; i++) { + if (!(breakpoints[i] instanceof ICWatchpoint)) { + continue; + } + ICWatchpoint breakpoint = (ICWatchpoint) breakpoints[i]; + if (breakpoint.getMarker().getType().equals(markerType)) { + if (sameSourceHandle(sourceHandle, breakpoint.getSourceHandle())) { + if (breakpoint.getMarker().getResource().equals(resource)) { + if (breakpoint.getExpression().equals(expression)) { + return breakpoint; + } + } + } + } + } + return null; + } + + /** + * Returns the function breakpoint that is already registered with the + * breakpoint manager for a source with the given handle and the given + * resource with the given function name. + * + * @param sourceHandle + * the source handle + * @param resource + * the breakpoint resource + * @param function + * the fully qualified function name + * @return the breakpoint that is already registered with the breakpoint + * manager or null if no such breakpoint is registered + * @exception CoreException + * if unable to retrieve the associated marker attributes + * (line number). + */ + public static ICFunctionBreakpoint functionBreakpointExists(String sourceHandle, IResource resource, String function) + throws CoreException { + String modelId = getPluginIdentifier(); + String markerType = ICFunctionBreakpoint.C_FUNCTION_BREAKPOINT_MARKER; + IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager(); + IBreakpoint[] breakpoints = manager.getBreakpoints(modelId); + for (int i = 0; i < breakpoints.length; i++) { + if (!(breakpoints[i] instanceof ICFunctionBreakpoint)) { + continue; + } + ICFunctionBreakpoint breakpoint = (ICFunctionBreakpoint) breakpoints[i]; + if (breakpoint.getMarker().getType().equals(markerType)) { + if (sameSourceHandle(sourceHandle, breakpoint.getSourceHandle())) { + if (breakpoint.getMarker().getResource().equals(resource)) { + if (breakpoint.getFunction() != null && breakpoint.getFunction().equals(function)) { + return breakpoint; + } + } + } + } + } + return null; + } + + /** + * @deprecated + */ + @Deprecated + public static IDebugTarget newDebugTarget(ILaunch launch, ICDITarget target, String name, IProcess iprocess, + IProcess debuggerProcess, IFile file, boolean allowTerminate, boolean allowDisconnect, boolean stopInMain) + throws CoreException { + IBinaryExecutable exeFile = getBinary(file); + String stopSymbol = null; + if (stopInMain) + stopSymbol = launch.getLaunchConfiguration().getAttribute( + ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_STOP_AT_MAIN_SYMBOL, + ICDTLaunchConfigurationConstants.DEBUGGER_STOP_AT_MAIN_SYMBOL_DEFAULT); + return newDebugTarget(launch, file.getProject(), target, name, iprocess, exeFile, allowTerminate, + allowDisconnect, stopSymbol, true); + } + + /** + * @deprecated + */ + @Deprecated + public static IDebugTarget newAttachDebugTarget(ILaunch launch, ICDITarget target, String name, + IProcess debuggerProcess, IFile file) throws CoreException { + IBinaryExecutable exeFile = getBinary(file); + return newDebugTarget(launch, file.getProject(), target, name, null, exeFile, true, true, false); + } + + /** + * @deprecated + */ + @Deprecated + public static IDebugTarget newCoreFileDebugTarget(final ILaunch launch, final ICDITarget target, final String name, + final IProcess debuggerProcess, final IFile file) throws CoreException { + IBinaryExecutable exeFile = getBinary(file); + return newDebugTarget(launch, file.getProject(), target, name, null, exeFile, true, false, false); + } + + private static IBinaryExecutable getBinary(IFile file) throws CoreException { + IProject project = file.getProject(); + ICConfigExtensionReference[] binaryParsersExt = CCorePlugin.getDefault().getDefaultBinaryParserExtensions( + project); + for (int i = 0; i < binaryParsersExt.length; i++) { + IBinaryParser parser = CoreModelUtil.getBinaryParser(binaryParsersExt[i]); + try { + IBinaryFile exe = parser.getBinary(file.getLocation()); + if (exe instanceof IBinaryExecutable) { + return (IBinaryExecutable) exe; + } + } catch (IOException e) { + } + } + throw new CoreException(new Status(IStatus.ERROR, CDebugCorePlugin.getUniqueIdentifier(), -1, + DebugCoreMessages.getString("CDIDebugModel.0"), null)); //$NON-NLS-1$ + } + + private static boolean sameSourceHandle(String handle1, String handle2) { + if (handle1 == null || handle2 == null) + return false; + IPath path1 = new Path(handle1); + IPath path2 = new Path(handle2); + if (path1.isValidPath(handle1) && path2.isValidPath(handle2)) { + return path1.equals(path2); + } + // If handles are not file names ???? + return handle1.equals(handle2); + } + + /** + * Checks whether an event breakpoint with given type and argument already + * exists. If multiple event breakpoints exist that match given parameters, + * only one of them will be returned. + * + * @param type + * Event type. + * @param arg + * Event argument. + * @return Event breakpoint, if found. + * @throws CoreException + * Exception in reading breakpoint properties. + */ + public static ICEventBreakpoint eventBreakpointExists(String type, String arg) throws CoreException { + String modelId = getPluginIdentifier(); + + IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager(); + IBreakpoint[] breakpoints = manager.getBreakpoints(modelId); + for (int i = 0; i < breakpoints.length; i++) { + if (!(breakpoints[i] instanceof ICEventBreakpoint)) { + continue; + } + ICEventBreakpoint breakpoint = (ICEventBreakpoint) breakpoints[i]; + + if (breakpoint.getEventType().equals(type)) { + String arg1 = breakpoint.getEventArgument(); + if (arg1 == null) + arg1 = ""; //$NON-NLS-1$ + String arg2 = arg == null ? "" : arg; //$NON-NLS-1$ + if (arg1.equals(arg2)) + return breakpoint; + } + + } + return null; + } + + /** + * Creates and registers a new event breakpoint. + * + * @param attributes + * Map to write the attributes into. + * @param type + * Event breakpoint type. + * @param arg + * Event-specific argument value. + * @param register + * whether to add this breakpoint to the breakpoint manager + * @return an event breakpoint + * + * @throws CoreException + * if this method fails. Reasons include: + *

    + *
  • Failure creating underlying marker. The exception's + * status contains the underlying exception responsible for the + * failure.
  • + *
+ */ + public static ICEventBreakpoint createEventBreakpoint(String type, String arg, boolean register) + throws CoreException { + final IResource resource = ResourcesPlugin.getWorkspace().getRoot(); + final Map attributes = new HashMap(); + setEventBreakpointAttributes(attributes, type, arg); + return new CEventBreakpoint(resource, attributes, register); + + } + + /** + * Helper function for setting common event breakpoint attributes. + * + * @param attributes + * Map to write the attributes into. + * @param type + * Event breakpoint type. + * @param arg + * Event-specific argument value. + * @param register + * whether to add this breakpoint to the breakpoint manager + * + * @since 7.2 + */ + public static void setEventBreakpointAttributes(Map attributes, String type, String arg) { + attributes.put(IBreakpoint.ID, CDIDebugModel.getPluginIdentifier()); + attributes.put(IBreakpoint.ENABLED, true); + attributes.put(ICBreakpoint.IGNORE_COUNT, 0); + attributes.put(ICBreakpoint.CONDITION, ""); //$NON-NLS-1$ + attributes.put(ICEventBreakpoint.EVENT_TYPE_ID, type); + attributes.put(ICEventBreakpoint.EVENT_ARG, arg); + } + + /** + * Creates a breakpoint without associated marker. + *

+ * Note: Before a breakpoint created using this method can be used, the + * client must first create a marker and register the breakpoint. The former + * is accomplished using {@link IBreakpoint#setMarker(IMarker)}, the latter + * using {@link IBreakpointManager#addBreakpoint(IBreakpoint)}. + * + * @since 7.2 + */ + public static ICEventBreakpoint createBlankEventBreakpoint() { + return new CEventBreakpoint(); + } + + /** + * Creates a marker for given C breakpoint. + * + * @param breakpoint + * Breakpoint to create the marker for. + * @param resource + * Resource to create the marker on. + * @param attributes + * Marker attributes to use. + * @param add + * Whether to register the breakpoint with breakpoint manager. + * @throws CoreException + * Error thrown while creating marker. + * + * @since 7.2 + */ + public static void createBreakpointMarker(final ICBreakpoint breakpoint, final IResource resource, + final Map attributes, final boolean add) throws CoreException { + if (breakpoint.getMarker() != null) { + throw new CoreException(new Status(IStatus.ERROR, CDebugCorePlugin.PLUGIN_ID, + "Cannot create breakpoint marker breakpoint given breakpoint already has an assotiated maker")); //$NON-NLS-1$ + } + + IWorkspaceRunnable wr = new IWorkspaceRunnable() { + @Override + public void run(IProgressMonitor monitor) throws CoreException { + // create the marker + IMarker marker = resource.createMarker(calculateMarkerType(breakpoint)); + breakpoint.setMarker(marker); + + // set attributes + marker.setAttributes(attributes); + + // set the marker message + if (breakpoint instanceof ICBreakpoint2) { + ((ICBreakpoint2) breakpoint).refreshMessage(); + } + + // add to breakpoint manager if requested + if (add) { + DebugPlugin.getDefault().getBreakpointManager().addBreakpoint(breakpoint); + } + } + }; + ResourcesPlugin.getWorkspace().run(wr, null); + } } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICAddressBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICAddressBreakpoint.java index 0d7ab756cd5..a56831d017a 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICAddressBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICAddressBreakpoint.java @@ -14,5 +14,11 @@ package org.eclipse.cdt.debug.core.model; * A breakpoint that suspend the execution when a particular address is reached. */ public interface ICAddressBreakpoint extends ICLineBreakpoint { + + /** + * Breakpoint marker type for this breakpoint type. + * @since 7.2 + */ + public static final String C_ADDRESS_BREAKPOINT_MARKER = "org.eclipse.cdt.debug.core.cAddressBreakpointMarker"; //$NON-NLS-1$ } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint.java index 4d00e6c4528..0d85e473e3e 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint.java @@ -26,6 +26,12 @@ import org.eclipse.debug.core.model.IBreakpoint; */ public interface ICBreakpoint extends IBreakpoint { + /** + * Breakpoint marker type for this breakpoint type. + * @since 7.2 + */ + public static final String C_BREAKPOINT_MARKER = "org.eclipse.cdt.debug.core.cBreakpointMarker"; //$NON-NLS-1$ + /** * This debug model identifier can be returned by a debug implementation * to indicate that a given debugger integration is using C Breakpoints. diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint2.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint2.java index 3e7acd6b207..0c2a784def7 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint2.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint2.java @@ -36,4 +36,9 @@ public interface ICBreakpoint2 extends ICBreakpoint { */ public void refreshMessage() throws CoreException; + /** + * Returns the marker type of the given CDT Breakpoint. + * @return marker type ID + */ + public String getMarkerType(); } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICEventBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICEventBreakpoint.java index ee635da0cb0..1be934e8665 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICEventBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICEventBreakpoint.java @@ -22,6 +22,13 @@ import org.eclipse.core.runtime.CoreException; * @since 7.0 */ public interface ICEventBreakpoint extends ICBreakpoint { + + /** + * Breakpoint marker type for this breakpoint type. + * @since 7.2 + */ + public static final String C_EVENT_BREAKPOINT_MARKER = "org.eclipse.cdt.debug.core.cEventBreakpointMarker"; //$NON-NLS-1$; + /** * Breakpoint attribute storing the event breakpoint event id. Basically, * this indicates what type of event the breakpoint catches--e.g., a C++ diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICFunctionBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICFunctionBreakpoint.java index 593bffe77fe..543e1864fc0 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICFunctionBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICFunctionBreakpoint.java @@ -15,5 +15,10 @@ package org.eclipse.cdt.debug.core.model; * A breakpoint that suspends the execution when a function is entered. */ public interface ICFunctionBreakpoint extends ICLineBreakpoint { + /** + * Breakpoint marker type for this breakpoint type. + * @since 7.2 + */ + public static final String C_FUNCTION_BREAKPOINT_MARKER = "org.eclipse.cdt.debug.core.cFunctionBreakpointMarker"; //$NON-NLS-1$ } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICLineBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICLineBreakpoint.java index 5f9fd93db9a..d3cc7d6ecd2 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICLineBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICLineBreakpoint.java @@ -19,6 +19,12 @@ import org.eclipse.debug.core.model.ILineBreakpoint; */ public interface ICLineBreakpoint extends ICBreakpoint, ILineBreakpoint { + /** + * Breakpoint marker type for this breakpoint type. + * @since 7.2 + */ + public static final String C_LINE_BREAKPOINT_MARKER = "org.eclipse.cdt.debug.core.cLineBreakpointMarker"; //$NON-NLS-1$ + /** * Breakpoint attribute storing the function this breakpoint suspends * execution at (value "org.eclipse.cdt.debug.core.function"). @@ -77,4 +83,5 @@ public interface ICLineBreakpoint extends ICBreakpoint, ILineBreakpoint { * underlying marker */ public String getFileName() throws CoreException; + } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICTracepoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICTracepoint.java index c55f1c3cd41..ba3fb2b8f1c 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICTracepoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICTracepoint.java @@ -18,6 +18,31 @@ import org.eclipse.core.runtime.CoreException; * @since 7.0 */ public interface ICTracepoint extends ICLineBreakpoint { + + /** + * Breakpoint marker type for this breakpoint type. + * @since 7.2 + */ + public static final String C_TRACEPOINT_MARKER = "org.eclipse.cdt.debug.core.cTracepointMarker"; //$NON-NLS-1$ + + /** + * Breakpoint marker type for this breakpoint type. + * @since 7.2 + */ + public static final String C_LINE_TRACEPOINT_MARKER = "org.eclipse.cdt.debug.core.cLineTracepointMarker"; //$NON-NLS-1$ + + /** + * Breakpoint marker type for this breakpoint type. + * @since 7.2 + */ + public static final String C_ADDRESS_TRACEPOINT_MARKER = "org.eclipse.cdt.debug.core.cAddressTracepointMarker"; //$NON-NLS-1$ + + /** + * Breakpoint marker type for this breakpoint type. + * @since 7.2 + */ + public static final String C_FUNCTION_TRACEPOINT_MARKER = "org.eclipse.cdt.debug.core.cFunctionTracepointMarker"; //$NON-NLS-1$ + /** * Tracepoint attribute storing a tracepoint's pass count value (value * "org.eclipse.cdt.debug.core.passCount"). This attribute diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICWatchpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICWatchpoint.java index f2e63b7345f..55bd9d38d98 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICWatchpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICWatchpoint.java @@ -18,6 +18,12 @@ import org.eclipse.debug.core.model.ILineBreakpoint; */ public interface ICWatchpoint extends ICBreakpoint, ILineBreakpoint { + /** + * Breakpoint marker type for this breakpoint type. + * @since 7.2 + */ + public static final String C_WATCHPOINT_MARKER = "org.eclipse.cdt.debug.core.cWatchpointMarker"; //$NON-NLS-1$ + /** * Watchpoint attribute storing the expression associated with this * watchpoint (value "org.eclipse.cdt.debug.core.expression"). diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/AbstractLineBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/AbstractLineBreakpoint.java index d5150ff1f75..1fae7032860 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/AbstractLineBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/AbstractLineBreakpoint.java @@ -42,8 +42,8 @@ public abstract class AbstractLineBreakpoint extends CBreakpoint implements ICLi * @param add * @throws CoreException */ - public AbstractLineBreakpoint( IResource resource, String markerType, Map attributes, boolean add ) throws CoreException { - super( resource, markerType, attributes, add ); + public AbstractLineBreakpoint( IResource resource, Map attributes, boolean add ) throws CoreException { + super( resource, attributes, add ); } /*(non-Javadoc) diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/AbstractTracepoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/AbstractTracepoint.java index 02611c9e218..a50acc756de 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/AbstractTracepoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/AbstractTracepoint.java @@ -42,8 +42,8 @@ public abstract class AbstractTracepoint extends CBreakpoint implements ICTracep * @param add * @throws CoreException */ - public AbstractTracepoint( IResource resource, String markerType, Map attributes, boolean add ) throws CoreException { - super( resource, markerType, attributes, add ); + public AbstractTracepoint( IResource resource, Map attributes, boolean add ) throws CoreException { + super( resource, attributes, add ); } /*(non-Javadoc) diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressBreakpoint.java index 7d31ce0ae1c..85df609b65f 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressBreakpoint.java @@ -24,8 +24,6 @@ import com.ibm.icu.text.MessageFormat; */ public class CAddressBreakpoint extends AbstractLineBreakpoint implements ICAddressBreakpoint { - private static final String C_ADDRESS_BREAKPOINT = "org.eclipse.cdt.debug.core.cAddressBreakpointMarker"; //$NON-NLS-1$ - /** * Constructor for CAddressBreakpoint. */ @@ -36,14 +34,14 @@ public class CAddressBreakpoint extends AbstractLineBreakpoint implements ICAddr * Constructor for CAddressBreakpoint. */ public CAddressBreakpoint( IResource resource, Map attributes, boolean add ) throws CoreException { - super( resource, getMarkerType(), attributes, add ); + super( resource, attributes, add ); } /** * Returns the type of marker associated with this type of breakpoints */ - public static String getMarkerType() { - return C_ADDRESS_BREAKPOINT; + public String getMarkerType() { + return C_ADDRESS_BREAKPOINT_MARKER; } /* diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressTracepoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressTracepoint.java index 0106803b448..f5852983ef3 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressTracepoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressTracepoint.java @@ -27,8 +27,6 @@ import com.ibm.icu.text.MessageFormat; */ public class CAddressTracepoint extends AbstractTracepoint implements ICAddressBreakpoint, ICTracepoint { - private static final String C_ADDRESS_TRACEPOINT_MARKER = "org.eclipse.cdt.debug.core.cAddressTracepointMarker"; //$NON-NLS-1$ - /** * Constructor for CAddressTracepoint. */ @@ -39,13 +37,13 @@ public class CAddressTracepoint extends AbstractTracepoint implements ICAddressB * Constructor for CAddressTracepoint. */ public CAddressTracepoint( IResource resource, Map attributes, boolean add ) throws CoreException { - super( resource, getMarkerType(), attributes, add ); + super( resource, attributes, add ); } /** * Returns the type of marker associated with this type of breakpoints */ - public static String getMarkerType() { + public String getMarkerType() { return C_ADDRESS_TRACEPOINT_MARKER; } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CBreakpoint.java index b8a8ccdb11d..6182be1db46 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CBreakpoint.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.cdt.debug.internal.core.breakpoints; -import com.ibm.icu.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -18,8 +17,7 @@ import java.util.Map; import org.eclipse.cdt.debug.core.CDIDebugModel; import org.eclipse.cdt.debug.core.CDebugCorePlugin; - -import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.cdt.debug.core.model.ICBreakpoint2; import org.eclipse.cdt.debug.core.model.ICBreakpointExtension; import org.eclipse.cdt.debug.core.model.ICBreakpointType; import org.eclipse.core.resources.IMarker; @@ -39,10 +37,12 @@ import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IDebugEventSetListener; import org.eclipse.debug.core.model.Breakpoint; +import com.ibm.icu.text.MessageFormat; + /** * The base class for all C/C++ specific breakpoints. */ -public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, ICBreakpointType, IDebugEventSetListener { +public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint2, ICBreakpointType, IDebugEventSetListener { /** * Map of breakpoint extensions. The keys to the map are debug model IDs @@ -67,14 +67,14 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC /** * Constructor for CBreakpoint. */ - public CBreakpoint( final IResource resource, final String markerType, final Map attributes, final boolean add ) throws CoreException { + public CBreakpoint( final IResource resource, final Map attributes, final boolean add ) throws CoreException { this(); IWorkspaceRunnable wr = new IWorkspaceRunnable() { @Override public void run( IProgressMonitor monitor ) throws CoreException { // create the marker - setMarker( resource.createMarker( markerType ) ); + setMarker( resource.createMarker( getMarkerType() ) ); // set attributes ensureMarker().setAttributes( attributes ); //set the marker message @@ -86,146 +86,69 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC run( wr ); } - public void createMarker( final IResource resource, final String markerType, final Map attributes, final boolean add ) throws DebugException { - IWorkspaceRunnable wr = new IWorkspaceRunnable() { - @Override - public void run( IProgressMonitor monitor ) throws CoreException { - // create the marker - setMarker( resource.createMarker( markerType ) ); - // set attributes - ensureMarker().setAttributes( attributes ); - //set the marker message - setAttribute( IMarker.MESSAGE, getMarkerMessage() ); - // add to breakpoint manager if requested - register( add ); - } - }; - run( wr ); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.debug.core.model.IBreakpoint#getModelIdentifier() - */ @Override public String getModelIdentifier() { return CDIDebugModel.getPluginIdentifier(); } - /* - * (non-Javadoc) - * - * @see org.eclipse.cdt.debug.core.ICBreakpoint#isInstalled() - */ @Override public boolean isInstalled() throws CoreException { return fInstallCount > 0; } - /* - * (non-Javadoc) - * - * @see org.eclipse.cdt.debug.core.ICBreakpoint#getCondition() - */ @Override public String getCondition() throws CoreException { return ensureMarker().getAttribute( CONDITION, "" ); //$NON-NLS-1$ } - /* - * (non-Javadoc) - * - * @see org.eclipse.cdt.debug.core.ICBreakpoint#setCondition(String) - */ @Override public void setCondition( String condition ) throws CoreException { setAttribute( CONDITION, condition ); setAttribute( IMarker.MESSAGE, getMarkerMessage() ); } - /* - * (non-Javadoc) - * - * @see org.eclipse.cdt.debug.core.ICBreakpoint#getIgnoreCount() - */ @Override public int getIgnoreCount() throws CoreException { return ensureMarker().getAttribute( IGNORE_COUNT, 0 ); } - /* - * (non-Javadoc) - * - * @see org.eclipse.cdt.debug.core.ICBreakpoint#setIgnoreCount(int) - */ @Override public void setIgnoreCount( int ignoreCount ) throws CoreException { setAttribute( IGNORE_COUNT, ignoreCount ); setAttribute( IMarker.MESSAGE, getMarkerMessage() ); } - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.core.model.ICBreakpoint#getType() - */ @Override public int getType() throws CoreException { return ensureMarker().getAttribute( TYPE, 0 ); } - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.core.model.ICBreakpoint#setType(int) - */ @Override public void setType(int type) throws CoreException { setAttribute( TYPE, type ); setAttribute( IMarker.MESSAGE, getMarkerMessage() ); } - - /* - * (non-Javadoc) - * - * @see org.eclipse.cdt.debug.core.ICBreakpoint#getThreadId() - */ @Override public String getThreadId() throws CoreException { return ensureMarker().getAttribute( THREAD_ID, null ); } - /* - * (non-Javadoc) - * - * @see org.eclipse.cdt.debug.core.ICBreakpoint#setThreadId(String) - */ @Override public void setThreadId( String threadId ) throws CoreException { setAttribute( THREAD_ID, threadId ); } - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.core.model.ICBreakpoint#getSourceHandle() - */ @Override public String getSourceHandle() throws CoreException { return ensureMarker().getAttribute( SOURCE_HANDLE, null ); } - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.core.model.ICBreakpoint#setSourceHandle(java.lang.String) - */ @Override public void setSourceHandle( String sourceHandle ) throws CoreException { setAttribute( SOURCE_HANDLE, sourceHandle ); } - /* - * (non-Javadoc) - * - * @see org.eclipse.debug.core.IDebugEventSetListener#handleDebugEvents(DebugEvent[]) - */ @Override public void handleDebugEvents( DebugEvent[] events ) { } @@ -257,9 +180,6 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC abstract protected String getMarkerMessage() throws CoreException; - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.core.model.ICBreakpoint#incrementInstallCount() - */ @Override public synchronized int incrementInstallCount() throws CoreException { ++fInstallCount; @@ -279,9 +199,6 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC return fInstallCount; } - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.core.model.ICBreakpoint#decrementInstallCount() - */ @Override public synchronized int decrementInstallCount() throws CoreException { fInstallCount--; @@ -293,9 +210,6 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC return fInstallCount; } - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.core.model.ICBreakpoint#resetInstallCount() - */ @Override public synchronized void resetInstallCount() throws CoreException { if (fInstallCount != 0) { @@ -304,31 +218,6 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC } } - /* - * (non-Javadoc) - * - * @see org.eclipse.debug.core.model.Breakpoint#ensureMarker() - */ - @Override - protected IMarker ensureMarker() throws DebugException { - return super.ensureMarker(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.debug.core.model.Breakpoint#setAttribute(String, Object) - */ - @Override - protected void setAttribute( String attributeName, Object value ) throws CoreException { - super.setAttribute( attributeName, value ); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.cdt.debug.core.model.ICBreakpoint#isConditional() - */ @Override public boolean isConditional() throws CoreException { return ((getCondition() != null && getCondition().trim().length() > 0) || getIgnoreCount() > 0); @@ -359,17 +248,11 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC } } - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.core.model.ICBreakpoint#getModule() - */ @Override public String getModule() throws CoreException { return ensureMarker().getAttribute( MODULE, null ); } - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.core.model.ICBreakpoint#setModule(java.lang.String) - */ @Override public void setModule( String module ) throws CoreException { setAttribute( MODULE, module ); @@ -436,6 +319,10 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC } return fExtensions.get(debugModelId); } - - + + @Override + public void refreshMessage() throws CoreException { + IMarker marker = ensureMarker(); + marker.setAttribute(IMarker.MESSAGE, getMarkerMessage()); + } } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CEventBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CEventBreakpoint.java index 70377807de7..96e16776e77 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CEventBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CEventBreakpoint.java @@ -14,24 +14,15 @@ package org.eclipse.cdt.debug.internal.core.breakpoints; import java.util.Map; +import org.eclipse.cdt.debug.core.CDIDebugModel; import org.eclipse.cdt.debug.core.model.ICEventBreakpoint; -import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.debug.core.DebugException; public class CEventBreakpoint extends CBreakpoint implements ICEventBreakpoint { - private static final String C_EVENTBREAKPOINT_MARKER_TYPE = "org.eclipse.cdt.debug.core.cEventBreakpointMarker"; //$NON-NLS-1$; - public CEventBreakpoint() { - - } - - public static String getMarkerType() { - return C_EVENTBREAKPOINT_MARKER_TYPE; } public CEventBreakpoint(IResource resource, Map attributes, boolean add) throws CoreException { @@ -39,29 +30,14 @@ public class CEventBreakpoint extends CBreakpoint implements ICEventBreakpoint { // event breakpoint must set non null EVENT_TYPE_ID property to be valid if (attributes.get(EVENT_TYPE_ID) == null) throw new IllegalArgumentException(); - setBreakpointMarker(resource, getMarkerType(), attributes, add); - + CDIDebugModel.createBreakpointMarker(this, resource, attributes, add); } - private void setBreakpointMarker(final IResource resource, final String markerType, - final Map attributes, final boolean add) throws DebugException { - IWorkspaceRunnable wr = new IWorkspaceRunnable() { - - @Override - public void run(IProgressMonitor monitor) throws CoreException { - // create the marker - setMarker(resource.createMarker(markerType)); - // set attributes - ensureMarker().setAttributes(attributes); - // set the marker message - setAttribute(IMarker.MESSAGE, getMarkerMessage()); - // add to breakpoint manager if requested - register(add); - } - }; - run(wr); + @Override + public String getMarkerType() { + return C_EVENT_BREAKPOINT_MARKER; } - + @Override protected String getMarkerMessage() throws CoreException { // default message, overridden by label provider, which would take care of translation diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionBreakpoint.java index a9f27aeb4fa..9d36cdd948a 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionBreakpoint.java @@ -24,8 +24,6 @@ import com.ibm.icu.text.MessageFormat; */ public class CFunctionBreakpoint extends AbstractLineBreakpoint implements ICFunctionBreakpoint { - private static final String C_FUNCTION_BREAKPOINT = "org.eclipse.cdt.debug.core.cFunctionBreakpointMarker"; //$NON-NLS-1$ - /** * Constructor for CFunctionBreakpoint. */ @@ -36,14 +34,14 @@ public class CFunctionBreakpoint extends AbstractLineBreakpoint implements ICFun * Constructor for CFunctionBreakpoint. */ public CFunctionBreakpoint( IResource resource, Map attributes, boolean add ) throws CoreException { - super( resource, getMarkerType(), attributes, add ); + super( resource, attributes, add ); } /** * Returns the type of marker associated with this type of breakpoints */ - public static String getMarkerType() { - return C_FUNCTION_BREAKPOINT; + public String getMarkerType() { + return C_FUNCTION_BREAKPOINT_MARKER; } /*(non-Javadoc) diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionTracepoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionTracepoint.java index ea0503cf0d6..8631eab5a39 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionTracepoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionTracepoint.java @@ -27,8 +27,6 @@ import com.ibm.icu.text.MessageFormat; */ public class CFunctionTracepoint extends AbstractTracepoint implements ICFunctionBreakpoint, ICTracepoint { - private static final String C_FUNCTION_TRACEPOINT_MARKER = "org.eclipse.cdt.debug.core.cFunctionTracepointMarker"; //$NON-NLS-1$ - /** * Constructor for CFunctionTracepoint. */ @@ -39,15 +37,15 @@ public class CFunctionTracepoint extends AbstractTracepoint implements ICFunctio * Constructor for CFunctionTracepoint. */ public CFunctionTracepoint( IResource resource, Map attributes, boolean add ) throws CoreException { - super( resource, getMarkerType(), attributes, add ); + super( resource, attributes, add ); } /** - * Returns the type of marker associated with this type of breakpoints - */ - public static String getMarkerType() { - return C_FUNCTION_TRACEPOINT_MARKER; - } + * Returns the type of marker associated with this type of breakpoints + */ + public String getMarkerType() { + return C_FUNCTION_TRACEPOINT_MARKER; + } /*(non-Javadoc) * @see org.eclipse.cdt.debug.internal.core.breakpoints.CBreakpoint#getMarkerMessage() diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineBreakpoint.java index 37f16afd8fd..05a4b0173fa 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineBreakpoint.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.cdt.debug.internal.core.breakpoints; -import com.ibm.icu.text.MessageFormat; import java.util.Map; import org.eclipse.cdt.debug.core.CDebugUtils; @@ -20,14 +19,14 @@ import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; +import com.ibm.icu.text.MessageFormat; + /** * A breakpoint that suspends the execution when a particular line of code is * reached. */ public class CLineBreakpoint extends AbstractLineBreakpoint { - private static final String C_LINE_BREAKPOINT = "org.eclipse.cdt.debug.core.cLineBreakpointMarker"; //$NON-NLS-1$ - /** * Constructor for CLineBreakpoint. */ @@ -38,14 +37,12 @@ public class CLineBreakpoint extends AbstractLineBreakpoint { * Constructor for CLineBreakpoint. */ public CLineBreakpoint( IResource resource, Map attributes, boolean add ) throws CoreException { - super( resource, getMarkerType(), attributes, add ); + super( resource, attributes, add ); } - - /** - * Returns the type of marker associated with this type of breakpoints - */ - public static String getMarkerType() { - return C_LINE_BREAKPOINT; + + @Override + public String getMarkerType() { + return C_LINE_BREAKPOINT_MARKER; } /*(non-Javadoc) diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineTracepoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineTracepoint.java index c911cc63daf..9089a732cd1 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineTracepoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineTracepoint.java @@ -29,8 +29,6 @@ import com.ibm.icu.text.MessageFormat; */ public class CLineTracepoint extends AbstractTracepoint implements ICTracepoint, ICLineBreakpoint2 { - private static final String C_LINE_TRACEPOINT_MARKER = "org.eclipse.cdt.debug.core.cLineTracepointMarker"; //$NON-NLS-1$ - /** * Constructor for CLineTracepoint. */ @@ -41,16 +39,14 @@ public class CLineTracepoint extends AbstractTracepoint implements ICTracepoint, * Constructor for CLineTracepoint. */ public CLineTracepoint( IResource resource, Map attributes, boolean add ) throws CoreException { - super( resource, getMarkerType(), attributes, add ); + super( resource, attributes, add ); } - /** - * Returns the type of marker associated with this type of breakpoints - */ - public static String getMarkerType() { - return C_LINE_TRACEPOINT_MARKER; + @Override + public String getMarkerType() { + return C_LINE_TRACEPOINT_MARKER; } - + @Override public synchronized int decrementInstallCount() throws CoreException { int count = super.decrementInstallCount(); diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CWatchpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CWatchpoint.java index 75f992d126d..e1a23732e1d 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CWatchpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CWatchpoint.java @@ -25,8 +25,6 @@ import org.eclipse.core.runtime.CoreException; */ public class CWatchpoint extends CBreakpoint implements ICWatchpoint2 { - private static final String C_WATCHPOINT = "org.eclipse.cdt.debug.core.cWatchpointMarker"; //$NON-NLS-1$ - /** * Constructor for CWatchpoint. */ @@ -37,13 +35,14 @@ public class CWatchpoint extends CBreakpoint implements ICWatchpoint2 { * Constructor for CWatchpoint. */ public CWatchpoint( IResource resource, Map attributes, boolean add ) throws CoreException { - super( resource, getMarkerType(), attributes, add ); + super( resource, attributes, add ); } - protected CWatchpoint( IResource resource, String marker, Map attributes, boolean add ) throws CoreException { - super( resource, marker, attributes, add ); + @Override + public String getMarkerType() { + return C_WATCHPOINT_MARKER; } - + /* (non-Javadoc) * @see org.eclipse.cdt.debug.core.model.ICWatchpoint#isWriteType() */ @@ -68,13 +67,6 @@ public class CWatchpoint extends CBreakpoint implements ICWatchpoint2 { return ensureMarker().getAttribute( EXPRESSION, "" ); //$NON-NLS-1$ } - /** - * Returns the type of marker associated with this type of breakpoints - */ - public static String getMarkerType() { - return C_WATCHPOINT; - } - /* (non-Javadoc) * @see org.eclipse.cdt.debug.internal.core.breakpoints.CBreakpoint#getMarkerMessage() */ diff --git a/debug/org.eclipse.cdt.debug.ui/META-INF/MANIFEST.MF b/debug/org.eclipse.cdt.debug.ui/META-INF/MANIFEST.MF index 934302b9c8d..11eba71e802 100644 --- a/debug/org.eclipse.cdt.debug.ui/META-INF/MANIFEST.MF +++ b/debug/org.eclipse.cdt.debug.ui/META-INF/MANIFEST.MF @@ -7,8 +7,10 @@ Bundle-Activator: org.eclipse.cdt.debug.ui.CDebugUIPlugin Bundle-Vendor: %providerName Bundle-Localization: plugin Export-Package: - org.eclipse.cdt.debug.internal.ui;x-internal:=true, + org.eclipse.cdt.debug.internal.ui;x-internal:x-friends:="org.eclipse.cdt.dsf.ui";x-friends:="org.eclipse.cdt.dsf.ui", org.eclipse.cdt.debug.internal.ui.actions;x-friends:="org.eclipse.cdt.dsf.ui,org.eclipse.cdt.debug.ui.memory.memorybrowser", + org.eclipse.cdt.debug.internal.ui.actions.breakpoints;x-internal:=true, + org.eclipse.cdt.debug.internal.ui.breakpoints;x-internal:=true, org.eclipse.cdt.debug.internal.ui.commands;x-internal:=true, org.eclipse.cdt.debug.internal.ui.dialogfields;x-internal:=true, org.eclipse.cdt.debug.internal.ui.dialogs;x-internal:=true, diff --git a/debug/org.eclipse.cdt.debug.ui/plugin.properties b/debug/org.eclipse.cdt.debug.ui/plugin.properties index 15a35463bcd..e2bd92dc753 100644 --- a/debug/org.eclipse.cdt.debug.ui/plugin.properties +++ b/debug/org.eclipse.cdt.debug.ui/plugin.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2011 QNX Software Systems and others. +# Copyright (c) 2000, 2012 QNX Software Systems and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -35,9 +35,10 @@ ToggleInstructionStepModeAction.tooltip=Instruction Stepping Mode ShowDebuggerConsoleAction.label=Show Debugger Console ShowDebuggerConsoleAction.tooltip=Show Debugger Console On Target Selection -AddBreakpoint.label=Toggle &Breakpoint -EnableBreakpoint.label=&Toggle Breakpoint Enabled -BreakpointProperties.label=Breakpoint P&roperties... +AddBreakpoint.label=Toggle &Breakpoint\tDouble Click +AddBreakpointInteractive.label=&Add Breakpoint...\tCtrl+Double Click +EnableBreakpoint.label=&Toggle Breakpoint Enabled\tShift+Double Click +BreakpointProperties.label=Breakpoint P&roperties...\tCtrl+Double Click BreakpointPropertiesCommand.name=C/C++ Breakpoint Properties BreakpointPropertiesCommand.description=View and edit properties for a given C/C++ breakpoint ManageFunctionBreakpointAction.label=Toggle Breakpoint @@ -57,6 +58,8 @@ AddWatchpoint.label=Add Watchpoint (C/C++)... AddWatchpoint.tooltip=Add Watchpoint (C/C++) AddEventBreakpoint.label=Add Event Breakpoint (C/C++)... AddEventBreakpoint.tooltip=Add Event Breakpoint (C/C++) +AddFunctionBreakpoint.label=Add Function Breakpoint (C/C++)... +AddFunctionBreakpoint.tooltip=Add Function Breakpoint (C/C++) AddGlobalsAction.label=Add Global Variables... AddGlobalsAction.tooltip=Add Global Variables diff --git a/debug/org.eclipse.cdt.debug.ui/plugin.xml b/debug/org.eclipse.cdt.debug.ui/plugin.xml index fa53348e75b..afdcbfac5a5 100644 --- a/debug/org.eclipse.cdt.debug.ui/plugin.xml +++ b/debug/org.eclipse.cdt.debug.ui/plugin.xml @@ -415,27 +415,27 @@ - - + + + + @@ -619,7 +626,7 @@ icon="icons/elcl16/function_brkpt_co.gif" helpContextId="manage_function_breakpoint_action_context" tooltip="%ManageFunctionBreakpointAction.tooltip" - class="org.eclipse.debug.ui.actions.ToggleMethodBreakpointActionDelegate" + class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.CToggleMethodBreakpointActionDelegate" menubarPath="additions" enablesFor="1" id="org.eclipse.cdt.debug.ui.actions.method.ToggleMethodBreakpointAction"> @@ -629,7 +636,7 @@ objectClass="org.eclipse.cdt.debug.internal.core.ICWatchpointTarget" id="org.eclipse.cdt.debug.ui.WatchpointActions"> + - - - - - + + + - - + + + + + + + + + + + + + + - @@ -1296,7 +1322,7 @@ @@ -1736,6 +1762,18 @@ + +

+ + + + + @@ -1766,14 +1804,14 @@ + class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.ToggleCBreakpointsTargetFactory"> @@ -1802,7 +1840,7 @@ + class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.ToggleCTracepointsTargetFactory"> @@ -2093,7 +2131,7 @@ point="org.eclipse.ui.commands"> + + + + diff --git a/debug/org.eclipse.cdt.debug.ui/schema/BreakpointUIContribution.exsd b/debug/org.eclipse.cdt.debug.ui/schema/BreakpointUIContribution.exsd index 85dd1dc6465..d9b6c850f5d 100644 --- a/debug/org.eclipse.cdt.debug.ui/schema/BreakpointUIContribution.exsd +++ b/debug/org.eclipse.cdt.debug.ui/schema/BreakpointUIContribution.exsd @@ -107,7 +107,7 @@ If not specified this attribute will not be visible in Common page. - Type of the attribute: boolean, string, integer + Type of the attribute. Value should be one of "boolean", "string", "integer", "float". diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/CDebugUIUtils.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/CDebugUIUtils.java index ac66eb4759d..473330f68a3 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/CDebugUIUtils.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/CDebugUIUtils.java @@ -11,9 +11,10 @@ *******************************************************************************/ package org.eclipse.cdt.debug.internal.ui; -import com.ibm.icu.text.MessageFormat; +import java.util.Iterator; import org.eclipse.cdt.debug.core.CDebugUtils; +import org.eclipse.cdt.debug.core.model.ICBreakpoint; import org.eclipse.cdt.debug.core.model.ICDebugElementStatus; import org.eclipse.cdt.debug.core.model.ICStackFrame; import org.eclipse.cdt.debug.core.model.ICType; @@ -21,7 +22,9 @@ import org.eclipse.cdt.debug.core.model.ICValue; import org.eclipse.cdt.debug.core.model.IEnableDisableTarget; import org.eclipse.cdt.debug.internal.ui.disassembly.rendering.DisassemblyEditorInput; import org.eclipse.cdt.debug.ui.CDebugUIPlugin; +import org.eclipse.cdt.debug.ui.breakpoints.CBreakpointPropertyDialogAction; import org.eclipse.core.filesystem.URIUtil; +import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; @@ -29,21 +32,38 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.DebugException; +import org.eclipse.debug.core.DebugPlugin; +import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.core.model.IValue; import org.eclipse.debug.core.model.IVariable; import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.debug.ui.contexts.IDebugContextListener; +import org.eclipse.debug.ui.contexts.IDebugContextProvider; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.jface.text.source.IVerticalRulerInfo; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IPathEditorInput; import org.eclipse.ui.IStorageEditorInput; import org.eclipse.ui.IURIEditorInput; +import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.progress.UIJob; +import org.eclipse.ui.texteditor.ITextEditor; +import org.eclipse.ui.texteditor.SimpleMarkerAnnotation; + +import com.ibm.icu.text.MessageFormat; /** * Utility methods for C/C++ Debug UI. @@ -209,7 +229,7 @@ public class CDebugUIUtils { return null; StringBuffer baseText = new StringBuffer( text ); if ( element instanceof ICDebugElementStatus && !((ICDebugElementStatus)element).isOK() ) { - baseText.append( MessageFormat.format( " <{0}>", new String[] { ((ICDebugElementStatus)element).getMessage() } ) ); //$NON-NLS-1$ + baseText.append( MessageFormat.format( " <{0}>", new Object[] { ((ICDebugElementStatus)element).getMessage() } ) ); //$NON-NLS-1$ } if ( element instanceof IAdaptable ) { IEnableDisableTarget target = (IEnableDisableTarget)((IAdaptable)element).getAdapter( IEnableDisableTarget.class ); @@ -251,5 +271,71 @@ public class CDebugUIUtils { uiJob.setSystem(true); uiJob.schedule(); } + + /** + * Resolves the {@link IBreakpoint} from the given editor and ruler information. Returns null + * if no breakpoint exists or the operation fails. + * + * @param editor the editor + * @param info the current ruler information + * @return the {@link IBreakpoint} from the current editor position or null + */ + public static IBreakpoint getBreakpointFromEditor(ITextEditor editor, IVerticalRulerInfo info) { + IAnnotationModel annotationModel = editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput()); + IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); + if (annotationModel != null) { + @SuppressWarnings("unchecked") + Iterator iterator = annotationModel.getAnnotationIterator(); + while (iterator.hasNext()) { + Object object = iterator.next(); + 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 line = document.getLineOfOffset(position.getOffset()); + if (line == info.getLineOfLastMouseButtonActivity()) { + IBreakpoint breakpoint = DebugPlugin.getDefault().getBreakpointManager().getBreakpoint(marker); + if (breakpoint != null) { + return breakpoint; + } + } + } + } catch (CoreException e) { + } catch (BadLocationException e) { + } + } + } + } + return null; + } + public static void editBreakpointProperties(IWorkbenchPart part, final ICBreakpoint bp) { + final ISelection debugContext = DebugUITools.getDebugContextForPart(part); + CBreakpointPropertyDialogAction propertiesAction = new CBreakpointPropertyDialogAction( + part.getSite(), + new ISelectionProvider() { + @Override + public ISelection getSelection() { + return new StructuredSelection( bp ); + } + @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(); + } } diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AbstractToggleBreakpointAdapter.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AbstractToggleBreakpointAdapter.java deleted file mode 100644 index 466d291bbdb..00000000000 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AbstractToggleBreakpointAdapter.java +++ /dev/null @@ -1,463 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 Mentor Graphics and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Mentor Graphics - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.debug.internal.ui.actions; - -import java.math.BigInteger; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IDeclaration; -import org.eclipse.cdt.core.model.IFunction; -import org.eclipse.cdt.core.model.IFunctionDeclaration; -import org.eclipse.cdt.core.model.IMethod; -import org.eclipse.cdt.core.model.ISourceRange; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.model.IVariable; -import org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint; -import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; -import org.eclipse.cdt.debug.core.model.ICWatchpoint; -import org.eclipse.cdt.debug.internal.ui.CDebugUIUtils; -import org.eclipse.cdt.debug.internal.ui.IInternalCDebugUIConstants; -import org.eclipse.cdt.debug.ui.CDebugUIPlugin; -import org.eclipse.cdt.internal.ui.util.ExternalEditorInput; -import org.eclipse.cdt.ui.CDTUITools; -import org.eclipse.core.filesystem.URIUtil; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.debug.core.DebugPlugin; -import org.eclipse.debug.ui.actions.IToggleBreakpointsTargetExtension; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.window.Window; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.editors.text.ILocationProvider; -import org.eclipse.ui.texteditor.IEditorStatusLine; -import org.eclipse.ui.texteditor.ITextEditor; - -abstract public class AbstractToggleBreakpointAdapter implements IToggleBreakpointsTargetExtension { - - /* (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 { - String errorMessage = null; - if ( part instanceof ITextEditor ) { - ITextEditor textEditor = (ITextEditor)part; - IEditorInput input = textEditor.getEditorInput(); - if ( input == null ) { - errorMessage = ActionMessages.getString( "ToggleBreakpointAdapter.Empty_editor_1" ); //$NON-NLS-1$ - } - else { - IDocument document = textEditor.getDocumentProvider().getDocument( input ); - if ( document == null ) { - errorMessage = ActionMessages.getString( "ToggleBreakpointAdapter.Missing_document_1" ); //$NON-NLS-1$ - } - else { - IResource resource = getResource( textEditor ); - if ( resource == null ) { - errorMessage = ActionMessages.getString( "ToggleBreakpointAdapter.Missing_resource_1" ); //$NON-NLS-1$ - } - else { - BreakpointLocationVerifier bv = new BreakpointLocationVerifier(); - int lineNumber = bv.getValidLineBreakpointLocation( document, ((ITextSelection)selection).getStartLine() ); - if ( lineNumber == -1 ) { - errorMessage = ActionMessages.getString( "ToggleBreakpointAdapter.Invalid_line_1" ); //$NON-NLS-1$ - } - else { - String sourceHandle = getSourceHandle( input ); - ICLineBreakpoint breakpoint = findLineBreakpoint( sourceHandle, resource, lineNumber ); - if ( breakpoint != null ) { - DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint( breakpoint, true ); - } - else { - createLineBreakpoint( sourceHandle, resource, lineNumber ); - } - return; - } - } - } - } - } - else { - errorMessage = ActionMessages.getString( "RunToLineAdapter.Operation_is_not_supported_1" ); //$NON-NLS-1$ - } - throw new CoreException( - new Status( IStatus.ERROR, CDebugUIPlugin.getUniqueIdentifier(), IInternalCDebugUIConstants.INTERNAL_ERROR, errorMessage, null ) ); - } - - /* (non-Javadoc) - * @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 ) { - return (selection instanceof ITextSelection); - } - - /* (non-Javadoc) - * @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 { - ICElement element = getCElementFromSelection( part, selection ); - if ( element instanceof IFunction || element instanceof IMethod ) { - toggleMethodBreakpoints0( (IDeclaration)element ); - } - } - - /* (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 ) { - ICElement element = getCElementFromSelection( part, selection ); - return (element instanceof IFunction || element instanceof IMethod); - } - - protected ICElement getCElementFromSelection( IWorkbenchPart part, ISelection selection ) { - if ( selection instanceof ITextSelection ) { - ITextSelection textSelection = (ITextSelection)selection; - String text = textSelection.getText(); - if ( text != null ) { - if ( part instanceof ITextEditor ) { - ICElement editorElement = CDTUITools.getEditorInputCElement( ((ITextEditor)part).getEditorInput() ); - if ( editorElement instanceof ITranslationUnit ) { - ITranslationUnit tu = (ITranslationUnit)editorElement; - try { - if ( tu.isStructureKnown() && tu.isConsistent() ) { - return tu.getElementAtOffset( textSelection.getOffset() ); - } - } - catch( CModelException exc ) { - // ignored on purpose - } - } - } - else { - IResource resource = getResource( part ); - if ( resource instanceof IFile ) { - ITranslationUnit tu = getTranslationUnit( (IFile)resource ); - if ( tu != null ) { - try { - ICElement element = tu.getElement( text.trim() ); - if ( element == null ) { - element = tu.getElementAtLine( textSelection.getStartLine() ); - } - return element; - } - catch( CModelException e ) { - } - } - } - } - } - } - else if ( selection instanceof IStructuredSelection ) { - IStructuredSelection ss = (IStructuredSelection)selection; - if ( ss.size() == 1 ) { - Object object = ss.getFirstElement(); - if ( object instanceof ICElement ) { - return (ICElement)object; - } - } - } - return null; - } - - /* (non-Javadoc) - * @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 { - IVariable variable = getVariableFromSelection( part, selection ); - if ( variable != null ) { - toggleVariableWatchpoint( part, variable ); - } - } - - /* (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 ) { - return getVariableFromSelection( part, selection ) != null; - } - - /* (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 ) - || canToggleWatchpoints( part, selection ) - || canToggleMethodBreakpoints( part, selection ) ); - } - - /* (non-Javadoc) - * @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 { - if ( canToggleLineBreakpoints( part, selection ) ) { - toggleLineBreakpoints( part, selection ); - } - else { - ICElement element = getCElementFromSelection( part, selection ); - if ( element instanceof IFunction || element instanceof IMethod ) { - toggleMethodBreakpoints0( (IDeclaration)element ); - } - else if ( element instanceof IVariable ) { - toggleVariableWatchpoint( part, (IVariable)element ); - } - } - } - - protected IVariable getVariableFromSelection( IWorkbenchPart part, ISelection selection ) { - ICElement element = getCElementFromSelection( part, selection ); - if ( element instanceof IVariable ) { - return (IVariable)element; - } - return null; - } - - protected void report( String message, IWorkbenchPart part ) { - IEditorStatusLine statusLine = (IEditorStatusLine)part.getAdapter( IEditorStatusLine.class ); - if ( statusLine != null ) { - if ( message != null ) { - statusLine.setMessage( true, message, null ); - } - else { - statusLine.setMessage( true, null, null ); - } - } - if ( message != null && CDebugUIPlugin.getActiveWorkbenchShell() != null ) { - CDebugUIPlugin.getActiveWorkbenchShell().getDisplay().beep(); - } - } - - protected static IResource getResource( IWorkbenchPart part ) { - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - if ( part instanceof IEditorPart ) { - IEditorInput editorInput = ((IEditorPart)part).getEditorInput(); - IResource resource = null; - if ( editorInput instanceof IFileEditorInput ) { - resource = ((IFileEditorInput)editorInput).getFile(); - } - else if ( editorInput instanceof ExternalEditorInput ) { - resource = ((ExternalEditorInput)editorInput).getMarkerResource(); - } - if ( resource != null ) - return resource; - /* This file is not in a project, let default case handle it */ - ILocationProvider provider = (ILocationProvider)editorInput.getAdapter( ILocationProvider.class ); - if ( provider != null ) { - IPath location = provider.getPath( editorInput ); - if ( location != null ) { - IFile[] files = root.findFilesForLocationURI( URIUtil.toURI( location ) ); - if ( files.length > 0 && files[0].isAccessible()) - return files[0]; - } - } - } - return root; - } - - private String getSourceHandle( IEditorInput input ) throws CoreException { - return CDebugUIUtils.getEditorFilePath( input ); - } - - private void toggleVariableWatchpoint( IWorkbenchPart part, IVariable variable ) throws CoreException { - String sourceHandle = getSourceHandle( variable ); - IResource resource = getElementResource( variable ); - String expression = getVariableName( variable ); - ICWatchpoint watchpoint = findWatchpoint( sourceHandle, resource, expression ); - if ( watchpoint != null ) { - DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint( watchpoint, true ); - } - else { - AddWatchpointDialog dlg = new AddWatchpointDialog( part.getSite().getShell(), AddWatchpointActionDelegate.getMemorySpaceManagement() ); - dlg.setExpression( expression ); - if ( dlg.open() != Window.OK ) - return; - expression = dlg.getExpression(); - int lineNumber = -1; - int charStart = -1; - int charEnd = -1; - try { - ISourceRange sourceRange = variable.getSourceRange(); - if ( sourceRange != null ) { - charStart = sourceRange.getStartPos(); - charEnd = charStart + sourceRange.getLength(); - if ( charEnd <= 0 ) { - charStart = -1; - charEnd = -1; - } - lineNumber = sourceRange.getStartLine(); - } - } - catch( CModelException e ) { - DebugPlugin.log( e ); - } - createWatchpoint( - sourceHandle, - resource, - charStart, - charEnd, - lineNumber, - dlg.getWriteAccess(), - dlg.getReadAccess(), - expression, - dlg.getMemorySpace(), - dlg.getRange() ); - } - } - - private String getSourceHandle( IDeclaration declaration ) { - ITranslationUnit tu = declaration.getTranslationUnit(); - if ( tu != null ) { - IPath location = tu.getLocation(); - if ( location != null ) { - return location.toOSString(); - } - } - return ""; //$NON-NLS-1$ - } - - private IResource getElementResource( IDeclaration declaration ) { - return declaration.getUnderlyingResource(); - } - - private String getFunctionName( IFunction function ) { - String functionName = function.getElementName(); - StringBuffer name = new StringBuffer( functionName ); - ITranslationUnit tu = function.getTranslationUnit(); - if ( tu != null && tu.isCXXLanguage() ) { - appendParameters( name, function ); - } - return name.toString(); - } - - private String getMethodName( IMethod method ) { - StringBuffer name = new StringBuffer(); - String methodName = method.getElementName(); - ICElement parent = method.getParent(); - while( parent != null - && (parent.getElementType() == ICElement.C_NAMESPACE || parent.getElementType() == ICElement.C_CLASS - || parent.getElementType() == ICElement.C_STRUCT || parent.getElementType() == ICElement.C_UNION) ) { - name.append( parent.getElementName() ).append( "::" ); //$NON-NLS-1$ - parent = parent.getParent(); - } - name.append( methodName ); - appendParameters( name, method ); - return name.toString(); - } - - private void appendParameters( StringBuffer sb, IFunctionDeclaration fd ) { - String[] params = fd.getParameterTypes(); - sb.append( '(' ); - for( int i = 0; i < params.length; ++i ) { - sb.append( params[i] ); - if ( i != params.length - 1 ) - sb.append( ',' ); - } - sb.append( ')' ); - } - - private String getVariableName( IVariable variable ) { - return variable.getElementName(); - } - - private ITranslationUnit getTranslationUnit( IFile file ) { - Object element = CoreModel.getDefault().create( file ); - if ( element instanceof ITranslationUnit ) { - return (ITranslationUnit)element; - } - return null; - } - - private void toggleMethodBreakpoints0( IDeclaration declaration ) throws CoreException { - String sourceHandle = getSourceHandle( declaration ); - IResource resource = getElementResource( declaration ); - String functionName = (declaration instanceof IFunction) ? getFunctionName( (IFunction)declaration ) : getMethodName( (IMethod)declaration ); - ICFunctionBreakpoint breakpoint = findFunctionBreakpoint( sourceHandle, resource, functionName ); - if ( breakpoint != null ) { - DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint( breakpoint, true ); - } - else { - int lineNumber = -1; - int charStart = -1; - int charEnd = -1; - try { - ISourceRange sourceRange = declaration.getSourceRange(); - if ( sourceRange != null ) { - charStart = sourceRange.getStartPos(); - charEnd = charStart + sourceRange.getLength(); - if ( charEnd <= 0 ) { - charStart = -1; - charEnd = -1; - } - lineNumber = sourceRange.getStartLine(); - } - } - catch( CModelException e ) { - DebugPlugin.log( e ); - } - createFunctionBreakpoint( - sourceHandle, - resource, - functionName, - charStart, - charEnd, - lineNumber ); - } - } - - protected abstract ICLineBreakpoint findLineBreakpoint( String sourceHandle, IResource resource, int lineNumber ) throws CoreException; - - protected abstract void createLineBreakpoint( String sourceHandle, IResource resource, int lineNumber ) throws CoreException; - - protected abstract ICFunctionBreakpoint findFunctionBreakpoint( String sourceHandle, IResource resource, String functionName ) throws CoreException; - - protected abstract void createFunctionBreakpoint( - String sourceHandle, - IResource resource, - String functionName, - int charStart, - int charEnd, - int lineNumber ) throws CoreException; - - protected abstract ICWatchpoint findWatchpoint( String sourceHandle, IResource resource, String expression ) throws CoreException; - - protected abstract void createWatchpoint( - String sourceHandle, - IResource resource, - int charStart, - int charEnd, - int lineNumber, - boolean writeAccess, - boolean readAccess, - String expression, - String memorySpace, - BigInteger range ) throws CoreException; -} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ActionMessages.properties b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ActionMessages.properties index 34fed677de0..eb47e4a36bb 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ActionMessages.properties +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ActionMessages.properties @@ -37,15 +37,15 @@ ToggleBreakpointAdapter.Missing_document_2=Missing document ToggleBreakpointAdapter.Missing_resource_2=Missing resource ToggleBreakpointAdapter.Invalid_expression_1=Invalid expression: RunToLineAdapter.Operation_is_not_supported_1=Operation is not supported. -EnableDisableBreakpointRulerAction.Enable_Breakpoint_1=&Enable Breakpoint +EnableDisableBreakpointRulerAction.Enable_Breakpoint_1=&Enable Breakpoint\tShift+Double Click EnableDisableBreakpointRulerAction.Enabling_disabling_breakpoints_1=Enabling/disabling breakpoints EnableDisableBreakpointRulerAction.Exceptions_occurred_enabling_or_disabling_breakpoint_1=Exceptions occurred enabling or disabling the breakpoint -EnableDisableBreakpointRulerAction.Disable_Breakpoint_1=&Disable Breakpoint -ToggleBreakpointRulerAction.Toggle_Breakpoint_1=Toggle &Breakpoint +EnableDisableBreakpointRulerAction.Disable_Breakpoint_1=&Disable Breakpoint\tShift+Double Click ToggleWatchpointActionDelegate.Operation_failed_1=Operation failed. ToggleBreakpointRulerAction.Error_1=Error ToggleBreakpointRulerAction.Operation_failed_1=Operation failed -CBreakpointPropertiesRulerAction.Breakpoint_Properties=Breakpoint &Properties... +CBreakpointPropertiesRulerAction.Breakpoint_Properties=Breakpoint &Properties...\tCtrl+Double Click +CBreakpointPropertiesRulerAction.Error=Unable to edit breakpoint properties. ResumeAtLineActionDelegate.Error_1=Error ResumeAtLineActionDelegate.1=Error ResumeAtLineActionDelegate.2=Resume at line failed @@ -129,3 +129,9 @@ RetargetAction.0=Error RetargetAction.1=Operation failed RetargetMoveToLineAction.0=The operation is unavailable on the current selection. Please place the cursor on valid line to run to. RetargetResumeAtLineAction.0=The operation is unavailable on the current selection. Please place the cursor on valid line to run to. +CAddBreakpointInteractiveRulerAction_label=&Add Breakpoint...\tCtrl+Double Click +CAddBreakpointInteractiveRulerAction_error_title=Error +CAddBreakpointInteractiveRulerAction_error_message=Unable to create breakpoint +CBreakpointToggleRulerAction_error_label=Toggle Brea&kpoint\tDouble Click +CBreakpointToggleRulerAction_error_title=Error +CBreakpointToggleRulerAction_error_message=Unable to toggle breakpoint \ No newline at end of file diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddWatchpointDialog.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddWatchpointDialog.java index 8d6bab94516..f7c4231a94e 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddWatchpointDialog.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddWatchpointDialog.java @@ -1,437 +1,29 @@ /******************************************************************************* - * Copyright (c) 2004, 2008, 2008 QNX Software Systems and others. + * Copyright (c) 2012 Wind River Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: - * QNX Software Systems - Initial API and implementation - * Freescale Semiconductor - Address watchpoints, https://bugs.eclipse.org/bugs/show_bug.cgi?id=118299 - * IBM Corporation + * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.debug.internal.ui.actions; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; - import org.eclipse.cdt.debug.core.cdi.model.ICDIMemorySpaceManagement; -import org.eclipse.debug.ui.DebugUITools; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.swt.SWT; -import org.eclipse.swt.accessibility.AccessibleAdapter; -import org.eclipse.swt.accessibility.AccessibleEvent; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.events.VerifyEvent; -import org.eclipse.swt.events.VerifyListener; -import org.eclipse.swt.graphics.FontMetrics; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; /** - * The "Add Watchpoint" dialog of the "Toggle watchpoint" action. + * This class was moved to the org.eclipse.cdt.debug.internal.ui.actions.breakpoints + * package. This class is left here for backward compatibility for extenders that + * reference this internal class (see Bug 374983). + * + * @deprecated Replaced by opening a properties dialog on a new breakpoint. */ -public class AddWatchpointDialog extends Dialog implements ModifyListener, SelectionListener { - - private Combo fExpressionInput; - private String fExpression; - private static List sExpressionHistory = new ArrayList(); - - private boolean fHasMemorySpaceControls; - private Button fMemorySpaceEnableButton; - private Combo fMemorySpaceInput; - private String fMemorySpace; - - private boolean fRangeInitialEnable; - private Button fRangeEnableButton; - private Text fRangeField; - private String fRange = ""; //$NON-NLS-1$ - - private Button fChkBtnWrite; - private Button fChkBtnRead; - private boolean fRead; - private boolean fWrite; - - private ICDIMemorySpaceManagement fMemManagement; - - - /** - * Constructor for AddWatchpointDialog. - * - * @param parentShell - */ - public AddWatchpointDialog( Shell parentShell, ICDIMemorySpaceManagement memMgmt ) { - super( parentShell ); - setShellStyle( getShellStyle() | SWT.RESIZE ); - fMemManagement = memMgmt; - } - - /* (non-Javadoc) - * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) - */ - @Override - protected Control createDialogArea( Composite parent ) { - // The button bar will work better if we make the parent composite - // a single column grid layout. For the widgets we add, we want a - // a two-column grid, so we just create a sub composite for that. - GridLayout gridLayout = new GridLayout(); - parent.setLayout( gridLayout ); - GridData gridData = new GridData( GridData.FILL_BOTH ); - parent.setLayoutData( gridData ); - Composite composite = new Composite( parent, SWT.None ); - gridLayout = new GridLayout(); - gridLayout.numColumns = 2; - composite.setLayout( gridLayout ); - parent = composite; - - // Create the controls - createExpressionControl( parent ); - boolean hasDebugContext = DebugUITools.getDebugContext() != null; - boolean hasMemorySpaces = hasDebugContext && fMemManagement != null && fMemManagement.getMemorySpaces() != null && fMemManagement.getMemorySpaces().length > 0; - fHasMemorySpaceControls = !hasDebugContext || hasMemorySpaces; - if ( fHasMemorySpaceControls ) { - createMemorySpaceControl( parent, hasMemorySpaces ); - } - createCountField( parent ); - createAccessWidgets( parent ); - - // Initialize the inter-control state - if ( fExpression != null && fExpression.length() > 0 ) { - fExpressionInput.add( fExpression, 0 ); - fExpressionInput.select( 0 ); - } - fExpressionInput.setFocus(); - if ( fHasMemorySpaceControls ) { - fMemorySpaceInput.setEnabled( fMemorySpaceEnableButton.getEnabled() ); - } - fRangeField.setEnabled( fRangeEnableButton.getEnabled() ); - updateUI(); - return parent; - } - - private void createExpressionControl(Composite parent ) { - - Label l = new Label( parent, GridData.FILL_HORIZONTAL ); - l.setText( ActionMessages.getString( "AddWatchpointDialog.1" ) ); //$NON-NLS-1$ - GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); - gridData.horizontalSpan = 2; - l.setLayoutData( gridData ); - - fExpressionInput = new Combo( parent, SWT.BORDER ); - gridData = new GridData( GridData.FILL_HORIZONTAL ); - gridData.horizontalSpan = 2; - fExpressionInput.setLayoutData( gridData ); - fExpressionInput.addModifyListener( this ); - for (String expression : sExpressionHistory) { - fExpressionInput.add( expression ); - } - } - - private void createMemorySpaceControl( Composite parent, boolean hasMemorySpaces ) { - fMemorySpaceEnableButton = new Button( parent, SWT.CHECK ); - GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); - gridData.horizontalSpan = 1; - fMemorySpaceEnableButton.setLayoutData( gridData ); - fMemorySpaceEnableButton.setText( ActionMessages.getString( "AddWatchpointDialog.5" ) ); //$NON-NLS-1$ - fMemorySpaceEnableButton.setSelection( false ); - fMemorySpaceEnableButton.addSelectionListener( this ); - - if ( hasMemorySpaces ) { - fMemorySpaceInput = new Combo( parent, SWT.BORDER | SWT.READ_ONLY ); - } else { - fMemorySpaceInput = new Combo( parent, SWT.BORDER ); - } - gridData = new GridData( GridData.FILL_HORIZONTAL ); - gridData.horizontalSpan = 1; - fMemorySpaceInput.setLayoutData( gridData ); - fMemorySpaceInput.addSelectionListener( this ); - if ( fMemManagement != null ) { - String [] memorySpaces = fMemManagement.getMemorySpaces(); - for ( int i = 0; i < memorySpaces.length; i++ ) { - fMemorySpaceInput.add( memorySpaces[i] ); - } - } - if ( fMemorySpace != null && fMemorySpace.length() > 0 ) { - int i = fMemorySpaceInput.indexOf( fMemorySpace ); - if ( i >= 0 ) { - fMemorySpaceInput.select( i ); - fMemorySpaceEnableButton.setSelection( true ); - } else { - fMemorySpaceInput.add( fMemorySpace ); - } - } - fMemorySpaceInput.addModifyListener( this ); - //234909 - for accessibility - fMemorySpaceInput.getAccessible().addAccessibleListener( - new AccessibleAdapter() { - @Override - public void getName(AccessibleEvent e) { - e.result = ActionMessages.getString( "AddWatchpointDialog.5" ); //$NON-NLS-1$ - } - - }); - } - - /** - * @param text - * @param c - * @return true if the concatenation of text + c results - * in a valid string representation of an integer - * @see verifyIntegerText() - */ - private static boolean verifyIntegerTextAddition( String text, char c ) { - - // pass through all control characters - if ( Character.isISOControl( c ) ) { - return true; - } - - // case-insensitive - c = Character.toLowerCase( c ); - text = text.toLowerCase(); - - // first character has to be 0-9 - if ( text.length() == 0 ) { - return Character.isDigit( c ); - } - - // second character must be x if preceded by a 0, otherwise 0-9 will do - if ( text.length() == 1 ) { - if ( text.equals( "0" ) ) { //$NON-NLS-1$ - return c == 'x'; - } - return Character.isDigit( c ); - } - - // all subsequent characters must be 0-9 or a-f if started with 0x - return Character.isDigit( c ) - || text.startsWith( "0x" ) && 'a' <= c && c <= 'f'; //$NON-NLS-1$ - } - - /** - * @param text integer string built up using verifyIntegerTextAddition() - * @return true if text represents a valid string representation of - * an integer - */ - private static boolean verifyIntegerText( String text ) { - if ( text.length() == 0 ) { - return false; - } - if ( text.length() == 1 ) { - return true; - } - if ( text.length() == 2 ) { - return !text.equals("0x"); //$NON-NLS-1$ - } - return true; - } - - private void createCountField( Composite parent ) { - fRangeEnableButton = new Button( parent, SWT.CHECK ); - GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); - gridData.horizontalSpan = 1; - fRangeEnableButton.setLayoutData( gridData ); - fRangeEnableButton.setText( ActionMessages.getString( "AddWatchpointDialog.6" ) ); //$NON-NLS-1$ - fRangeEnableButton.setSelection( fRangeInitialEnable && fRange.length() > 0 ); - fRangeEnableButton.addSelectionListener( this ); - - fRangeField = new Text( parent, SWT.BORDER ); - gridData = new GridData( GridData.FILL_HORIZONTAL ); - gridData.horizontalSpan = 1; - GC gc = new GC( fRangeField ); - FontMetrics fm = gc.getFontMetrics(); - gridData.minimumWidth = 8 * fm.getAverageCharWidth(); - fRangeField.setLayoutData( gridData ); - fRangeField.setText( fRange ); - fRangeField.addVerifyListener( new VerifyListener() { - @Override - public void verifyText( VerifyEvent e ) { - e.doit = verifyIntegerTextAddition( fRangeField.getText(), e.character ); - } - }); - fRangeField.addModifyListener( this ); - //234909 - for accessibility - fRangeField.getAccessible().addAccessibleListener( - new AccessibleAdapter() { - @Override - public void getName(AccessibleEvent e) { - e.result = ActionMessages.getString( "AddWatchpointDialog.6" ); //$NON-NLS-1$ - } - - }); - } - - private void createAccessWidgets( Composite parent ) { - GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); - gridData.horizontalSpan = 3; - - Group group = new Group( parent, SWT.NONE ); - group.setLayout( new GridLayout() ); - group.setLayoutData( gridData ); - group.setText( ActionMessages.getString( "AddWatchpointDialog.2" ) ); //$NON-NLS-1$ - fChkBtnWrite = new Button( group, SWT.CHECK ); - fChkBtnWrite.setText( ActionMessages.getString( "AddWatchpointDialog.3" ) ); //$NON-NLS-1$ - fChkBtnWrite.setSelection( true ); - fChkBtnWrite.addSelectionListener( this ); - fChkBtnRead = new Button( group, SWT.CHECK ); - fChkBtnRead.setText( ActionMessages.getString( "AddWatchpointDialog.4" ) ); //$NON-NLS-1$ - fChkBtnRead.setSelection( false ); - fChkBtnRead.addSelectionListener( this ); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell) - */ - @Override - protected void configureShell( Shell newShell ) { - super.configureShell( newShell ); - - // use the same title used by the platform dialog - newShell.setText( ActionMessages.getString( "AddWatchpointDialog.0" ) ); //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see org.eclipse.jface.dialogs.Dialog#okPressed() - */ - @Override - protected void okPressed() { - fExpression = fExpressionInput.getText().trim(); - if ( fExpression.length() > 0 ) { - addHistory( fExpression ); - } - if ( fHasMemorySpaceControls ) { - fMemorySpace = fMemorySpaceEnableButton.getSelection() ? fMemorySpaceInput.getText().trim() : ""; //$NON-NLS-1$ - } - fRange = fRangeEnableButton.getSelection() ? fRangeField.getText().trim() : "0"; //$NON-NLS-1$ - fRead = fChkBtnRead.getSelection(); - fWrite = fChkBtnWrite.getSelection(); - super.okPressed(); - } - - /* (non-Javadoc) - * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) - */ - @Override - public void modifyText( ModifyEvent e ) { - updateUI(); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.dialogs.TrayDialog#createButtonBar(org.eclipse.swt.widgets.Composite) - */ - @Override - protected Control createButtonBar( Composite parent ) { - return super.createButtonBar( parent ); - } - - public String getExpression() { - return fExpression; - } - - public String getMemorySpace() { - return fMemorySpace; - } - - private static void addHistory( String item ) { - if ( !sExpressionHistory.contains( item ) ) { - sExpressionHistory.add( 0, item ); - - if ( sExpressionHistory.size() > 5 ) - sExpressionHistory.remove( sExpressionHistory.size() - 1 ); - } - } - - /* (non-Javadoc) - * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent) - */ - @Override - public void widgetDefaultSelected( SelectionEvent e ) { - // ignore - } - - /* (non-Javadoc) - * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent) - */ - @Override - public void widgetSelected( SelectionEvent e ) { - updateUI(); - } - - private void updateUI() { - if ( fHasMemorySpaceControls ) { - fMemorySpaceInput.setEnabled( fMemorySpaceEnableButton.getSelection() ); - } - fRangeField.setEnabled( fRangeEnableButton.getSelection() ); - Button b = getButton( IDialogConstants.OK_ID ); - if ( b == null ) { - return; - } - b.setEnabled( okayEnabled() ); - } - - private boolean okayEnabled() { - if ( !fChkBtnRead.getSelection() && !fChkBtnWrite.getSelection() ) { - return false ; - } - if ( fExpressionInput.getText().length() == 0 ) { - return false; - } - if ( fHasMemorySpaceControls && fMemorySpaceInput.getEnabled() && fMemorySpaceInput.getText().length() == 0 ) { - return false; - } - if ( fRangeField.getEnabled() - && ( fRangeField.getText().length() == 0 || !verifyIntegerText( fRangeField.getText() ) ) ) { - return false; - } - return true; - } - - public boolean getWriteAccess() { - return fWrite; - } - - public boolean getReadAccess() { - return fRead; - } - - public void setExpression(String expressionString ) { - fExpression = expressionString; - } - - public BigInteger getRange() { - return BigInteger.valueOf( Long.decode(fRange).longValue() ); - } - - public void initializeRange( boolean enable, String range ) { - fRangeInitialEnable = enable; - fRange = range; - } - - public void initializeMemorySpace( String memorySpace ) { - fMemorySpace = memorySpace; - } - - @Override - protected void createButtonsForButtonBar(Composite parent) { - // override so we can change the initial okay enabled state - createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, - true ).setEnabled( okayEnabled() ); - createButton( parent, IDialogConstants.CANCEL_ID, - IDialogConstants.CANCEL_LABEL, false ); - } +public class AddWatchpointDialog extends org.eclipse.cdt.debug.internal.ui.actions.breakpoints.AddWatchpointDialog { + public AddWatchpointDialog( Shell parentShell, ICDIMemorySpaceManagement memMgmt ) { + super(parentShell, memMgmt); + } + } diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/BreakpointLocationVerifier.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/BreakpointLocationVerifier.java deleted file mode 100644 index d51adf334fc..00000000000 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/BreakpointLocationVerifier.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2006 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; - -import org.eclipse.jface.text.IDocument; - -/** - * - * Enter type comment. - * - * @since Aug 29, 2002 - */ -public class BreakpointLocationVerifier -{ - /** - * Returns the line number closest to the given line number that represents a - * valid location for a breakpoint in the given document, or -1 if a valid location - * cannot be found. - */ - public int getValidLineBreakpointLocation( IDocument doc, int lineNumber ) - { - // for now - return lineNumber + 1; - } - - public int getValidAddressBreakpointLocation( IDocument doc, int lineNumber ) - { - // for now - return lineNumber + 1; - } -} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/CBreakpointPropertiesRulerAction.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/CBreakpointPropertiesRulerAction.java deleted file mode 100644 index 1a82827cb9f..00000000000 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/CBreakpointPropertiesRulerAction.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2008 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - Initial API and implementation - * Anton Leherbauer (Wind River Systems) - bug 183397 - *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; - -import org.eclipse.cdt.debug.core.model.ICBreakpoint; -import org.eclipse.cdt.debug.internal.ui.CBreakpointContext; -import org.eclipse.cdt.debug.internal.ui.ICDebugHelpContextIds; -import org.eclipse.cdt.debug.internal.ui.IInternalCDebugUIConstants; -import org.eclipse.debug.core.model.IBreakpoint; -import org.eclipse.debug.ui.DebugUITools; -import org.eclipse.jface.text.source.IVerticalRulerInfo; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.dialogs.PropertyDialogAction; - -/** - * Opens a custom properties dialog to configure the attibutes of a C/C++ breakpoint - * from the ruler popup menu. - */ -public class CBreakpointPropertiesRulerAction extends AbstractBreakpointRulerAction { - - private Object fContext; - - /** - * Creates the action to modify the breakpoint properties. - */ - public CBreakpointPropertiesRulerAction( IWorkbenchPart part, IVerticalRulerInfo info ) { - super( part, info ); - setText( ActionMessages.getString( "CBreakpointPropertiesRulerAction.Breakpoint_Properties" ) ); //$NON-NLS-1$ - part.getSite().getWorkbenchWindow().getWorkbench().getHelpSystem().setHelp( this, ICDebugHelpContextIds.BREAKPOINT_PROPERTIES_ACTION ); - setId( IInternalCDebugUIConstants.ACTION_BREAKPOINT_PROPERTIES ); - } - - /* (non-Javadoc) - * @see Action#run() - */ - @Override - public void run() { - if ( fContext != null ) { - PropertyDialogAction action = new PropertyDialogAction( getTargetPart().getSite(), new ISelectionProvider() { - - @Override - public void addSelectionChangedListener( ISelectionChangedListener listener ) { - } - - @Override - public ISelection getSelection() { - return new StructuredSelection( fContext ); - } - - @Override - public void removeSelectionChangedListener( ISelectionChangedListener listener ) { - } - - @Override - public void setSelection( ISelection selection ) { - } - } ); - action.run(); - action.dispose(); - } - } - - /* (non-Javadoc) - * @see IUpdate#update() - */ - @Override - public void update() { - IBreakpoint breakpoint = getBreakpoint(); - if (breakpoint instanceof ICBreakpoint) { - fContext = new CBreakpointContext((ICBreakpoint)breakpoint, getDebugContext()); - } else { - fContext = breakpoint; - } - setEnabled( fContext != null ); - } - - private ISelection getDebugContext() { - return DebugUITools.getDebugContextManager().getContextService(getTargetPart().getSite().getWorkbenchWindow()).getActiveContext(); - } -} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/EnableDisableBreakpointRulerActionDelegate.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/EnableDisableBreakpointRulerActionDelegate.java deleted file mode 100644 index de3df78eb7d..00000000000 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/EnableDisableBreakpointRulerActionDelegate.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2006 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.text.source.IVerticalRulerInfo; -import org.eclipse.ui.texteditor.AbstractRulerActionDelegate; -import org.eclipse.ui.texteditor.ITextEditor; - -public class EnableDisableBreakpointRulerActionDelegate extends AbstractRulerActionDelegate { - - /* - * @see AbstractRulerActionDelegate#createAction(ITextEditor, IVerticalRulerInfo) - */ - @Override - protected IAction createAction( ITextEditor editor, IVerticalRulerInfo rulerInfo ) { - return new EnableDisableBreakpointRulerAction( editor, rulerInfo ); - } -} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleBreakpointAdapter.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleBreakpointAdapter.java deleted file mode 100644 index 3212ffcb7f3..00000000000 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleBreakpointAdapter.java +++ /dev/null @@ -1,132 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2010 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - Initial API and implementation - * Freescale Semiconductor - Address watchpoints, https://bugs.eclipse.org/bugs/show_bug.cgi?id=118299 - * Warren Paul (Nokia) - Bug 217485, Bug 218342 - * Oyvind Harboe (oyvind.harboe@zylin.com) - Bug 225099 - *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; - -import java.math.BigInteger; - -import org.eclipse.cdt.debug.core.CDIDebugModel; -import org.eclipse.cdt.debug.core.model.ICBreakpointType; -import org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint; -import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; -import org.eclipse.cdt.debug.core.model.ICWatchpoint; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; - -/** - * Toggles a line breakpoint in a C/C++ editor. - */ -public class ToggleBreakpointAdapter extends AbstractToggleBreakpointAdapter { - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.internal.ui.actions.AbstractToggleBreakpointAdapter#findLineBreakpoint(java.lang.String, org.eclipse.core.resources.IResource, int) - */ - @Override - protected ICLineBreakpoint findLineBreakpoint( String sourceHandle, IResource resource, int lineNumber ) throws CoreException { - return CDIDebugModel.lineBreakpointExists( sourceHandle, resource, lineNumber ); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.internal.ui.actions.AbstractToggleBreakpointAdapter#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, - "", //$NON-NLS-1$ - true ); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.internal.ui.actions.AbstractToggleBreakpointAdapter#findFunctionBreakpoint(java.lang.String, org.eclipse.core.resources.IResource, java.lang.String) - */ - @Override - protected ICFunctionBreakpoint findFunctionBreakpoint( - String sourceHandle, - IResource resource, - String functionName ) throws CoreException { - return CDIDebugModel.functionBreakpointExists( sourceHandle, resource, functionName ); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.internal.ui.actions.AbstractToggleBreakpointAdapter#createFunctionBreakpoint(java.lang.String, org.eclipse.core.resources.IResource, java.lang.String, int, int, int) - */ - @Override - protected void createFunctionBreakpoint( - String sourceHandle, - IResource resource, - String functionName, - int charStart, - int charEnd, - int lineNumber ) throws CoreException { - CDIDebugModel.createFunctionBreakpoint( sourceHandle, - resource, - getBreakpointType(), - functionName, - charStart, - charEnd, - lineNumber, - true, - 0, - "", //$NON-NLS-1$ - true ); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.internal.ui.actions.AbstractToggleBreakpointAdapter#findWatchpoint(java.lang.String, org.eclipse.core.resources.IResource, java.lang.String) - */ - @Override - protected ICWatchpoint findWatchpoint( String sourceHandle, IResource resource, String expression ) throws CoreException { - return CDIDebugModel.watchpointExists( sourceHandle, resource, expression ); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.internal.ui.actions.AbstractToggleBreakpointAdapter#createWatchpoint(java.lang.String, org.eclipse.core.resources.IResource, int, int, int, boolean, boolean, java.lang.String, java.lang.String, java.math.BigInteger) - */ - @Override - protected void createWatchpoint( - String sourceHandle, - IResource resource, - int charStart, - int charEnd, - int lineNumber, - boolean writeAccess, - boolean readAccess, - String expression, - String memorySpace, - BigInteger range ) throws CoreException { - - CDIDebugModel.createWatchpoint( sourceHandle, - resource, - charStart, - charEnd, - lineNumber, - writeAccess, - readAccess, - expression, - memorySpace, - range, - true, - 0, - "", //$NON-NLS-1$ - true ); - } - - protected int getBreakpointType() { - return ICBreakpointType.REGULAR; - } -} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleShowColumnsAction.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleShowColumnsAction.java deleted file mode 100644 index b0b57142df3..00000000000 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleShowColumnsAction.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; - -import org.eclipse.cdt.debug.internal.ui.CDebugImages; -import org.eclipse.cdt.debug.internal.ui.ICDebugHelpContextIds; -import org.eclipse.cdt.debug.ui.CDebugUIPlugin; -import org.eclipse.debug.internal.ui.viewers.model.provisional.TreeModelViewer; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IAction; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.texteditor.IUpdate; - -/** - * Action to toggle the use of contributed variables content providers on and off. - * When on, all registered variables content providers for the current debug model - * are used. When off, the default content provider (that shows all children) - * is used for all debug models. - */ -public class ToggleShowColumnsAction extends Action implements IUpdate { - - private TreeModelViewer fViewer; - - public ToggleShowColumnsAction( TreeModelViewer viewew ) { - super( "&Show Columns", IAction.AS_CHECK_BOX ); - fViewer = viewew; - setToolTipText( "Show Columns" ); - setImageDescriptor( CDebugImages.DESC_OBJS_COMMON_TAB ); - setId( CDebugUIPlugin.getUniqueIdentifier() + ".ToggleShowColumsAction" ); //$NON-NLS-1$ - PlatformUI.getWorkbench().getHelpSystem().setHelp( this, ICDebugHelpContextIds.SHOW_COLUMNS_ACTION ); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.action.Action#run() - */ - @Override - public void run() { - if ( fViewer.getControl().isDisposed() ) { - return; - } - BusyIndicator.showWhile( fViewer.getControl().getDisplay(), new Runnable() { - @Override - public void run() { - fViewer.setShowColumns( isChecked() ); - } - } ); - } - - /* (non-Javadoc) - * @see org.eclipse.ui.texteditor.IUpdate#update() - */ - @Override - public void update() { - setEnabled( fViewer.canToggleColumns() ); - setChecked( fViewer.isShowColumns() ); - } -} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleTracepointAdapter.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleTracepointAdapter.java deleted file mode 100644 index b7c07a60377..00000000000 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleTracepointAdapter.java +++ /dev/null @@ -1,115 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Ericsson and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Ericsson - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; - -import java.math.BigInteger; - -import org.eclipse.cdt.debug.core.CDIDebugModel; -import org.eclipse.cdt.debug.core.model.ICBreakpointType; -import org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint; -import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; -import org.eclipse.cdt.debug.core.model.ICWatchpoint; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; - -/** - * Toggles a tracepoint in a C/C++ editor. - */ -public class ToggleTracepointAdapter extends AbstractToggleBreakpointAdapter { - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.internal.ui.actions.AbstractToggleBreakpointAdapter#findLineBreakpoint(java.lang.String, org.eclipse.core.resources.IResource, int) - */ - @Override - protected ICLineBreakpoint findLineBreakpoint( String sourceHandle, IResource resource, int lineNumber ) throws CoreException { - return CDIDebugModel.lineBreakpointExists( sourceHandle, resource, lineNumber ); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.internal.ui.actions.AbstractToggleBreakpointAdapter#createLineBreakpoint(java.lang.String, org.eclipse.core.resources.IResource, int) - */ - @Override - protected void createLineBreakpoint( String sourceHandle, IResource resource, int lineNumber ) throws CoreException { - - CDIDebugModel.createLineTracepoint( - sourceHandle, - resource, - getBreakpointType(), - lineNumber, - true, - 0, - "", //$NON-NLS-1$ - true ); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.internal.ui.actions.AbstractToggleBreakpointAdapter#findFunctionBreakpoint(java.lang.String, org.eclipse.core.resources.IResource, java.lang.String) - */ - @Override - protected ICFunctionBreakpoint findFunctionBreakpoint( String sourceHandle, IResource resource, String functionName ) throws CoreException { - return CDIDebugModel.functionBreakpointExists( sourceHandle, resource, functionName ); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.internal.ui.actions.AbstractToggleBreakpointAdapter#createFunctionBreakpoint(java.lang.String, org.eclipse.core.resources.IResource, java.lang.String, int, int, int) - */ - @Override - protected void createFunctionBreakpoint( - String sourceHandle, - IResource resource, - String functionName, - int charStart, - int charEnd, - int lineNumber ) throws CoreException { - - CDIDebugModel.createFunctionTracepoint( - sourceHandle, - resource, - getBreakpointType(), - functionName, - charStart, - charEnd, - lineNumber, - true, - 0, - "", //$NON-NLS-1$ - true ); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.internal.ui.actions.AbstractToggleBreakpointAdapter#findWatchpoint(java.lang.String, org.eclipse.core.resources.IResource, java.lang.String) - */ - @Override - protected ICWatchpoint findWatchpoint( String sourceHandle, IResource resource, String expression ) throws CoreException { - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.debug.internal.ui.actions.AbstractToggleBreakpointAdapter#createWatchpoint(java.lang.String, org.eclipse.core.resources.IResource, int, int, int, boolean, boolean, java.lang.String, java.lang.String, java.math.BigInteger) - */ - @Override - protected void createWatchpoint( - String sourceHandle, - IResource resource, - int charStart, - int charEnd, - int lineNumber, - boolean writeAccess, - boolean readAccess, - String expression, - String memorySpace, - BigInteger range ) throws CoreException { - } - - protected int getBreakpointType() { - return ICBreakpointType.REGULAR; - } -} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/WatchpointExpressionVerifier.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/WatchpointExpressionVerifier.java deleted file mode 100644 index 5335df117bf..00000000000 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/WatchpointExpressionVerifier.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2006 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; - -import org.eclipse.jface.text.IDocument; - -/** - * - * Enter type comment. - * - * @since Sep 5, 2002 - */ -public class WatchpointExpressionVerifier -{ - /** - * Returns whether the specified expression is valid for a watchpoint. - */ - public boolean isValidExpression( IDocument doc, String expression ) - { - // for now - return expression.trim().length() > 0; - } -} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AbstractBreakpointRulerAction.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AbstractBreakpointRulerAction.java similarity index 50% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AbstractBreakpointRulerAction.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AbstractBreakpointRulerAction.java index 1578a3eb803..6402f536567 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AbstractBreakpointRulerAction.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AbstractBreakpointRulerAction.java @@ -9,27 +9,17 @@ * QNX Software Systems - Initial API and implementation * Anton Leherbauer (Wind River Systems) - bug 183397 *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; -import java.util.Iterator; - -import org.eclipse.core.resources.IMarker; +import org.eclipse.cdt.debug.internal.ui.CDebugUIUtils; import org.eclipse.core.runtime.Assert; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.ui.actions.RulerBreakpointAction; import org.eclipse.jface.action.Action; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IVerticalRulerInfo; import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.IUpdate; -import org.eclipse.ui.texteditor.SimpleMarkerAnnotation; /** * Abstract base implementation of the breakpoint ruler actions. @@ -61,33 +51,11 @@ public abstract class AbstractBreakpointRulerAction extends Action implements IU * @return breakpoint associated with activity in the ruler or null */ protected IBreakpoint getBreakpoint() { - IAnnotationModel annotationModel = getAnnotationModel(); - IDocument document = getDocument(); - if (annotationModel != null) { - Iterator iterator = annotationModel.getAnnotationIterator(); - while (iterator.hasNext()) { - Object object = iterator.next(); - 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 line = document.getLineOfOffset(position.getOffset()); - if (line == fRulerInfo.getLineOfLastMouseButtonActivity()) { - IBreakpoint breakpoint = DebugPlugin.getDefault().getBreakpointManager().getBreakpoint(marker); - if (breakpoint != null) { - return breakpoint; - } - } - } - } catch (CoreException e) { - } catch (BadLocationException e) { - } - } - } - } - return null; + IWorkbenchPart targetPart = getTargetPart(); + if (targetPart instanceof ITextEditor) { + return CDebugUIUtils.getBreakpointFromEditor((ITextEditor)targetPart, getVerticalRulerInfo()); + } + return null; } /** @@ -108,25 +76,4 @@ public abstract class AbstractBreakpointRulerAction extends Action implements IU return fRulerInfo; } - private IDocument getDocument() { - IWorkbenchPart targetPart = getTargetPart(); - if ( targetPart instanceof ITextEditor ) { - ITextEditor textEditor = (ITextEditor)targetPart; - IDocumentProvider provider = textEditor.getDocumentProvider(); - if ( provider != null ) - return provider.getDocument( textEditor.getEditorInput() ); - } - return null; - } - - private IAnnotationModel getAnnotationModel() { - IWorkbenchPart targetPart = getTargetPart(); - if ( targetPart instanceof ITextEditor ) { - ITextEditor textEditor = (ITextEditor)targetPart; - IDocumentProvider provider = textEditor.getDocumentProvider(); - if ( provider != null ) - return provider.getAnnotationModel( textEditor.getEditorInput() ); - } - return null; - } } diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddEventBreakpointActionDelegate.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddEventBreakpointActionDelegate.java similarity index 95% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddEventBreakpointActionDelegate.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddEventBreakpointActionDelegate.java index c4637bfbfe5..b959f77ebfe 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddEventBreakpointActionDelegate.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddEventBreakpointActionDelegate.java @@ -10,9 +10,10 @@ * QNX Software Systems - Initial API and implementation * QNX Software Systems - catchpoints - bug 226689 *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; import org.eclipse.cdt.debug.core.CDIDebugModel; +import org.eclipse.cdt.debug.internal.ui.actions.ActionMessages; import org.eclipse.cdt.debug.internal.ui.dialogs.AddEventBreakpointDialog; import org.eclipse.cdt.debug.ui.CDebugUIPlugin; import org.eclipse.cdt.debug.ui.UIMessages; diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddFunctionBreakpointActionDelegate.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddFunctionBreakpointActionDelegate.java new file mode 100644 index 00000000000..b6b50b235b7 --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddFunctionBreakpointActionDelegate.java @@ -0,0 +1,75 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007-7 QNX Software Systems and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * QNX Software Systems - Initial API and implementation + * Freescale Semiconductor - Address watchpoints, https://bugs.eclipse.org/bugs/show_bug.cgi?id=118299 +*******************************************************************************/ +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; + +import org.eclipse.cdt.debug.internal.ui.actions.ActionMessages; +import org.eclipse.cdt.debug.ui.CDebugUIPlugin; +import org.eclipse.cdt.debug.ui.breakpoints.IToggleBreakpointsTargetCExtension; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.ui.IViewActionDelegate; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.actions.ActionDelegate; + +/** + * A delegate for the "Add Function Breakpoint" action. + */ +public class AddFunctionBreakpointActionDelegate extends ActionDelegate implements IViewActionDelegate { + + private IViewPart fView; + private ISelection fSelection; + private ToggleBreakpointAdapter fDefaultToggleTarget = new ToggleBreakpointAdapter(); + + /* (non-Javadoc) + * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart) + */ + @Override + public void init( IViewPart view ) { + setView( view ); + } + + private void setView(IViewPart view) { + fView = view; + } + + protected IViewPart getView() { + return fView; + } + + @Override + public void selectionChanged(IAction action, ISelection selection) { + fSelection = selection; + } + + /* (non-Javadoc) + * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) + */ + @Override + public void run( IAction action ) { + IToggleBreakpointsTarget toggleTarget = DebugUITools.getToggleBreakpointsTargetManager().getToggleBreakpointsTarget(fView, fSelection); + IToggleBreakpointsTargetCExtension cToggleTarget = null; + if (toggleTarget instanceof IToggleBreakpointsTargetCExtension) { + cToggleTarget = (IToggleBreakpointsTargetCExtension)toggleTarget; + } else { + cToggleTarget = fDefaultToggleTarget; + } + + try { + cToggleTarget.createFunctionBreakpointInteractive(fView, fSelection); + } catch (CoreException e) { + CDebugUIPlugin.errorDialog( ActionMessages.getString( "AddWatchpointActionDelegate1.0" ), e ); //$NON-NLS-1$ + } + } +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddWatchpointActionDelegate.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddWatchpointActionDelegate.java similarity index 70% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddWatchpointActionDelegate.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddWatchpointActionDelegate.java index 2cdfb1f1aa7..9fab7944647 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddWatchpointActionDelegate.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddWatchpointActionDelegate.java @@ -9,7 +9,7 @@ * QNX Software Systems - Initial API and implementation * Freescale Semiconductor - Address watchpoints, https://bugs.eclipse.org/bugs/show_bug.cgi?id=118299 *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; import java.math.BigInteger; @@ -17,14 +17,17 @@ import org.eclipse.cdt.debug.core.CDIDebugModel; import org.eclipse.cdt.debug.core.cdi.model.ICDIMemorySpaceManagement; import org.eclipse.cdt.debug.core.cdi.model.ICDITarget; import org.eclipse.cdt.debug.core.model.ICDebugTarget; +import org.eclipse.cdt.debug.internal.ui.actions.ActionMessages; import org.eclipse.cdt.debug.ui.CDebugUIPlugin; +import org.eclipse.cdt.debug.ui.breakpoints.IToggleBreakpointsTargetCExtension; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget; import org.eclipse.jface.action.IAction; -import org.eclipse.jface.window.Window; +import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; import org.eclipse.ui.actions.ActionDelegate; @@ -35,7 +38,9 @@ import org.eclipse.ui.actions.ActionDelegate; public class AddWatchpointActionDelegate extends ActionDelegate implements IViewActionDelegate { private IViewPart fView; - + private ISelection fSelection; + private ToggleBreakpointAdapter fDefaultToggleTarget = new ToggleBreakpointAdapter(); + /* (non-Javadoc) * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart) */ @@ -52,15 +57,29 @@ public class AddWatchpointActionDelegate extends ActionDelegate implements IView return fView; } + @Override + public void selectionChanged(IAction action, ISelection selection) { + fSelection = selection; + } + /* (non-Javadoc) * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */ @Override public void run( IAction action ) { - AddWatchpointDialog dlg = new AddWatchpointDialog( CDebugUIPlugin.getActiveWorkbenchShell(), getMemorySpaceManagement() ); - if ( dlg.open() == Window.OK ) { - addWatchpoint( dlg.getWriteAccess(), dlg.getReadAccess(), dlg.getExpression(), dlg.getMemorySpace(), dlg.getRange() ); - } + IToggleBreakpointsTarget toggleTarget = DebugUITools.getToggleBreakpointsTargetManager().getToggleBreakpointsTarget(fView, fSelection); + IToggleBreakpointsTargetCExtension cToggleTarget = null; + if (toggleTarget instanceof IToggleBreakpointsTargetCExtension) { + cToggleTarget = (IToggleBreakpointsTargetCExtension)toggleTarget; + } else { + cToggleTarget = fDefaultToggleTarget; + } + + try { + cToggleTarget.createWatchpointsInteractive(fView, fSelection); + } catch (CoreException e) { + CDebugUIPlugin.errorDialog( ActionMessages.getString( "AddWatchpointActionDelegate1.0" ), e ); //$NON-NLS-1$ + } } protected void addWatchpoint(boolean write, boolean read, String expression, String memorySpace, BigInteger range) { @@ -82,7 +101,7 @@ public class AddWatchpointActionDelegate extends ActionDelegate implements IView return ""; //$NON-NLS-1$ } - static ICDIMemorySpaceManagement getMemorySpaceManagement(){ + public static ICDIMemorySpaceManagement getMemorySpaceManagement(){ IAdaptable debugViewElement = DebugUITools.getDebugContext(); ICDIMemorySpaceManagement memMgr = null; diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddWatchpointDialog.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddWatchpointDialog.java new file mode 100644 index 00000000000..8144e4d4cd4 --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddWatchpointDialog.java @@ -0,0 +1,439 @@ +/******************************************************************************* + * Copyright (c) 2004, 2008, 2008 QNX Software Systems and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * QNX Software Systems - Initial API and implementation + * Freescale Semiconductor - Address watchpoints, https://bugs.eclipse.org/bugs/show_bug.cgi?id=118299 + * IBM Corporation + *******************************************************************************/ +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.cdt.debug.core.cdi.model.ICDIMemorySpaceManagement; +import org.eclipse.cdt.debug.internal.ui.actions.ActionMessages; +import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.swt.SWT; +import org.eclipse.swt.accessibility.AccessibleAdapter; +import org.eclipse.swt.accessibility.AccessibleEvent; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.events.VerifyEvent; +import org.eclipse.swt.events.VerifyListener; +import org.eclipse.swt.graphics.FontMetrics; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + +/** + * The "Add Watchpoint" dialog of the "Toggle watchpoint" action. + * @deprecated Replaced by opening a properties dialog on a new breakpoint. + */ +public class AddWatchpointDialog extends Dialog implements ModifyListener, SelectionListener { + + private Combo fExpressionInput; + private String fExpression; + private static List sExpressionHistory = new ArrayList(); + + private boolean fHasMemorySpaceControls; + private Button fMemorySpaceEnableButton; + private Combo fMemorySpaceInput; + private String fMemorySpace; + + private boolean fRangeInitialEnable; + private Button fRangeEnableButton; + private Text fRangeField; + private String fRange = ""; //$NON-NLS-1$ + + private Button fChkBtnWrite; + private Button fChkBtnRead; + private boolean fRead; + private boolean fWrite; + + private ICDIMemorySpaceManagement fMemManagement; + + + /** + * Constructor for AddWatchpointDialog. + * + * @param parentShell + */ + public AddWatchpointDialog( Shell parentShell, ICDIMemorySpaceManagement memMgmt ) { + super( parentShell ); + setShellStyle( getShellStyle() | SWT.RESIZE ); + fMemManagement = memMgmt; + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) + */ + @Override + protected Control createDialogArea( Composite parent ) { + // The button bar will work better if we make the parent composite + // a single column grid layout. For the widgets we add, we want a + // a two-column grid, so we just create a sub composite for that. + GridLayout gridLayout = new GridLayout(); + parent.setLayout( gridLayout ); + GridData gridData = new GridData( GridData.FILL_BOTH ); + parent.setLayoutData( gridData ); + Composite composite = new Composite( parent, SWT.None ); + gridLayout = new GridLayout(); + gridLayout.numColumns = 2; + composite.setLayout( gridLayout ); + parent = composite; + + // Create the controls + createExpressionControl( parent ); + boolean hasDebugContext = DebugUITools.getDebugContext() != null; + boolean hasMemorySpaces = hasDebugContext && fMemManagement != null && fMemManagement.getMemorySpaces() != null && fMemManagement.getMemorySpaces().length > 0; + fHasMemorySpaceControls = !hasDebugContext || hasMemorySpaces; + if ( fHasMemorySpaceControls ) { + createMemorySpaceControl( parent, hasMemorySpaces ); + } + createCountField( parent ); + createAccessWidgets( parent ); + + // Initialize the inter-control state + if ( fExpression != null && fExpression.length() > 0 ) { + fExpressionInput.add( fExpression, 0 ); + fExpressionInput.select( 0 ); + } + fExpressionInput.setFocus(); + if ( fHasMemorySpaceControls ) { + fMemorySpaceInput.setEnabled( fMemorySpaceEnableButton.getEnabled() ); + } + fRangeField.setEnabled( fRangeEnableButton.getEnabled() ); + updateUI(); + return parent; + } + + private void createExpressionControl(Composite parent ) { + + Label l = new Label( parent, GridData.FILL_HORIZONTAL ); + l.setText( ActionMessages.getString( "AddWatchpointDialog.1" ) ); //$NON-NLS-1$ + GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); + gridData.horizontalSpan = 2; + l.setLayoutData( gridData ); + + fExpressionInput = new Combo( parent, SWT.BORDER ); + gridData = new GridData( GridData.FILL_HORIZONTAL ); + gridData.horizontalSpan = 2; + fExpressionInput.setLayoutData( gridData ); + fExpressionInput.addModifyListener( this ); + for (String expression : sExpressionHistory) { + fExpressionInput.add( expression ); + } + } + + private void createMemorySpaceControl( Composite parent, boolean hasMemorySpaces ) { + fMemorySpaceEnableButton = new Button( parent, SWT.CHECK ); + GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); + gridData.horizontalSpan = 1; + fMemorySpaceEnableButton.setLayoutData( gridData ); + fMemorySpaceEnableButton.setText( ActionMessages.getString( "AddWatchpointDialog.5" ) ); //$NON-NLS-1$ + fMemorySpaceEnableButton.setSelection( false ); + fMemorySpaceEnableButton.addSelectionListener( this ); + + if ( hasMemorySpaces ) { + fMemorySpaceInput = new Combo( parent, SWT.BORDER | SWT.READ_ONLY ); + } else { + fMemorySpaceInput = new Combo( parent, SWT.BORDER ); + } + gridData = new GridData( GridData.FILL_HORIZONTAL ); + gridData.horizontalSpan = 1; + fMemorySpaceInput.setLayoutData( gridData ); + fMemorySpaceInput.addSelectionListener( this ); + if ( fMemManagement != null ) { + String [] memorySpaces = fMemManagement.getMemorySpaces(); + for ( int i = 0; i < memorySpaces.length; i++ ) { + fMemorySpaceInput.add( memorySpaces[i] ); + } + } + if ( fMemorySpace != null && fMemorySpace.length() > 0 ) { + int i = fMemorySpaceInput.indexOf( fMemorySpace ); + if ( i >= 0 ) { + fMemorySpaceInput.select( i ); + fMemorySpaceEnableButton.setSelection( true ); + } else { + fMemorySpaceInput.add( fMemorySpace ); + } + } + fMemorySpaceInput.addModifyListener( this ); + //234909 - for accessibility + fMemorySpaceInput.getAccessible().addAccessibleListener( + new AccessibleAdapter() { + @Override + public void getName(AccessibleEvent e) { + e.result = ActionMessages.getString( "AddWatchpointDialog.5" ); //$NON-NLS-1$ + } + + }); + } + + /** + * @param text + * @param c + * @return true if the concatenation of text + c results + * in a valid string representation of an integer + * @see verifyIntegerText() + */ + private static boolean verifyIntegerTextAddition( String text, char c ) { + + // pass through all control characters + if ( Character.isISOControl( c ) ) { + return true; + } + + // case-insensitive + c = Character.toLowerCase( c ); + text = text.toLowerCase(); + + // first character has to be 0-9 + if ( text.length() == 0 ) { + return Character.isDigit( c ); + } + + // second character must be x if preceded by a 0, otherwise 0-9 will do + if ( text.length() == 1 ) { + if ( text.equals( "0" ) ) { //$NON-NLS-1$ + return c == 'x'; + } + return Character.isDigit( c ); + } + + // all subsequent characters must be 0-9 or a-f if started with 0x + return Character.isDigit( c ) + || text.startsWith( "0x" ) && 'a' <= c && c <= 'f'; //$NON-NLS-1$ + } + + /** + * @param text integer string built up using verifyIntegerTextAddition() + * @return true if text represents a valid string representation of + * an integer + */ + private static boolean verifyIntegerText( String text ) { + if ( text.length() == 0 ) { + return false; + } + if ( text.length() == 1 ) { + return true; + } + if ( text.length() == 2 ) { + return !text.equals("0x"); //$NON-NLS-1$ + } + return true; + } + + private void createCountField( Composite parent ) { + fRangeEnableButton = new Button( parent, SWT.CHECK ); + GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); + gridData.horizontalSpan = 1; + fRangeEnableButton.setLayoutData( gridData ); + fRangeEnableButton.setText( ActionMessages.getString( "AddWatchpointDialog.6" ) ); //$NON-NLS-1$ + fRangeEnableButton.setSelection( fRangeInitialEnable && fRange.length() > 0 ); + fRangeEnableButton.addSelectionListener( this ); + + fRangeField = new Text( parent, SWT.BORDER ); + gridData = new GridData( GridData.FILL_HORIZONTAL ); + gridData.horizontalSpan = 1; + GC gc = new GC( fRangeField ); + FontMetrics fm = gc.getFontMetrics(); + gridData.minimumWidth = 8 * fm.getAverageCharWidth(); + fRangeField.setLayoutData( gridData ); + fRangeField.setText( fRange ); + fRangeField.addVerifyListener( new VerifyListener() { + @Override + public void verifyText( VerifyEvent e ) { + e.doit = verifyIntegerTextAddition( fRangeField.getText(), e.character ); + } + }); + fRangeField.addModifyListener( this ); + //234909 - for accessibility + fRangeField.getAccessible().addAccessibleListener( + new AccessibleAdapter() { + @Override + public void getName(AccessibleEvent e) { + e.result = ActionMessages.getString( "AddWatchpointDialog.6" ); //$NON-NLS-1$ + } + + }); + } + + private void createAccessWidgets( Composite parent ) { + GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); + gridData.horizontalSpan = 3; + + Group group = new Group( parent, SWT.NONE ); + group.setLayout( new GridLayout() ); + group.setLayoutData( gridData ); + group.setText( ActionMessages.getString( "AddWatchpointDialog.2" ) ); //$NON-NLS-1$ + fChkBtnWrite = new Button( group, SWT.CHECK ); + fChkBtnWrite.setText( ActionMessages.getString( "AddWatchpointDialog.3" ) ); //$NON-NLS-1$ + fChkBtnWrite.setSelection( true ); + fChkBtnWrite.addSelectionListener( this ); + fChkBtnRead = new Button( group, SWT.CHECK ); + fChkBtnRead.setText( ActionMessages.getString( "AddWatchpointDialog.4" ) ); //$NON-NLS-1$ + fChkBtnRead.setSelection( false ); + fChkBtnRead.addSelectionListener( this ); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell) + */ + @Override + protected void configureShell( Shell newShell ) { + super.configureShell( newShell ); + + // use the same title used by the platform dialog + newShell.setText( ActionMessages.getString( "AddWatchpointDialog.0" ) ); //$NON-NLS-1$ + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.Dialog#okPressed() + */ + @Override + protected void okPressed() { + fExpression = fExpressionInput.getText().trim(); + if ( fExpression.length() > 0 ) { + addHistory( fExpression ); + } + if ( fHasMemorySpaceControls ) { + fMemorySpace = fMemorySpaceEnableButton.getSelection() ? fMemorySpaceInput.getText().trim() : ""; //$NON-NLS-1$ + } + fRange = fRangeEnableButton.getSelection() ? fRangeField.getText().trim() : "0"; //$NON-NLS-1$ + fRead = fChkBtnRead.getSelection(); + fWrite = fChkBtnWrite.getSelection(); + super.okPressed(); + } + + /* (non-Javadoc) + * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) + */ + @Override + public void modifyText( ModifyEvent e ) { + updateUI(); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.TrayDialog#createButtonBar(org.eclipse.swt.widgets.Composite) + */ + @Override + protected Control createButtonBar( Composite parent ) { + return super.createButtonBar( parent ); + } + + public String getExpression() { + return fExpression; + } + + public String getMemorySpace() { + return fMemorySpace; + } + + private static void addHistory( String item ) { + if ( !sExpressionHistory.contains( item ) ) { + sExpressionHistory.add( 0, item ); + + if ( sExpressionHistory.size() > 5 ) + sExpressionHistory.remove( sExpressionHistory.size() - 1 ); + } + } + + /* (non-Javadoc) + * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetDefaultSelected( SelectionEvent e ) { + // ignore + } + + /* (non-Javadoc) + * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected( SelectionEvent e ) { + updateUI(); + } + + private void updateUI() { + if ( fHasMemorySpaceControls ) { + fMemorySpaceInput.setEnabled( fMemorySpaceEnableButton.getSelection() ); + } + fRangeField.setEnabled( fRangeEnableButton.getSelection() ); + Button b = getButton( IDialogConstants.OK_ID ); + if ( b == null ) { + return; + } + b.setEnabled( okayEnabled() ); + } + + private boolean okayEnabled() { + if ( !fChkBtnRead.getSelection() && !fChkBtnWrite.getSelection() ) { + return false ; + } + if ( fExpressionInput.getText().length() == 0 ) { + return false; + } + if ( fHasMemorySpaceControls && fMemorySpaceInput.getEnabled() && fMemorySpaceInput.getText().length() == 0 ) { + return false; + } + if ( fRangeField.getEnabled() + && ( fRangeField.getText().length() == 0 || !verifyIntegerText( fRangeField.getText() ) ) ) { + return false; + } + return true; + } + + public boolean getWriteAccess() { + return fWrite; + } + + public boolean getReadAccess() { + return fRead; + } + + public void setExpression(String expressionString ) { + fExpression = expressionString; + } + + public BigInteger getRange() { + return BigInteger.valueOf( Long.decode(fRange).longValue() ); + } + + public void initializeRange( boolean enable, String range ) { + fRangeInitialEnable = enable; + fRange = range; + } + + public void initializeMemorySpace( String memorySpace ) { + fMemorySpace = memorySpace; + } + + @Override + protected void createButtonsForButtonBar(Composite parent) { + // override so we can change the initial okay enabled state + createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, + true ).setEnabled( okayEnabled() ); + createButton( parent, IDialogConstants.CANCEL_ID, + IDialogConstants.CANCEL_LABEL, false ); + } + +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddWatchpointOnMemoryActionDelegate.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddWatchpointOnMemoryActionDelegate.java similarity index 98% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddWatchpointOnMemoryActionDelegate.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddWatchpointOnMemoryActionDelegate.java index c403a5e34ee..01e61b53471 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddWatchpointOnMemoryActionDelegate.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddWatchpointOnMemoryActionDelegate.java @@ -8,7 +8,7 @@ * Contributors: * Nokia - initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; import java.math.BigInteger; diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddWatchpointOnVariableActionDelegate.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddWatchpointOnVariableActionDelegate.java similarity index 97% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddWatchpointOnVariableActionDelegate.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddWatchpointOnVariableActionDelegate.java index 131616fb9af..66a5d5e03de 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/AddWatchpointOnVariableActionDelegate.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/AddWatchpointOnVariableActionDelegate.java @@ -8,11 +8,12 @@ * Contributors: * Nokia - initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; import org.eclipse.cdt.debug.internal.core.CRequest; import org.eclipse.cdt.debug.internal.core.ICWatchpointTarget; +import org.eclipse.cdt.debug.internal.ui.actions.ActionMessages; import org.eclipse.cdt.debug.ui.CDebugUIPlugin; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CAddBreakpointInteractiveRulerAction.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CAddBreakpointInteractiveRulerAction.java new file mode 100644 index 00000000000..a7923b204cc --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CAddBreakpointInteractiveRulerAction.java @@ -0,0 +1,218 @@ +/******************************************************************************* + * Copyright (c) 2005, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Wind River Systems - added support for IToggleBreakpointsTargetFactory + *******************************************************************************/ +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; + +import org.eclipse.cdt.debug.internal.ui.actions.ActionMessages; +import org.eclipse.cdt.debug.ui.CDebugUIPlugin; +import org.eclipse.cdt.debug.ui.breakpoints.IToggleBreakpointsTargetCExtension; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget; +import org.eclipse.debug.ui.actions.IToggleBreakpointsTargetManagerListener; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.dialogs.ErrorDialog; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.text.source.IVerticalRulerInfo; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditor; +import org.eclipse.ui.texteditor.IUpdate; + +/** + * Action to interactively create a breakpoint from vertical ruler of a + * workbench part containing a document. The part must provide an + * IToggleBreakpointsTargetExtension2 adapter. + *

+ * Clients may instantiate this class. + *

+ * @since 3.8 + * @see org.eclipse.debug.ui.actions.RulerToggleBreakpointActionDelegate + */ +public class CAddBreakpointInteractiveRulerAction extends Action implements IUpdate { + + private IWorkbenchPart fPart; + private IDocument fDocument; + private IVerticalRulerInfo fRulerInfo; + private IToggleBreakpointsTargetManagerListener fListener = new IToggleBreakpointsTargetManagerListener() { + public void preferredTargetsChanged() { + update(); + } + }; + + /** + * Constructs a new action to toggle a breakpoint in the given + * part containing the given document and ruler. + * + * @param part the part in which to toggle the breakpoint - provides + * an IToggleBreakpointsTarget adapter + * @param document the document breakpoints are being set in or + * null when the document should be derived from the + * given part + * @param rulerInfo specifies location the user has double-clicked + */ + public CAddBreakpointInteractiveRulerAction(IWorkbenchPart part, IDocument document, IVerticalRulerInfo rulerInfo) { + super(ActionMessages.getString("CAddBreakpointInteractiveRulerAction_label")); //$NON-NLS-1$ + fPart = part; + fDocument = document; + fRulerInfo = rulerInfo; + DebugUITools.getToggleBreakpointsTargetManager().addChangedListener(fListener); + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.action.IAction#run() + */ + public void run() { + IDocument document= getDocument(); + if (document == null) { + return; + } + + int line = fRulerInfo.getLineOfLastMouseButtonActivity(); + + // Test if line is valid + if (line == -1) + return; + + try { + ITextSelection selection = getTextSelection(document, line); + IToggleBreakpointsTarget toggleTarget = + DebugUITools.getToggleBreakpointsTargetManager().getToggleBreakpointsTarget(fPart, selection); + if (toggleTarget instanceof IToggleBreakpointsTargetCExtension) { + IToggleBreakpointsTargetCExtension extension = (IToggleBreakpointsTargetCExtension) toggleTarget; + if (extension.canCreateLineBreakpointsInteractive(fPart, selection)) { + extension.createLineBreakpointsInteractive(fPart, selection); + } + } + } catch (BadLocationException e) { + reportException(e); + } catch (CoreException e) { + reportException(e); + } + } + + /** + * 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( + fPart.getSite().getShell(), + ActionMessages.getString("CAddBreakpointInteractiveRulerAction_error_title"), //$NON-NLS-1$ + ActionMessages.getString("CAddBreakpointInteractiveRulerAction_error_message"), //$NON-NLS-1$ + status); + CDebugUIPlugin.log(status); // + } + + /** + * Disposes this action. Clients must call this method when + * this action is no longer needed. + */ + public void dispose() { + fDocument = null; + fPart = null; + fRulerInfo = null; + DebugUITools.getToggleBreakpointsTargetManager().removeChangedListener(fListener); + } + + /** + * Returns the document on which this action operates. + * + * @return the document or null if none + */ + private IDocument getDocument() { + if (fDocument != null) + return fDocument; + + if (fPart instanceof ITextEditor) { + ITextEditor editor= (ITextEditor)fPart; + IDocumentProvider provider = editor.getDocumentProvider(); + if (provider != null) + return provider.getDocument(editor.getEditorInput()); + } + + IDocument doc = (IDocument) fPart.getAdapter(IDocument.class); + if (doc != null) { + return doc; + } + + return null; + } + + /* (non-Javadoc) + * @see org.eclipse.ui.texteditor.IUpdate#update() + */ + public void update() { + IDocument document= getDocument(); + if (document != null) { + int line = fRulerInfo.getLineOfLastMouseButtonActivity(); + if (line > -1) { + try { + ITextSelection selection = getTextSelection(document, line); + + IToggleBreakpointsTarget adapter = + DebugUITools.getToggleBreakpointsTargetManager().getToggleBreakpointsTarget(fPart, selection); + if (adapter == null) { + setEnabled(false); + return; + } + if (adapter instanceof IToggleBreakpointsTargetCExtension) { + IToggleBreakpointsTargetCExtension extension = (IToggleBreakpointsTargetCExtension) adapter; + if (extension.canCreateLineBreakpointsInteractive(fPart, selection)) { + setEnabled(true); + return; + } + } + } catch (BadLocationException e) { + reportException(e); + } + } + } + setEnabled(false); + } + + /** + * 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. + * + * @param document The IDocument backing the Editor. + * @param line The line clicked on in the ruler. + * @return An ITextSelection as described. + * @throws BadLocationException If underlying operations throw. + */ + private ITextSelection getTextSelection(IDocument document, int line) throws BadLocationException { + IRegion region = document.getLineInformation(line); + ITextSelection textSelection = new TextSelection(document, region.getOffset(), 0); + ISelectionProvider provider = fPart.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; + } + +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CAddBreakpointInteractiveRulerActionDelegate.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CAddBreakpointInteractiveRulerActionDelegate.java new file mode 100644 index 00000000000..c6a4e0edb9b --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CAddBreakpointInteractiveRulerActionDelegate.java @@ -0,0 +1,97 @@ +/******************************************************************************* + * Copyright (c) 2005, 2012 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; + +import org.eclipse.cdt.debug.ui.breakpoints.IToggleBreakpointsTargetCExtension; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.text.source.IVerticalRulerInfo; +import org.eclipse.ui.IActionDelegate2; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.texteditor.AbstractRulerActionDelegate; +import org.eclipse.ui.texteditor.ITextEditor; + +/** + * Creates a breakpoint interactively, that is with user input as well as context + * information gathered from editor location. This action delegate can be + * contributed to an editor with the editorActions extension point. + * This action is as a factory that creates another action that performs the + * actual breakpoint toggling. The created action acts on the editor's + * IToggleBreakpointsTagretCExtension to create the breakpoint. + *

+ * This action should be be contributed to a vertical ruler context menu via the + * popupMenus extension point, by referencing the ruler's context + * menu identifier in the targetID attribute. + *

+ * <extension point="org.eclipse.ui.popupMenus">
+ *   <viewerContribution
+ *     targetID="example.rulerContextMenuId"
+ *     id="example.RulerPopupActions">
+ *       <action
+ *         label="Toggle Breakpoint"
+ *         class="org.eclipse.debug.ui.actions.RulerCreateBreakpointInteractiveActionDelegate"
+ *         menubarPath="additions"
+ *         id="example.rulerContextMenu.createBreakpointAction">
+ *       </action>
+ *   </viewerContribution>
+ * 
+ *

+ *

+ * Clients may refer to this class as an action delegate in plug-in XML. + *

+ * @see IToggleBreakpointsTargetCExtension + * @since 7.2 + * @noextend This class is not intended to be sub-classed by clients. + * @noinstantiate This class is not intended to be instantiated by clients. + */ +public class CAddBreakpointInteractiveRulerActionDelegate extends AbstractRulerActionDelegate implements IActionDelegate2 { + + private IEditorPart fEditor = null; + private CAddBreakpointInteractiveRulerAction fDelegate = null; + + /* (non-Javadoc) + * @see org.eclipse.ui.texteditor.AbstractRulerActionDelegate#createAction(org.eclipse.ui.texteditor.ITextEditor, org.eclipse.jface.text.source.IVerticalRulerInfo) + */ + protected IAction createAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { + fDelegate = new CAddBreakpointInteractiveRulerAction(editor, null, rulerInfo); + return fDelegate; + } + + /* (non-Javadoc) + * @see org.eclipse.ui.IEditorActionDelegate#setActiveEditor(org.eclipse.jface.action.IAction, org.eclipse.ui.IEditorPart) + */ + public void setActiveEditor(IAction callerAction, IEditorPart targetEditor) { + if (fEditor != null) { + if (fDelegate != null) { + fDelegate.dispose(); + fDelegate = null; + } + } + fEditor = targetEditor; + super.setActiveEditor(callerAction, targetEditor); + } + + /* (non-Javadoc) + * @see org.eclipse.ui.IActionDelegate2#init(org.eclipse.jface.action.IAction) + */ + public void init(IAction action) { + } + + /* (non-Javadoc) + * @see org.eclipse.ui.IActionDelegate2#dispose() + */ + public void dispose() { + if (fDelegate != null) { + fDelegate.dispose(); + } + fDelegate = null; + fEditor = null; + } +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/CBreakpointPropertiesHandler.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CBreakpointPropertiesHandler.java similarity index 59% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/CBreakpointPropertiesHandler.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CBreakpointPropertiesHandler.java index 5dc43b5f299..10bab0d10c1 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/CBreakpointPropertiesHandler.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CBreakpointPropertiesHandler.java @@ -9,24 +9,18 @@ * QNX Software Systems - Initial API and implementation * Wind River Systems - Converted into a command *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; import org.eclipse.cdt.debug.core.model.ICBreakpoint; -import org.eclipse.cdt.debug.internal.ui.CBreakpointContext; +import org.eclipse.cdt.debug.internal.ui.CDebugUIUtils; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.expressions.IEvaluationContext; import org.eclipse.debug.core.DebugPlugin; -import org.eclipse.debug.ui.DebugUITools; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.ISources; import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.dialogs.PropertyDialogAction; import org.eclipse.ui.handlers.HandlerUtil; /** @@ -44,36 +38,12 @@ public class CBreakpointPropertiesHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchPart part = HandlerUtil.getActivePartChecked(event); - ICBreakpoint bp = getBreakpoint(event.getApplicationContext()); + final ICBreakpoint bp = getBreakpoint(event.getApplicationContext()); if (part != null && bp != null) { - ISelection debugContext = DebugUITools.getDebugContextManager(). - getContextService(part.getSite().getWorkbenchWindow()).getActiveContext(); - - final CBreakpointContext bpContext = new CBreakpointContext(bp, debugContext); - - PropertyDialogAction propertyAction = new PropertyDialogAction( part.getSite(), new ISelectionProvider() { - - @Override - public void addSelectionChangedListener( ISelectionChangedListener listener ) { - } - - @Override - public ISelection getSelection() { - return new StructuredSelection( bpContext ); - } - - @Override - public void removeSelectionChangedListener( ISelectionChangedListener listener ) { - } - - @Override - public void setSelection( ISelection selection ) { - assert false; // Not supported - } - } ); - propertyAction.run(); - } + CDebugUIUtils.editBreakpointProperties(part, bp); + } + return null; } diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CBreakpointPropertiesRulerAction.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CBreakpointPropertiesRulerAction.java new file mode 100644 index 00000000000..49f5b40c95e --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CBreakpointPropertiesRulerAction.java @@ -0,0 +1,96 @@ +/******************************************************************************* + * Copyright (c) 2004, 2008 QNX Software Systems and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * QNX Software Systems - Initial API and implementation + * Anton Leherbauer (Wind River Systems) - bug 183397 + *******************************************************************************/ +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; + +import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.cdt.debug.internal.ui.ICDebugHelpContextIds; +import org.eclipse.cdt.debug.internal.ui.IInternalCDebugUIConstants; +import org.eclipse.cdt.debug.internal.ui.actions.ActionMessages; +import org.eclipse.cdt.debug.ui.breakpoints.CBreakpointPropertyDialogAction; +import org.eclipse.debug.core.model.IBreakpoint; +import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.debug.ui.contexts.IDebugContextListener; +import org.eclipse.debug.ui.contexts.IDebugContextProvider; +import org.eclipse.jface.text.source.IVerticalRulerInfo; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.ui.IWorkbenchPart; + +/** + * Opens a custom properties dialog to configure the attibutes of a C/C++ breakpoint + * from the ruler popup menu. + */ +public class CBreakpointPropertiesRulerAction extends AbstractBreakpointRulerAction { + + private ICBreakpoint fBreakpoint; + + /** + * Creates the action to modify the breakpoint properties. + */ + public CBreakpointPropertiesRulerAction( IWorkbenchPart part, IVerticalRulerInfo info ) { + super( part, info ); + setText( ActionMessages.getString( "CBreakpointPropertiesRulerAction.Breakpoint_Properties" ) ); //$NON-NLS-1$ + part.getSite().getWorkbenchWindow().getWorkbench().getHelpSystem().setHelp( this, ICDebugHelpContextIds.BREAKPOINT_PROPERTIES_ACTION ); + setId( IInternalCDebugUIConstants.ACTION_BREAKPOINT_PROPERTIES ); + } + + /* (non-Javadoc) + * @see Action#run() + */ + @Override + public void run() { + if ( fBreakpoint != null ) { + final ISelection debugContext = DebugUITools.getDebugContextForPart(getTargetPart()); + CBreakpointPropertyDialogAction propertiesAction = new CBreakpointPropertyDialogAction( + getTargetPart().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(); + } + } + + /* (non-Javadoc) + * @see IUpdate#update() + */ + @Override + public void update() { + IBreakpoint breakpoint= getBreakpoint(); + + if (breakpoint instanceof ICBreakpoint) { + fBreakpoint = (ICBreakpoint)breakpoint; + } else { + fBreakpoint = null; + } + setEnabled( fBreakpoint != null ); + } +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/CBreakpointPropertiesRulerActionDelegate.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CBreakpointPropertiesRulerActionDelegate.java similarity index 95% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/CBreakpointPropertiesRulerActionDelegate.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CBreakpointPropertiesRulerActionDelegate.java index 30adad5629c..e4d58903a2f 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/CBreakpointPropertiesRulerActionDelegate.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CBreakpointPropertiesRulerActionDelegate.java @@ -8,7 +8,7 @@ * Contributors: * QNX Software Systems - initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; import org.eclipse.jface.action.IAction; import org.eclipse.jface.text.source.IVerticalRulerInfo; diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CToggleBreakpointObjectActionDelegate.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CToggleBreakpointObjectActionDelegate.java new file mode 100644 index 00000000000..14e1e3e24be --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CToggleBreakpointObjectActionDelegate.java @@ -0,0 +1,97 @@ +/******************************************************************************* + * Copyright (c) 2000, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Wind River Systems - added support for IToggleBreakpointsTargetFactory + *******************************************************************************/ +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.debug.core.DebugPlugin; +import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.swt.widgets.Event; +import org.eclipse.ui.IActionDelegate2; +import org.eclipse.ui.IObjectActionDelegate; +import org.eclipse.ui.IWorkbenchPart; + +/** + * A toggle breakpoint action that can be contributed to an object. The action + * will perform a toggle breakpoint operation for a selected object. + *

+ * This class is based on {@link org.eclipse.debug.internal.ui.actions.breakpoints.ToggleBreakpointObjectActionDelegate } + * class. In addition to the copied functionality, it adds the handling of + * action-triggering event. + *

+ * + * @since 7.2 + */ +public abstract class CToggleBreakpointObjectActionDelegate implements IObjectActionDelegate, IActionDelegate2 { + + private IWorkbenchPart fPart; + private IStructuredSelection fSelection; + + public void setActivePart(IAction action, IWorkbenchPart targetPart) { + fPart = targetPart; + } + + public void run(IAction action) { + runWithEvent(action, null); + } + + public void runWithEvent(IAction action, Event event) { + IToggleBreakpointsTarget target = + DebugUITools.getToggleBreakpointsTargetManager().getToggleBreakpointsTarget(fPart, fSelection); + if (target != null) { + try { + performAction(target, fPart, fSelection, event); + } catch (CoreException e) { + DebugPlugin.log(e); + } + } + } + + /** + * Performs the operation specific to this action. + * + * @param target adapter to toggle breakpoints + * @param part the active part + * @param selection the selection in the active part + * @param event that triggered this action + * @exception CoreException if an exception occurs + */ + protected abstract void performAction(IToggleBreakpointsTarget target, IWorkbenchPart part, ISelection selection, Event event) + throws CoreException; + + public void selectionChanged(IAction action, ISelection selection) { + boolean enabled = false; + if (selection instanceof IStructuredSelection) { + IStructuredSelection ss = (IStructuredSelection) selection; + this.fSelection = ss; + // selectionChagned() can sometimes be called before setActivePart(). + // Guard here against that possibility. + if (fPart != null) { + IToggleBreakpointsTarget target = + DebugUITools.getToggleBreakpointsTargetManager().getToggleBreakpointsTarget(fPart, fSelection); + enabled = target != null; + } + } + action.setEnabled(enabled); + } + + public void init(IAction action) { + } + + public void dispose() { + fSelection = null; + fPart = null; + } +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CToggleMethodBreakpointActionDelegate.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CToggleMethodBreakpointActionDelegate.java new file mode 100644 index 00000000000..37aa40ad275 --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/CToggleMethodBreakpointActionDelegate.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; + +import org.eclipse.cdt.debug.ui.breakpoints.IToggleBreakpointsTargetCExtension; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Event; +import org.eclipse.ui.IWorkbenchPart; + +/** + * A toggle method breakpoint action that can be contributed an object + * contribution. The action will toggle method breakpoints on objects + * that provide an IToggleBreakpointsTarget adapter. + *

+ * This class is based on {@link org.eclipse.debug.ui.actions.ToggleMethodBreakpointActionDelegate } + * class. In addition to the copied functionality, it adds the handling of + * action-triggering event. + *

+ * + * @since 7.2 + */ +public class CToggleMethodBreakpointActionDelegate extends CToggleBreakpointObjectActionDelegate { + + protected void performAction(IToggleBreakpointsTarget target, IWorkbenchPart part, ISelection selection, Event event) + throws CoreException + { + if ((event.stateMask & SWT.MOD1) != 0 && + target instanceof IToggleBreakpointsTargetCExtension && + ((IToggleBreakpointsTargetCExtension)target).canCreateFunctionBreakpointInteractive(part, selection)) + { + ((IToggleBreakpointsTargetCExtension)target).createFunctionBreakpointInteractive(part, selection); + } + else { + target.toggleMethodBreakpoints(part, selection); + } + } +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/EnableDisableBreakpointRulerAction.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/EnableDisableBreakpointRulerAction.java similarity index 95% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/EnableDisableBreakpointRulerAction.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/EnableDisableBreakpointRulerAction.java index 858d371b37b..586020c4fae 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/EnableDisableBreakpointRulerAction.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/EnableDisableBreakpointRulerAction.java @@ -9,10 +9,11 @@ * QNX Software Systems - Initial API and implementation * Anton Leherbauer (Wind River Systems) - bug 183397 *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; import org.eclipse.cdt.debug.internal.ui.ICDebugHelpContextIds; import org.eclipse.cdt.debug.internal.ui.IInternalCDebugUIConstants; +import org.eclipse.cdt.debug.internal.ui.actions.ActionMessages; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.model.IBreakpoint; diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/ToggleBreakpointAdapter.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/ToggleBreakpointAdapter.java new file mode 100644 index 00000000000..41201f51497 --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/ToggleBreakpointAdapter.java @@ -0,0 +1,123 @@ +/******************************************************************************* + * Copyright (c) 2004, 2010 QNX Software Systems and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * QNX Software Systems - Initial API and implementation + * Freescale Semiconductor - Address watchpoints, https://bugs.eclipse.org/bugs/show_bug.cgi?id=118299 + * Warren Paul (Nokia) - Bug 217485, Bug 218342 + * Oyvind Harboe (oyvind.harboe@zylin.com) - Bug 225099 + *******************************************************************************/ +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; + +import java.math.BigInteger; +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.cdt.debug.core.CDIDebugModel; +import org.eclipse.cdt.debug.core.cdi.model.ICDIMemorySpaceManagement; +import org.eclipse.cdt.debug.core.cdi.model.ICDITarget; +import org.eclipse.cdt.debug.core.model.ICBreakpointType; +import org.eclipse.cdt.debug.core.model.ICDebugTarget; +import org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint; +import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; +import org.eclipse.cdt.debug.core.model.ICWatchpoint; +import org.eclipse.cdt.debug.ui.breakpoints.AbstractToggleBreakpointAdapter; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.ui.IWorkbenchPart; + +/** + * Toggles a line breakpoint in a C/C++ editor. + * + * @since 7.2 + */ +public class ToggleBreakpointAdapter extends AbstractToggleBreakpointAdapter { + + @Override + protected ICLineBreakpoint findLineBreakpoint( String sourceHandle, IResource resource, int lineNumber ) throws CoreException { + return CDIDebugModel.lineBreakpointExists( sourceHandle, resource, lineNumber ); + } + + @Override + protected void createLineBreakpoint(boolean interactive, IWorkbenchPart part, String sourceHandle, + IResource resource, int lineNumber) throws CoreException + { + if (interactive) { + ICLineBreakpoint lineBp = CDIDebugModel.createBlankLineBreakpoint(); + Map attributes = new HashMap(); + CDIDebugModel.setLineBreakpointAttributes( + attributes, sourceHandle, getBreakpointType(), lineNumber, true, 0, "" ); //$NON-NLS-1$ + openBreakpointPropertiesDialog(lineBp, part, resource, attributes); + } else { + CDIDebugModel.createLineBreakpoint( sourceHandle, resource, getBreakpointType(), lineNumber, true, 0, "", true );//$NON-NLS-1$ + } + } + + @Override + protected ICFunctionBreakpoint findFunctionBreakpoint(String sourceHandle, IResource resource, String functionName) + throws CoreException + { + return CDIDebugModel.functionBreakpointExists( sourceHandle, resource, functionName ); + } + + @Override + protected void createFunctionBreakpoint(boolean interactive, IWorkbenchPart part, String sourceHandle, + IResource resource, String functionName, int charStart, int charEnd, int lineNumber ) throws CoreException + { + if (interactive) { + ICFunctionBreakpoint bp = CDIDebugModel.createBlankFunctionBreakpoint(); + Map attributes = new HashMap(); + CDIDebugModel.setFunctionBreakpointAttributes( attributes, sourceHandle, getBreakpointType(), functionName, + charStart, charEnd, lineNumber, true, 0, "" ); //$NON-NLS-1$ + openBreakpointPropertiesDialog(bp, part, resource, attributes); + } else { + CDIDebugModel.createFunctionBreakpoint(sourceHandle, resource, getBreakpointType(), functionName, charStart, + charEnd, lineNumber, true, 0, "", true); //$NON-NLS-1$ + } + } + + @Override + protected ICWatchpoint findWatchpoint( String sourceHandle, IResource resource, String expression ) throws CoreException { + return CDIDebugModel.watchpointExists( sourceHandle, resource, expression ); + } + + @Override + protected void createWatchpoint( boolean interactive, IWorkbenchPart part, String sourceHandle, IResource resource, + int charStart, int charEnd, int lineNumber, String expression) throws CoreException + { + ICWatchpoint bp = CDIDebugModel.createBlankWatchpoint(); + Map attributes = new HashMap(); + CDIDebugModel.setWatchPointAttributes(attributes, sourceHandle, resource, true, false, + expression, "", new BigInteger("0"), true, 0, ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + openBreakpointPropertiesDialog(bp, part, resource, attributes); + } + + protected int getBreakpointType() { + return ICBreakpointType.REGULAR; + } + + public static ICDIMemorySpaceManagement getMemorySpaceManagement(){ + IAdaptable debugViewElement = DebugUITools.getDebugContext(); + ICDIMemorySpaceManagement memMgr = null; + + if ( debugViewElement != null ) { + ICDebugTarget debugTarget = (ICDebugTarget)debugViewElement.getAdapter(ICDebugTarget.class); + + if ( debugTarget != null ){ + ICDITarget target = (ICDITarget)debugTarget.getAdapter(ICDITarget.class); + + if (target instanceof ICDIMemorySpaceManagement) + memMgr = (ICDIMemorySpaceManagement)target; + } + } + + return memMgr; + } + +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleCBreakpointsTargetFactory.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/ToggleCBreakpointsTargetFactory.java similarity index 95% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleCBreakpointsTargetFactory.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/ToggleCBreakpointsTargetFactory.java index d394abe0a3a..44a38a5baa2 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleCBreakpointsTargetFactory.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/ToggleCBreakpointsTargetFactory.java @@ -8,13 +8,14 @@ * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; import java.util.HashSet; import java.util.Set; import org.eclipse.cdt.debug.core.CDIDebugModel; import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.cdt.debug.internal.ui.actions.ActionMessages; import org.eclipse.cdt.debug.ui.CDebugUIPlugin; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.debug.core.model.IDebugElement; @@ -86,8 +87,7 @@ public class ToggleCBreakpointsTargetFactory implements IToggleBreakpointsTarget } @Override - @SuppressWarnings("unchecked") - public Set getToggleTargets(IWorkbenchPart part, ISelection selection) { + public Set getToggleTargets(IWorkbenchPart part, ISelection selection) { return TOGGLE_TARGET_IDS; } diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleCTracepointsTargetFactory.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/ToggleCTracepointsTargetFactory.java similarity index 92% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleCTracepointsTargetFactory.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/ToggleCTracepointsTargetFactory.java index 75789e586b7..70668a699c4 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/ToggleCTracepointsTargetFactory.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/ToggleCTracepointsTargetFactory.java @@ -8,11 +8,12 @@ * Contributors: * Ericsson - initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.actions; +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; import java.util.HashSet; import java.util.Set; +import org.eclipse.cdt.debug.internal.ui.actions.ActionMessages; import org.eclipse.cdt.debug.ui.CDebugUIPlugin; import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget; import org.eclipse.debug.ui.actions.IToggleBreakpointsTargetFactory; @@ -66,8 +67,7 @@ public class ToggleCTracepointsTargetFactory implements IToggleBreakpointsTarget } @Override - @SuppressWarnings("unchecked") - public Set getToggleTargets(IWorkbenchPart part, ISelection selection) { + public Set getToggleTargets(IWorkbenchPart part, ISelection selection) { return TOGGLE_TARGET_IDS; } } diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/ToggleTracepointAdapter.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/ToggleTracepointAdapter.java new file mode 100644 index 00000000000..375c8f7f00f --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/actions/breakpoints/ToggleTracepointAdapter.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright (c) 2009 Ericsson and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Ericsson - Initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.debug.internal.ui.actions.breakpoints; + +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.cdt.debug.core.CDIDebugModel; +import org.eclipse.cdt.debug.core.model.ICBreakpointType; +import org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint; +import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; +import org.eclipse.cdt.debug.core.model.ICWatchpoint; +import org.eclipse.cdt.debug.ui.breakpoints.AbstractToggleBreakpointAdapter; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.ui.IWorkbenchPart; + +/** + * Toggles a tracepoint in a C/C++ editor. + */ +public class ToggleTracepointAdapter extends AbstractToggleBreakpointAdapter { + + @Override + protected ICLineBreakpoint findLineBreakpoint( String sourceHandle, IResource resource, int lineNumber ) throws CoreException { + return CDIDebugModel.lineBreakpointExists( sourceHandle, resource, lineNumber ); + } + + @Override + protected void createLineBreakpoint(boolean interactive, IWorkbenchPart part, String sourceHandle, + IResource resource, int lineNumber) throws CoreException + { + if (interactive) { + ICLineBreakpoint lineBp = CDIDebugModel.createBlankLineTracepoint(); + Map attributes = new HashMap(); + CDIDebugModel.setLineBreakpointAttributes( + attributes, sourceHandle, getBreakpointType(), lineNumber, true, 0, "" ); //$NON-NLS-1$ + openBreakpointPropertiesDialog(lineBp, part, resource, attributes); + } else { + CDIDebugModel.createLineTracepoint( sourceHandle, resource, getBreakpointType(), lineNumber, true, 0, "", true );//$NON-NLS-1$ + } + } + + @Override + protected ICFunctionBreakpoint findFunctionBreakpoint( String sourceHandle, IResource resource, String functionName ) throws CoreException { + return CDIDebugModel.functionBreakpointExists( sourceHandle, resource, functionName ); + } + + @Override + protected void createFunctionBreakpoint(boolean interactive, IWorkbenchPart part, String sourceHandle, + IResource resource, String functionName, int charStart, int charEnd, int lineNumber ) throws CoreException + { + if (interactive) { + ICFunctionBreakpoint bp = CDIDebugModel.createBlankFunctionTracepoint(); + Map attributes = new HashMap(); + CDIDebugModel.setFunctionBreakpointAttributes( attributes, sourceHandle, getBreakpointType(), functionName, + charStart, charEnd, lineNumber, true, 0, "" ); //$NON-NLS-1$ + openBreakpointPropertiesDialog(bp, part, resource, attributes); + } else { + CDIDebugModel.createFunctionTracepoint(sourceHandle, resource, getBreakpointType(), functionName, charStart, + charEnd, lineNumber, true, 0, "", true); //$NON-NLS-1$ + } + } + + @Override + protected ICWatchpoint findWatchpoint( String sourceHandle, IResource resource, String expression ) throws CoreException { + return null; + } + + @Override + public boolean canToggleWatchpoints(IWorkbenchPart part, ISelection selection) { + return false; + } + + protected void createWatchpoint( boolean interactive, IWorkbenchPart part, String sourceHandle, IResource resource, + int charStart, int charEnd, int lineNumber, String expression) throws CoreException + { + } + + protected int getBreakpointType() { + return ICBreakpointType.REGULAR; + } +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/BreakpointImageProvider.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/BreakpointImageProvider.java similarity index 97% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/BreakpointImageProvider.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/BreakpointImageProvider.java index 3b490af3c32..c18640cccc7 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/BreakpointImageProvider.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/BreakpointImageProvider.java @@ -8,7 +8,7 @@ * Contributors: * QNX Software Systems - Initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui; +package org.eclipse.cdt.debug.internal.ui.breakpoints; import org.eclipse.core.resources.IMarker; import org.eclipse.debug.core.DebugPlugin; diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/BreakpointsMessages.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/BreakpointsMessages.java new file mode 100644 index 00000000000..e6742c6bbc3 --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/BreakpointsMessages.java @@ -0,0 +1,33 @@ +/******************************************************************************* + * Copyright (c) 2004, 2006 QNX Software Systems and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * QNX Software Systems - Initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.debug.internal.ui.breakpoints; + +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +public class BreakpointsMessages { + + private static final String BUNDLE_NAME = "org.eclipse.cdt.debug.internal.ui.breakpoints.BreakpointsMessages"; //$NON-NLS-1$ + + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME ); + + private BreakpointsMessages() { + } + + public static String getString( String key ) { + try { + return RESOURCE_BUNDLE.getString( key ); + } + catch( MissingResourceException e ) { + return '!' + key + '!'; + } + } +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/BreakpointsMessages.properties b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/BreakpointsMessages.properties new file mode 100644 index 00000000000..ecc61aa6bf0 --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/BreakpointsMessages.properties @@ -0,0 +1,40 @@ +############################################################################### +# Copyright (c) 2003, 2009 QNX Software Systems and others. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# QNX Software Systems - initial API and implementation +# Nokia - https://bugs.eclipse.org/bugs/show_bug.cgi?id=145606 +# IBM Corporation +############################################################################### + +CBreakpointPropertyPage.0=Ignore count must be a nonnegative integer +CBreakpointPropertyPage.function_valueNotAvailable_label=Not available +CBreakpointPropertyPage.function_label=Function name: +CBreakpointPropertyPage.function_value_errorMessage=Enter a function expression: +CBreakpointPropertyPage.breakpointType_function_label=C/C++ Function Breakpoint +CBreakpointPropertyPage.address_valueNotAvailable_label=Not available +CBreakpointPropertyPage.address_label=Address: +CBreakpointPropertyPage.breakpointType_address_label=C/C++ Address Breakpoint +CBreakpointPropertyPage.sourceHandle_label=File: +CBreakpointPropertyPage.breakpointType_line_label=C/C++ Line Breakpoint +CBreakpointPropertyPage.lineNumber_label=Line number: +CBreakpointPropertyPage.breakpointType_event_label=C/C++ Event Breakpoint +CBreakpointPropertyPage.project_label=Project: +CBreakpointPropertyPage.breakpointType_watchpoint_label=C/C++ Watchpoint +CBreakpointPropertyPage.breakpointType_watchpoint_read_label=C/C++ Read Watchpoint +CBreakpointPropertyPage.breakpointType_watchpoint_access_label=C/C++ Access Watchpoint +CBreakpointPropertyPage.watchpointType_read_label=Read +CBreakpointPropertyPage.watchpointType_write_label=Write +CBreakpointPropertyPage.watchpoint_expression_label=Expression to watch: +CBreakpointPropertyPage.watchpoint_expression_errorMessage=Enter the expression to watch: +CBreakpointPropertyPage.condition_label=&Condition: +CBreakpointPropertyPage.condition_invalidValue_message=Invalid condition. +CBreakpointPropertyPage.ignoreCount_label=&Ignore count: +CBreakpointPropertyPage.breakpointType_label=Class: +CBreakpointPropertyPage.enabled_label=Enabled + +ThreadFilterEditor.0=&Restrict to Selected Targets and Threads: diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/CBreakpointContext.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointContext.java similarity index 51% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/CBreakpointContext.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointContext.java index 22a7bd92f31..bc179355e35 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/CBreakpointContext.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointContext.java @@ -9,10 +9,20 @@ * Wind River Systems - initial API and implementation * Ericsson - Added tracepoint support (284286) *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui; +package org.eclipse.cdt.debug.internal.ui.breakpoints; +import java.util.Map; + +import org.eclipse.cdt.debug.core.CDIDebugModel; +import org.eclipse.cdt.debug.core.model.ICAddressBreakpoint; import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.cdt.debug.core.model.ICEventBreakpoint; +import org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint; +import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; import org.eclipse.cdt.debug.core.model.ICTracepoint; +import org.eclipse.cdt.debug.core.model.ICWatchpoint; +import org.eclipse.cdt.debug.ui.breakpoints.ICBreakpointContext; +import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IAdapterFactory; import org.eclipse.core.runtime.Platform; @@ -20,9 +30,14 @@ import org.eclipse.core.runtime.PlatformObject; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.core.model.IDebugElement; import org.eclipse.debug.core.model.IDebugModelProvider; +import org.eclipse.debug.ui.contexts.IDebugContextListener; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IActionFilter; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.model.IWorkbenchAdapter; /** * Input for breakpoint properties dialog. It captures both the @@ -30,7 +45,7 @@ import org.eclipse.ui.IActionFilter; * This combined context can then be used by breakpoint property * pages to access model and target specific breakpoint settings. */ -public class CBreakpointContext extends PlatformObject { +public class CBreakpointContext extends PlatformObject implements ICBreakpointContext { // Register an adapter factory for the class when it is first loaded. static { @@ -42,29 +57,61 @@ public class CBreakpointContext extends PlatformObject { */ private final ICBreakpoint fBreakpoint; + /** + * The resource that the breakpoint is to be created for. + */ + private final IResource fResource; + /** * The active debug context held by this context. */ private final ISelection fDebugContext; /** - * Creates a new breakpoint context with given breakpoint and debbug + * Associated preference store. + */ + private final CBreakpointPreferenceStore fPreferenceStore; + + /** + * Creates a new breakpoint context with given breakpoint and debug * context selection. */ public CBreakpointContext(ICBreakpoint breakpoint, ISelection debugContext) { - fBreakpoint = breakpoint; - fDebugContext = debugContext; + this (breakpoint, debugContext, null, null); } - /** - * Returns the breakpoint. - */ + public CBreakpointContext(ICBreakpoint breakpoint, ISelection debugContext, IResource resource, Map attributes) { + fBreakpoint = breakpoint; + fResource = resource; + fDebugContext = debugContext; + fPreferenceStore = new CBreakpointPreferenceStore(this, attributes); + } + + @Override public ICBreakpoint getBreakpoint() { return fBreakpoint; } + + @Override + public IResource getResource() { return fResource; } + + @Override + public IPreferenceStore getPreferenceStore() { return fPreferenceStore; } /** * Returns the debug context. */ public ISelection getDebugContext() { return fDebugContext; } + + /** + * (non-Javadoc) + * @see org.eclipse.debug.ui.contexts.IDebugContextProvider implementation + */ + public IWorkbenchPart getPart() { return null; } + public void addDebugContextListener(IDebugContextListener listener) {} + public void removeDebugContextListener(IDebugContextListener listener) {} + + public ISelection getActiveContext() { + return fDebugContext; + } } /** @@ -109,30 +156,84 @@ class CBreakpointContextActionFilter implements IActionFilter { } } +class CBreakpointContextWorkbenchAdapter implements IWorkbenchAdapter { + @Override + public String getLabel(Object o) { + if (o instanceof ICBreakpointContext) { + ICBreakpoint bp = ((ICBreakpointContext)o).getBreakpoint(); + return getBreakpointMainLabel(bp); + } + return ""; //$NON-NLS-1$ + } + + @Override + public Object[] getChildren(Object o) { return null; } + + @Override + public ImageDescriptor getImageDescriptor(Object object) { return null; } + + @Override + public Object getParent(Object o) { return null; } + + private String getBreakpointMainLabel(ICBreakpoint breakpoint) { + if (breakpoint instanceof ICFunctionBreakpoint) { + return BreakpointsMessages.getString("CBreakpointPropertyPage.breakpointType_function_label"); //$NON-NLS-1$ + } else if (breakpoint instanceof ICAddressBreakpoint) { + return BreakpointsMessages.getString("CBreakpointPropertyPage.breakpointType_address_label"); //$NON-NLS-1$ + } else if (breakpoint instanceof ICLineBreakpoint) { + return BreakpointsMessages.getString("CBreakpointPropertyPage.breakpointType_line_label"); //$NON-NLS-1$ + } else if (breakpoint instanceof ICEventBreakpoint) { + return BreakpointsMessages.getString("CBreakpointPropertyPage.breakpointType_event_label"); //$NON-NLS-1$ + } else if (breakpoint instanceof ICWatchpoint) { + return BreakpointsMessages.getString("CBreakpointPropertyPage.breakpointType_watchpoint_label"); //$NON-NLS-1$ + } + // default main label is the label of marker type for the breakpoint + return CDIDebugModel.calculateMarkerType(breakpoint); + } + +} + /** * Adapter factory which returns the breakpoint object and the action * filter for the CBreakpointContext type. */ class CBreakpointContextAdapterFactory implements IAdapterFactory { - private static final Class[] fgAdapterList = new Class[] { - IBreakpoint.class, ICBreakpoint.class, ICTracepoint.class, IActionFilter.class + private static final Class[] fgAdapterList = new Class[] { + IBreakpoint.class, ICBreakpoint.class, ICTracepoint.class, IActionFilter.class, IPreferenceStore.class, + IWorkbenchAdapter.class, }; private static final IActionFilter fgActionFilter = new CBreakpointContextActionFilter(); + private static final IWorkbenchAdapter fgWorkbenchAdapter = new CBreakpointContextWorkbenchAdapter(); @Override - public Object getAdapter(Object obj, Class adapterType) { - if (adapterType.isInstance( ((CBreakpointContext)obj).getBreakpoint() )) { + public Object getAdapter(Object obj, @SuppressWarnings("rawtypes") Class adapterType) { + // Note: only return the breakpoint object as an adapter if it has + // an associated marker. Otherwise the property pages will throw multiple + // exceptions. + if (adapterType.isInstance( ((CBreakpointContext)obj).getBreakpoint() ) && + ((CBreakpointContext)obj).getBreakpoint().getMarker() != null) + { return ((CBreakpointContext)obj).getBreakpoint(); } + if ( IPreferenceStore.class.equals(adapterType) ) { + return ((CBreakpointContext)obj).getPreferenceStore(); + } + if (IActionFilter.class.equals(adapterType)) { return fgActionFilter; } + + if (IWorkbenchAdapter.class.equals(adapterType)) { + return fgWorkbenchAdapter; + } + return null; } + @SuppressWarnings("rawtypes") @Override public Class[] getAdapterList() { return fgAdapterList; diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/CBreakpointFilteringPage.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointFilteringPage.java similarity index 95% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/CBreakpointFilteringPage.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointFilteringPage.java index 7879cd8ccc4..a74f4707bbe 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/CBreakpointFilteringPage.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointFilteringPage.java @@ -8,7 +8,7 @@ * Contributors: * QNX Software Systems - Initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.propertypages; +package org.eclipse.cdt.debug.internal.ui.breakpoints; import org.eclipse.cdt.debug.core.CDIDebugModel; import org.eclipse.cdt.debug.core.model.ICBreakpoint; @@ -48,7 +48,7 @@ public class CBreakpointFilteringPage extends PropertyPage { ICBreakpoint bp = getBreakpoint(); if (bp != null) { try { - return (ICBreakpointFilterExtension)bp.getExtension( + return bp.getExtension( CDIDebugModel.getPluginIdentifier(), ICBreakpointFilterExtension.class); } catch (CoreException e) {} } diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointPreferenceStore.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointPreferenceStore.java new file mode 100644 index 00000000000..c558db83b63 --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointPreferenceStore.java @@ -0,0 +1,299 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 QNX Software Systems and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * QNX Software Systems - Initial API and implementation + * QNX Software Systems - Refactored to use platform implementation + *******************************************************************************/ +package org.eclipse.cdt.debug.internal.ui.breakpoints; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.eclipse.cdt.debug.core.CDIDebugModel; +import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.cdt.debug.core.model.ICLineBreakpoint2; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspaceRunnable; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.ListenerList; +import org.eclipse.debug.core.DebugPlugin; +import org.eclipse.jface.preference.IPersistentPreferenceStore; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; + +/** + * A preference store that presents the state of the properties of a C/C++ breakpoint. + */ +public class CBreakpointPreferenceStore implements IPersistentPreferenceStore { + + // This map is the current properties/values being maintained/manipulated + private HashMap fProperties = new HashMap(); + + // Original set of values. So we can see what has really changed on the save and + // perform appropriate change operations. We only really want to operate on changed + // values, to avoid generating churn. + private HashMap fOriginalValues = new HashMap(); + private boolean fIsDirty = false; + private boolean fIsCanceled = false; + private ListenerList fListeners; + private final CBreakpointContext fContext; + + // TODO: remove after fixing add event breapoint dialog. + public CBreakpointPreferenceStore() { + this (null, null); + } + + public CBreakpointPreferenceStore(CBreakpointContext context, Map attributes) { + fListeners = new ListenerList(org.eclipse.core.runtime.ListenerList.IDENTITY); + fContext = context; + + fOriginalValues.clear(); + fProperties.clear(); + if (context != null) { + IMarker marker = context.getBreakpoint().getMarker(); + if (marker != null) { + Map bpAttrs = Collections.emptyMap(); + try { + bpAttrs = marker.getAttributes(); + fOriginalValues.putAll(bpAttrs); + fProperties.putAll(bpAttrs); + } catch (CoreException e) { + DebugPlugin.log(e); + } + } + } + if (attributes != null) { + fProperties.putAll(attributes); + fIsDirty = true; + } + } + + public Map getAttributes() { + return fProperties; + } + + public void setCanceled(boolean canceled) { + fIsCanceled = canceled; + } + + public void save() throws IOException { + if (!fIsCanceled && fContext != null && fContext.getBreakpoint() != null) { + ICBreakpoint bp = fContext.getBreakpoint(); + if (bp.getMarker() != null && fIsDirty) { + saveToExistingMarker(bp, bp.getMarker()); + } + else if (fContext.getResource() != null){ + saveToNewMarker(bp, fContext.getResource()); + } else { + throw new IOException("Unable to create breakpoint: no resource specified."); //$NON-NLS-1$ + } + } + + } + + private void saveToExistingMarker(final ICBreakpoint breakpoint, final IMarker marker) throws IOException { + final List changedProperties = new ArrayList( 5 ); + Set valueNames = fProperties.keySet(); + for ( String name : valueNames ) { + if ( fProperties.containsKey( name ) ) { + Object originalObject = fOriginalValues.get( name ); + Object currentObject = fProperties.get( name ); + if ( originalObject == null ) { + changedProperties.add( name ); + } + else if ( ! originalObject.equals( currentObject ) ) { + changedProperties.add( name ); + } + } + } + if ( ! changedProperties.isEmpty() ) { + IWorkspaceRunnable wr = new IWorkspaceRunnable() { + public void run( IProgressMonitor monitor ) throws CoreException { + Iterator changed = changedProperties.iterator(); + while( changed.hasNext() ) { + String property = changed.next(); + if ( property.equals( ICBreakpoint.ENABLED ) ) { + breakpoint.setEnabled( getBoolean( ICBreakpoint.ENABLED ) ); + } + else if ( property.equals( ICBreakpoint.IGNORE_COUNT ) ) { + breakpoint.setIgnoreCount( getInt( ICBreakpoint.IGNORE_COUNT ) ); + } + else if ( property.equals( ICBreakpoint.CONDITION ) ) { + breakpoint.setCondition( getString( ICBreakpoint.CONDITION ) ); + } + else if ( property.equals( IMarker.LINE_NUMBER ) ) { + // already workspace runnable, setting markers are safe + breakpoint.getMarker().setAttribute(IMarker.LINE_NUMBER, getInt(IMarker.LINE_NUMBER)); + breakpoint.getMarker().setAttribute(ICLineBreakpoint2.REQUESTED_LINE, getInt(IMarker.LINE_NUMBER)); + } else { + // this allow set attributes contributed by other plugins + Object value = fProperties.get(property); + if ( value != null ) { + marker.setAttribute(property, value); + } + } + } + } + }; + try { + ResourcesPlugin.getWorkspace().run( wr, null ); + } + catch( CoreException ce ) { + throw new IOException("Cannot save properties to breakpoint.", ce); //$NON-NLS-1$ + } + } + } + + private void saveToNewMarker(final ICBreakpoint breakpoint, final IResource resource) throws IOException { + try { + CDIDebugModel.createBreakpointMarker(breakpoint, resource, fProperties, true); + } + catch( CoreException ce ) { + throw new IOException("Cannot save properties to new breakpoint.", ce); //$NON-NLS-1$ + } + } + + /////////////////////////////////////////////////////////////////////// + // IPreferenceStore + + public boolean needsSaving() { + return fIsDirty && !fIsCanceled; + } + + public boolean contains(String name) { + return fProperties.containsKey(name); + } + + public void addPropertyChangeListener(IPropertyChangeListener listener) { + fListeners.add(listener); + } + + public void removePropertyChangeListener(IPropertyChangeListener listener) { + fListeners.remove(listener); + } + + public void firePropertyChangeEvent(String name, + Object oldValue, + Object newValue) + { + Object[] listeners = fListeners.getListeners(); + // Do we need to fire an event. + if (listeners.length > 0 && (oldValue == null || !oldValue.equals(newValue))) { + PropertyChangeEvent pe = new PropertyChangeEvent(this, name, oldValue, newValue); + for (int i = 0; i < listeners.length; ++i) { + IPropertyChangeListener l = (IPropertyChangeListener) listeners[i]; + l.propertyChange(pe); + } + } + } + + public boolean getBoolean(String name) { + boolean retVal = false; + Object o = fProperties.get(name); + if (o instanceof Boolean) { + retVal = ((Boolean)o).booleanValue(); + } + return retVal; + } + + public int getInt(String name) { + int retVal = 0; + Object o = fProperties.get(name); + if (o instanceof Integer) { + retVal = ((Integer)o).intValue(); + } + return retVal; + } + + public String getString(String name) { + String retVal = null; + Object o = fProperties.get(name); + if (o instanceof String) { + retVal = (String)o; + } + return retVal; + } + + public double getDouble(String name) { return 0; } + public float getFloat(String name) { return 0; } + public long getLong(String name) { return 0; } + + public boolean isDefault(String name) { return false; } + + public boolean getDefaultBoolean(String name) { return false; } + public double getDefaultDouble(String name) { return 0; } + public float getDefaultFloat(String name) { return 0; } + public int getDefaultInt(String name) { return 0; } + public long getDefaultLong(String name) { return 0; } + public String getDefaultString(String name) { return null; } + + public void putValue(String name, String value) { + Object oldValue = fProperties.get(name); + if ( oldValue == null || !oldValue.equals(value) ) { + fProperties.put(name, value); + setDirty(true); + } + } + + public void setDefault(String name, double value) {} + public void setDefault(String name, float value) {} + public void setDefault(String name, int value) {} + public void setDefault(String name, long value) {} + public void setDefault(String name, String defaultObject) {} + public void setDefault(String name, boolean value) {} + public void setToDefault(String name) {} + + public void setValue(String name, boolean value) { + boolean oldValue = getBoolean(name); + if (oldValue != value) { + fProperties.put( name, new Boolean(value) ); + setDirty(true); + firePropertyChangeEvent(name, new Boolean(oldValue), new Boolean(value) ); + } + } + + public void setValue(String name, int value) { + int oldValue = getInt(name); + if (oldValue != value) { + fProperties.put( name, new Integer(value) ); + setDirty(true); + firePropertyChangeEvent(name, new Integer(oldValue), new Integer(value) ); + } + } + + public void setValue(String name, String value) { + Object oldValue = fProperties.get(name); + if ( (oldValue == null && value != null) || + (oldValue != null && !oldValue.equals(value)) ) + { + fProperties.put(name, value); + setDirty(true); + firePropertyChangeEvent(name, oldValue, value); + } + } + + public void setValue(String name, float value) {} + public void setValue(String name, double value) {} + public void setValue(String name, long value) {} + + // IPreferenceStore + /////////////////////////////////////////////////////////////////////// + + private void setDirty(boolean isDirty) { + fIsDirty = isDirty; + } +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointPropertyPage.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointPropertyPage.java new file mode 100644 index 00000000000..587abcbfa04 --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointPropertyPage.java @@ -0,0 +1,498 @@ +/******************************************************************************* + * Copyright (c) 2004, 2008 QNX Software Systems and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * QNX Software Systems - Initial API and implementation + * Nokia - https://bugs.eclipse.org/bugs/show_bug.cgi?id=145606 + * QNX Software Systems - Catchpoints support https://bugs.eclipse.org/bugs/show_bug.cgi?id=226689 + *******************************************************************************/ +package org.eclipse.cdt.debug.internal.ui.breakpoints; + +import org.eclipse.cdt.debug.core.CDIDebugModel; +import org.eclipse.cdt.debug.core.model.ICAddressBreakpoint; +import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint; +import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; +import org.eclipse.cdt.debug.core.model.ICWatchpoint; +import org.eclipse.cdt.debug.ui.CDebugUIPlugin; +import org.eclipse.cdt.debug.ui.breakpoints.CBreakpointUIContributionFactory; +import org.eclipse.cdt.debug.ui.breakpoints.ICBreakpointContext; +import org.eclipse.cdt.debug.ui.breakpoints.ICBreakpointsUIContribution; +import org.eclipse.cdt.debug.ui.preferences.ReadOnlyFieldEditor; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.debug.core.model.ILineBreakpoint; +import org.eclipse.jface.preference.BooleanFieldEditor; +import org.eclipse.jface.preference.FieldEditor; +import org.eclipse.jface.preference.FieldEditorPreferencePage; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.IntegerFieldEditor; +import org.eclipse.jface.preference.StringFieldEditor; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.IWorkbenchPropertyPage; +import org.eclipse.ui.model.IWorkbenchAdapter; + +/** + * The preference page used to present the properties of a breakpoint as preferences. A CBreakpointPreferenceStore is used to interface between this page and + * the breakpoint. + */ +public class CBreakpointPropertyPage extends FieldEditorPreferencePage implements IWorkbenchPropertyPage { + + class BreakpointIntegerFieldEditor extends IntegerFieldEditor { + + public BreakpointIntegerFieldEditor( String name, String labelText, Composite parent ) { + super( name, labelText, parent ); + setErrorMessage( BreakpointsMessages.getString( "CBreakpointPropertyPage.0" ) ); //$NON-NLS-1$ + } + + /** + * @see IntegerFieldEditor#checkState() + */ + @Override + protected boolean checkState() { + Text control = getTextControl(); + if ( !control.isEnabled() ) { + clearErrorMessage(); + return true; + } + return super.checkState(); + } + + /** + * Overrode here to be package visible. + */ + @Override + protected void refreshValidState() { + super.refreshValidState(); + } + + /** + * Only store if the text control is enabled + * + * @see FieldEditor#doStore() + */ + @Override + protected void doStore() { + Text text = getTextControl(); + if ( text.isEnabled() ) { + super.doStore(); + } + } + + /** + * Clears the error message from the message line if the error message is the error message from this field editor. + */ + @Override + protected void clearErrorMessage() { + if ( getPage() != null ) { + String message = getPage().getErrorMessage(); + if ( message != null ) { + if ( getErrorMessage().equals( message ) ) { + super.clearErrorMessage(); + } + } + else { + super.clearErrorMessage(); + } + } + } + } + + class BreakpointStringFieldEditor extends StringFieldEditor { + + public BreakpointStringFieldEditor( String name, String labelText, Composite parent ) { + super( name, labelText, parent ); + } + + /** + * @see StringFieldEditor#checkState() + */ + @Override + protected boolean checkState() { + Text control = getTextControl(); + if ( !control.isEnabled() ) { + clearErrorMessage(); + return true; + } + return super.checkState(); + } + + @Override + protected void doStore() { + Text text = getTextControl(); + if ( text.isEnabled() ) { + super.doStore(); + } + } + protected void doLoad() { + String value = getPreferenceStore().getString(getPreferenceName()); + setStringValue(value); + } + + /** + * @see FieldEditor#refreshValidState() + */ + @Override + protected void refreshValidState() { + super.refreshValidState(); + } + + /** + * Clears the error message from the message line if the error message is the error message from this field editor. + */ + @Override + protected void clearErrorMessage() { + if ( getPage() != null ) { + String message = getPage().getErrorMessage(); + if ( message != null ) { + if ( getErrorMessage().equals( message ) ) { + super.clearErrorMessage(); + } + } + else { + super.clearErrorMessage(); + } + } + } + } + + class LabelFieldEditor extends ReadOnlyFieldEditor { + private String fValue; + + public LabelFieldEditor( Composite parent, String title, String value ) { + super(title, title, parent); + fValue = value; + } + + @Override + protected void doLoad() { + if (textField != null) { + textField.setText(fValue); + } + } + @Override + protected void doLoadDefault() { + // nothing + } + + } + + private BooleanFieldEditor fEnabled; + + private BreakpointStringFieldEditor fCondition; + + private Text fIgnoreCountTextControl; + + private BreakpointIntegerFieldEditor fIgnoreCount; + + private IAdaptable fElement; + + /** + * The preference store used to interface between the breakpoint and the + * breakpoint preference page. This preference store is initialized only + * when the preference store cannot be retrieved from the preference + * dialog's element. + * @see #getPreferenceStore() + */ + private CBreakpointPreferenceStore fCBreakpointPreferenceStore; + + /** + * Constructor for CBreakpointPropertyPage. + * + * @param breakpoint + */ + public CBreakpointPropertyPage() { + super( GRID ); + noDefaultAndApplyButton(); +// Control control = getControl(); +// fCBreakpointPreferenceStore = new CBreakpointPreferenceStore(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors() + */ + @Override + protected void createFieldEditors() { + ICBreakpoint breakpoint = getBreakpoint(); + createMainLabel(breakpoint); + createContributedFieldEditors(breakpoint); + createTypeSpecificLabelFieldEditors( breakpoint ); + createEnabledField( getFieldEditorParent() ); + createConditionEditor( getFieldEditorParent() ); + createIgnoreCountEditor( getFieldEditorParent() ); + } + + private void createMainLabel(ICBreakpoint breakpoint) { + String label = getBreakpointMainLabel(breakpoint); + addField( createLabelEditor( + getFieldEditorParent(), + BreakpointsMessages.getString( "CBreakpointPropertyPage.breakpointType_label" ), //$NON-NLS-1$ + label) ); + } + + /** + * Method createTypeSpecificLabelFieldEditors. + * + * @param breakpoint + */ + private void createTypeSpecificLabelFieldEditors( ICBreakpoint breakpoint ) { + + if ( breakpoint instanceof ICFunctionBreakpoint ) { + createFunctionEditor(getFieldEditorParent()); + } + else if ( breakpoint instanceof ICAddressBreakpoint ) { + String title = BreakpointsMessages.getString( "CBreakpointPropertyPage.address_label" ); //$NON-NLS-1$ + + String address = getPreferenceStore().getString(ICLineBreakpoint.ADDRESS); + if (address == null || address.trim().length() == 0) { + address = BreakpointsMessages.getString( "CBreakpointPropertyPage.address_valueNotAvailable_label" ); //$NON-NLS-1$ + } + addField( createLabelEditor( getFieldEditorParent(), title, address ) ); + } + else if ( breakpoint instanceof ICWatchpoint ) { + IResource resource = getResource(); + if (resource != null) { + IProject project = resource.getProject(); + if ( project != null ) { + addField( createLabelEditor( getFieldEditorParent(), BreakpointsMessages.getString( "CBreakpointPropertyPage.project_label" ), project.getName() ) ); //$NON-NLS-1$ + } + } + String filename = getPreferenceStore().getString(ICBreakpoint.SOURCE_HANDLE); + if (filename != null && !"".equals(filename)) { //$NON-NLS-1$ + addField( createLabelEditor( getFieldEditorParent(), BreakpointsMessages.getString( "CBreakpointPropertyPage.sourceHandle_label" ), filename ) ); //$NON-NLS-1$ + } + createWatchExpressionEditor(getFieldEditorParent()); + createWatchTypeEditors(getFieldEditorParent()); + + } + else if ( breakpoint instanceof ILineBreakpoint ) { + String fileName = getPreferenceStore().getString(ICBreakpoint.SOURCE_HANDLE); + if ( fileName != null ) { + addField( createLabelEditor( getFieldEditorParent(), BreakpointsMessages.getString( "CBreakpointPropertyPage.sourceHandle_label" ), fileName ) ); //$NON-NLS-1$ + } + int lNumber = getPreferenceStore().getInt(IMarker.LINE_NUMBER); + if (lNumber > 0) { + getPreferenceStore().setValue( IMarker.LINE_NUMBER, lNumber); + createLineNumberEditor(getFieldEditorParent()); + } + } + } + + private String getBreakpointMainLabel(ICBreakpoint breakpoint) { + if (breakpoint instanceof ICWatchpoint && breakpoint.getMarker() != null) { + // For an existing breakpoint, calculate watchpoint label based + // on read/write type. + boolean isReadType = getPreferenceStore().getBoolean(ICWatchpoint.READ); + boolean isWriteType = getPreferenceStore().getBoolean(ICWatchpoint.WRITE); + if (isReadType && !isWriteType) { + return BreakpointsMessages.getString("CBreakpointPropertyPage.breakpointType_watchpoint_read_label"); //$NON-NLS-1$ + } else if (!isReadType && isWriteType) { + return BreakpointsMessages.getString("CBreakpointPropertyPage.breakpointType_watchpoint_label"); //$NON-NLS-1$ + } else { + return BreakpointsMessages.getString("CBreakpointPropertyPage.watchpointType_breakpointType_watchpoint_access_label"); //$NON-NLS-1$ + } + } + + IWorkbenchAdapter labelProvider = (IWorkbenchAdapter)getElement().getAdapter(IWorkbenchAdapter.class); + if (labelProvider != null) { + return labelProvider.getLabel(getElement()); + } + // default main label is the label of marker type for the breakpoint + return CDIDebugModel.calculateMarkerType(breakpoint); + } + + protected void createFunctionEditor( Composite parent ) { + + ICBreakpoint breakpoint = getBreakpoint(); + String title = BreakpointsMessages.getString("CBreakpointPropertyPage.function_label"); //$NON-NLS-1$ + if (breakpoint == null || breakpoint.getMarker() == null) { + BreakpointStringFieldEditor expressionEditor = new BreakpointStringFieldEditor( + ICLineBreakpoint.FUNCTION, title, parent); + expressionEditor.setErrorMessage(BreakpointsMessages.getString("CBreakpointPropertyPage.function_value_errorMessage")); //$NON-NLS-1$ + expressionEditor.setEmptyStringAllowed(false); + addField(expressionEditor); + } else { + String function = getPreferenceStore().getString(ICLineBreakpoint.FUNCTION); + if ( function == null ) { + function = BreakpointsMessages.getString( "CBreakpointPropertyPage.function_valueNotAvailable_label" ); //$NON-NLS-1$ + } + addField( createLabelEditor( getFieldEditorParent(), BreakpointsMessages.getString( "CBreakpointPropertyPage.function_label" ), function ) ); //$NON-NLS-1$ + } + } + + protected void createLineNumberEditor( Composite parent ) { + String title = BreakpointsMessages.getString( "CBreakpointPropertyPage.lineNumber_label" ); //$NON-NLS-1$ + BreakpointIntegerFieldEditor labelFieldEditor =new BreakpointIntegerFieldEditor( IMarker.LINE_NUMBER ,title, parent); + labelFieldEditor.setValidRange( 1, Integer.MAX_VALUE ); + addField( labelFieldEditor ); + } + + protected void createWatchExpressionEditor( Composite parent ) { + ICBreakpoint breakpoint = getBreakpoint(); + if (breakpoint == null || breakpoint.getMarker() == null) { + BreakpointStringFieldEditor expressionEditor =new BreakpointStringFieldEditor( + ICWatchpoint.EXPRESSION, + BreakpointsMessages.getString("CBreakpointPropertyPage.watchpoint_expression_label"), //$NON-NLS-1$ + parent); + expressionEditor.setErrorMessage(BreakpointsMessages.getString("CBreakpointPropertyPage.watchpoint_expression_errorMessage")); //$NON-NLS-1$ + expressionEditor.setEmptyStringAllowed(false); + addField(expressionEditor); + } else { + addField(createLabelEditor( + parent, + BreakpointsMessages.getString("CBreakpointPropertyPage.watchpoint_expression_label"), //$NON-NLS-1$ + getPreferenceStore().getString(ICWatchpoint.EXPRESSION) )); + } + } + + protected void createWatchTypeEditors( Composite parent ) { + // Edit read/write options only when creating the breakpoint. + ICBreakpoint breakpoint = getBreakpoint(); + if (breakpoint != null && breakpoint.getMarker() == null) { + addField( new BooleanFieldEditor( + ICWatchpoint.READ, + BreakpointsMessages.getString("CBreakpointPropertyPage.watchpointType_read_label"), //$NON-NLS-1$ + parent) ); + addField( new BooleanFieldEditor( + ICWatchpoint.WRITE, + BreakpointsMessages.getString("CBreakpointPropertyPage.watchpointType_write_label"), //$NON-NLS-1$ + parent) ); + } + } + + protected void createEnabledField( Composite parent ) { + fEnabled = new BooleanFieldEditor( ICBreakpoint.ENABLED, BreakpointsMessages.getString( "CBreakpointPropertyPage.enabled_label" ), parent ); //$NON-NLS-1$ + addField( fEnabled ); + } + + protected void createConditionEditor( Composite parent ) { + fCondition = new BreakpointStringFieldEditor( ICBreakpoint.CONDITION, BreakpointsMessages.getString( "CBreakpointPropertyPage.condition_label" ), parent ); //$NON-NLS-1$ + fCondition.setEmptyStringAllowed( true ); + fCondition.setErrorMessage( BreakpointsMessages.getString( "CBreakpointPropertyPage.condition_invalidValue_message" ) ); //$NON-NLS-1$ + addField( fCondition ); + } + + protected void createIgnoreCountEditor( Composite parent ) { + fIgnoreCount = new BreakpointIntegerFieldEditor( ICBreakpoint.IGNORE_COUNT, BreakpointsMessages.getString( "CBreakpointPropertyPage.ignoreCount_label" ), parent ); //$NON-NLS-1$ + fIgnoreCount.setValidRange( 0, Integer.MAX_VALUE ); + fIgnoreCountTextControl = fIgnoreCount.getTextControl( parent ); + fIgnoreCountTextControl.setEnabled( getPreferenceStore().getInt(ICBreakpoint.IGNORE_COUNT) >= 0 ); + addField( fIgnoreCount ); + } + + protected FieldEditor createLabelEditor( Composite parent, String title, String value ) { + return new LabelFieldEditor( parent, title, value ); + } + + protected ICBreakpoint getBreakpoint() { + IAdaptable element = getElement(); + if (element instanceof ICBreakpoint) { + return (ICBreakpoint)element; + } else if (element instanceof ICBreakpointContext) { + return ((ICBreakpointContext)element).getBreakpoint(); + } else { + return (ICBreakpoint)element.getAdapter(ICBreakpoint.class); + } + } + + protected IResource getResource() { + IAdaptable element = getElement(); + if (element instanceof ICBreakpoint) { + IMarker marker = ((ICBreakpoint)element).getMarker(); + if (marker != null) { + return marker.getResource(); + } + } else if (element instanceof ICBreakpointContext) { + return ((ICBreakpointContext)element).getResource(); + } + return null; + } + + public IPreferenceStore getPreferenceStore() { + IAdaptable element = getElement(); + if (element instanceof ICBreakpointContext) { + return ((ICBreakpointContext)element).getPreferenceStore(); + } + + if (fCBreakpointPreferenceStore == null) { + CBreakpointContext bpContext = element instanceof CBreakpointContext ? + (CBreakpointContext)element : null; + fCBreakpointPreferenceStore = new CBreakpointPreferenceStore(bpContext, null); + } + return fCBreakpointPreferenceStore; + } + + @Override + public boolean performCancel() { + IPreferenceStore store = getPreferenceStore(); + if (store instanceof CBreakpointPreferenceStore) { + ((CBreakpointPreferenceStore)store).setCanceled(true); + } + return super.performCancel(); + } + + @Override + public boolean performOk() { + IPreferenceStore store = getPreferenceStore(); + if (store instanceof CBreakpointPreferenceStore) { + ((CBreakpointPreferenceStore)store).setCanceled(false); + } + return super.performOk(); + } + + /* (non-Javadoc) + * @see org.eclipse.ui.IWorkbenchPropertyPage#getElement() + */ + @Override + public IAdaptable getElement() { + return fElement; + } + + /* (non-Javadoc) + * @see org.eclipse.ui.IWorkbenchPropertyPage#setElement(org.eclipse.core.runtime.IAdaptable) + */ + @Override + public void setElement( IAdaptable element ) { + fElement = element; + } + + /** + * Creates field editors contributed using breakpointUIContribution extension point + * @param breakpoint + */ + private void createContributedFieldEditors(ICBreakpoint breakpoint) { + Composite parent = getFieldEditorParent(); + try { + ICBreakpointsUIContribution[] cons; + CBreakpointUIContributionFactory factory = CBreakpointUIContributionFactory.getInstance(); + IPreferenceStore prefStore = getPreferenceStore(); + if (prefStore instanceof CBreakpointPreferenceStore) { + cons = factory.getBreakpointUIContributions( + breakpoint, ((CBreakpointPreferenceStore) prefStore).getAttributes()); + } else { + cons = factory.getBreakpointUIContributions(breakpoint); + } + + for (ICBreakpointsUIContribution con : cons) { + FieldEditor fieldEditor = con.getFieldEditor(con.getId(), con.getLabel()+":", parent); //$NON-NLS-1$ + if (fieldEditor != null) { + addField(fieldEditor); + } + } + } catch (CoreException ce) { + CDebugUIPlugin.log(ce); + } + + } + +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/CBreakpointUpdater.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointUpdater.java similarity index 97% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/CBreakpointUpdater.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointUpdater.java index 01556ead2e2..b555f52ce2f 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/CBreakpointUpdater.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointUpdater.java @@ -8,7 +8,7 @@ * Contributors: * QNX Software Systems - Initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui; +package org.eclipse.cdt.debug.internal.ui.breakpoints; import java.util.Map; import org.eclipse.cdt.debug.core.ICBreakpointListener; @@ -79,7 +79,7 @@ public class CBreakpointUpdater implements ICBreakpointListener { * org.eclipse.debug.core.model.IBreakpoint, java.util.Map) */ @Override - public void breakpointChanged( IDebugTarget target, final IBreakpoint breakpoint, final Map attributes ) { + public void breakpointChanged( IDebugTarget target, final IBreakpoint breakpoint, @SuppressWarnings("rawtypes") final Map attributes ) { asyncExec( new Runnable() { @Override diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/CBreakpointWorkbenchAdapterFactory.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointWorkbenchAdapterFactory.java similarity index 87% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/CBreakpointWorkbenchAdapterFactory.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointWorkbenchAdapterFactory.java index 38014d83d93..53812b2ee5a 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/CBreakpointWorkbenchAdapterFactory.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CBreakpointWorkbenchAdapterFactory.java @@ -8,11 +8,12 @@ * Contributors: * QNX Software Systems - Initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui; +package org.eclipse.cdt.debug.internal.ui.breakpoints; import org.eclipse.cdt.debug.core.model.ICBreakpoint; import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; import org.eclipse.cdt.debug.core.model.ICWatchpoint; +import org.eclipse.cdt.debug.internal.ui.CDebugUIMessages; import org.eclipse.core.runtime.IAdapterFactory; import org.eclipse.ui.model.IWorkbenchAdapter; import org.eclipse.ui.model.WorkbenchAdapter; @@ -26,7 +27,7 @@ public class CBreakpointWorkbenchAdapterFactory implements IAdapterFactory { * @see org.eclipse.core.runtime.IAdapterFactory#getAdapter(java.lang.Object, java.lang.Class) */ @Override - public Object getAdapter( Object adaptableObject, Class adapterType ) { + public Object getAdapter( Object adaptableObject, @SuppressWarnings("rawtypes") Class adapterType ) { if ( adapterType != IWorkbenchAdapter.class || !(adaptableObject instanceof ICBreakpoint) ) { return null; } @@ -48,7 +49,8 @@ public class CBreakpointWorkbenchAdapterFactory implements IAdapterFactory { /* (non-Javadoc) * @see org.eclipse.core.runtime.IAdapterFactory#getAdapterList() */ - @Override + @SuppressWarnings("rawtypes") + @Override public Class[] getAdapterList() { return new Class[] { IWorkbenchAdapter.class }; } diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CreateBreakpointTester.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CreateBreakpointTester.java new file mode 100644 index 00000000000..a2f1824acb8 --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/CreateBreakpointTester.java @@ -0,0 +1,43 @@ +/******************************************************************************* + * Copyright (c) 2012 Wind River Systems and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wind River Systems - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.debug.internal.ui.breakpoints; + +import org.eclipse.cdt.debug.ui.CDebugUIPlugin; +import org.eclipse.cdt.debug.ui.breakpoints.ICBreakpointContext; +import org.eclipse.core.expressions.PropertyTester; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; + +/** + * + */ +public class CreateBreakpointTester extends PropertyTester { + + private final static String PROP_CREATE_BREAKPOINT_ADAPT = "createBreakpointAdapt"; //$NON-NLS-1$ + + @Override + public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { + if (PROP_CREATE_BREAKPOINT_ADAPT.equals(property) && + receiver instanceof ICBreakpointContext && + expectedValue instanceof String) + { + try { + Class expectedClass = Class.forName((String)expectedValue); + return expectedClass.isAssignableFrom( + ((ICBreakpointContext)receiver).getBreakpoint().getClass()); + } catch (ClassNotFoundException e) { + CDebugUIPlugin.log(new Status(IStatus.ERROR, CDebugUIPlugin.PLUGIN_ID, "Unable to create class: " + expectedValue, e)); //$NON-NLS-1$ + } + } + return false; + } + +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/ThreadFilterEditor.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/ThreadFilterEditor.java similarity index 96% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/ThreadFilterEditor.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/ThreadFilterEditor.java index b02390ca10f..cb341c364b8 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/ThreadFilterEditor.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/ThreadFilterEditor.java @@ -8,7 +8,7 @@ * Contributors: * QNX Software Systems - Initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.propertypages; +package org.eclipse.cdt.debug.internal.ui.breakpoints; import java.util.ArrayList; import java.util.List; @@ -149,7 +149,7 @@ public class ThreadFilterEditor { } } if ( parent instanceof ILaunchManager ) { - List children = new ArrayList(); + List children = new ArrayList(); ILaunch[] launches = ((ILaunchManager)parent).getLaunches(); IDebugTarget[] targets; ICDebugTarget target; @@ -251,7 +251,7 @@ public class ThreadFilterEditor { private void createThreadViewer( Composite parent ) { Label label = new Label( parent, SWT.NONE ); - label.setText( PropertyPageMessages.getString( "ThreadFilterEditor.0" ) ); //$NON-NLS-1$ + label.setText( BreakpointsMessages.getString( "ThreadFilterEditor.0" ) ); //$NON-NLS-1$ label.setFont( parent.getFont() ); label.setLayoutData( new GridData() ); GridData data = new GridData( GridData.FILL_BOTH ); @@ -338,11 +338,11 @@ public class ThreadFilterEditor { private ICThread[] getTargetThreadFilters( ICDebugTarget target ) { Object[] threads = ((ITreeContentProvider)getThreadViewer().getContentProvider()).getChildren( target ); - ArrayList list = new ArrayList( threads.length ); + ArrayList list = new ArrayList( threads.length ); for ( int i = 0; i < threads.length; ++i ) { if ( getThreadViewer().getChecked( threads[i] ) ) - list.add( threads[i] ); + list.add( (ICThread)threads[i] ); } - return (ICThread[])list.toArray( new ICThread[list.size()] ); + return list.toArray( new ICThread[list.size()] ); } } diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/ToggleCBreakpointTester.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/ToggleCBreakpointTester.java similarity index 98% rename from debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/ToggleCBreakpointTester.java rename to debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/ToggleCBreakpointTester.java index 74cae165f56..d4b161db193 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/ToggleCBreakpointTester.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/breakpoints/ToggleCBreakpointTester.java @@ -9,7 +9,7 @@ * Patrick Chuong (Texas Instruments) - * Update CDT ToggleBreakpointTargetFactory enablement (340177) *****************************************************************/ -package org.eclipse.cdt.debug.internal.ui; +package org.eclipse.cdt.debug.internal.ui.breakpoints; import java.util.List; diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/dialogs/AddEventBreakpointDialog.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/dialogs/AddEventBreakpointDialog.java index a7760a44005..5be9925b9b4 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/dialogs/AddEventBreakpointDialog.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/dialogs/AddEventBreakpointDialog.java @@ -18,8 +18,7 @@ import java.util.Map; import org.eclipse.cdt.debug.core.CDIDebugModel; import org.eclipse.cdt.debug.core.model.ICBreakpointType; import org.eclipse.cdt.debug.core.model.ICEventBreakpoint; -import org.eclipse.cdt.debug.internal.core.breakpoints.CEventBreakpoint; -import org.eclipse.cdt.debug.internal.ui.propertypages.CBreakpointPreferenceStore; +import org.eclipse.cdt.debug.internal.ui.breakpoints.CBreakpointPreferenceStore; import org.eclipse.cdt.debug.ui.CDebugUIPlugin; import org.eclipse.cdt.debug.ui.breakpoints.CBreakpointUIContributionFactory; import org.eclipse.cdt.debug.ui.breakpoints.ICBreakpointsUIContribution; @@ -75,10 +74,10 @@ public class AddEventBreakpointDialog extends Dialog implements ModifyListener, protected void createFieldEditors() { Composite parent = getFieldEditorParent(); try { - Map map = new HashMap(); + Map map = new HashMap(); map.put(ICEventBreakpoint.EVENT_TYPE_ID, eventType); ICBreakpointsUIContribution cons[] = CBreakpointUIContributionFactory.getInstance() - .getBreakpointUIContributions(modelId, CEventBreakpoint.getMarkerType(), map); + .getBreakpointUIContributions(modelId, ICEventBreakpoint.C_EVENT_BREAKPOINT_MARKER, map); for (ICBreakpointsUIContribution con : cons) { if (con.getId().equals(ICEventBreakpoint.EVENT_TYPE_ID)) continue; @@ -116,7 +115,7 @@ public class AddEventBreakpointDialog extends Dialog implements ModifyListener, private void loadEventTypes() { ICBreakpointsUIContribution[] cons = factory.getBreakpointUIContributions(debugModelId, - CEventBreakpoint.getMarkerType(), null); + ICEventBreakpoint.C_EVENT_BREAKPOINT_MARKER, null); for (int i = 0; i < cons.length; i++) { ICBreakpointsUIContribution con = cons[i]; if (con.getId().equals(ICEventBreakpoint.EVENT_TYPE_ID)) { diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/disassembly/editor/DisassemblyEditor.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/disassembly/editor/DisassemblyEditor.java index 00f7a7e1d3d..bcc888c780d 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/disassembly/editor/DisassemblyEditor.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/disassembly/editor/DisassemblyEditor.java @@ -13,8 +13,8 @@ package org.eclipse.cdt.debug.internal.ui.disassembly.editor; import org.eclipse.cdt.debug.core.disassembly.IDisassemblyContextProvider; import org.eclipse.cdt.debug.internal.ui.IInternalCDebugUIConstants; -import org.eclipse.cdt.debug.internal.ui.actions.CBreakpointPropertiesRulerAction; -import org.eclipse.cdt.debug.internal.ui.actions.EnableDisableBreakpointRulerAction; +import org.eclipse.cdt.debug.internal.ui.actions.breakpoints.CBreakpointPropertiesRulerAction; +import org.eclipse.cdt.debug.internal.ui.actions.breakpoints.EnableDisableBreakpointRulerAction; import org.eclipse.cdt.debug.internal.ui.disassembly.viewer.DisassemblyDocumentProvider; import org.eclipse.cdt.debug.internal.ui.disassembly.viewer.DisassemblyPane; import org.eclipse.cdt.debug.internal.ui.disassembly.viewer.DocumentContentProvider; diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/CBreakpointPreferenceStore.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/CBreakpointPreferenceStore.java deleted file mode 100644 index e873bd5bde4..00000000000 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/CBreakpointPreferenceStore.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - Initial API and implementation - * QNX Software Systems - Refactored to use platform implementation - *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.propertypages; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceStore; - -/** - * A preference store that presents the state of the properties of a C/C++ breakpoint. - */ -public class CBreakpointPreferenceStore extends PreferenceStore implements IPreferenceStore { - - protected final static String ENABLED = "ENABLED"; //$NON-NLS-1$ - - protected final static String CONDITION = "CONDITION"; //$NON-NLS-1$ - - protected final static String IGNORE_COUNT = "IGNORE_COUNT"; //$NON-NLS-1$ - - protected final static String LINE = "LINE"; //$NON-NLS-1$ - - /** - * Constructor for CBreakpointPreferenceStore. - */ - public CBreakpointPreferenceStore() { - - } - - /** - * Override to not save. - * This store used for temporary breakpoint setting in dialogs - * and does not require permanent storage. - */ - @Override - public boolean needsSaving() { - return false; - } -} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/CBreakpointPropertyPage.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/CBreakpointPropertyPage.java deleted file mode 100644 index 006f98937e8..00000000000 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/CBreakpointPropertyPage.java +++ /dev/null @@ -1,525 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2008 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - Initial API and implementation - * Nokia - https://bugs.eclipse.org/bugs/show_bug.cgi?id=145606 - * QNX Software Systems - Catchpoints support https://bugs.eclipse.org/bugs/show_bug.cgi?id=226689 - *******************************************************************************/ -package org.eclipse.cdt.debug.internal.ui.propertypages; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.cdt.debug.core.model.ICAddressBreakpoint; -import org.eclipse.cdt.debug.core.model.ICBreakpoint; -import org.eclipse.cdt.debug.core.model.ICEventBreakpoint; -import org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint; -import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; -import org.eclipse.cdt.debug.core.model.ICLineBreakpoint2; -import org.eclipse.cdt.debug.core.model.ICWatchpoint; -import org.eclipse.cdt.debug.ui.CDebugUIPlugin; -import org.eclipse.cdt.debug.ui.breakpoints.CBreakpointUIContributionFactory; -import org.eclipse.cdt.debug.ui.breakpoints.ICBreakpointsUIContribution; -import org.eclipse.cdt.debug.ui.preferences.ReadOnlyFieldEditor; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspaceRunnable; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.debug.core.model.ILineBreakpoint; -import org.eclipse.jface.preference.BooleanFieldEditor; -import org.eclipse.jface.preference.FieldEditor; -import org.eclipse.jface.preference.FieldEditorPreferencePage; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.IntegerFieldEditor; -import org.eclipse.jface.preference.StringFieldEditor; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.IWorkbenchPropertyPage; - -/** - * The preference page used to present the properties of a breakpoint as preferences. A CBreakpointPreferenceStore is used to interface between this page and - * the breakpoint. - */ -public class CBreakpointPropertyPage extends FieldEditorPreferencePage implements IWorkbenchPropertyPage { - - class BreakpointIntegerFieldEditor extends IntegerFieldEditor { - - public BreakpointIntegerFieldEditor( String name, String labelText, Composite parent ) { - super( name, labelText, parent ); - setErrorMessage( PropertyPageMessages.getString( "CBreakpointPropertyPage.0" ) ); //$NON-NLS-1$ - } - - /** - * @see IntegerFieldEditor#checkState() - */ - @Override - protected boolean checkState() { - Text control = getTextControl(); - if ( !control.isEnabled() ) { - clearErrorMessage(); - return true; - } - return super.checkState(); - } - - /** - * Overrode here to be package visible. - */ - @Override - protected void refreshValidState() { - super.refreshValidState(); - } - - /** - * Only store if the text control is enabled - * - * @see FieldEditor#doStore() - */ - @Override - protected void doStore() { - Text text = getTextControl(); - if ( text.isEnabled() ) { - super.doStore(); - } - } - - /** - * Clears the error message from the message line if the error message is the error message from this field editor. - */ - @Override - protected void clearErrorMessage() { - if ( getPage() != null ) { - String message = getPage().getErrorMessage(); - if ( message != null ) { - if ( getErrorMessage().equals( message ) ) { - super.clearErrorMessage(); - } - } - else { - super.clearErrorMessage(); - } - } - } - } - - class BreakpointStringFieldEditor extends StringFieldEditor { - - public BreakpointStringFieldEditor( String name, String labelText, Composite parent ) { - super( name, labelText, parent ); - } - - /** - * @see StringFieldEditor#checkState() - */ - @Override - protected boolean checkState() { - Text control = getTextControl(); - if ( !control.isEnabled() ) { - clearErrorMessage(); - return true; - } - return super.checkState(); - } - - @Override - protected void doStore() { - Text text = getTextControl(); - if ( text.isEnabled() ) { - super.doStore(); - } - } - - /** - * @see FieldEditor#refreshValidState() - */ - @Override - protected void refreshValidState() { - super.refreshValidState(); - } - - /** - * Clears the error message from the message line if the error message is the error message from this field editor. - */ - @Override - protected void clearErrorMessage() { - if ( getPage() != null ) { - String message = getPage().getErrorMessage(); - if ( message != null ) { - if ( getErrorMessage().equals( message ) ) { - super.clearErrorMessage(); - } - } - else { - super.clearErrorMessage(); - } - } - } - } - - class LabelFieldEditor extends ReadOnlyFieldEditor { - private String fValue; - - public LabelFieldEditor( Composite parent, String title, String value ) { - super(title, title, parent); - fValue = value; - } - - @Override - protected void doLoad() { - if (textField != null) { - textField.setText(fValue); - } - } - @Override - protected void doLoadDefault() { - // nothing - } - - } - - private BooleanFieldEditor fEnabled; - - private BreakpointStringFieldEditor fCondition; - - private Text fIgnoreCountTextControl; - - private BreakpointIntegerFieldEditor fIgnoreCount; - - private IAdaptable fElement; - - /** - * The "fake" preference store used to interface between - * the breakpoint and the breakpoint preference page. - */ - private CBreakpointPreferenceStore fCBreakpointPreferenceStore; - - /** - * Constructor for CBreakpointPropertyPage. - * - * @param breakpoint - */ - public CBreakpointPropertyPage() { - super( GRID ); - noDefaultAndApplyButton(); - fCBreakpointPreferenceStore = new CBreakpointPreferenceStore(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors() - */ - @Override - protected void createFieldEditors() { - ICBreakpoint breakpoint = getBreakpoint(); - createMainLabel(breakpoint); - createContributetedFieldEditors(breakpoint); - createTypeSpecificLabelFieldEditors( breakpoint ); - createEnabledField( getFieldEditorParent() ); - IPreferenceStore store = getPreferenceStore(); - try { - String condition = breakpoint.getCondition(); - if ( condition == null ) { - condition = ""; //$NON-NLS-1$ - } - store.setValue( CBreakpointPreferenceStore.CONDITION, condition ); - createConditionEditor( getFieldEditorParent() ); - store.setValue( CBreakpointPreferenceStore.ENABLED, breakpoint.isEnabled() ); - int ignoreCount = breakpoint.getIgnoreCount(); - store.setValue( CBreakpointPreferenceStore.IGNORE_COUNT, (ignoreCount >= 0) ? ignoreCount : 0 ); - createIgnoreCountEditor( getFieldEditorParent() ); - } - catch( CoreException ce ) { - CDebugUIPlugin.log( ce ); - } - } - - private void createMainLabel(ICBreakpoint breakpoint) { - addField( createLabelEditor( getFieldEditorParent(), PropertyPageMessages.getString( "CBreakpointPropertyPage.18" ), //$NON-NLS-1$ - getBreakpointMainLabel(breakpoint) ) ); - } - - /** - * Method createTypeSpecificLabelFieldEditors. - * - * @param breakpoint - */ - private void createTypeSpecificLabelFieldEditors( ICBreakpoint breakpoint ) { - - if ( breakpoint instanceof ICFunctionBreakpoint ) { - ICFunctionBreakpoint fbrkpt = (ICFunctionBreakpoint)breakpoint; - String function = PropertyPageMessages.getString( "CBreakpointPropertyPage.1" ); //$NON-NLS-1$ - try { - function = fbrkpt.getFunction(); - } - catch( CoreException e ) { - } - catch( NumberFormatException e ) { - } - if ( function != null ) { - addField( createLabelEditor( getFieldEditorParent(), PropertyPageMessages.getString( "CBreakpointPropertyPage.2" ), function ) ); //$NON-NLS-1$ - } - } - else if ( breakpoint instanceof ICAddressBreakpoint ) { - ICAddressBreakpoint abrkpt = (ICAddressBreakpoint)breakpoint; - String address = PropertyPageMessages.getString( "CBreakpointPropertyPage.4" ); //$NON-NLS-1$ - try { - address = abrkpt.getAddress(); - } - catch( CoreException e ) { - } - if ( address != null ) { - addField( createLabelEditor( getFieldEditorParent(), PropertyPageMessages.getString( "CBreakpointPropertyPage.5" ), address ) ); //$NON-NLS-1$ - } - } - else if ( breakpoint instanceof ICWatchpoint ) { - ICWatchpoint watchpoint = (ICWatchpoint)breakpoint; - String expression = ""; //$NON-NLS-1$ - try { - expression = watchpoint.getExpression(); - } - catch( CoreException ce ) { - CDebugUIPlugin.log( ce ); - } - IProject project = breakpoint.getMarker().getResource().getProject(); - if ( project != null ) { - addField( createLabelEditor( getFieldEditorParent(), PropertyPageMessages.getString( "CBreakpointPropertyPage.10" ), project.getName() ) ); //$NON-NLS-1$ - } - IResource resource = breakpoint.getMarker().getResource(); - if ( resource instanceof IFile ) { - String filename = resource.getLocation().toOSString(); - if ( filename != null ) { - addField( createLabelEditor( getFieldEditorParent(), PropertyPageMessages.getString( "CBreakpointPropertyPage.20" ), filename ) ); //$NON-NLS-1$ - } - } - addField( createLabelEditor( getFieldEditorParent(), PropertyPageMessages.getString( "CBreakpointPropertyPage.14" ), expression ) ); //$NON-NLS-1$ - } - else if ( breakpoint instanceof ILineBreakpoint ) { - String fileName = null; - try { - fileName = breakpoint.getSourceHandle(); - } - catch( CoreException e ) { - } - if ( fileName != null ) { - addField( createLabelEditor( getFieldEditorParent(), PropertyPageMessages.getString( "CBreakpointPropertyPage.7" ), fileName ) ); //$NON-NLS-1$ - } - ILineBreakpoint lBreakpoint = (ILineBreakpoint) breakpoint; - - int lNumber = 0; - try { - lNumber = lBreakpoint.getLineNumber(); - } catch (CoreException e) { - CDebugUIPlugin.log(e); - } - - if (lNumber > 0) { - getPreferenceStore().setValue( CBreakpointPreferenceStore.LINE, lNumber); - createLineNumberEditor(getFieldEditorParent()); - } - } - } - - private String getBreakpointMainLabel(ICBreakpoint breakpoint) { - if (breakpoint instanceof ICFunctionBreakpoint) - return PropertyPageMessages.getString("CBreakpointPropertyPage.3"); //$NON-NLS-1$ - if (breakpoint instanceof ICAddressBreakpoint) - return PropertyPageMessages.getString("CBreakpointPropertyPage.4"); //$NON-NLS-1$ - if (breakpoint instanceof ICLineBreakpoint) - return PropertyPageMessages.getString("CBreakpointPropertyPage.8"); //$NON-NLS-1$ - if (breakpoint instanceof ICEventBreakpoint) - return PropertyPageMessages.getString("CBreakpointPropertyPage.21"); //$NON-NLS-1$ - if (breakpoint instanceof ICWatchpoint) { - ICWatchpoint watchpoint = (ICWatchpoint) breakpoint; - String type = ""; //$NON-NLS-1$ - try { - if (watchpoint.isReadType() && !watchpoint.isWriteType()) - type = PropertyPageMessages.getString("CBreakpointPropertyPage.11"); //$NON-NLS-1$ - else if (!watchpoint.isReadType() && watchpoint.isWriteType()) - type = PropertyPageMessages.getString("CBreakpointPropertyPage.12"); //$NON-NLS-1$ - else - type = PropertyPageMessages.getString("CBreakpointPropertyPage.13"); //$NON-NLS-1$ - - } catch (CoreException ce) { - CDebugUIPlugin.log(ce); - } - return type; - } - // default main label is the label of marker type for the breakpoint - String type = ""; //$NON-NLS-1$ - try { - type = breakpoint.getMarker().getType(); // TODO: how to get label? - } catch (CoreException ce) { - CDebugUIPlugin.log(ce); - } - return type; - } - protected void createLineNumberEditor( Composite parent ) { - String title = PropertyPageMessages.getString( "CBreakpointPropertyPage.9" ); //$NON-NLS-1$ - BreakpointIntegerFieldEditor labelFieldEditor =new BreakpointIntegerFieldEditor( CBreakpointPreferenceStore.LINE ,title, parent); - labelFieldEditor.setValidRange( 1, Integer.MAX_VALUE ); - addField( labelFieldEditor ); - } - - - protected void createEnabledField( Composite parent ) { - fEnabled = new BooleanFieldEditor( CBreakpointPreferenceStore.ENABLED, PropertyPageMessages.getString( "CBreakpointPropertyPage.19" ), parent ); //$NON-NLS-1$ - addField( fEnabled ); - } - - protected void createConditionEditor( Composite parent ) { - fCondition = new BreakpointStringFieldEditor( CBreakpointPreferenceStore.CONDITION, PropertyPageMessages.getString( "CBreakpointPropertyPage.15" ), parent ); //$NON-NLS-1$ - fCondition.setEmptyStringAllowed( true ); - fCondition.setErrorMessage( PropertyPageMessages.getString( "CBreakpointPropertyPage.16" ) ); //$NON-NLS-1$ - addField( fCondition ); - } - - protected void createIgnoreCountEditor( Composite parent ) { - fIgnoreCount = new BreakpointIntegerFieldEditor( CBreakpointPreferenceStore.IGNORE_COUNT, PropertyPageMessages.getString( "CBreakpointPropertyPage.17" ), parent ); //$NON-NLS-1$ - fIgnoreCount.setValidRange( 0, Integer.MAX_VALUE ); - fIgnoreCountTextControl = fIgnoreCount.getTextControl( parent ); - try { - fIgnoreCountTextControl.setEnabled( getBreakpoint().getIgnoreCount() >= 0 ); - } - catch( CoreException ce ) { - CDebugUIPlugin.log( ce ); - } - addField( fIgnoreCount ); - } - - protected FieldEditor createLabelEditor( Composite parent, String title, String value ) { - return new LabelFieldEditor( parent, title, value ); - } - - protected ICBreakpoint getBreakpoint() { - IAdaptable element = getElement(); - return ( element instanceof ICBreakpoint ) ? (ICBreakpoint)element : (ICBreakpoint)element.getAdapter(ICBreakpoint.class); - } - - /* (non-Javadoc) - * @see org.eclipse.ui.IWorkbenchPropertyPage#getElement() - */ - @Override - public IAdaptable getElement() { - return fElement; - } - - /* (non-Javadoc) - * @see org.eclipse.ui.IWorkbenchPropertyPage#setElement(org.eclipse.core.runtime.IAdaptable) - */ - @Override - public void setElement( IAdaptable element ) { - fElement = element; - } - - @Override - public IPreferenceStore getPreferenceStore() { - return fCBreakpointPreferenceStore; - } - - @Override - public boolean performOk() { - final List changedProperties = new ArrayList( 5 ); - getPreferenceStore().addPropertyChangeListener( new IPropertyChangeListener() { - - /** - * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) - */ - @Override - public void propertyChange( PropertyChangeEvent event ) { - changedProperties.add( event.getProperty() ); - } - } ); - boolean result = super.performOk(); - setBreakpointProperties( changedProperties ); - return result; - } - - protected void setBreakpointProperties( final List changedProperties ) { - IWorkspaceRunnable wr = new IWorkspaceRunnable() { - - @Override - public void run( IProgressMonitor monitor ) throws CoreException { - ICBreakpoint breakpoint = getBreakpoint(); - Iterator changed = changedProperties.iterator(); - while( changed.hasNext() ) { - String property = (String)changed.next(); - if ( property.equals( CBreakpointPreferenceStore.ENABLED ) ) { - breakpoint.setEnabled( getPreferenceStore().getBoolean( CBreakpointPreferenceStore.ENABLED ) ); - } - else if ( property.equals( CBreakpointPreferenceStore.IGNORE_COUNT ) ) { - breakpoint.setIgnoreCount( getPreferenceStore().getInt( CBreakpointPreferenceStore.IGNORE_COUNT ) ); - } - else if ( property.equals( CBreakpointPreferenceStore.CONDITION ) ) { - breakpoint.setCondition( getPreferenceStore().getString( CBreakpointPreferenceStore.CONDITION ) ); - } - else if ( property.equals( CBreakpointPreferenceStore.LINE ) ) { - // already workspace runnable, setting markers are safe - breakpoint.getMarker().setAttribute(IMarker.LINE_NUMBER, getPreferenceStore().getInt(CBreakpointPreferenceStore.LINE)); - breakpoint.getMarker().setAttribute(ICLineBreakpoint2.REQUESTED_LINE, getPreferenceStore().getInt(CBreakpointPreferenceStore.LINE)); - } else { - // this allow set attributes contributed by other plugins - String value = getPropertyAsString(property); - breakpoint.getMarker().setAttribute(property, value); - } - } - } - }; - try { - ResourcesPlugin.getWorkspace().run( wr, null ); - } - catch( CoreException ce ) { - CDebugUIPlugin.log( ce ); - } - } - - /** - * Creates field editors contributed using breakpointUIContribution extension point - * @param breakpoint - */ - private void createContributetedFieldEditors(ICBreakpoint breakpoint) { - Composite parent = getFieldEditorParent(); - try { - ICBreakpointsUIContribution cons[] = CBreakpointUIContributionFactory.getInstance() - .getBreakpointUIContributions(breakpoint); - for (ICBreakpointsUIContribution con : cons) { - - FieldEditor fieldEditor = con.getFieldEditor(con.getId(), con.getLabel()+":", parent); //$NON-NLS-1$ - if (fieldEditor != null) - addField(fieldEditor); - Object o = breakpoint.getMarker().getAttribute(con.getId()); - String value = o==null?"":o.toString(); //$NON-NLS-1$ - getPreferenceStore().setValue(con.getId(), value); - } - } catch (CoreException ce) { - CDebugUIPlugin.log(ce); - } - - } - - /** - * Return string value of given property or null. - */ - protected String getPropertyAsString(String property) { - // currently only supports String and Integer - IPreferenceStore store = getPreferenceStore(); - - if (store.contains(property)) { - String value = store.getString(property); - return value; - } else return null; - } -} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/PropertyPageMessages.properties b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/PropertyPageMessages.properties index 309d5581f45..4861ba4ac0d 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/PropertyPageMessages.properties +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/PropertyPageMessages.properties @@ -11,29 +11,6 @@ # IBM Corporation ############################################################################### -CBreakpointPropertyPage.0=Ignore count must be a nonnegative integer -CBreakpointPropertyPage.1=Not available -CBreakpointPropertyPage.2=Function name: -CBreakpointPropertyPage.3=C/C++ function breakpoint -CBreakpointPropertyPage.4=Not available -CBreakpointPropertyPage.5=Address: -CBreakpointPropertyPage.6=C/C++ address breakpoint -CBreakpointPropertyPage.7=File: -CBreakpointPropertyPage.8=C/C++ line breakpoint -CBreakpointPropertyPage.9=Line number: -CBreakpointPropertyPage.10=Project: -CBreakpointPropertyPage.11=C/C++ read watchpoint -CBreakpointPropertyPage.12=C/C++ watchpoint -CBreakpointPropertyPage.13=C/C++ access watchpoint -CBreakpointPropertyPage.14=Expression to watch: -CBreakpointPropertyPage.15=&Condition: -CBreakpointPropertyPage.16=Invalid condition. -CBreakpointPropertyPage.17=&Ignore count: -CBreakpointPropertyPage.18=Class: -CBreakpointPropertyPage.19=Enabled -CBreakpointPropertyPage.20=File: -CBreakpointPropertyPage.21=C/C++ Event Breakpoint -ThreadFilterEditor.0=&Restrict to Selected Targets and Threads: SignalPropertyPage.0=Description: {0}. SignalPropertyPage.1=Pass this signal to the program. SignalPropertyPage.2=Suspend the program when this signal happens. diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/CDebugUIPlugin.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/CDebugUIPlugin.java index bf211af2577..559574ece95 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/CDebugUIPlugin.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/CDebugUIPlugin.java @@ -17,7 +17,6 @@ import java.util.Map; import org.eclipse.cdt.debug.core.CDebugCorePlugin; import org.eclipse.cdt.debug.core.model.ICDebugElement; -import org.eclipse.cdt.debug.internal.ui.CBreakpointUpdater; import org.eclipse.cdt.debug.internal.ui.CDebugImageDescriptorRegistry; import org.eclipse.cdt.debug.internal.ui.CDebugModelPresentation; import org.eclipse.cdt.debug.internal.ui.CDebuggerPageAdapter; @@ -25,6 +24,7 @@ import org.eclipse.cdt.debug.internal.ui.CRegisterManagerProxies; import org.eclipse.cdt.debug.internal.ui.ColorManager; import org.eclipse.cdt.debug.internal.ui.EvaluationContextManager; import org.eclipse.cdt.debug.internal.ui.IInternalCDebugUIConstants; +import org.eclipse.cdt.debug.internal.ui.breakpoints.CBreakpointUpdater; import org.eclipse.cdt.debug.internal.ui.disassembly.dsf.DisassemblyBackendCdiFactory; import org.eclipse.cdt.debug.internal.ui.disassembly.editor.DisassemblyEditorManager; import org.eclipse.cdt.debug.internal.ui.pinclone.ViewIDCounterManager; diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/AbstractToggleBreakpointAdapter.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/AbstractToggleBreakpointAdapter.java new file mode 100644 index 00000000000..22dd8d73e79 --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/AbstractToggleBreakpointAdapter.java @@ -0,0 +1,752 @@ +/******************************************************************************* + * Copyright (c) 2011 Mentor Graphics and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Mentor Graphics - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.debug.ui.breakpoints; + +import java.util.Iterator; +import java.util.Map; + +import org.eclipse.cdt.core.model.CModelException; +import org.eclipse.cdt.core.model.CoreModel; +import org.eclipse.cdt.core.model.ICElement; +import org.eclipse.cdt.core.model.IDeclaration; +import org.eclipse.cdt.core.model.IFunction; +import org.eclipse.cdt.core.model.IFunctionDeclaration; +import org.eclipse.cdt.core.model.IMethod; +import org.eclipse.cdt.core.model.ISourceRange; +import org.eclipse.cdt.core.model.ITranslationUnit; +import org.eclipse.cdt.core.model.IVariable; +import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint; +import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; +import org.eclipse.cdt.debug.core.model.ICWatchpoint; +import org.eclipse.cdt.debug.internal.ui.CDebugUIUtils; +import org.eclipse.cdt.debug.internal.ui.IInternalCDebugUIConstants; +import org.eclipse.cdt.debug.internal.ui.actions.ActionMessages; +import org.eclipse.cdt.debug.internal.ui.actions.breakpoints.EnableDisableBreakpointRulerAction; +import org.eclipse.cdt.debug.internal.ui.breakpoints.CBreakpointContext; +import org.eclipse.cdt.debug.ui.CDebugUIPlugin; +import org.eclipse.cdt.internal.ui.util.ExternalEditorInput; +import org.eclipse.cdt.ui.CDTUITools; +import org.eclipse.core.filesystem.URIUtil; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.debug.core.DebugPlugin; +import org.eclipse.debug.core.model.IBreakpoint; +import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.debug.ui.actions.IToggleBreakpointsTargetExtension2; +import org.eclipse.jface.preference.PreferenceDialog; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.jface.text.source.IVerticalRulerInfo; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Event; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.dialogs.PreferencesUtil; +import org.eclipse.ui.editors.text.ILocationProvider; +import org.eclipse.ui.texteditor.IEditorStatusLine; +import org.eclipse.ui.texteditor.ITextEditor; +import org.eclipse.ui.texteditor.SimpleMarkerAnnotation; + +/** + * Base class for toggle adapter to create/remove CDT breakpoints. Clients may + * extend this class to gather additional data prior to creating the breakpoints. + * + * @since 7.2 + */ +abstract public class AbstractToggleBreakpointAdapter + implements IToggleBreakpointsTargetExtension2, IToggleBreakpointsTargetCExtension +{ + + + @Override + public boolean canToggleBreakpointsWithEvent(IWorkbenchPart part, ISelection selection, Event event) { + return canToggleBreakpoints(part, selection); + } + + @Override + public void toggleBreakpointsWithEvent(IWorkbenchPart part, ISelection selection, Event event) throws CoreException { + if(event != null && (event.stateMask & SWT.MOD2) > 0) { + if (toggleBreakpointEnable(part)) { + return; + } + } + else { + boolean interactive = event != null && (event.stateMask & SWT.MOD1) > 0; + updateBreakpoints(true, interactive, part, selection); + } + } + + @Override + public void toggleLineBreakpoints( IWorkbenchPart part, ISelection selection ) throws CoreException { + updateLineBreakpoints(true, false, part, selection); + } + + @Override + public boolean canToggleLineBreakpoints( IWorkbenchPart part, ISelection selection ) { + return (selection instanceof ITextSelection); + } + + @Override + public void toggleMethodBreakpoints( IWorkbenchPart part, ISelection selection ) throws CoreException { + ICElement element = getCElementFromSelection( part, selection ); + if ( element instanceof IFunction || element instanceof IMethod) { + updateMethodBreakpoints(true, false, part, (IDeclaration)element); + } + } + + @Override + public boolean canToggleMethodBreakpoints( IWorkbenchPart part, ISelection selection ) { + ICElement element = getCElementFromSelection( part, selection ); + return (element instanceof IFunction || element instanceof IMethod); + } + + @Override + public void toggleWatchpoints( IWorkbenchPart part, ISelection selection ) throws CoreException { + IVariable variable = getVariableFromSelection( part, selection ); + if ( variable != null ) { + updateVariableWatchpoint(true, false, part, variable); + } + } + + @Override + public boolean canToggleWatchpoints( IWorkbenchPart part, ISelection selection ) { + return getVariableFromSelection( part, selection ) != null; + } + + @Override + public boolean canToggleBreakpoints( IWorkbenchPart part, ISelection selection ) { + return ( canToggleLineBreakpoints( part, selection ) + || canToggleWatchpoints( part, selection ) + || canToggleMethodBreakpoints( part, selection ) ); + } + + @Override + public void toggleBreakpoints( IWorkbenchPart part, ISelection selection ) throws CoreException { + updateBreakpoints(true, false, part, selection); + } + + @Override + public boolean canCreateLineBreakpointsInteractive(IWorkbenchPart part, ISelection selection) { + return canToggleLineBreakpoints( part, selection ); + } + + @Override + public void createLineBreakpointsInteractive(IWorkbenchPart part, ISelection selection) throws CoreException { + updateLineBreakpoints(false, true, part, selection); + } + + @Override + public boolean canCreateWatchpointsInteractive(IWorkbenchPart part, ISelection selection) { + // Gather all input from user if needed. + return true; + } + + @Override + public void createWatchpointsInteractive(IWorkbenchPart part, ISelection selection) throws CoreException { + ICElement element = getCElementFromSelection( part, selection ); + if (element instanceof IVariable) { + updateVariableWatchpoint(false, true, part, (IVariable)element); + } else { + String text = ""; //$NON-NLS-1$ + if (selection instanceof ITextSelection) { + text = ((ITextSelection)selection).getText(); + } + createWatchpoint(true, part, null, ResourcesPlugin.getWorkspace().getRoot(), -1, -1, -1, text); + } + } + + @Override + public boolean canCreateFunctionBreakpointInteractive(IWorkbenchPart part, ISelection selection) { + return true; + } + + @Override + public void createFunctionBreakpointInteractive(IWorkbenchPart part, ISelection selection) throws CoreException { + ICElement element = getCElementFromSelection( part, selection ); + if ( element instanceof IFunction || element instanceof IMethod ) { + updateMethodBreakpoints(false, true, part, (IDeclaration)element); + } else { + String text = ""; //$NON-NLS-1$ + if (selection instanceof ITextSelection) { + text = ((ITextSelection)selection).getText(); + } + createFunctionBreakpoint(true, part, null, ResourcesPlugin.getWorkspace().getRoot(), text, -1, -1, -1); + } + } + + /** + * Updates the breakpoint for given part and selection. + * Depending on the flags and on whether a breakpoint exists, this method + * executes the toggle action. + * + * @param toggle Whether the toggle action is requested. If + * true and the breakpoint currently exists, it will cause the + * toggle action to either remove breakpoint or edit its properties. + * Otherwise a new breakpoint will be created. + * @param interactive If true the toggle adapter should open a dialog before + * creating a breakpoint, or open a properties dialog on an existing + * breakpoint. + * @param part Workbench part where the toggle action is to be executed. + * @param selection Current selection on which the toggle action is to be + * executed. + * @throws CoreException Any error in creating or editing the breakpoint. + */ + private void updateBreakpoints(boolean toggle, boolean interactive, IWorkbenchPart part, ISelection selection ) throws CoreException { + if ( canToggleLineBreakpoints( part, selection ) ) { + updateLineBreakpoints(toggle, interactive, part, selection); + } + else { + ICElement element = getCElementFromSelection( part, selection ); + if ( element instanceof IFunction || element instanceof IMethod ) { + updateMethodBreakpoints(toggle, interactive, part, (IDeclaration)element); + } + else if ( element instanceof IVariable ) { + updateVariableWatchpoint(toggle, interactive, part, (IVariable)element); + } + } + } + + private void updateLineBreakpoints(boolean toggle, boolean interactive, IWorkbenchPart part, ISelection selection) + throws CoreException { + String errorMessage = null; + if (part instanceof ITextEditor) { + ITextEditor textEditor = (ITextEditor) part; + IEditorInput input = textEditor.getEditorInput(); + if (input == null) { + errorMessage = ActionMessages.getString("ToggleBreakpointAdapter.Empty_editor_1"); //$NON-NLS-1$ + } else { + IDocument document = textEditor.getDocumentProvider().getDocument(input); + if (document == null) { + errorMessage = ActionMessages.getString("ToggleBreakpointAdapter.Missing_document_1"); //$NON-NLS-1$ + } else { + IResource resource = getResource(textEditor); + if (resource == null) { + errorMessage = ActionMessages.getString("ToggleBreakpointAdapter.Missing_resource_1"); //$NON-NLS-1$ + } else { + int lineNumber = ((ITextSelection) selection).getStartLine() + 1; + if (lineNumber == -1) { + errorMessage = ActionMessages.getString("ToggleBreakpointAdapter.Invalid_line_1"); //$NON-NLS-1$ + } else { + String sourceHandle = getSourceHandle(input); + if (interactive && !toggle) { + createLineBreakpoint(true, part, sourceHandle, resource, lineNumber); + } else { + ICLineBreakpoint breakpoint = findLineBreakpoint(sourceHandle, resource, lineNumber); + if (breakpoint != null) { + if (interactive) { + CDebugUIUtils.editBreakpointProperties(part, breakpoint); + } else { + DebugPlugin.getDefault().getBreakpointManager() + .removeBreakpoint(breakpoint, true); + } + } else { + createLineBreakpoint(interactive, part, sourceHandle, resource, lineNumber); + } + } + return; + } + } + } + } + } else { + errorMessage = ActionMessages.getString("RunToLineAdapter.Operation_is_not_supported_1"); //$NON-NLS-1$ + } + throw new CoreException(new Status(IStatus.ERROR, CDebugUIPlugin.getUniqueIdentifier(), + IInternalCDebugUIConstants.INTERNAL_ERROR, errorMessage, null)); + } + + private void updateMethodBreakpoints(boolean toggle, boolean interactive, IWorkbenchPart part, + IDeclaration declaration) throws CoreException { + String sourceHandle = getSourceHandle(declaration); + IResource resource = getElementResource(declaration); + String functionName = (declaration instanceof IFunction) ? getFunctionName((IFunction) declaration) + : getMethodName((IMethod) declaration); + ICFunctionBreakpoint breakpoint = findFunctionBreakpoint(sourceHandle, resource, functionName); + if (toggle && breakpoint != null) { + if (interactive) { + CDebugUIUtils.editBreakpointProperties(part, breakpoint); + } else { + DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(breakpoint, true); + } + } else { + int lineNumber = -1; + int charStart = -1; + int charEnd = -1; + try { + ISourceRange sourceRange = declaration.getSourceRange(); + if (sourceRange != null) { + charStart = sourceRange.getStartPos(); + charEnd = charStart + sourceRange.getLength(); + if (charEnd <= 0) { + charStart = -1; + charEnd = -1; + } + lineNumber = sourceRange.getStartLine(); + } + } catch (CModelException e) { + DebugPlugin.log(e); + } + createFunctionBreakpoint(interactive, part, sourceHandle, resource, functionName, charStart, charEnd, + lineNumber); + } + } + + /** + * Updates a watchpoint. Depending on the flags and on whether a breakpoint + * exists, this method executes the toggle action. + * + * @param toggle + * Whether the toggle action is requested. If true and the + * breakpoint currently exists, it will cause the toggle action + * to either remove breakpoint or edit its properties. Otherwise + * a new breakpoint will be created. + * @param interactive + * If true the toggle adapter should open a dialog before + * creating a breakpoint, or open a properties dialog on an + * existing breakpoint. + * @param part + * Workbench part where the toggle action is to be executed. + * @param selection + * Variable on which to execute the toggle action. + * @throws CoreException + * Any error in creating or editing the breakpoint. + */ + private void updateVariableWatchpoint(boolean toggle, boolean interactive, IWorkbenchPart part, IVariable variable) + throws CoreException { + String sourceHandle = getSourceHandle(variable); + IResource resource = getElementResource(variable); + String expression = getVariableName(variable); + ICWatchpoint watchpoint = findWatchpoint(sourceHandle, resource, expression); + if (toggle && watchpoint != null) { + if (interactive) { + CDebugUIUtils.editBreakpointProperties(part, watchpoint); + } else { + DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(watchpoint, true); + } + } else { + int lineNumber = -1; + int charStart = -1; + int charEnd = -1; + try { + ISourceRange sourceRange = variable.getSourceRange(); + if (sourceRange != null) { + charStart = sourceRange.getStartPos(); + charEnd = charStart + sourceRange.getLength(); + if (charEnd <= 0) { + charStart = -1; + charEnd = -1; + } + lineNumber = sourceRange.getStartLine(); + } + } catch (CModelException e) { + CDebugUIPlugin.log(e); + } + createWatchpoint(interactive, part, sourceHandle, resource, charStart, charEnd, lineNumber, expression); + } + } + + /** + * Returns the C model element at the given selection. + * @param part Workbench part where the selection is. + * @param selection Selection in part. + * @return C model element if found. + */ + protected ICElement getCElementFromSelection( IWorkbenchPart part, ISelection selection ) { + if ( selection instanceof ITextSelection ) { + ITextSelection textSelection = (ITextSelection)selection; + String text = textSelection.getText(); + if ( text != null ) { + if ( part instanceof ITextEditor ) { + ICElement editorElement = CDTUITools.getEditorInputCElement( ((ITextEditor)part).getEditorInput() ); + if ( editorElement instanceof ITranslationUnit ) { + ITranslationUnit tu = (ITranslationUnit)editorElement; + try { + if ( tu.isStructureKnown() && tu.isConsistent() ) { + return tu.getElementAtOffset( textSelection.getOffset() ); + } + } + catch( CModelException exc ) { + // ignored on purpose + } + } + } + else { + IResource resource = getResource( part ); + if ( resource instanceof IFile ) { + ITranslationUnit tu = getTranslationUnit( (IFile)resource ); + if ( tu != null ) { + try { + ICElement element = tu.getElement( text.trim() ); + if ( element == null ) { + element = tu.getElementAtLine( textSelection.getStartLine() ); + } + return element; + } + catch( CModelException e ) { + } + } + } + } + } + } + else if ( selection instanceof IStructuredSelection ) { + IStructuredSelection ss = (IStructuredSelection)selection; + if ( ss.size() == 1 ) { + Object object = ss.getFirstElement(); + if ( object instanceof ICElement ) { + return (ICElement)object; + } + } + } + return null; + } + + /** + * Returns the variable object at the given selection. + * Returns the C model element at the given selection. + * @param part Workbench part where the selection is. + * @param selection Selection in part. + * @return C model variable, if found. + */ + protected IVariable getVariableFromSelection( IWorkbenchPart part, ISelection selection ) { + ICElement element = getCElementFromSelection( part, selection ); + if ( element instanceof IVariable ) { + return (IVariable)element; + } + return null; + } + + /** + * Reports the given error message to the user. + * @param message Message to report. + * @param part Workbench part where action was invoked. + */ + protected void report( String message, IWorkbenchPart part ) { + IEditorStatusLine statusLine = (IEditorStatusLine)part.getAdapter( IEditorStatusLine.class ); + if ( statusLine != null ) { + if ( message != null ) { + statusLine.setMessage( true, message, null ); + } + else { + statusLine.setMessage( true, null, null ); + } + } + if ( message != null && CDebugUIPlugin.getActiveWorkbenchShell() != null ) { + CDebugUIPlugin.getActiveWorkbenchShell().getDisplay().beep(); + } + } + + /** + * Returns the resource being edited in the given workbench part. + * @param part Workbench part to checm. + * @return Resource being edited. + */ + protected static IResource getResource( IWorkbenchPart part ) { + IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); + if ( part instanceof IEditorPart ) { + IEditorInput editorInput = ((IEditorPart)part).getEditorInput(); + IResource resource = null; + if ( editorInput instanceof IFileEditorInput ) { + resource = ((IFileEditorInput)editorInput).getFile(); + } + else if ( editorInput instanceof ExternalEditorInput ) { + resource = ((ExternalEditorInput)editorInput).getMarkerResource(); + } + if ( resource != null ) + return resource; + /* This file is not in a project, let default case handle it */ + ILocationProvider provider = (ILocationProvider)editorInput.getAdapter( ILocationProvider.class ); + if ( provider != null ) { + IPath location = provider.getPath( editorInput ); + if ( location != null ) { + IFile[] files = root.findFilesForLocationURI( URIUtil.toURI( location ) ); + if ( files.length > 0 && files[0].isAccessible()) + return files[0]; + } + } + } + return root; + } + + private String getSourceHandle( IEditorInput input ) throws CoreException { + return CDebugUIUtils.getEditorFilePath( input ); + } + + protected String getSourceHandle( IDeclaration declaration ) { + ITranslationUnit tu = declaration.getTranslationUnit(); + if ( tu != null ) { + IPath location = tu.getLocation(); + if ( location != null ) { + return location.toOSString(); + } + } + return ""; //$NON-NLS-1$ + } + + protected IResource getElementResource( IDeclaration declaration ) { + return declaration.getUnderlyingResource(); + } + + private String getFunctionName( IFunction function ) { + String functionName = function.getElementName(); + StringBuffer name = new StringBuffer( functionName ); + ITranslationUnit tu = function.getTranslationUnit(); + if ( tu != null && tu.isCXXLanguage() ) { + appendParameters( name, function ); + } + return name.toString(); + } + + private String getMethodName( IMethod method ) { + StringBuffer name = new StringBuffer(); + String methodName = method.getElementName(); + ICElement parent = method.getParent(); + while( parent != null + && (parent.getElementType() == ICElement.C_NAMESPACE || parent.getElementType() == ICElement.C_CLASS + || parent.getElementType() == ICElement.C_STRUCT || parent.getElementType() == ICElement.C_UNION) ) { + name.append( parent.getElementName() ).append( "::" ); //$NON-NLS-1$ + parent = parent.getParent(); + } + name.append( methodName ); + appendParameters( name, method ); + return name.toString(); + } + + private void appendParameters( StringBuffer sb, IFunctionDeclaration fd ) { + String[] params = fd.getParameterTypes(); + sb.append( '(' ); + for( int i = 0; i < params.length; ++i ) { + sb.append( params[i] ); + if ( i != params.length - 1 ) + sb.append( ',' ); + } + sb.append( ')' ); + } + + private String getVariableName( IVariable variable ) { + return variable.getElementName(); + } + + private ITranslationUnit getTranslationUnit( IFile file ) { + Object element = CoreModel.getDefault().create( file ); + if ( element instanceof ITranslationUnit ) { + return (ITranslationUnit)element; + } + return null; + } + + private boolean toggleBreakpointEnable(IWorkbenchPart part) { + ITextEditor textEditor = getTextEditor(part); + if(textEditor != null) { + IVerticalRulerInfo info = (IVerticalRulerInfo) textEditor.getAdapter(IVerticalRulerInfo.class); + if(info != null) { + EnableDisableBreakpointRulerAction enableAction = new EnableDisableBreakpointRulerAction(part, info); + enableAction.update(); + enableAction.run(); + } + } + return false; + } + + /** + * Returns the text editor associated with the given part or null + * if none. In case of a multi-page editor, this method should be used to retrieve + * the correct editor to perform the breakpoint operation on. + * + * @param part workbench part + * @return text editor part or null + */ + protected ITextEditor getTextEditor(IWorkbenchPart part) { + if (part instanceof ITextEditor) { + return (ITextEditor) part; + } + return (ITextEditor) part.getAdapter(ITextEditor.class); + } + + /** + * Resolves the {@link IBreakpoint} from the given editor and ruler information. Returns null + * if no breakpoint exists or the operation fails. + * + * @param editor the editor + * @param info the current ruler information + * @return the {@link IBreakpoint} from the current editor position or null + */ + protected IBreakpoint getBreakpointFromEditor(ITextEditor editor, IVerticalRulerInfo info) { + IAnnotationModel annotationModel = editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput()); + IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); + if (annotationModel != null) { + @SuppressWarnings("unchecked") + Iterator iterator = annotationModel.getAnnotationIterator(); + while (iterator.hasNext()) { + Object object = iterator.next(); + 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 line = document.getLineOfOffset(position.getOffset()); + if (line == info.getLineOfLastMouseButtonActivity()) { + IBreakpoint breakpoint = DebugPlugin.getDefault().getBreakpointManager().getBreakpoint(marker); + if (breakpoint != null) { + return breakpoint; + } + } + } + } catch (CoreException e) { + } catch (BadLocationException e) { + } + } + } + } + return null; + } + + /** + * 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 + * null. + */ + protected void openBreakpointPropertiesDialog(ICBreakpoint bp, IWorkbenchPart part, IResource resource, + Map 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(); + } + } + + /** + * Finds the line breakpoint at the given location. + * + * @param sourceHandle + * Source handle for the line breakpoint. + * @param resource + * Resource of the line breakpoint. + * @param lineNumber + * Line number. + * @return Line breakpoint with given parameters, if found. + * @throws CoreException + * Exception thrown while reading breakpoints' properties. + */ + protected abstract ICLineBreakpoint findLineBreakpoint(String sourceHandle, IResource resource, int lineNumber) + throws CoreException; + + /** + * Creates a line breakpoint at the given location. + * @param interactive true if action should open a dialog to let user edit + * breakpoint properties prior to creation. + * @param part Workbench part where action was invoked. + * @param source Handle Source handle for the new breakpoint. + * @param resource Resource to create breakpoint on. + * @param lineNumber Line number for new breakpoint. + * @throws CoreException Exception while creating breakpoint. + */ + protected abstract void createLineBreakpoint(boolean interactive, IWorkbenchPart part, String sourceHandle, + IResource resource, int lineNumber) throws CoreException; + + /** + * Finds the function breakpoint at the given location. + * + * @param sourceHandle + * Source handle for the line breakpoint. + * @param resource + * Resource of the line breakpoint. + * @param functionName + * Function for the breakpoint. + * @return Function breakpoint with given parameters, if found. + * @throws CoreException + * Exception thrown while reading breakpoints' properties. + */ + protected abstract ICFunctionBreakpoint findFunctionBreakpoint(String sourceHandle, IResource resource, + String functionName) throws CoreException; + + /** + * Creates a function breakpoint at the given location. + * @param interactive true if action should open a dialog to let user edit + * breakpoint properties prior to creation. + * @param part Workbench part where action was invoked. + * @param source Handle Source handle for the new breakpoint. + * @param resource Resource to create breakpoint on. + * @param charStart Beginning of range where function is located. Can be + * -1 if not known. + * @param charStart End of range where function is located. Can be + * -1 if not known. + * @param lineNumber Line number where the function is located. + * @throws CoreException Exception while creating breakpoint. + */ + protected abstract void createFunctionBreakpoint(boolean interactive, IWorkbenchPart part, String sourceHandle, + IResource resource, String functionName, int charStart, int charEnd, int lineNumber) throws CoreException; + + /** + * Finds the watchpoint with given expression. + * + * @param sourceHandle Source handle for the line breakpoint. + * @param resource Resource of the line breakpoint. + * @param expression Expression of the breakpoint. + * @return Watchpoing with given parameters, if found. + * @throws CoreException Exception thrown while reading breakpoints' + */ + protected abstract ICWatchpoint findWatchpoint( String sourceHandle, IResource resource, String expression ) + throws CoreException; + + /** + * Creates a watchpoint at the given location. + * @param interactive true if action should open a dialog to let user edit + * breakpoint properties prior to creation. + * @param part Workbench part where action was invoked. + * @param source Handle Source handle for the new breakpoint. + * @param resource Resource to create breakpoint on. + * @param charStart Beginning of range where variable is located. Can be + * -1 if not known. + * @param charStart End of range where variable is located. Can be + * -1 if not known. + * @param lineNumber Line number where the variable is located. + * @throws CoreException Exception while creating breakpoint. + */ + protected abstract void createWatchpoint(boolean interactive, IWorkbenchPart part, String sourceHandle, + IResource resource, int charStart, int charEnd, int lineNumber, String expression) throws CoreException; + +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/CBreakpointPropertyDialogAction.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/CBreakpointPropertyDialogAction.java new file mode 100644 index 00000000000..16883079cf1 --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/CBreakpointPropertyDialogAction.java @@ -0,0 +1,182 @@ +/******************************************************************************* + * Copyright (c) 2012 Wind River Systems and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wind River Systems - Initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.debug.ui.breakpoints; + +import java.util.Iterator; + +import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.cdt.debug.internal.ui.breakpoints.CBreakpointContext; +import org.eclipse.core.runtime.Assert; +import org.eclipse.debug.ui.contexts.IDebugContextProvider; +import org.eclipse.jface.preference.PreferenceDialog; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.window.IShellProvider; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.actions.SelectionProviderAction; +import org.eclipse.ui.dialogs.PreferencesUtil; +import org.eclipse.ui.internal.IWorkbenchHelpContextIds; +import org.eclipse.ui.internal.WorkbenchMessages; + +/** + * Action for opening a Property Pages Dialog on the C breakpoint object + * in the currently selected element. + *

+ * Generally speaking, this action is useful in pop-up menus because it allows + * the user to browse and change properties of selected elements. When + * performed, the action will bring up a Property Pages Dialog containing + * property pages registered with the workbench for elements of the selected + * type. + *

+ *

+ * Although the action is capable of calculating if there are any applicable + * pages for the current selection, this calculation is costly because it + * require searching the workbench registry. Where performance is critical, the + * action can simply be added to the pop-up menu. In the event of no applicable + * pages, the action will just open an appropriate message dialog. + *

+ * @noextend This class is not intended to be subclassed by clients. + * @since 7.2 + */ +public class CBreakpointPropertyDialogAction extends SelectionProviderAction { + + /** + * Provides the shell in which to open the property dialog. + */ + private IShellProvider fShellProvider; + + private IDebugContextProvider fDebugContextProvider; + + /** + * The id of the page to open up on. + */ + private String fInitialPageId = "org.eclipse.cdt.debug.ui.propertypages.breakpoint.common"; //$NON-NLS-1$ + + public CBreakpointPropertyDialogAction(IShellProvider shell, ISelectionProvider selectionProvider, IDebugContextProvider debugContextProvider) { + super(selectionProvider, WorkbenchMessages.PropertyDialog_text); + Assert.isNotNull(shell); + fDebugContextProvider = debugContextProvider; + fShellProvider = shell; + setToolTipText(WorkbenchMessages.PropertyDialog_toolTip); + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, + IWorkbenchHelpContextIds.PROPERTY_DIALOG_ACTION); + } + + protected ISelection getDebugContext() { + return fDebugContextProvider.getActiveContext(); + } + + /** + * Returns whether this action is actually applicable to the current + * selection. If this action is disabled, it will return false + * without further calculation. If it is enabled, it will check with the + * workbench's property page manager to see if there are any property pages + * registered for the selected element's type. + *

+ * This method is generally too expensive to use when updating the enabled + * state of the action on each selection change. + *

+ * + * @return true if the selection is not empty and there are + * property pages for the selected element, and false + * otherwise + */ + public boolean isCBreakpointSelection() { + if (!isEnabled()) { + return false; + } + return isApplicableForSelection(getStructuredSelection(), getDebugContext()); + } + + /** + * Returns whether this action is applicable to the current selection. This + * checks that the selection is not empty, and checks with the workbench's + * property page manager to see if there are any property pages registered + * for the selected element's type. + *

+ * This method is generally too expensive to use when updating the enabled + * state of the action on each selection change. + *

+ * + * @param selection + * The selection to test + * @return true if the selection is of not empty and there are + * property pages for the selected element, and false + * otherwise + */ + public boolean isApplicableForSelection(IStructuredSelection selection, ISelection debugContext) { + return isCBreakpointSelection(selection); + } + + /** + * Returns whether the given selection contains only elements of type ICBreakpoint + * @param selection + * @return + */ + private boolean isCBreakpointSelection(IStructuredSelection selection) { + if (selection.isEmpty()) return false; + + for (Iterator itr = selection.iterator(); itr.hasNext();) { + if ( !(itr.next() instanceof ICBreakpoint) ) { + return false; + } + } + return true; + } + + + /* (non-Javadoc) + * @see org.eclipse.jface.action.IAction#run() + */ + public void run() { + CBreakpointContext bpContext = getCBreakpointContext(); + if (bpContext != null) { + PreferenceDialog dialog = createDialog(bpContext); + + if (dialog != null) { + dialog.open(); + } + } + } + + private CBreakpointContext getCBreakpointContext() { + IStructuredSelection ss = getStructuredSelection(); + if (ss.size() >= 1 && ss.getFirstElement() instanceof ICBreakpoint) { + return new CBreakpointContext((ICBreakpoint)ss.getFirstElement(), fDebugContextProvider.getActiveContext()); + } + return null; + } + + /** + * Create the dialog for the receiver. If no pages are found, an informative + * message dialog is presented instead. + * + * @return PreferenceDialog or null if no applicable pages + * are found. + */ + protected PreferenceDialog createDialog(CBreakpointContext bpContext) { + IStructuredSelection ss = getStructuredSelection(); + if (ss.isEmpty()) + return null; + + return PreferencesUtil.createPropertyDialogOn(fShellProvider.getShell(), bpContext, fInitialPageId, null, null); + } + + + /* (non-Javadoc) + * @see org.eclipse.ui.actions.SelectionProviderAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection) + */ + public void selectionChanged(IStructuredSelection selection) { + setEnabled(!selection.isEmpty()); + } + +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/CBreakpointUIContributionFactory.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/CBreakpointUIContributionFactory.java index fb5ad942b0a..9631e55c387 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/CBreakpointUIContributionFactory.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/CBreakpointUIContributionFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008 QNX Software Systems and others. + * Copyright (c) 2008, 2012 QNX Software Systems and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -13,8 +13,10 @@ package org.eclipse.cdt.debug.ui.breakpoints; import java.util.ArrayList; +import java.util.Collections; import java.util.Map; +import org.eclipse.cdt.debug.core.CDIDebugModel; import org.eclipse.cdt.debug.ui.CDebugUIPlugin; import org.eclipse.core.internal.resources.Workspace; import org.eclipse.core.resources.IMarker; @@ -40,23 +42,60 @@ public class CBreakpointUIContributionFactory { } /** + * Calculates the breakpoint contributions for the given breakpoint. * - * @param breakpoint + * @param breakpoint Breakpoint to find UI contributions for. * @return non-null array of ICBreakpointsUIContribution - * @throws CoreException - * @throws CoreException if cannot get marker attributes from berakpoint + * @throws CoreException if cannot get marker attributes from bearkpoint */ - public ICBreakpointsUIContribution[] getBreakpointUIContributions(IBreakpoint breakpoint) throws CoreException { String debugModelId = breakpoint.getModelIdentifier(); IMarker bmarker = breakpoint.getMarker(); - Map attributes = bmarker.getAttributes(); - String markerType = bmarker.getType(); + Map attributes = Collections.emptyMap(); + String markerType = CDIDebugModel.calculateMarkerType(breakpoint); + if (bmarker != null) { + Map _attributes = bmarker.getAttributes(); + attributes = _attributes; + markerType = bmarker.getType(); + } return getBreakpointUIContributions(debugModelId, markerType, attributes); } + /** + * Calculates the breakpoint contributions for the given breakpoint. + * + * @param breakpoint Breakpoint to find UI contributions for. + * @param attributes Attributes of the breakpoint + * @return non-null array of ICBreakpointsUIContribution + * @throws CoreException if cannot get marker attributes from bearkpoint + * @since 7.2 + */ + public ICBreakpointsUIContribution[] getBreakpointUIContributions(IBreakpoint breakpoint, + Map attributes) + throws CoreException + { + String debugModelId = breakpoint.getModelIdentifier(); + IMarker bmarker = breakpoint.getMarker(); + String markerType = CDIDebugModel.calculateMarkerType(breakpoint); + if (bmarker != null) { + markerType = bmarker.getType(); + } + return getBreakpointUIContributions(debugModelId, markerType, attributes); + } + + /** + * Calculates the breakpoint UI contributions for the given breakpoint. + * + * @param breakpoint Breakpoint to find UI contributions for. + * @param markerType Marker type of the breakpoint. + * @param attributes Attributes of the breakpoint + * @return non-null array of ICBreakpointsUIContribution + * @throws CoreException + * @throws CoreException if cannot get marker attributes from berakpoint + */ public ICBreakpointsUIContribution[] getBreakpointUIContributions(String debugModelId, String markerType, - Map attributes) { + Map attributes) + { ArrayList list = new ArrayList(); for (ICBreakpointsUIContribution con : contributions) { try { @@ -185,9 +224,9 @@ public class CBreakpointUIContributionFactory { String elementValue = configurationElement.getAttribute(name); if (elementValue == null) CDebugUIPlugin.log(new Status(IStatus.ERROR, CDebugUIPlugin.getUniqueIdentifier(), - DebugPlugin.INTERNAL_ERROR, "Extension " + DebugPlugin.INTERNAL_ERROR, "Extension " //$NON-NLS-1$ + configurationElement.getDeclaringExtension().getUniqueIdentifier() - + " missing required attribute: " + name, null)); + + " missing required attribute: " + name, null)); //$NON-NLS-1$ return elementValue; } diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/ICBreakpointContext.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/ICBreakpointContext.java new file mode 100644 index 00000000000..8527732e80b --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/ICBreakpointContext.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (c) 2012 Wind River Systems and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wind River Systems - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.debug.ui.breakpoints; + +import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.core.resources.IResource; +import org.eclipse.debug.ui.contexts.IDebugContextProvider; +import org.eclipse.jface.preference.IPreferenceStore; + +/** + * Input for the breakpoint properties dialog. It captures both the + * selected breakpoint object as well as the selected debug context. + * This combined context can then be used by breakpoint property + * pages to access model and target specific breakpoint settings. + * + * @since 7.2 + */ +public interface ICBreakpointContext extends IDebugContextProvider { + + /** + * Returns the breakpoint object that this context represents. + *

+ * Note: The returned breakpoint may not yet have an associated marker. + * This is for the case where the property dialog is opened for a breakpoint + * that is yet to be created. + * + * @return Breakpoint object. + */ + public ICBreakpoint getBreakpoint(); + + /** + * Resource object that the breakpoint marker is on. In case where + * the breakpoint marker is not yet created, clients can access the intended + * breakpoint resource object through this method. + * + * @return The breakpoint's resource object. + */ + public IResource getResource(); + + /** + * Returns the preference store to be used by property pages. This + * preference overrides values in the breakpoint marker. + * @return Preference store for the property pages. + */ + public IPreferenceStore getPreferenceStore(); + +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/ICBreakpointsUIContribution.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/ICBreakpointsUIContribution.java index 311b325fe56..a0a5aaf2c9a 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/ICBreakpointsUIContribution.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/ICBreakpointsUIContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008 QNX Software Systems and others. + * Copyright (c) 2008, 2012 QNX Software Systems and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -82,5 +82,5 @@ public interface ICBreakpointsUIContribution { * @param map - contains pairs of attribute=value for other breakpoint attributes * @return */ - public boolean isApplicable(Map map); + public boolean isApplicable(Map map); } diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/IToggleBreakpointsTargetCExtension.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/IToggleBreakpointsTargetCExtension.java new file mode 100644 index 00000000000..ed7fa04d634 --- /dev/null +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/breakpoints/IToggleBreakpointsTargetCExtension.java @@ -0,0 +1,133 @@ +/******************************************************************************* + * Copyright (c) 2012 Wind River Systems and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wind River Systems - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.debug.ui.breakpoints; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.debug.ui.actions.IToggleBreakpointsTargetExtension; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.ui.IWorkbenchPart; + +/** + * Second extension interface for {@link org.eclipse.debug.ui.actions.IToggleBreakpointsTarget}. + * This interface provides the ability open edit a breakpoint's properties and + * to create a breakpoint in the given context with additional user input + * (such as using a dialog or a wizard). + *

+ * Clients implementing IToggleBreakpointsTarget may optionally + * implement this interface. + *

+ * @since 7.2 + * @see org.eclipse.debug.ui.actions.ToggleBreakpointAction + */ +public interface IToggleBreakpointsTargetCExtension extends IToggleBreakpointsTargetExtension { + + /** + * Returns whether the toggle target can create a line breakpoint at the + * given location. If the implementation does not support creating the + * breakpoint interactively then it should return false. + *

+ * The selection varies depending on the given part. For example, + * a text selection is provided for text editors, and a structured + * selection is provided for tree views, and may be a multi-selection. + *

+ * @param part the part on which the action has been invoked + * @param selection selection on which line breakpoints should be toggled + * @return Returns true if toggle target is able interactively + * create a breakpoint(s) at the given location. + */ + public boolean canCreateLineBreakpointsInteractive(IWorkbenchPart part, ISelection selection); + + /** + * Creates new line breakpoints interactively. The implementation should + * allows the user to edit all of the breakpoint's settings prior to + * creating the breakpoint. Unlike the + * {@link #toggleLineBreakpoints(IWorkbenchPart, ISelection)} + * method, this method does not remove the existing breakpoint at given + * location. It always creates a new breakpoint + *

+ * The selection varies depending on the given part. For example, + * a text selection is provided for text editors, and a structured + * selection is provided for tree views, and may be a multi-selection. + *

+ * @param part the part on which the action has been invoked + * @param selection selection on which line breakpoints should be toggled + * @throws CoreException if unable to perform the action + */ + public void createLineBreakpointsInteractive(IWorkbenchPart part, ISelection selection) throws CoreException; + + /** + * Returns whether the toggle target can create a watchpoint at the + * given location. If the implementation does not support creating the + * breakpoint interactively then it should return false. + *

+ * The selection varies depending on the given part. For example, + * a text selection is provided for text editors, and a structured + * selection is provided for tree views, and may be a multi-selection. + *

+ * @param part the part on which the action has been invoked + * @param selection selection on which line breakpoints should be toggled + * @return Returns true if toggle target is able interactively + * create a breakpoint(s) at the given location. + */ + public boolean canCreateWatchpointsInteractive(IWorkbenchPart part, ISelection selection); + + /** + * Creates new watchpoint interactively. The implementation should + * allows the user to edit all of the breakpoint's settings prior to + * creating the breakpoint. Unlike the + * {@link #toggleLineBreakpoints(IWorkbenchPart, ISelection)} + * method, this method does not remove the existing breakpoint at given + * location. It always creates a new breakpoint + *

+ * The selection varies depending on the given part. For example, + * a text selection is provided for text editors, and a structured + * selection is provided for tree views, and may be a multi-selection. + *

+ * @param part the part on which the action has been invoked + * @param selection selection on which line breakpoints should be toggled + * @throws CoreException if unable to perform the action + */ + public void createWatchpointsInteractive(IWorkbenchPart part, ISelection selection) throws CoreException; + + /** + * Returns whether the toggle target can create a function breakpoint at the + * given location. If the implementation does not support creating the + * breakpoint interactively then it should return false. + *

+ * The selection varies depending on the given part. For example, + * a text selection is provided for text editors, and a structured + * selection is provided for tree views, and may be a multi-selection. + *

+ * @param part the part on which the action has been invoked + * @param selection selection on which line breakpoints should be toggled + * @return Returns true if toggle target is able interactively + * create a breakpoint(s) at the given location. + */ + public boolean canCreateFunctionBreakpointInteractive(IWorkbenchPart part, ISelection selection); + + /** + * Creates new function breakpoint interactively. The implementation should + * allows the user to edit all of the breakpoint's settings prior to + * creating the breakpoint. Unlike the + * {@link #toggleLineBreakpoints(IWorkbenchPart, ISelection)} + * method, this method does not remove the existing breakpoint at given + * location. It always creates a new breakpoint + *

+ * The selection varies depending on the given part. For example, + * a text selection is provided for text editors, and a structured + * selection is provided for tree views, and may be a multi-selection. + *

+ * @param part the part on which the action has been invoked + * @param selection selection on which line breakpoints should be toggled + * @throws CoreException if unable to perform the action + */ + public void createFunctionBreakpointInteractive(IWorkbenchPart part, ISelection selection) throws CoreException; +} diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/preferences/ReadOnlyFieldEditor.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/preferences/ReadOnlyFieldEditor.java index 5b6f2615ec3..85ffee374e6 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/preferences/ReadOnlyFieldEditor.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/ui/preferences/ReadOnlyFieldEditor.java @@ -75,11 +75,22 @@ public class ReadOnlyFieldEditor extends FieldEditor implements ICBreakpointsUIC if (textField != null) { String value = getPreferenceStore().getString(getPreferenceName()); if (contribution!=null) { + if ("integer".equals (contribution.getType())) { //$NON-NLS-1$ + value = Integer.toString( getPreferenceStore().getInt(getPreferenceName()) ); + } else if ("boolean".equals (contribution.getType()) ) {//$NON-NLS-1$ + value = Boolean.toString( getPreferenceStore().getBoolean(getPreferenceName()) ); + } else if ("float".equals (contribution.getType()) ) {//$NON-NLS-1$ + value = Float.toString( getPreferenceStore().getFloat(getPreferenceName()) ); + } else if ("double".equals (contribution.getType()) ) {//$NON-NLS-1$ + value = Double.toString( getPreferenceStore().getDouble(getPreferenceName()) ); + } String tryValue = contribution.getLabelForValue(value); if (tryValue!=null) value = tryValue; } - textField.setText(value); + if (value != null) { + textField.setText(value); + } } } diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizer.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizer.java index 0b9d2188815..2aca3f6ad35 100755 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizer.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizer.java @@ -33,8 +33,8 @@ import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils.DSFDebugModel; import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils.DSFDebugModelListener; import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils.DSFSessionState; import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils.DebugViewUtils; -import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.ICPUDMContext; -import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.ICoreDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardwareAndOS.ICPUDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardwareAndOS.ICoreDMContext; import org.eclipse.cdt.dsf.mi.service.IMIExecutionDMContext; import org.eclipse.cdt.dsf.mi.service.IMIProcessDMContext; import org.eclipse.cdt.dsf.ui.viewmodel.datamodel.IDMVMContext; diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModel.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModel.java index 101673d3b91..d7b65a1020e 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModel.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModel.java @@ -30,10 +30,10 @@ import org.eclipse.cdt.dsf.debug.service.IRunControl.StateChangeReason; import org.eclipse.cdt.dsf.debug.service.command.ICommandControlService; import org.eclipse.cdt.dsf.debug.service.command.ICommandControlService.ICommandControlDMContext; import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerExecutionState; -import org.eclipse.cdt.dsf.gdb.service.IGDBHardware; -import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.ICPUDMContext; -import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.ICoreDMContext; -import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.IHardwareTargetDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardwareAndOS; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardwareAndOS.ICPUDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardwareAndOS.ICoreDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardwareAndOS.IHardwareTargetDMContext; import org.eclipse.cdt.dsf.gdb.service.IGDBProcesses.IGdbThreadDMData; import org.eclipse.cdt.dsf.mi.service.IMIExecutionDMContext; @@ -61,7 +61,7 @@ public class DSFDebugModel { final Object arg) { ICommandControlService controlService = sessionState.getService(ICommandControlService.class); - IGDBHardware hwService = sessionState.getService(IGDBHardware.class); + IGDBHardwareAndOS hwService = sessionState.getService(IGDBHardwareAndOS.class); if (controlService == null || hwService == null) { listener.getCPUsDone(null, arg); return; @@ -99,7 +99,7 @@ public class DSFDebugModel { final DSFDebugModelListener listener, final Object arg) { - IGDBHardware hwService = sessionState.getService(IGDBHardware.class); + IGDBHardwareAndOS hwService = sessionState.getService(IGDBHardwareAndOS.class); if (hwService == null) { listener.getCoresDone(cpuContext, null, arg); return; diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModelListener.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModelListener.java index ccc0eed5fb8..f55a2594d9a 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModelListener.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModelListener.java @@ -15,8 +15,8 @@ package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils; import org.eclipse.cdt.dsf.datamodel.IDMContext; import org.eclipse.cdt.dsf.debug.service.IProcesses.IThreadDMData; import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerExecutionState; -import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.ICPUDMContext; -import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.ICoreDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardwareAndOS.ICPUDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardwareAndOS.ICoreDMContext; import org.eclipse.cdt.dsf.mi.service.IMIExecutionDMContext; /** Interface for classes that interact with DSFDebugModel. diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/launching/ProcessPrompter.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/launching/ProcessPrompter.java index 764b2409a07..8df673aa10c 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/launching/ProcessPrompter.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/launching/ProcessPrompter.java @@ -97,6 +97,12 @@ public class ProcessPrompter implements IStatusHandler { // we will get confused when using path.lastSegment(), so, // let's only keep the name to be sure String name = info.getName(); + if (name == null || name.isEmpty()) { + // Skip elements that have no name + // Bug 374823 + return null; + } + name = name.split("\\s", 2)[0]; //$NON-NLS-1$ IPath path = new Path(name); diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/internal/CoreList.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/internal/CoreList.java index 55007d29bb0..0b2f5dfdbca 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/internal/CoreList.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/internal/CoreList.java @@ -51,40 +51,43 @@ public class CoreList { Vector coreInfo = new Vector(); BufferedReader reader = null; try { + String processorId = null; String physicalId = null; - String coreId = null; - String cpuCores = null; Reader r = new InputStreamReader(new FileInputStream(cpuInfo)); reader = new BufferedReader(r); String line; while ((line = reader.readLine()) != null) { line = line.trim(); - if (line.startsWith("physical id")) { //$NON-NLS-1$ + if (line.startsWith("processor")) { //$NON-NLS-1$ + if (processorId != null) { + // We are already at the next 'processor' entry, without + // having found the 'physical id' entry. This means + // there is a single physical CPU. + physicalId = "0"; //$NON-NLS-1$ + + coreInfo.add(new CoreInfo(processorId, physicalId)); + processorId = null; + } + // Found the processor id of this core, so store it temporarily + processorId = line.split(":")[1].trim(); //$NON-NLS-1$ + } else if (line.startsWith("physical id")) { //$NON-NLS-1$ // Found the physical id of this core, so store it temporarily + + assert physicalId == null; physicalId = line.split(":")[1].trim(); //$NON-NLS-1$ - } else if (line.startsWith("core id")) { //$NON-NLS-1$ - // Found core id of this core which come after the entry - // for physical id, so we have both now. - coreId = line.split(":")[1].trim(); //$NON-NLS-1$ - } else if (line.startsWith("cpu cores")) { //$NON-NLS-1$ - // Found CPU core count which comes after the entry - // for core id, so we have all three by now. - cpuCores = line.split(":")[1].trim(); //$NON-NLS-1$ - - int cid = Integer.parseInt(coreId); - int pid = Integer.parseInt(physicalId); - int cores_per_pid = Integer.parseInt(cpuCores); - String absoluteCoreID = Integer.toString(cid + pid * cores_per_pid); - - coreInfo.add(new CoreInfo(absoluteCoreID, physicalId)); + + coreInfo.add(new CoreInfo(processorId, physicalId)); // Get ready to look for the next core. + processorId = null; physicalId = null; - coreId = null; - cpuCores = null; } - } + } + if (processorId != null) { + // This will happen when there is no 'physical id' field + coreInfo.add(new CoreInfo(processorId, "0")); //$NON-NLS-1$ + } } catch (IOException e) { } finally { try { diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/launching/ServicesLaunchSequence.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/launching/ServicesLaunchSequence.java index 22ffdf57f92..ad15fc60642 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/launching/ServicesLaunchSequence.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/launching/ServicesLaunchSequence.java @@ -29,7 +29,7 @@ import org.eclipse.cdt.dsf.debug.service.ISourceLookup; import org.eclipse.cdt.dsf.debug.service.ISourceLookup.ISourceLookupDMContext; import org.eclipse.cdt.dsf.debug.service.IStack; import org.eclipse.cdt.dsf.debug.service.command.ICommandControlService; -import org.eclipse.cdt.dsf.gdb.service.IGDBHardware; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardwareAndOS; import org.eclipse.cdt.dsf.gdb.service.IGDBTraceControl; import org.eclipse.cdt.dsf.mi.service.CSourceLookup; import org.eclipse.cdt.dsf.mi.service.IMIBackend; @@ -62,7 +62,7 @@ public class ServicesLaunchSequence extends Sequence { }, new Step() { @Override public void execute(RequestMonitor requestMonitor) { - IGDBHardware hwService = fLaunch.getServiceFactory().createService(IGDBHardware.class, fSession, fLaunch.getLaunchConfiguration()); + IGDBHardwareAndOS hwService = fLaunch.getServiceFactory().createService(IGDBHardwareAndOS.class, fSession, fLaunch.getLaunchConfiguration()); hwService.initialize(requestMonitor); }}, new Step() { @Override diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GDBHardware.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GDBHardwareAndOS.java similarity index 98% rename from dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GDBHardware.java rename to dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GDBHardwareAndOS.java index 48d0a69d9ce..fb848126623 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GDBHardware.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GDBHardwareAndOS.java @@ -60,13 +60,13 @@ import org.eclipse.core.runtime.Status; import org.osgi.framework.BundleContext; /** - * This class implements the IGDBHardware interface which gives access + * This class implements the {@link IGDBHardwareAndOS} interface which gives access * to hardware information about the target. * * @since 4.1 */ @SuppressWarnings("restriction") -public class GDBHardware extends AbstractDsfService implements IGDBHardware, ICachingService { +public class GDBHardwareAndOS extends AbstractDsfService implements IGDBHardwareAndOS, ICachingService { @Immutable protected static class GDBCPUDMC extends AbstractDMContext @@ -171,7 +171,7 @@ public class GDBHardware extends AbstractDsfService implements IGDBHardware, ICa // Bug 374293 private boolean fSessionInitializationComplete; - public GDBHardware(DsfSession session) { + public GDBHardwareAndOS(DsfSession session) { super(session); } @@ -216,8 +216,8 @@ public class GDBHardware extends AbstractDsfService implements IGDBHardware, ICa getSession().addServiceEventListener(this, null); // Register this service. - register(new String[] { IGDBHardware.class.getName(), - GDBHardware.class.getName() }, + register(new String[] { IGDBHardwareAndOS.class.getName(), + GDBHardwareAndOS.class.getName() }, new Hashtable()); requestMonitor.done(); diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GdbDebugServicesFactory.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GdbDebugServicesFactory.java index 7d6c78fcee7..a419748ed67 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GdbDebugServicesFactory.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GdbDebugServicesFactory.java @@ -96,10 +96,10 @@ public class GdbDebugServicesFactory extends AbstractDsfDebugServicesFactory { return (V)createTraceControlService(session, (ILaunchConfiguration)arg); } } - } else if (IGDBHardware.class.isAssignableFrom(clazz)) { + } else if (IGDBHardwareAndOS.class.isAssignableFrom(clazz)) { for (Object arg : optionalArguments) { if (arg instanceof ILaunchConfiguration) { - return (V)createHardwareService(session, (ILaunchConfiguration)arg); + return (V)createHardwareAndOSService(session, (ILaunchConfiguration)arg); } } } @@ -223,7 +223,7 @@ public class GdbDebugServicesFactory extends AbstractDsfDebugServicesFactory { } /** @since 4.1 */ - protected IGDBHardware createHardwareService(DsfSession session, ILaunchConfiguration config) { - return new GDBHardware(session); + protected IGDBHardwareAndOS createHardwareAndOSService(DsfSession session, ILaunchConfiguration config) { + return new GDBHardwareAndOS(session); } } diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/IGDBHardware.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/IGDBHardwareAndOS.java similarity index 98% rename from dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/IGDBHardware.java rename to dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/IGDBHardwareAndOS.java index 205d38ebadd..b3035e8e59e 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/IGDBHardware.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/IGDBHardwareAndOS.java @@ -25,7 +25,7 @@ import org.eclipse.cdt.dsf.service.IDsfService; * * @since 4.1 */ -public interface IGDBHardware extends IDsfService { +public interface IGDBHardwareAndOS extends IDsfService { /** * The physical target that has CPUs and Cores. diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/command/GDBControlDMContext.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/command/GDBControlDMContext.java index 546e1a094d2..bd1b0f3ba0e 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/command/GDBControlDMContext.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/command/GDBControlDMContext.java @@ -15,7 +15,7 @@ package org.eclipse.cdt.dsf.gdb.service.command; import org.eclipse.cdt.dsf.debug.service.IModules.ISymbolDMContext; import org.eclipse.cdt.dsf.debug.service.ISignals.ISignalsDMContext; import org.eclipse.cdt.dsf.debug.service.ISourceLookup.ISourceLookupDMContext; -import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.IHardwareTargetDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardwareAndOS.IHardwareTargetDMContext; import org.eclipse.cdt.dsf.gdb.service.IGDBTraceControl.ITraceTargetDMContext; import org.eclipse.cdt.dsf.mi.service.command.MIControlDMContext; diff --git a/dsf/org.eclipse.cdt.dsf.ui/plugin.properties b/dsf/org.eclipse.cdt.dsf.ui/plugin.properties index fa604141f8f..996feae9d4d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/plugin.properties +++ b/dsf/org.eclipse.cdt.dsf.ui/plugin.properties @@ -31,8 +31,9 @@ commandContext.name= In Disassembly commandContext.description= When debugging in assembly mode # actions -action.breakpointProperties.label = Breakpoint Properties... -action.toggleBreakpoint.label = Toggle Breakpoint +action.breakpointProperties.label = Breakpoint Properties...\Ctrl+Double Click +action.toggleBreakpoint.label = Toggle Breakpoint\tDouble Click +action.addBreakpoint.label = Add Breakpoint...\tCtrl+Double Click menu.updatePolicy = Update Policy menu.threadsUpdatePolicy = Threads Update Policy diff --git a/dsf/org.eclipse.cdt.dsf.ui/plugin.xml b/dsf/org.eclipse.cdt.dsf.ui/plugin.xml index 5233ceaa15a..c745ce4544d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/plugin.xml +++ b/dsf/org.eclipse.cdt.dsf.ui/plugin.xml @@ -468,7 +468,7 @@ id="org.eclipse.cdt.dsf.debug.ui.disassemblyViewToggleBreakpointTester" namespace="org.eclipse.cdt.dsf.debug.ui" properties="isDisassemblyViewSupportsCBreakpoint" - type="org.eclipse.cdt.dsf.debug.internal.ui.disassembly.DisassemblyView"> + type="org.eclipse.cdt.dsf.debug.internal.ui.disassembly.DisassemblyPart"> + + attributes = new HashMap(); + 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) */ @@ -38,6 +54,17 @@ public class DisassemblyToggleBreakpointsTarget extends AbstractDisassemblyBreak 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 attributes = new HashMap(); + 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/disassembly/DisassemblyMessages.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyMessages.java index 909f8e9f931..cb73691e57e 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 @@ -83,7 +83,10 @@ 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; + 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/DisassemblyMessages.properties b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyMessages.properties index a4098d6aa1b..fbe8b0b165f 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyMessages.properties +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyMessages.properties @@ -18,13 +18,16 @@ Disassembly_action_GotoPC_tooltip=Go to Current Program Counter Disassembly_action_GotoAddress_label=Go to Address... Disassembly_action_Copy_label=&Copy Disassembly_action_SelectAll_label=Select &All -Disassembly_action_BreakpointProperties_label=Breakpoint Properties... -Disassembly_action_DisableBreakpoint_label=Disable Breakpoint -Disassembly_action_EnableBreakpoint_label=Enable Breakpoint +Disassembly_action_BreakpointProperties_label=Breakpoint Properties...\tCtrl+Double Click +Disassembly_action_DisableBreakpoint_label=Disable Breakpoint\tShift+Double Click +Disassembly_action_EnableBreakpoint_label=Enable Breakpoint\tShift+Double Click Disassembly_action_RefreshView_label=Re&fresh View Disassembly_action_OpenPreferences_label=&Preferences... Disassembly_action_Sync_label=Link with Active Debug Context Disassembly_action_TrackExpression_label=Track Expression +Disassembly_action_AddBreakpoint_label=Add Breakpoint...\tCtrl+Double Click +Disassembly_action_AddBreakpoint_errorTitle=Error +Disassembly_action_AddBreakpoint_errorMessage=Unable to create breakpoint Disassembly_GotoAddressDialog_title=Go to Address Disassembly_GotoAddressDialog_label=Address expression: 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 308999dadbc..4b1187a6a07 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 @@ -156,6 +156,7 @@ import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.ui.IActionBars; @@ -1309,12 +1310,23 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem fActionToggleSource.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(DsfUIPlugin.PLUGIN_ID, "icons/source.gif")); //$NON-NLS-1$ fVerticalRuler.getControl().addMouseListener(new MouseAdapter() { @Override - public void mouseDoubleClick(MouseEvent e) { + public void mouseDoubleClick(final MouseEvent e) { // invoke toggle breakpoint IHandlerService handlerService = (IHandlerService) getSite().getService(IHandlerService.class); if (handlerService != null) { try { - handlerService.executeCommand(COMMAND_ID_TOGGLE_BREAKPOINT, null); + 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); } catch (NotDefinedException exc) { 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 new file mode 100644 index 00000000000..7e4df04046d --- /dev/null +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AddBreakpointRulerAction.java @@ -0,0 +1,136 @@ +/******************************************************************************* + * Copyright (c) 2008, 2012 Wind River Systems, Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wind River Systems - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.dsf.debug.internal.ui.disassembly.actions; + +import org.eclipse.cdt.debug.internal.ui.actions.ActionMessages; +import org.eclipse.cdt.debug.ui.CDebugUIPlugin; +import org.eclipse.cdt.debug.ui.breakpoints.IToggleBreakpointsTargetCExtension; +import org.eclipse.cdt.dsf.debug.internal.ui.disassembly.DisassemblyMessages; +import org.eclipse.cdt.dsf.debug.internal.ui.disassembly.provisional.IDisassemblyPart; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget; +import org.eclipse.debug.ui.actions.IToggleBreakpointsTargetManager; +import org.eclipse.jface.dialogs.ErrorDialog; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.text.source.IVerticalRulerInfo; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.StructuredSelection; +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); + } + + /* + * @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); + } + } + } + + @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); + } + + private IToggleBreakpointsTargetCExtension getToggleTarget(ISelection selection) { + 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(), + ActionMessages.getString("DisassemblyMessages.Disassembly_action_AddBreakpoint_errorTitle"), //$NON-NLS-1$ + ActionMessages.getString("DisassemblyMessages.Disassembly_action_AddBreakpoint_errorMessage"), //$NON-NLS-1$ + 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; + } + +} diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AddBreakpointRulerActionDelegate.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AddBreakpointRulerActionDelegate.java new file mode 100644 index 00000000000..6a1791aa7a6 --- /dev/null +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/actions/AddBreakpointRulerActionDelegate.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * Copyright (c) 2008, 2012 Wind River Systems, Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wind River Systems - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.dsf.debug.internal.ui.disassembly.actions; + +import org.eclipse.cdt.dsf.debug.internal.ui.disassembly.provisional.IDisassemblyPart; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.text.source.IVerticalRulerInfo; + +/** + * Ruler action delegate for the "Add Breakpoint..." action. + */ +public class AddBreakpointRulerActionDelegate extends AbstractDisassemblyRulerActionDelegate { + + /* + * @see org.eclipse.cdt.dsf.debug.internal.ui.disassembly.actions.AbstractDisassemblyRulerActionDelegate#createAction(org.eclipse.cdt.dsf.debug.internal.ui.disassembly.IDisassemblyPart, org.eclipse.jface.text.source.IVerticalRulerInfo) + */ + @Override + protected IAction createAction(IDisassemblyPart disassemblyPart, IVerticalRulerInfo rulerInfo) { + return new AddBreakpointRulerAction(disassemblyPart, rulerInfo); + } + +} 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 3bc945de35f..fd3010d83a9 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 Wind River Systems, Inc. and others. + * Copyright (c) 2008, 2012 Wind River Systems, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,58 +11,65 @@ package org.eclipse.cdt.dsf.debug.internal.ui.disassembly.actions; import org.eclipse.cdt.debug.core.model.ICBreakpoint; -import org.eclipse.cdt.debug.internal.ui.CBreakpointContext; +import org.eclipse.cdt.debug.ui.breakpoints.CBreakpointPropertyDialogAction; import org.eclipse.cdt.dsf.debug.internal.ui.disassembly.DisassemblyMessages; import org.eclipse.cdt.dsf.debug.internal.ui.disassembly.provisional.IDisassemblyPart; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.debug.ui.contexts.IDebugContextListener; +import org.eclipse.debug.ui.contexts.IDebugContextProvider; import org.eclipse.jface.text.source.IVerticalRulerInfo; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.ui.dialogs.PropertyDialogAction; +import org.eclipse.ui.IWorkbenchPart; /** * Ruler action to display breakpoint properties. */ -@SuppressWarnings("restriction") public class BreakpointPropertiesRulerAction extends AbstractDisassemblyBreakpointRulerAction { - - private Object fContext; + + + private ICBreakpoint fBreakpoint; protected BreakpointPropertiesRulerAction(IDisassemblyPart disassemblyPart, IVerticalRulerInfo rulerInfo) { super(disassemblyPart, rulerInfo); setText(DisassemblyMessages.Disassembly_action_BreakpointProperties_label); } - + /* * @see org.eclipse.cdt.dsf.debug.internal.ui.disassembly.actions.AbstractDisassemblyAction#run() */ @Override public void run() { - if ( fContext != null ) { - PropertyDialogAction action = new PropertyDialogAction( getDisassemblyPart().getSite(), new ISelectionProvider() { - - @Override - public void addSelectionChangedListener( ISelectionChangedListener listener ) { - } - - @Override - public ISelection getSelection() { - return new StructuredSelection( fContext ); - } - - @Override - public void removeSelectionChangedListener( ISelectionChangedListener listener ) { - } - - @Override - public void setSelection( ISelection selection ) { - } - } ); - action.run(); - action.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(); } } @@ -72,12 +79,13 @@ public class BreakpointPropertiesRulerAction extends AbstractDisassemblyBreakpoi @Override public void update() { IBreakpoint breakpoint= getBreakpoint(); + if (breakpoint instanceof ICBreakpoint) { - fContext = new CBreakpointContext((ICBreakpoint)breakpoint, getDebugContext()); + fBreakpoint = (ICBreakpoint)breakpoint; } else { - fContext = breakpoint; + fBreakpoint = null; } - setEnabled( fContext != null ); + setEnabled( fBreakpoint != null ); } private ISelection getDebugContext() { 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 fdfcd6ef466..1e56cfd7200 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 @@ -17,6 +17,7 @@ import org.eclipse.core.commands.ExecutionException; import org.eclipse.debug.ui.actions.ToggleBreakpointAction; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.source.IVerticalRulerInfo; +import org.eclipse.swt.widgets.Event; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.handlers.HandlerUtil; @@ -39,7 +40,14 @@ public class RulerToggleBreakpointHandler extends AbstractHandler { final ToggleBreakpointAction toggleBpAction= new ToggleBreakpointAction(part, document, rulerInfo); toggleBpAction.update(); if (toggleBpAction.isEnabled()) { - 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(); + } } } } 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 db70e81e714..7221649161d 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 @@ -15,8 +15,14 @@ import java.net.URI; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Map; import org.eclipse.cdt.core.IAddress; +import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.cdt.debug.internal.ui.CDebugUIUtils; +import org.eclipse.cdt.debug.internal.ui.breakpoints.CBreakpointContext; +import org.eclipse.cdt.debug.ui.CDebugUIPlugin; +import org.eclipse.cdt.debug.ui.breakpoints.IToggleBreakpointsTargetCExtension; import org.eclipse.cdt.dsf.debug.internal.ui.disassembly.provisional.DisassemblySelection; import org.eclipse.cdt.dsf.debug.internal.ui.disassembly.provisional.IDisassemblyPart; import org.eclipse.cdt.dsf.debug.internal.ui.disassembly.provisional.IDisassemblySelection; @@ -28,21 +34,28 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.model.IBreakpoint; -import org.eclipse.debug.ui.actions.IToggleBreakpointsTargetExtension; +import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.debug.ui.actions.IToggleBreakpointsTargetExtension2; +import org.eclipse.jface.preference.PreferenceDialog; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.viewers.ISelection; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Event; import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.dialogs.PreferencesUtil; import org.eclipse.ui.texteditor.SimpleMarkerAnnotation; /** * Base class for toggle breakpoint targets for the disassembly part. * @since 2.2 */ -public abstract class AbstractDisassemblyBreakpointsTarget implements IToggleBreakpointsTargetExtension { +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) @@ -58,7 +71,7 @@ public abstract class AbstractDisassemblyBreakpointsTarget implements IToggleBre int line = disassemblySelection.getStartLine(); IBreakpoint[] bp = getBreakpointsAtLine( (IDisassemblyPart)part, line ); if ( bp == null || bp.length == 0 ) { - insertBreakpoint( disassemblySelection ); + insertBreakpoint(part, disassemblySelection, false); } else { for( int i = 0; i < bp.length; i++ ) { @@ -121,10 +134,126 @@ public abstract class AbstractDisassemblyBreakpointsTarget implements IToggleBre return canToggleLineBreakpoints( part, selection ); } + /** + * @since 2.3 + */ + @Override + public boolean canToggleBreakpointsWithEvent(IWorkbenchPart part, ISelection selection, Event event) { + return canToggleBreakpoints(part, selection); + } + + /** + * @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(); + } + } + } + + /** + * @since 2.3 + */ + @Override + public boolean canCreateLineBreakpointsInteractive(IWorkbenchPart part, ISelection selection) { + return canToggleLineBreakpoints(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 { + } + + + private void toggleBreakpointEnabled(IBreakpoint bp) { + try { + bp.setEnabled(!bp.isEnabled()); + } catch (CoreException e) { + CDebugUIPlugin.log(e.getStatus()); + } + } + 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); + } + 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); + } + private IBreakpoint[] getBreakpointsAtLine( IDisassemblyPart part, int line ) { List breakpoints = new ArrayList(); IAnnotationModel annotationModel = part.getTextViewer().getAnnotationModel(); @@ -159,7 +288,7 @@ public abstract class AbstractDisassemblyBreakpointsTarget implements IToggleBre return breakpoints.toArray( breakpointsArray ); } - private void insertBreakpoint( IDisassemblySelection selection ) throws CoreException { + private void insertBreakpoint(IWorkbenchPart part, IDisassemblySelection selection, boolean interactive) throws CoreException { IAddress address = selection.getStartAddress(); if ( address == null ) { return; @@ -180,11 +309,53 @@ public abstract class AbstractDisassemblyBreakpointsTarget implements IToggleBre filePath = URIUtil.toPath( fileUri ).toOSString(); } int srcLine = selection.getSourceLine(); - createLineBreakpoint( filePath, resource, srcLine + 1 ); + if (interactive) { + createLineBreakpointInteractive(part, filePath, resource, srcLine + 1 ); + } else { + createLineBreakpoint( filePath, resource, srcLine + 1 ); + } } else { IResource resource = ResourcesPlugin.getWorkspace().getRoot(); - 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 + * null. + * @since 2.3 + */ + protected void openBreakpointPropertiesDialog(ICBreakpoint bp, IWorkbenchPart part, IResource resource, + Map 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/releng/org.eclipse.cdt-feature/feature.xml b/releng/org.eclipse.cdt-feature/feature.xml index a9de22a273f..7c60b7c13f2 100644 --- a/releng/org.eclipse.cdt-feature/feature.xml +++ b/releng/org.eclipse.cdt-feature/feature.xml @@ -42,8 +42,4 @@ id="org.eclipse.cdt.gnu.dsf" version="0.0.0"/> - - diff --git a/releng/org.eclipse.cdt.repo/category.xml b/releng/org.eclipse.cdt.repo/category.xml index 6be8d24d638..41a589de88f 100644 --- a/releng/org.eclipse.cdt.repo/category.xml +++ b/releng/org.eclipse.cdt.repo/category.xml @@ -56,4 +56,10 @@ + + + + + + diff --git a/releng/org.eclipse.cdt.sdk-feature/feature.xml b/releng/org.eclipse.cdt.sdk-feature/feature.xml index fe5d8838bff..ac1bca3c926 100644 --- a/releng/org.eclipse.cdt.sdk-feature/feature.xml +++ b/releng/org.eclipse.cdt.sdk-feature/feature.xml @@ -45,10 +45,6 @@ id="org.eclipse.cdt" version="0.0.0"/> - -