1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-07-23 08:55:25 +02:00

Merge remote-tracking branch 'cdt/master' into sd90

This commit is contained in:
Andrew Gvozdev 2012-03-22 11:33:30 -04:00
commit 897c840238
167 changed files with 7961 additions and 5310 deletions

View file

@ -63,5 +63,12 @@
download-size="0"
install-size="0"
version="0.0.0"/>
<plugin
id="org.eclipse.linuxtools.cdt.autotools.core"
download-size="0"
install-size="0"
version="0.0.0"
unpack="false"/>
</feature>

View file

@ -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<String, String> envMap = new HashMap<String, String>();
if (info.appendEnvironment()) {
@SuppressWarnings({"unchecked", "rawtypes"})
Map<String, String> env = (Map)launcher.getEnvironment();
envMap.putAll(env);
}
// Add variables from build info
envMap.putAll(info.getExpandedEnvironment());
List<String> strings= new ArrayList<String>(envMap.size());
Set<Entry<String, String>> entrySet = envMap.entrySet();
for (Entry<String, String> 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<String, String> envMap = getEnvironment(launcher, info);
String[] envp = BuildRunnerHelper.envMapToEnvp(envMap);
String[] errorParsers = info.getErrorParsers();
ErrorParserManager epm = new ErrorParserManager(getProject(), workingDirectoryURI, this, errorParsers);
List<IConsoleParser> parsers = new ArrayList<IConsoleParser>();
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<String, String> getEnvironment(ICommandLauncher launcher, IMakeBuilderInfo info)
throws CoreException {
HashMap<String, String> envMap = new HashMap<String, String>();
if (info.appendEnvironment()) {
@SuppressWarnings({"unchecked", "rawtypes"})
Map<String, String> 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);
}
}
}

View file

@ -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

View file

@ -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);
}
}

View file

@ -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;
}
}

View file

@ -44,10 +44,7 @@ public class GCCSpecsConsoleParser implements IScannerInfoConsoleParser {
protected List<String> symbols = new ArrayList<String>();
protected List<String> includes = new ArrayList<String>();
/* (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)

View file

@ -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();

View file

@ -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,

View file

@ -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<String, String> 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<String, String> 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<IConsoleParser> parsers = new ArrayList<IConsoleParser>();
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<String, String> env) {
// Convert into env strings
List<String> strings= new ArrayList<String>(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<IConsoleParser> parsers) {
ICfgScannerConfigBuilderInfo2Set container = CfgScannerConfigProfileManager.getCfgScannerConfigBuildInfo(cfg);
Map<CfgInfoContext, IScannerConfigBuilderInfo2> map = container.getInfoMap();
List<IConsoleParser> clParserList = new ArrayList<IConsoleParser>();
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<ILanguageSettingsProvider> 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<CfgInfoContext, IScannerConfigBuilderInfo2> map,
CfgInfoContext context,
IPath workingDirectory,
IMarkerGenerator markerGenerator,
IScannerInfoCollector collector,
List<IConsoleParser> 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<CfgInfoContext, IScannerConfigBuilderInfo2> map,
CfgInfoContext context, IPath workingDirectory, IMarkerGenerator markerGenerator) {
return ScannerInfoConsoleParserFactory.getScannerInfoConsoleParser(project, context.toInfoContext(), workingDirectory, map.get(context), markerGenerator, null);
}
}

View file

@ -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<String, String> map){
if(map == null)
return null;
List<String> list = new ArrayList<String>();
for (Entry<String, String> 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<IConsoleParser> parsers = new ArrayList<IConsoleParser>();
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<String, String> 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<ILanguageSettingsProvider> 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;
}
}

View file

@ -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<IConsoleParser> parsers) {
if (cfgDescription instanceof ILanguageSettingsProvidersKeeper) {
List<ILanguageSettingsProvider> 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$
}
}
}
}
}
}

View file

@ -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;
}

View file

@ -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();
}
}
}

View file

@ -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<IResource> 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<String> envList = new ArrayList<String>();
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<IProject, List<IFile>> arrangeFilesByProject(List<IFile> files) {
Map<IProject, List<IFile>> projectMap = new HashMap<IProject, List<IFile>>();
for (IFile file : files) {
IProject project = file.getProject();
List<IFile> filesInProject = projectMap.get(project);
if (filesInProject == null) {
filesInProject = new ArrayList<IFile>();
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<IFile> 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<IProject, List<IFile>> 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<IFile> 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<IFile> 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<IBuildStep> dependentSteps = new HashSet<IBuildStep>();
// 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<IBuildStep> 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<IBuildStep> dependentSteps = new HashSet<IBuildStep>();
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<IFile> 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<IProject, List<IFile>> projectMap = arrangeFilesByProject(files);
monitor.beginTask("", projectMap.size() * MONITOR_SCALE); //$NON-NLS-1$
for (List<IFile> 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<IFile> 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<IBuildStep> dependentSteps = new HashSet<IBuildStep>();
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<IBuildStep> stepIter = dependentSteps.iterator();
try {
IBuildResource buildResource = des.getBuildResource(file);
if (buildResource != null) {
Set<IBuildStep> dependentSteps = new HashSet<IBuildStep>();
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();
}
}

View file

@ -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

View file

@ -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);
}
}

View file

@ -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<IFile> files;
BuildFilesJob(List<IFile> 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<IFile> 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<IFile> selectedFiles = getSelectedBuildableFiles();
Job buildFilesJob = new BuildFilesJob(selectedFiles);
List<IProject> 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();

View file

@ -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<IFile> files;
protected Vector<?> generationProblems;
private CleanFilesJob(String name, List<IFile> filesToBuild) {
super(name);
private CleanFilesJob(List<IFile> 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<IFile> 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<IFile> selectedFiles = getSelectedBuildableFiles();
CleanFilesJob job = new CleanFilesJob(
ManagedMakeMessages
.getResourceString("CleanFilesAction.cleaningFiles"), selectedFiles); //$NON-NLS-1$
CleanFilesJob job = new CleanFilesJob(selectedFiles);
job.schedule();
}

View file

@ -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

View file

@ -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

View file

@ -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.
* <code>0</code> will be returned in case the hash-code is unknown.
* @return the hash-code of the file encoding or <code>0</code>.
* @since 5.3
* @deprecated Returns 0.
*/
@Deprecated
int getEncodingHashcode() throws CoreException;
/**

View file

@ -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.

View file

@ -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));

View file

@ -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<ICPPFunction> fResult;
private Set<String> 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:

View file

@ -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
*/

View file

@ -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;

View file

@ -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 <code>0</code> 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 <code>0</code> 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

View file

@ -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"));
}
}

View file

@ -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<String> added, Collection<String> changed, Collection<String> removed, boolean isFast) {
protected StandaloneIndexerTask(StandaloneIndexer indexer, Collection<String> added,
Collection<String> changed, Collection<String> 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);
}
}

View file

@ -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.

View file

@ -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<IIndexFileLocation, LocationTask> 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;
}

View file

@ -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 <code>null</code>, 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);
}

View file

@ -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) {

View file

@ -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();

View file

@ -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 <code>true</code> to continue the visit, <code>false</code> to abort it.
* @throws CoreException
*/
public abstract boolean visit(long record) throws CoreException;
public abstract boolean visit(long record) throws CoreException;
}

View file

@ -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

View file

@ -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();

View file

@ -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() {
}
}

View file

@ -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<String,HashMap<IResource, List<RefreshExclusion>>> configMap = fProjToConfToResToExcluMap.get(project);
if (configMap == null) {
configMap = new HashMap<String,HashMap<IResource, List<RefreshExclusion>>>();
CProjectDescriptionManager descriptionManager = CProjectDescriptionManager.getInstance();
ICProjectDescription projectDescription = descriptionManager.getProjectDescription(project, false);
ICConfigurationDescription cfgDescs[] = projectDescription.getConfigurations();
for (ICConfigurationDescription cfgDesc : cfgDescs) {
String configName = cfgDesc.getName();
HashMap<IResource, List<RefreshExclusion>> resourceMap = new HashMap<IResource, List<RefreshExclusion>>();
resourceMap.put(project, new LinkedList<RefreshExclusion>());
configMap.put(configName, resourceMap);
}
fProjToConfToResToExcluMap.put(project,configMap);
}
}
/**
* @since 5.4
*/

View file

@ -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.
* <strong>API is unstable and subject to change.</strong>
*/
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<IConsoleParser> 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<IConsoleParser> parsers = new ArrayList<IConsoleParser>();
// 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)}.
*
* <br><strong>Important: {@link #close()} the streams BEFORE calling this method to properly flush all outputs</strong>
*/
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<String, String> envMap) {
// Convert into env strings
List<String> strings= new ArrayList<String>(envMap.size());
for (Entry<String, String> 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$
}
}
}

View file

@ -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

View file

@ -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 {
}
}
}
}

View file

@ -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;
}
}

View file

@ -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);
}
}

View file

@ -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_

View file

@ -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)",

View file

@ -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();

View file

@ -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;

View file

@ -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);

View file

@ -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;
}
}

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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;
}

View file

@ -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 <eclipse.sprigogin@gmail.com> - [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;
/**
* <p>
* 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.
* </p>
* <p>
* This class is intended to be subclassed by clients wishing to implement new refactorings that
* depend on resources that have to be explicitly released.
* </p>
*/
public class RefactoringContext {
private Refactoring fRefactoring;
/**
* Creates a context for the given refactoring.
*
* @param refactoring The refactoring associated with the context. Cannot be <code>null</code>.
* @throws NullPointerException if refactoring is <code>null</code>.
*/
public RefactoringContext(Refactoring refactoring) {
if (refactoring == null)
throw new NullPointerException();
fRefactoring= refactoring;
}
/**
* Returns the refactoring associated with the context.
* <p>
* The returned refactoring must be in an initialized state, i.e. ready to
* be executed via {@link PerformRefactoringOperation}.
* </p>
* @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.
* <p>
* Subclasses may extend this method (must call super).
* </p>
*/
public void dispose() {
if (fRefactoring == null)
throw new IllegalStateException("dispose() called more than once."); //$NON-NLS-1$
fRefactoring= null;
}
}

View file

@ -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;
}
}

View file

@ -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()) {

View file

@ -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;
}
}

View file

@ -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);

View file

@ -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;
}
}

View file

@ -93,7 +93,7 @@ public class HideMethodRefactoring extends CRefactoring {
return initStatus;
}
if (isProgressMonitorCanceld(sm, initStatus))
if (isProgressMonitorCanceled(sm, initStatus))
return initStatus;
List<IASTName> 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();

View file

@ -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);
}
}

View file

@ -1,5 +1,86 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<component id="org.eclipse.cdt.debug.core" version="2">
<resource path="src/org/eclipse/cdt/debug/core/ICDebugConstants.java" type="org.eclipse.cdt.debug.core.ICDebugConstants">
<filter id="403853384">
<message_arguments>
<message_argument value="org.eclipse.cdt.debug.core.ICDebugConstants"/>
</message_arguments>
</filter>
</resource>
<resource path="src/org/eclipse/cdt/debug/core/model/ICAddressBreakpoint.java" type="org.eclipse.cdt.debug.core.model.ICAddressBreakpoint">
<filter comment="Binay backward compatible change." id="403767336">
<message_arguments>
<message_argument value="org.eclipse.cdt.debug.core.model.ICAddressBreakpoint"/>
<message_argument value="C_ADDRESS_BREAKPOINT_MARKER"/>
</message_arguments>
</filter>
</resource>
<resource path="src/org/eclipse/cdt/debug/core/model/ICBreakpoint.java" type="org.eclipse.cdt.debug.core.model.ICBreakpoint">
<filter comment="Binary backward compatible change." id="403767336">
<message_arguments>
<message_argument value="org.eclipse.cdt.debug.core.model.ICBreakpoint"/>
<message_argument value="C_BREAKPOINT_MARKER"/>
</message_arguments>
</filter>
</resource>
<resource path="src/org/eclipse/cdt/debug/core/model/ICEventBreakpoint.java" type="org.eclipse.cdt.debug.core.model.ICEventBreakpoint">
<filter comment="Binary backward compatible change." id="403767336">
<message_arguments>
<message_argument value="org.eclipse.cdt.debug.core.model.ICEventBreakpoint"/>
<message_argument value="C_EVENT_BREAKPOINT_MARKER"/>
</message_arguments>
</filter>
</resource>
<resource path="src/org/eclipse/cdt/debug/core/model/ICFunctionBreakpoint.java" type="org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint">
<filter comment="Binay backward compatible change." id="403767336">
<message_arguments>
<message_argument value="org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint"/>
<message_argument value="C_FUNCTION_BREAKPOINT_MARKER"/>
</message_arguments>
</filter>
</resource>
<resource path="src/org/eclipse/cdt/debug/core/model/ICLineBreakpoint.java" type="org.eclipse.cdt.debug.core.model.ICLineBreakpoint">
<filter id="403767336">
<message_arguments>
<message_argument value="org.eclipse.cdt.debug.core.model.ICLineBreakpoint"/>
<message_argument value="C_LINE_BREAKPOINT_MARKER"/>
</message_arguments>
</filter>
</resource>
<resource path="src/org/eclipse/cdt/debug/core/model/ICTracepoint.java" type="org.eclipse.cdt.debug.core.model.ICTracepoint">
<filter comment="Binay backward compatible change." id="403767336">
<message_arguments>
<message_argument value="org.eclipse.cdt.debug.core.model.ICTracepoint"/>
<message_argument value="C_ADDRESS_TRACEPOINT_MARKER"/>
</message_arguments>
</filter>
<filter comment="Binay backward compatible change." id="403767336">
<message_arguments>
<message_argument value="org.eclipse.cdt.debug.core.model.ICTracepoint"/>
<message_argument value="C_FUNCTION_TRACEPOINT_MARKER"/>
</message_arguments>
</filter>
<filter comment="Binary backward compatible change." id="403767336">
<message_arguments>
<message_argument value="org.eclipse.cdt.debug.core.model.ICTracepoint"/>
<message_argument value="C_LINE_TRACEPOINT_MARKER"/>
</message_arguments>
</filter>
<filter comment="Binary backward compatible change." id="403767336">
<message_arguments>
<message_argument value="org.eclipse.cdt.debug.core.model.ICTracepoint"/>
<message_argument value="C_TRACEPOINT_MARKER"/>
</message_arguments>
</filter>
</resource>
<resource path="src/org/eclipse/cdt/debug/core/model/ICWatchpoint.java" type="org.eclipse.cdt.debug.core.model.ICWatchpoint">
<filter comment="Binay backward compatible change." id="403767336">
<message_arguments>
<message_argument value="org.eclipse.cdt.debug.core.model.ICWatchpoint"/>
<message_argument value="C_WATCHPOINT_MARKER"/>
</message_arguments>
</filter>
</resource>
<resource path="src/org/eclipse/cdt/debug/core/sourcelookup/MappingSourceContainer.java" type="org.eclipse.cdt.debug.core.sourcelookup.MappingSourceContainer">
<filter id="643846161">
<message_arguments>

View file

@ -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$
}

View file

@ -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.

View file

@ -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();
}

View file

@ -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++

View file

@ -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$
}

View file

@ -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 <code>"org.eclipse.cdt.debug.core.function"</code>).
@ -77,4 +83,5 @@ public interface ICLineBreakpoint extends ICBreakpoint, ILineBreakpoint {
* underlying marker
*/
public String getFileName() throws CoreException;
}

View file

@ -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
* <code>"org.eclipse.cdt.debug.core.passCount"</code>). This attribute

View file

@ -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 <code>"org.eclipse.cdt.debug.core.expression"</code>).

View file

@ -42,8 +42,8 @@ public abstract class AbstractLineBreakpoint extends CBreakpoint implements ICLi
* @param add
* @throws CoreException
*/
public AbstractLineBreakpoint( IResource resource, String markerType, Map<String, Object> attributes, boolean add ) throws CoreException {
super( resource, markerType, attributes, add );
public AbstractLineBreakpoint( IResource resource, Map<String, Object> attributes, boolean add ) throws CoreException {
super( resource, attributes, add );
}
/*(non-Javadoc)

View file

@ -42,8 +42,8 @@ public abstract class AbstractTracepoint extends CBreakpoint implements ICTracep
* @param add
* @throws CoreException
*/
public AbstractTracepoint( IResource resource, String markerType, Map<String, Object> attributes, boolean add ) throws CoreException {
super( resource, markerType, attributes, add );
public AbstractTracepoint( IResource resource, Map<String, Object> attributes, boolean add ) throws CoreException {
super( resource, attributes, add );
}
/*(non-Javadoc)

View file

@ -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<String, Object> 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;
}
/*

View file

@ -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<String, Object> 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;
}

View file

@ -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<String, Object> attributes, final boolean add ) throws CoreException {
public CBreakpoint( final IResource resource, final Map<String, Object> 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<String, Object> 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());
}
}

View file

@ -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<String, Object> 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<String, Object> 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

View file

@ -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<String, Object> 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)

View file

@ -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<String, Object> 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()

View file

@ -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<String, Object> 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)

View file

@ -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<String, Object> 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();

View file

@ -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<String, Object> attributes, boolean add ) throws CoreException {
super( resource, getMarkerType(), attributes, add );
super( resource, attributes, add );
}
protected CWatchpoint( IResource resource, String marker, Map<String, Object> 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()
*/

View file

@ -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,

View file

@ -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

View file

@ -415,27 +415,27 @@
<viewerContribution
targetID="#CEditorRulerContext"
id="org.eclipse.cdt.debug.ui.CEditorRulerActions">
<action
label="%BreakpointTypes.label"
class="org.eclipse.debug.ui.actions.RulerBreakpointTypesActionDelegate"
id="org.eclipse.cdt.debug.ui.breakpointTypesAction"
menubarPath="debug"
style="pulldown">
</action>
<action
label="%BreakpointProperties.label"
helpContextId="breakpoint_properties_action_context"
class="org.eclipse.cdt.debug.internal.ui.actions.CBreakpointPropertiesRulerActionDelegate"
class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.CBreakpointPropertiesRulerActionDelegate"
menubarPath="debug"
id="org.eclipse.cdt.debug.internal.ui.actions.CBreakpointPropertiesRulerActionDelegate">
</action>
<action
label="%EnableBreakpoint.label"
helpContextId="enable_disable_breakpoint_action_context"
class="org.eclipse.cdt.debug.internal.ui.actions.EnableDisableBreakpointRulerActionDelegate"
class="org.eclipse.debug.ui.actions.RulerEnableDisableBreakpointActionDelegate"
menubarPath="debug"
id="org.eclipse.cdt.debug.internal.ui.actions.EnableDisableBreakpointRulerActionDelegate">
</action>
<action
label="%AddBreakpointInteractive.label"
helpContextId="add_breakpoint_interactive_action_context"
class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.CAddBreakpointInteractiveRulerActionDelegate"
menubarPath="debug"
id="org.eclipse.debug.ui.actions.RulerCreateBreakpointInteractiveAction">
</action>
<action
label="%AddBreakpoint.label"
helpContextId="manage_breakpoint_action_context"
@ -496,17 +496,24 @@
<action
label="%BreakpointProperties.label"
helpContextId="breakpoint_properties_action_context"
class="org.eclipse.cdt.debug.internal.ui.actions.CBreakpointPropertiesRulerActionDelegate"
class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.CBreakpointPropertiesRulerActionDelegate"
menubarPath="debug"
id="org.eclipse.cdt.debug.internal.ui.actions.CBreakpointPropertiesRulerActionDelegate">
</action>
<action
label="%EnableBreakpoint.label"
helpContextId="enable_disable_breakpoint_action_context"
class="org.eclipse.cdt.debug.internal.ui.actions.EnableDisableBreakpointRulerActionDelegate"
class="org.eclipse.debug.ui.actions.RulerEnableDisableBreakpointActionDelegate"
menubarPath="debug"
id="org.eclipse.cdt.debug.internal.ui.actions.EnableDisableBreakpointRulerActionDelegate">
</action>
<action
label="%AddBreakpointInteractive.label"
helpContextId="create_breakpoint_interactive_action_context"
class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.CAddBreakpointInteractiveRulerActionDelegate"
menubarPath="debug"
id="org.eclipse.debug.ui.actions.RulerCreateBreakpointInteractiveAction">
</action>
<action
label="%AddBreakpoint.label"
helpContextId="manage_breakpoint_action_context"
@ -605,7 +612,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.function.ToggleMethodBreakpointAction">
@ -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">
<action
class="org.eclipse.cdt.debug.internal.ui.actions.AddWatchpointOnVariableActionDelegate"
class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.AddWatchpointOnVariableActionDelegate"
enablesFor="1"
icon="icons/elcl16/watchpoint_co.gif"
id="org.eclipse.cdt.debug.internal.ui.actions.AddWatchpointOnVariableActionDelegate"
@ -854,7 +861,7 @@
id="org.eclipse.debug.ui.MemoryView.RenderingViewPane.popupMenu.1"
targetID="org.eclipse.debug.ui.MemoryView.RenderingViewPane.1">
<action
class="org.eclipse.cdt.debug.internal.ui.actions.AddWatchpointOnMemoryActionDelegate"
class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.AddWatchpointOnMemoryActionDelegate"
enablesFor="1"
icon="icons/elcl16/watchpoint_co.gif"
id="org.eclipse.cdt.debug.internal.ui.actions.AddWatchpointOnMemoryActionDelegate.1"
@ -867,7 +874,7 @@
id="org.eclipse.debug.ui.MemoryView.RenderingViewPane.popupMenu.2"
targetID="org.eclipse.debug.ui.MemoryView.RenderingViewPane.2">
<action
class="org.eclipse.cdt.debug.internal.ui.actions.AddWatchpointOnMemoryActionDelegate"
class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.AddWatchpointOnMemoryActionDelegate"
enablesFor="1"
icon="icons/elcl16/watchpoint_co.gif"
id="org.eclipse.cdt.debug.internal.ui.actions.AddWatchpointOnMemoryActionDelegate.2"
@ -946,7 +953,7 @@
</enablement>
</action>
<action
class="org.eclipse.cdt.debug.internal.ui.actions.AddWatchpointActionDelegate"
class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.AddWatchpointActionDelegate"
icon="icons/elcl16/watchpoint_co.gif"
id="org.eclipse.cdt.debug.ui.addWatchpoint"
label="%AddWatchpoint.label"
@ -955,7 +962,7 @@
helpContextId="add_watchpoint_action_context"
tooltip="%AddWatchpoint.tooltip"/>
<action
class="org.eclipse.cdt.debug.internal.ui.actions.AddEventBreakpointActionDelegate"
class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.AddEventBreakpointActionDelegate"
icon="icons/obj16/eventbreakpoint_obj.gif"
id="org.eclipse.cdt.debug.internal.ui.actions.AddEventBreakpointActionDelegate"
label="%AddEventBreakpoint.label"
@ -963,6 +970,15 @@
style="push"
tooltip="%AddEventBreakpoint.tooltip">
</action>
<action
class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.AddFunctionBreakpointActionDelegate"
icon="icons/elcl16/function_brkpt_co.gif"
id="org.eclipse.cdt.debug.ui.addFunctionBreakpoint"
label="%AddFunctionBreakpoint.label"
menubarPath="cDebugActions"
style="push"
helpContextId="add_function_breakpoint_action_context"
tooltip="%AddFunctionBreakpoint.tooltip"/>
</viewContribution>
<viewContribution
targetID="org.eclipse.debug.ui.VariableView"
@ -1172,18 +1188,28 @@
<extension
point="org.eclipse.ui.propertyPages">
<page
class="org.eclipse.cdt.debug.internal.ui.propertypages.CBreakpointPropertyPage"
class="org.eclipse.cdt.debug.internal.ui.breakpoints.CBreakpointPropertyPage"
id="org.eclipse.cdt.debug.ui.propertypages.breakpoint.common"
name="%CommonBreakpointPage.label">
<enabledWhen>
<and>
<adapt type="org.eclipse.cdt.debug.core.model.ICBreakpoint">
</adapt>
<not>
<adapt type="org.eclipse.cdt.debug.core.model.ICTracepoint">
<or>
<and>
<adapt type="org.eclipse.cdt.debug.core.model.ICBreakpoint">
</adapt>
</not>
</and>
<not>
<adapt type="org.eclipse.cdt.debug.core.model.ICTracepoint">
</adapt>
</not>
</and>
<and>
<instanceof value="org.eclipse.cdt.debug.ui.breakpoints.ICBreakpointContext"/>
<test property="org.eclipse.cdt.debug.ui.createBreakpointAdapt" value="org.eclipse.cdt.debug.core.model.ICBreakpoint" />
<not>
<test property="org.eclipse.cdt.debug.ui.createBreakpointAdapt" value="org.eclipse.cdt.debug.core.model.ICTracepoint"/>
</not>
</and>
</or>
</enabledWhen>
</page>
<page
@ -1201,7 +1227,7 @@
</and>
</enabledWhen>
</page>
<page class="org.eclipse.cdt.debug.internal.ui.propertypages.CBreakpointFilteringPage"
<page class="org.eclipse.cdt.debug.internal.ui.breakpoints.CBreakpointFilteringPage"
id="org.eclipse.cdt.debug.ui.propertypages.breakpoint.filtering"
name="%FilteringBreakpointPage.label">
<filter name="debugModelId" value="org.eclipse.cdt.debug.core"/>
@ -1296,7 +1322,7 @@
<extension
point="org.eclipse.ui.editors.markerAnnotationSpecification">
<specification
annotationImageProvider="org.eclipse.cdt.debug.internal.ui.BreakpointImageProvider"
annotationImageProvider="org.eclipse.cdt.debug.internal.ui.breakpoints.BreakpointImageProvider"
annotationType="org.eclipse.cdt.debug.core.breakpoint"
colorPreferenceKey="breakpointIndicationColor"
colorPreferenceValue="0,0,255"
@ -1340,7 +1366,7 @@
<adapter type="org.eclipse.cdt.debug.internal.ui.actions.IMoveToLineTarget"/>
</factory>
<factory
class="org.eclipse.cdt.debug.internal.ui.CBreakpointWorkbenchAdapterFactory"
class="org.eclipse.cdt.debug.internal.ui.breakpoints.CBreakpointWorkbenchAdapterFactory"
adaptableType="org.eclipse.cdt.debug.core.model.ICBreakpoint">
<adapter type="org.eclipse.ui.model.IWorkbenchAdapter"/>
</factory>
@ -1736,6 +1762,18 @@
</visibleWhen>
</command>
</menuContribution>
<menuContribution
locationURI="popup:#CEditorRulerContext?after=debug">
<menu
id="breakpointTypes"
label="%BreakpointTypes.label">
<dynamic
id="org.eclipse.debug.ui.actions.BreakpointTypesContribution"
class="org.eclipse.debug.ui.actions.BreakpointTypesContribution">
</dynamic>
</menu>
</menuContribution>
</extension>
<extension
point="org.eclipse.core.runtime.adapters">
@ -1766,14 +1804,14 @@
<extension
point="org.eclipse.core.expressions.propertyTesters">
<propertyTester
class="org.eclipse.cdt.debug.internal.ui.ToggleCBreakpointTester"
class="org.eclipse.cdt.debug.internal.ui.breakpoints.ToggleCBreakpointTester"
id="org.eclipse.cdt.debug.ui.editorToggleBreakpointTester"
namespace="org.eclipse.cdt.debug.ui"
properties="isCEditorSupportsCBreakpoint,isAsmEditorSupportsCBreakpoint,isDisassemblyEditorSupportsCBreakpoint"
type="org.eclipse.ui.IWorkbenchPart">
</propertyTester>
<propertyTester
class="org.eclipse.cdt.debug.internal.ui.ToggleCBreakpointTester"
class="org.eclipse.cdt.debug.internal.ui.breakpoints.ToggleCBreakpointTester"
id="org.eclipse.cdt.debug.ui.declarationToggleBreakpointTester"
namespace="org.eclipse.cdt.debug.ui"
properties="isCDeclarationSupportsCBreakpoint"
@ -1784,7 +1822,7 @@
<extension point="org.eclipse.debug.ui.toggleBreakpointsTargetFactories">
<toggleTargetFactory
id="org.eclipse.cdt.debug.ui.ToggleCBreakpointsTargetFactory"
class="org.eclipse.cdt.debug.internal.ui.actions.ToggleCBreakpointsTargetFactory">
class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.ToggleCBreakpointsTargetFactory">
<enablement>
<!-- Enable the breakpoint toggle for CDT's editors and model elements -->
<or>
@ -1802,7 +1840,7 @@
</toggleTargetFactory>
<toggleTargetFactory
id="org.eclipse.cdt.debug.ui.ToggleCTracepointsTargetFactory"
class="org.eclipse.cdt.debug.internal.ui.actions.ToggleCTracepointsTargetFactory">
class="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.ToggleCTracepointsTargetFactory">
<enablement>
<!-- Enable the breakpoint toggle for CDT's editors and model elements -->
<and>
@ -2093,7 +2131,7 @@
point="org.eclipse.ui.commands">
<command
categoryId="org.eclipse.debug.ui.category.run"
defaultHandler="org.eclipse.cdt.debug.internal.ui.actions.CBreakpointPropertiesHandler"
defaultHandler="org.eclipse.cdt.debug.internal.ui.actions.breakpoints.CBreakpointPropertiesHandler"
description="%BreakpointPropertiesCommand.description"
helpContextId="breakpoint_properties_action_context"
id="org.eclipse.cdt.debug.command.breakpointProperties"
@ -2534,5 +2572,15 @@
</activeWhen>
</handler>
</extension>
<extension
point="org.eclipse.core.expressions.propertyTesters">
<propertyTester
class="org.eclipse.cdt.debug.internal.ui.breakpoints.CreateBreakpointTester"
id="org.eclipse.cdt.debug.ui.CreateBreakpointTester"
namespace="org.eclipse.cdt.debug.ui"
properties="createBreakpointAdapt"
type="org.eclipse.cdt.debug.ui.breakpoints.ICBreakpointContext">
</propertyTester>
</extension>
</plugin>

View file

@ -107,7 +107,7 @@ If not specified this attribute will not be visible in Common page.
<attribute name="type" type="string" use="default" value="string">
<annotation>
<documentation>
Type of the attribute: boolean, string, integer
Type of the attribute. Value should be one of "boolean", "string", "integer", "float".
</documentation>
</annotation>
</attribute>

View file

@ -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 <code>null</code>
* 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 <code>null</code>
*/
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<Annotation> 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();
}
}

View file

@ -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;
}

View file

@ -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

View file

@ -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<String> sExpressionHistory = new ArrayList<String>();
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);
}
}

View file

@ -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;
}
}

View file

@ -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();
}
}

View file

@ -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 );
}
}

View file

@ -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;
}
}

View file

@ -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() );
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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 <code>null</code>
*/
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;
}
}

Some files were not shown because too many files have changed in this diff Show more