- sample new campaign creation

- sample project builder+marking for errors/warnings
This commit is contained in:
Timotei Dolean 2010-04-08 16:00:05 +00:00
parent 7e4913916b
commit 59805680b5
11 changed files with 534 additions and 91 deletions

2
utils/java/eclipse_plugin/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
bin
dummytool.exe

View file

@ -8,6 +8,8 @@ Bundle-Vendor: www.wesnoth.org
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
org.eclipse.core.resources,
org.eclipse.ui.ide
org.eclipse.ui.ide,
org.eclipse.jface.text;bundle-version="3.5.2",
org.eclipse.ui.editors;bundle-version="3.5.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Bundle-ActivationPolicy: lazy

View file

@ -6,11 +6,8 @@
id="sampleBuilder"
name="Sample Project Builder"
point="org.eclipse.core.resources.builders">
<builder
hasNature="true">
<run
class="wesnoth_eclipse_plugin.builder.SampleBuilder">
</run>
<builder hasNature="true">
<run class="wesnoth_eclipse_plugin.builder.SampleBuilder"/>
</builder>
</extension>
<extension

View file

@ -0,0 +1,32 @@
/**
*
*/
package wesnoth_eclipse_plugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
/**
* @author Timotei Dolean
*
*/
public class Logger {
/**
* Prints a message to the error log (severity: info)
* @param message the message to print
*/
public static void print(String message)
{
print(message, IStatus.INFO);
}
/**
* Prints a message to the error log with the specified severity
* @param message the message to print
* @param severity the severity level from IStatus enum
*/
public static void print(String message, int severity)
{
Activator.getDefault().getLog().log(new Status(IStatus.INFO,"wesnoth_plugin",message));
}
}

View file

@ -0,0 +1,94 @@
package wesnoth_eclipse_plugin.builder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
/**
* @author Timotei Dolean
*
*/
public class ExternalToolInvoker {
private Process process_;
private ProcessBuilder processBuilder_;
private Thread processThread_;
private BufferedReader bufferedReaderOutput_;
private BufferedReader bufferedReaderError_;
/**
* Creates an external tool invoker with specified options
* @param fileName the file name to be invoked
* @param arguments the arguments passed to the file
* @param useThread true if the process will run in a thread
* @throws IOException
*/
public ExternalToolInvoker(String fileName, String arguments, boolean useThread) throws IOException
{
processBuilder_ = new ProcessBuilder(fileName,arguments);
if (useThread)
processThread_ = new Thread(new Runnable() {
@Override
public void run() {
try {
process_ = processBuilder_.start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void run() throws IOException
{
if (processThread_ == null)
process_ = processBuilder_.start();
else
processThread_.run();
bufferedReaderOutput_ = new BufferedReader(new InputStreamReader(process_.getInputStream()));
bufferedReaderError_ = new BufferedReader(new InputStreamReader(process_.getErrorStream()));
}
public void waitFor() throws InterruptedException
{
process_.waitFor();
}
public String readOutputLine()
{
if (process_ == null)
return null;
try {
return bufferedReaderOutput_.readLine();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public String readErrorLine()
{
if (process_ == null)
return null;
try {
return bufferedReaderError_.readLine();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public OutputStream getOutputStream()
{
return process_.getOutputStream();
}
public InputStream getInputStream()
{
return process_.getInputStream();
}
public InputStream getErrorStream()
{
return process_.getErrorStream();
}
}

View file

@ -0,0 +1,106 @@
package wesnoth_eclipse_plugin.builder;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IMarker;
/**
* @author Timotei Dolean
*/
public class MarkerToken{
private MarkerTokenType type_ = MarkerTokenType.INFO;
private String message_ = "";
private int line_ ;
private int columnStart_;
private int columnEnd_;
public MarkerToken(MarkerTokenType type,String message,int line, int columnStart,int columnEnd)
{
type_ = type;
message_ = message;
line_ = line;
columnStart_ = columnStart;
columnEnd_ = columnEnd;
}
/**
* Parses the current line and returns a marker token
* Current used format: Type#line:column#message
* @param line the line to parse
* @return
*/
public static MarkerToken parseToken(String line)
{
// severity#Line{:columnStart-columnEnd}#message
StringTokenizer tokenizer = new StringTokenizer(line,"#");
try{
int lineIndex=1,columnIndexStart=0,columnIndexEnd=0;
MarkerTokenType type = MarkerTokenType.valueOf(tokenizer.nextToken().toUpperCase());
if (tokenizer.countTokens() > 1) // we have the line+column indexes
{
String[] tmp = tokenizer.nextToken().split(":");
if (tmp.length >0)
lineIndex = Integer.parseInt(tmp[0]);
if (tmp.length > 1)
{
// get columnstart-columnEnd
String[] colTmp = tmp[1].split("-");
columnIndexStart = Integer.parseInt(colTmp[0]);
if(colTmp.length > 1)
columnIndexEnd = Integer.parseInt(colTmp[1]);
}
}
return new MarkerToken(type, tokenizer.nextToken(), lineIndex,columnIndexStart,columnIndexEnd);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
/** Returns the of the marker
* @return the line
*/
public int getLine() {
return line_;
}
/** Returns the message of the marker
* @return the message of the marker
*/
public String getMessage() {
return message_;
}
/** Returns the column start index of the marker
* @return the column_
*/
public int getColumnStart() {
return columnStart_;
}
/** Returns the column end index of the marker
* @return the columnEnd_
*/
public int getColumnEnd() {
return columnEnd_;
}
/**
* @return the type of the marker
*/
public MarkerTokenType getType() {
return type_;
}
}
enum MarkerTokenType
{
ERROR, WARNING, INFO;
public int toMarkerSeverity()
{
if (this == ERROR)
return IMarker.SEVERITY_ERROR;
else if (this == WARNING)
return IMarker.SEVERITY_WARNING;
return IMarker.SEVERITY_INFO;
}
}

View file

@ -1,11 +1,15 @@
package wesnoth_eclipse_plugin.builder;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.eclipse.core.internal.resources.IMarkerSetElement;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
@ -16,10 +20,27 @@ import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.INodeChangeListener;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.IDocumentPartitioningListener;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import wesnoth_eclipse_plugin.Logger;
public class SampleBuilder extends IncrementalProjectBuilder {
class SampleDeltaVisitor implements IResourceDeltaVisitor {
@ -85,7 +106,7 @@ public class SampleBuilder extends IncrementalProjectBuilder {
public static final String BUILDER_ID = "Wesnoth_Eclipse_Plugin.sampleBuilder";
private static final String MARKER_TYPE = "Wesnoth_Eclipse_Plugin.xmlProblem";
private String TOOL_PATH = "E:\\work\\java\\eclipse_plugin\\dummytool.exe";
private SAXParserFactory parserFactory;
private void addMarker(IFile file, String message, int lineNumber,
@ -110,6 +131,8 @@ public class SampleBuilder extends IncrementalProjectBuilder {
*/
protected IProject[] build(int kind, Map args, IProgressMonitor monitor)
throws CoreException {
Logger.print("building");
if (kind == FULL_BUILD) {
fullBuild(monitor);
} else {
@ -124,13 +147,43 @@ public class SampleBuilder extends IncrementalProjectBuilder {
}
void checkXML(IResource resource) {
if (resource instanceof IFile && resource.getName().endsWith(".xml")) {
IFile file = (IFile) resource;
deleteMarkers(file);
XMLErrorHandler reporter = new XMLErrorHandler(file);
Logger.print("got a _main.cfg file");
// dummy condition
if (resource instanceof IFile && resource.getName().equals("_main.cfg")) {
try {
getParser().parse(file.getContents(), reporter);
} catch (Exception e1) {
IFile file = (IFile) resource;
deleteMarkers(file);
IMarker[] resIMarkers = file.findMarkers(MARKER_TYPE, false, IResource.DEPTH_ZERO);
Logger.print("found markers: " + resIMarkers.length);
ExternalToolInvoker invoker = new ExternalToolInvoker(TOOL_PATH, resource.getFullPath().toOSString(), true);
Logger.print("Tool: "+TOOL_PATH+ " checking file: "+resource.getFullPath().toOSString());
invoker.run();
invoker.waitFor();
// we need to find the correct column start/end based on the current document
// (or get that from the tool)
IDocumentProvider provider = new TextFileDocumentProvider();
provider.connect(file);
IDocument document = provider.getDocument(file);
String line;MarkerToken token;
while((line = invoker.readOutputLine()) != null)
{
token = MarkerToken.parseToken(line);
IMarker marker = file.createMarker(MARKER_TYPE);
marker.setAttribute(IMarker.MESSAGE, token.getMessage());
if (token.getColumnEnd() != 0)
{
marker.setAttribute(IMarker.CHAR_START,document.getLineOffset(token.getLine()-1) + token.getColumnStart());
marker.setAttribute(IMarker.CHAR_END, document.getLineOffset(token.getLine()-1) + token.getColumnEnd());
}
marker.setAttribute(IMarker.LINE_NUMBER, token.getLine());
marker.setAttribute(IMarker.SEVERITY,token.getType().toMarkerSeverity());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@ -143,6 +196,7 @@ public class SampleBuilder extends IncrementalProjectBuilder {
}
protected void fullBuild(final IProgressMonitor monitor)
throws CoreException {
try {
getProject().accept(new SampleResourceVisitor());

View file

@ -1,91 +1,160 @@
package wesnoth_eclipse_plugin.wizards;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
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.jface.dialogs.ErrorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.views.markers.MarkerField;
import wesnoth_eclipse_plugin.Logger;
public class CampaignNewWizard extends Wizard implements INewWizard {
private org.eclipse.ui.IWorkbench workbench;
private org.eclipse.jface.viewers.IStructuredSelection selection;
protected NewCampaignCreationPage fMainPage;
protected CampaignPage0 page0_;
protected CampaignPage1 page1_;
protected int _lastPageHashCode=0;
private IConfigurationElement fConfig;
public void addPages() {
fMainPage = new NewCampaignCreationPage("blah");
addPage(fMainPage);
page0_ = new CampaignPage0();
addPage(page0_);
page1_ = new CampaignPage1();
addPage(page1_);
_lastPageHashCode = page1_.hashCode();
}
// protected PluginContentPage fContentPage;
public CampaignNewWizard() {
// setDefaultPageImageDescriptor(PDEPluginImages.DESC_NEWPPRJ_WIZ);
// setDialogSettings(PDEPlugin.getDefault().getDialogSettings());
// setWindowTitle(PDEUIMessages.NewProjectWizard_title);
// System.exit(0);
setWindowTitle("Create a new Campaign");
setNeedsProgressMonitor(true);
// fPluginData = new PluginFieldData();
setNeedsProgressMonitor(true);
}
public CampaignNewWizard(String osgiFramework) {
this();
// fPluginData.setOSGiFramework(osgiFramework);
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
this.workbench = workbench;
this.selection = selection;
}
// public void init(IWorkbench workbench, IStructuredSelection selection) {
// // TODO Auto-generated method stub
// }
@Override
public boolean performFinish() {
// try {
// fMainPage.updateData();
//// fContentPage.updateData();
// // IDialogSettings settings = getDialogSettings();
//// if (settings != null) {
//// fMainPage.saveSettings(settings);
//// fContentPage.saveSettings(settings);
//// }
// BasicNewProjectResourceWizard.updatePerspective(fConfig);
// // IPluginContentWizard contentWizard = fWizardListPage.getSelectedWizard();
// // getContainer().run(false, true, new NewProjectCreationOperation(fPluginData, fProjectProvider, contentWizard));
//
// // IWorkingSet[] workingSets = fMainPage.getSelectedWorkingSets();
//// if (workingSets.length > 0)
//// getWorkbench().getWorkingSetManager().addToWorkingSets(fProjectProvider.getProject(), workingSets);
//
// return true;
//// } catch (InvocationTargetException e) {
//// // PDEPlugin.logException(e);
//// } catch (InterruptedException e) {
//// }
//// return false;
return true;
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#canFinish()
*/
public boolean canFinish() {
IWizardPage page = getContainer().getCurrentPage();
return super.canFinish() && page != fMainPage;
}
try{
// let's create the project
getContainer().run(false, false, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException {
monitor.beginTask("Creating the project structure...", 10);
try {
IProject currentProject = page0_.getProjectHandle();
// the project
currentProject.create(new NullProgressMonitor());
monitor.worked(2);
// directory structure
createFolder(currentProject, "ai");
createFolder(currentProject, "images");
createFolder(currentProject, "utils");
createFolder(currentProject, "maps");
createFolder(currentProject, "scenarios");
monitor.worked(6);
// _main.cfg
createFile(currentProject, "_main.cfg",String.format("# Hello! \n# Campaign name: %s ",page1_.getCampaignName()));
monitor.worked(2);
} catch (CoreException e) {
e.printStackTrace();
}
monitor.done();
}
});
}
catch (Exception e) {
return false;
}
return true;
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#canFinish()
*/
public boolean canFinish() {
IWizardPage page = getContainer().getCurrentPage();
return super.canFinish() && page.hashCode() == _lastPageHashCode && page.isPageComplete();
}
public void createFolder(IProject project,String folderName)
{
IFolder folder = project.getFolder(folderName);
createResource(folder, project, folderName,null);
}
public void createFile(IProject project, String fileName, String fileContentsString)
{
IFile file = project.getFile(fileName);
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContentsString.getBytes());
createResource(file, project, fileName,inputStream);
}
/**
* Creates the desired resource
* @param resource the resource to be created (IFile/IFolder)
* @param project the project where to be created the resource
* @param resourceName the name of the resource
* @param input the contents of the resource or null if no contents needed
*/
private void createResource(IResource resource, IProject project, String resourceName, InputStream input)
{
try{
if (!project.isOpen())
project.open(new NullProgressMonitor());
if (resource.exists())
return;
if (resource instanceof IFile)
{
((IFile)resource).create(input, true, new NullProgressMonitor());
}
else if (resource instanceof IFolder)
{
((IFolder)resource).create(true, true,new NullProgressMonitor());
}
}catch (CoreException e) {
Logger.print("Error creating the resource"+resourceName, IStatus.ERROR);
ErrorDialog dlgDialog = new ErrorDialog(getShell(), "Error creating the file", "There was an error creating the resource: "+resourceName,
new Status(IStatus.ERROR,"wesnoth_plugin","error"),0);
dlgDialog.open();
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,28 @@
package wesnoth_eclipse_plugin.wizards;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
public class CampaignPage0 extends WizardNewProjectCreationPage {
public CampaignPage0() {
super("wizardPage");
}
/* (non-Javadoc)
* @see org.eclipse.ui.dialogs.WizardNewProjectCreationPage#createControl(org.eclipse.swt.widgets.Composite)
*/
@Override
public void createControl(Composite parent) {
super.createControl(parent);
setMessage("Specify the name of the campaign project.");
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.WizardPage#canFlipToNextPage()
*/
@Override
public boolean canFlipToNextPage() {
return super.canFlipToNextPage();
}
}

View file

@ -0,0 +1,76 @@
/**
* @author Timotei Dolean
*/
package wesnoth_eclipse_plugin.wizards;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import wesnoth_eclipse_plugin.Logger;
public class CampaignPage1 extends WizardPage {
private Text _txtCampaignName;
/**
* Create the wizard.
*/
public CampaignPage1() {
super("wizardPage");
setTitle("Create New Campaign");
setDescription("Creates a new campaign and the files structure.");
setPageComplete(false);
}
/**
* Create contents of the wizard.
* @param parent
*/
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
setControl(container);
_txtCampaignName = new Text(container, SWT.BORDER);
_txtCampaignName.setBounds(112, 7, 179, 21);
_txtCampaignName.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
updateIsPageComplete();
}
});
Label _lblCampaignName = new Label(container, SWT.NONE);
_lblCampaignName.setBounds(10, 10, 96, 15);
_lblCampaignName.setText("Campaign name:");
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.WizardPage#canFlipToNextPage()
*/
@Override
public boolean canFlipToNextPage() {
return getNextPage() != null ;
}
public void updateIsPageComplete()
{
boolean res = true;
if (_txtCampaignName.getText().length() == 0)
res = false;
setPageComplete(res);
}
/**
* @return the Campaign Name
*/
public String getCampaignName() {
return _txtCampaignName.getText();
}
}

View file

@ -1,17 +0,0 @@
package wesnoth_eclipse_plugin.wizards;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
public class NewCampaignCreationPage extends WizardNewProjectCreationPage {
public NewCampaignCreationPage(String pageName) {
super(pageName);
// TODO Auto-generated constructor stub
}
public void updateData() {
// TODO Auto-generated method stub
}
}