eclipse plugin: implement automatic creation of file/directories...

...for campaign project based on text files, so no more source code
changes (part1)
This commit is contained in:
Timotei Dolean 2010-07-01 21:48:12 +00:00
parent bce6bdae0c
commit e5500cd451
15 changed files with 572 additions and 489 deletions

View file

@ -3,16 +3,18 @@
<plugin>
<extension
id="sampleBuilder"
id="Wesnoth_Eclipse_Plugin.projectBuilder"
name="Sample Project Builder"
point="org.eclipse.core.resources.builders">
<builder hasNature="true">
<run class="wesnoth_eclipse_plugin.builder.WesnothProjectBuilder"/>
<run
class="wesnoth_eclipse_plugin.builder.WesnothProjectBuilder">
</run>
</builder>
</extension>
<extension
id="sampleNature"
name="Sample Project Nature"
id="Wesnoth_Eclipse_Plugin.sampleNature"
name="ProjectNature"
point="org.eclipse.core.resources.natures">
<runtime>
<run
@ -20,7 +22,7 @@
</run>
</runtime>
<builder
id="Wesnoth_Eclipse_Plugin.sampleBuilder">
id="Wesnoth_Eclipse_Plugin.projectBuilder">
</builder>
</extension>
<extension

View file

@ -5,16 +5,19 @@ import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import wesnoth_eclipse_plugin.wizards.TemplateProvider;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
public class Activator extends AbstractUIPlugin
{
// The plug-in ID
public static final String PLUGIN_ID = "Wesnoth_Eclipse_Plugin";
public static final String PLUGIN_ID = "Wesnoth_Eclipse_Plugin";
// The shared instance
private static Activator plugin;
private static Activator plugin;
/**
* The constructor
@ -24,10 +27,13 @@ public class Activator extends AbstractUIPlugin {
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
* )
*/
@Override
public void start(BundleContext context) throws Exception {
public void start(BundleContext context) throws Exception
{
super.start(context);
plugin = this;
TemplateProvider.getInstance().loadTemplates();
@ -35,31 +41,36 @@ public class Activator extends AbstractUIPlugin {
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
* )
*/
@Override
public void stop(BundleContext context) throws Exception {
public void stop(BundleContext context) throws Exception
{
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
*
* @return the shared instance
*/
public static Activator getDefault() {
public static Activator getDefault()
{
return plugin;
}
/**
* Returns an image descriptor for the image file at the given
* plug-in relative path
*
* Returns an image descriptor for the image file at the given plug-in
* relative path
*
* @param path the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
public static ImageDescriptor getImageDescriptor(String path)
{
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}

View file

@ -1,120 +0,0 @@
/**
* @author Timotei Dolean
*/
package wesnoth_eclipse_plugin;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import wesnoth_eclipse_plugin.utils.StringUtils;
public class TemplateProvider {
private static TemplateProvider instance_;
private HashMap<String, String> templates_ = new HashMap<String, String>();
public static TemplateProvider getInstance(){
if (instance_ == null) {
instance_ = new TemplateProvider();
}
return instance_;
}
public final String templatesFile = "templatesIndex.txt";
private final String pluginFullPath_ = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
/** Loads the templates from the file system
*/
public void loadTemplates()
{
try {
Logger.print("reading templates...");
Logger.print(pluginFullPath_+ templatesFile);
BufferedReader reader = new BufferedReader(
new FileReader(getClass().getProtectionDomain().getCodeSource().getLocation().getPath()+
templatesFile));
BufferedReader tmpReader;
String line,tmpLine,content;
// read the main "templatesIndex.txt" file
while((line = reader.readLine()) != null)
{
// comment
if (line.startsWith("#")) {
continue;
}
// 0 - template name | 1 - template file
String[] tokensStrings = line.split(" ");
if (tokensStrings.length != 2) {
continue;
}
content ="";
if (new File(pluginFullPath_+tokensStrings[1]).exists())
{
tmpReader = new BufferedReader(new FileReader(pluginFullPath_+tokensStrings[1]));
while((tmpLine = tmpReader.readLine())!=null)
{
content += tmpLine + '\n';
}
templates_.put(tokensStrings[0],content);
//System.out.println(String.format("read %s with content: %s\n",tokensStrings[0],content));
tmpReader.close();
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getProcessedTemplate(String templateName, ArrayList<ReplaceableParameter> parameters)
{
String tmpTemplate=TemplateProvider.getInstance().getTemplate(templateName);
if (tmpTemplate == null)
{
return null;
}
String result="";
String[] template = tmpTemplate.split("\\r?\\n");
for (int i=0;i<template.length;++i) {
for (ReplaceableParameter param : parameters) {
if (template[i].contains(param.paramName))
{
template[i] = template[i].replace(param.paramName, param.paramValue);
if (param.paramValue == null || param.paramValue.isEmpty())
{
// we don't have any value supplied -
// let's comment that line (if it's not already commented)
if (!(StringUtils.startsWith(template[i],"#"))) {
template[i]= "#" + template[i];
}
}
}
}
result+= template[i]+"\n";
}
return result;
}
public String getTemplate(String name)
{
if (templates_.get(name) == null) {
return "";
}
return templates_.get(name);
}
}

View file

@ -25,15 +25,20 @@ import wesnoth_eclipse_plugin.utils.AntUtils;
import wesnoth_eclipse_plugin.utils.GUIUtils;
import wesnoth_eclipse_plugin.utils.WorkspaceUtils;
public class WesnothProjectBuilder extends IncrementalProjectBuilder {
public class WesnothProjectBuilder extends IncrementalProjectBuilder
{
public static final String BUILDER_ID = "Wesnoth_Eclipse_Plugin.projectBuilder";
private static final String MARKER_TYPE = "Wesnoth_Eclipse_Plugin.configProblem";
public static final String BUILDER_ID = "Wesnoth_Eclipse_Plugin.projectBuilder";
private static final String MARKER_TYPE = "Wesnoth_Eclipse_Plugin.configProblem";
class SampleDeltaVisitor implements IResourceDeltaVisitor {
public boolean visit(IResourceDelta delta) throws CoreException {
class SampleDeltaVisitor implements IResourceDeltaVisitor
{
@Override
public boolean visit(IResourceDelta delta) throws CoreException
{
IResource resource = delta.getResource();
switch (delta.getKind()) {
switch (delta.getKind())
{
case IResourceDelta.ADDED:
// handle added resource
checkResource(resource);
@ -46,40 +51,47 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder {
checkResource(resource);
break;
}
//return true to continue visiting children.
// return true to continue visiting children.
return true;
}
}
class SampleResourceVisitor implements IResourceVisitor {
public boolean visit(IResource resource) {
class SampleResourceVisitor implements IResourceVisitor
{
@Override
public boolean visit(IResource resource)
{
checkResource(resource);
//return true to continue visiting children.
// return true to continue visiting children.
return true;
}
}
protected void fullBuild(final IProgressMonitor monitor) throws CoreException {
try {
protected void fullBuild(final IProgressMonitor monitor) throws CoreException
{
try
{
getProject().accept(new SampleResourceVisitor());
} catch (CoreException e) {
} catch (CoreException e)
{
e.printStackTrace();
}
}
protected void incrementalBuild(IResourceDelta delta, IProgressMonitor monitor) throws CoreException {
protected void incrementalBuild(IResourceDelta delta, IProgressMonitor monitor) throws CoreException
{
// the visitor does the work.
delta.accept(new SampleDeltaVisitor());
}
@Override
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException {
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException
{
System.out.println("building");
if (PreferenceInitializer.getString(PreferenceConstants.P_WESNOTH_USER_DIR).isEmpty())
{
GUIUtils.showMessageBox(WorkspaceUtils.getWorkbenchWindow(),
"Please set the wesnoth user dir before creating the content");
GUIUtils.showMessageBox(WorkspaceUtils.getWorkbenchWindow(), "Please set the wesnoth user dir before creating the content");
return null;
}
@ -87,17 +99,15 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder {
// in the user add-ons directory (incremental)
if (!(new File(getProject().getLocation().toOSString() + "/build.xml").exists()))
{
GUIUtils.showMessageBox(WorkspaceUtils.getWorkbenchWindow(),
"The 'build.xml' file is missing. The building cannot continue.");
//TODO: better way of handling this - maybe regenerating?
GUIUtils.showMessageBox(WorkspaceUtils.getWorkbenchWindow(), "The 'build.xml' file is missing. The building cannot continue.");
// TODO: better way of handling this - maybe regenerating?
return null;
}
HashMap<String, String> properties = new HashMap<String, String>();
properties.put("wesnoth.user.dir",
PreferenceInitializer.getString(PreferenceConstants.P_WESNOTH_USER_DIR) + Path.SEPARATOR);
properties.put("wesnoth.user.dir", PreferenceInitializer.getString(PreferenceConstants.P_WESNOTH_USER_DIR) + Path.SEPARATOR);
System.out.println("Ant result:");
String result = AntUtils.runAnt(getProject().getLocation().toOSString() + "/build.xml",properties,true);
String result = AntUtils.runAnt(getProject().getLocation().toOSString() + "/build.xml", properties, true);
System.out.println(result);
if (result == null)
@ -110,91 +120,103 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder {
// create the temporary directory used by the plugin if not created
WorkspaceUtils.getTemporaryFolder();
if (kind == FULL_BUILD) {
if (kind == FULL_BUILD)
{
fullBuild(monitor);
} else {
}
else
{
IResourceDelta delta = getDelta(getProject());
if (delta == null) {
if (delta == null)
{
fullBuild(monitor);
} else {
}
else
{
incrementalBuild(delta, monitor);
}
}
return null;
}
void checkResource(IResource resource) {
void checkResource(IResource resource)
{
// config files
if (resource instanceof IFile &&
(resource.getName().toLowerCase(Locale.ENGLISH).endsWith(".cfg")))
if (resource instanceof IFile && (resource.getName().toLowerCase(Locale.ENGLISH).endsWith(".cfg")))
{
try
{
IFile file = (IFile) resource;
deleteMarkers(file);
PreprocessorActions.preprocessFile(WorkspaceUtils.getPathRelativeToUserDir(file),
WorkspaceUtils.getTemporaryFolder(), null, true,false);
PreprocessorActions.preprocessFile(WorkspaceUtils.getPathRelativeToUserDir(file), WorkspaceUtils.getTemporaryFolder(), null, true, false);
// TODO: here be dragons
// - add markers for wmllint, wmlscope
// - need a better output from wmltools
/*
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) {
* 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();
}
}
}
private void addMarker(IFile file, String message, int lineNumber,
int severity) {
try {
private void addMarker(IFile file, String message, int lineNumber, int severity)
{
try
{
IMarker marker = file.createMarker(MARKER_TYPE);
marker.setAttribute(IMarker.MESSAGE, message);
marker.setAttribute(IMarker.SEVERITY, severity);
if (lineNumber == -1) {
if (lineNumber == -1)
{
lineNumber = 1;
}
marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
} catch (CoreException e) {
} catch (CoreException e)
{
e.printStackTrace();
}
}
private void deleteMarkers(IFile file) {
try {
private void deleteMarkers(IFile file)
{
try
{
file.deleteMarkers(MARKER_TYPE, false, IResource.DEPTH_ZERO);
} catch (CoreException e) {
} catch (CoreException e)
{
e.printStackTrace();
}
}

View file

@ -14,7 +14,7 @@ import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import wesnoth_eclipse_plugin.Activator;
import wesnoth_eclipse_plugin.utils.FileUtils;
import wesnoth_eclipse_plugin.utils.ResourceUtils;
import wesnoth_eclipse_plugin.utils.WorkspaceUtils;
public class MapActions
@ -47,7 +47,7 @@ public class MapActions
return;
}
FileUtils.copyTo(source, target);
ResourceUtils.copyTo(source, target);
WorkspaceUtils.getSelectedFolder(window).refreshLocal(IResource.DEPTH_INFINITE, null);
}
catch (Exception e)

View file

@ -1,65 +0,0 @@
/**
* @author Timotei Dolean
*/
package wesnoth_eclipse_plugin.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class FileUtils
{
/**
* Copies a file from source to target
* @param source
* @param target
* @throws Exception
*/
public static void copyTo(File source, File target) throws Exception
{
if (source == null || target == null)
return;
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
public static String getFileContents(File file)
{
String contentsString = "";
BufferedReader reader = null;
try
{
String line = "";
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while((line = reader.readLine()) != null)
contentsString += (line + "\n");
}
catch (Exception e)
{
e.printStackTrace();
}
finally{
try{
reader.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
return contentsString;
}
}

View file

@ -16,7 +16,7 @@ public class ProjectUtils
if (!file.exists())
return null;
String fileContents = FileUtils.getFileContents(file);
String fileContents = ResourceUtils.getFileContents(file);
int index = fileContents.indexOf(propertyName + "=");
if (index == -1)
return null;
@ -62,13 +62,13 @@ public class ProjectUtils
public static boolean isCampaignFile(String fileName)
{
//TODO: replace this with a better checking
String fileContentString = FileUtils.getFileContents(new File(fileName));
String fileContentString = ResourceUtils.getFileContents(new File(fileName));
return (fileContentString.contains("[campaign]") && fileContentString.contains("[/campaign]"));
}
public static boolean isScenarioFile(String fileName)
{
//TODO: replace this with a better checking
String fileContentString = FileUtils.getFileContents(new File(fileName));
String fileContentString = ResourceUtils.getFileContents(new File(fileName));
return (fileContentString.contains("[scenario]") && fileContentString.contains("[/scenario]"));
}
}

View file

@ -0,0 +1,150 @@
/**
* @author Timotei Dolean
*/
package wesnoth_eclipse_plugin.utils;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
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.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import wesnoth_eclipse_plugin.Activator;
import wesnoth_eclipse_plugin.Logger;
public class ResourceUtils
{
/**
* Copies a file from source to target
* @param source
* @param target
* @throws Exception
*/
public static void copyTo(File source, File target) throws Exception
{
if (source == null || target == null)
return;
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
public static String getFileContents(File file)
{
String contentsString = "";
BufferedReader reader = null;
try
{
String line = "";
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((line = reader.readLine()) != null)
{
contentsString += (line + "\n");
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
try
{
reader.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
return contentsString;
}
/**
* 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
*/
public static 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(Activator.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();
}
}
/**
* Creates a folder in the specified project with the specified details
* @param project the project in which the folder will be created
* @param folderName the name of the folder
*/
public static void createFolder(IProject project, String folderName)
{
IFolder folder = project.getFolder(folderName);
createResource(folder, project, folderName, null);
}
/**
* Creates a file in the specified project with the specified details
* @param project the project in which the file will be created
* @param fileName the filename of the file
* @param fileContentsString the text which will be contained in the file
*/
public static void createFile(IProject project, String fileName, String fileContentsString)
{
IFile file = project.getFile(fileName);
if (fileContentsString == null)
{
fileContentsString = "";
Logger.print("file contents are null", 2);
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContentsString.getBytes());
createResource(file, project, fileName, inputStream);
}
}

View file

@ -6,10 +6,11 @@ package wesnoth_eclipse_plugin.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtils {
public class StringUtils
{
public static boolean startsWith(String target, String sequence)
{
Pattern pattern = Pattern.compile("[\t| ]*\\"+sequence);
Pattern pattern = Pattern.compile("[\t| ]*" + Pattern.quote(sequence));
Matcher matcher = pattern.matcher(target);
return (matcher.find() && matcher.start() == 0);
}
@ -26,10 +27,10 @@ public class StringUtils {
return -1;
int cnt = 0;
String tmpString = target;
while(tmpString.contains(new String(new char[]{ character} )))
while (tmpString.contains(new String(new char[] { character })))
{
++cnt;
tmpString = tmpString.substring(tmpString.indexOf(character) +1);
tmpString = tmpString.substring(tmpString.indexOf(character) + 1);
}
return cnt;
}
@ -46,7 +47,7 @@ public class StringUtils {
if (countOf(target, character) < n)
return -1;
int index=-1,cnt=0;
int index = -1, cnt = 0;
for (int i = 0; i < target.length() && cnt <= n; ++i)
{
if (target.charAt(i) == character)
@ -60,34 +61,39 @@ public class StringUtils {
/**
* Removes all consecutive aparitions of a character in the specified string
* so that only one appearance remains in each past duplications of that string
* so that only one appearance remains in each past duplications of that
* string
* @param target the string to process
* @param character the character to remove
* @param removeTrailing removes or not the trailing 'character' characters
* @param removeTrailing removes or not the preceding 'character' characters
* @return
*/
public static String removeIncorrectCharacters(String target, char character,
boolean removeTrailing, boolean removePreceding)
public static String removeIncorrectCharacters(String target, char character, boolean removeTrailing, boolean removePreceding)
{
StringBuilder resString = new StringBuilder();
for(int i=0;i<target.length();i++)
for (int i = 0; i < target.length(); i++)
{
// pass over successive repetitions:
// abbbac will become: abac
if (i>0 && (target.charAt(i) == target.charAt(i-1)))
if (i > 0 && (target.charAt(i) == target.charAt(i - 1)))
{
continue;
}
if (target.charAt(i) == character &&(
(removeTrailing && i == target.length()) ||
(removePreceding && i == 0))
)
if (target.charAt(i) == character && ((removeTrailing && i == target.length()) || (removePreceding && i == 0)))
{
continue;
}
resString.append(target.charAt(i));
}
return resString.toString();
}
public static String[] getLines(String string)
{
return string.split("\\r?\\n");
}
}

View file

@ -1,20 +1,12 @@
package wesnoth_eclipse_plugin.wizards;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
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.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;
@ -22,20 +14,20 @@ import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import wesnoth_eclipse_plugin.Logger;
import wesnoth_eclipse_plugin.ReplaceableParameter;
import wesnoth_eclipse_plugin.TemplateProvider;
import wesnoth_eclipse_plugin.utils.ResourceUtils;
import wesnoth_eclipse_plugin.utils.StringUtils;
public class CampaignNewWizard extends Wizard implements INewWizard {
protected CampaignPage0 page0_;
protected CampaignPage1 page1_;
protected CampaignPage2 page2_;
public class CampaignNewWizard extends Wizard implements INewWizard
{
protected CampaignPage0 page0_;
protected CampaignPage1 page1_;
protected CampaignPage2 page2_;
protected int lastPageHashCode_=0;
protected int lastPageHashCode_ = 0;
@Override
public void addPages() {
public void addPages()
{
page0_ = new CampaignPage0();
addPage(page0_);
@ -45,78 +37,88 @@ public class CampaignNewWizard extends Wizard implements INewWizard {
page2_ = new CampaignPage2();
addPage(page2_);
lastPageHashCode_ = getPages()[getPageCount()-1].hashCode();
lastPageHashCode_ = getPages()[getPageCount() - 1].hashCode();
}
public CampaignNewWizard() {
setWindowTitle("Create a new Campaign");
setNeedsProgressMonitor(true);
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
public void init(IWorkbench workbench, IStructuredSelection selection)
{
}
@Override
public boolean performFinish() {
try{
public boolean performFinish()
{
try
{
// let's create the project
getContainer().run(false, false, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
{
createProject(monitor);
monitor.done();
}
});
}
catch (Exception e) {
} catch (Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
public void createProject(IProgressMonitor monitor)
{
monitor.beginTask("Creating the project structure...", 15);
try {
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, "music");
createFolder(currentProject, "scenarios");
createFolder(currentProject, "units");
monitor.worked(5);
String campaignStructure = prepareTemplate("campaign_structure");
if (campaignStructure == null)
return;
// _main.cfg
createFile(currentProject, "_main.cfg",prepareTemplate("campaign"));
monitor.worked(2);
for (String line : StringUtils.getLines(campaignStructure))
{
if (StringUtils.startsWith(line, "#"))
continue;
// campaign_name.pbl - for uploading the campaign on the webserver
createFile(currentProject, page1_.getCampaignName()+".pbl",prepareTemplate("pbl"));
monitor.worked(2);
if (line.contains(":")) // file with template
{
String[] tmpLine = line.split(":");
createFile(currentProject, "build.xml", prepareTemplate("build.xml"));
monitor.worked(4);
// oops. error
if (tmpLine.length != 2)
continue;
} catch (CoreException e) {
ResourceUtils.createFile(currentProject, tmpLine[0].trim(), prepareTemplate(tmpLine[1].trim()));
}
else
{
ResourceUtils.createFolder(currentProject, line.trim());
}
monitor.worked(1);
}
} catch (CoreException e)
{
e.printStackTrace();
}
monitor.done();
}
public String prepareTemplate(String templateName)
private String prepareTemplate(String templateName)
{
ArrayList<ReplaceableParameter> params = new ArrayList<ReplaceableParameter>();
@ -137,85 +139,15 @@ public class CampaignNewWizard extends Wizard implements INewWizard {
params.add(new ReplaceableParameter("$$first_scenario", page2_.getFirstScenario()));
params.add(new ReplaceableParameter("$$project_name", page0_.getProjectName()));
params.add(new ReplaceableParameter("$$type", page1_.isMultiplayer()?"campaign_mp":"campaign"));
params.add(new ReplaceableParameter("$$type", page1_.isMultiplayer() ? "campaign_mp" : "campaign"));
return TemplateProvider.getProcessedTemplate(templateName, params);
}
public void replaceParameter(String templateName, String[] template, String paramName,String paramValue)
{
for (int i=0;i<template.length;++i) {
if (template[i].contains(paramName))
{
template[i] = template[i].replace(paramName, paramValue);
if (paramValue == null || paramValue.isEmpty())
{
// we don't have any value supplied -
// let's comment that line (if it's not already commented)
if (!(StringUtils.startsWith(template[i],"#"))) {
template[i]= "#" + template[i];
}
}
}
}
}
@Override
public boolean 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);
if (fileContentsString == null) {
fileContentsString = "";
Logger.print("file contents are null (CampaignNewWizard.java)", 2);
}
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

@ -1,7 +1,7 @@
/**
* @author Timotei Dolean
*/
package wesnoth_eclipse_plugin;
package wesnoth_eclipse_plugin.wizards;
public class ReplaceableParameter{
public String paramName;

View file

@ -30,28 +30,25 @@ import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import wesnoth_eclipse_plugin.ReplaceableParameter;
import wesnoth_eclipse_plugin.TemplateProvider;
import wesnoth_eclipse_plugin.utils.GUIUtils;
import wesnoth_eclipse_plugin.utils.WorkspaceUtils;
/**
* This is a sample new wizard. Its role is to create a new file
* resource in the provided container. If the container resource
* (a folder or a project) is selected in the workspace
* when the wizard is opened, it will accept it as the target
* container. The wizard creates one file with the extension
* "cfg". If a sample multi-page editor (also available
* as a template) is registered for the same extension, it will
* be able to open it.
* This is a sample new wizard. Its role is to create a new file resource in the
* provided container. If the container resource (a folder or a project) is
* selected in the workspace when the wizard is opened, it will accept it as the
* target container. The wizard creates one file with the extension "cfg". If a
* sample multi-page editor (also available as a template) is registered for the
* same extension, it will be able to open it.
*/
public class ScenarioNewWizard extends Wizard implements INewWizard {
private ScenarioPage0 page0_;
private ScenarioPage1 page1_;
private ISelection selection;
public class ScenarioNewWizard extends Wizard implements INewWizard
{
private ScenarioPage0 page0_;
private ScenarioPage1 page1_;
private ISelection selection;
protected int lastPageHashCode_;
protected int lastPageHashCode_;
/**
* Constructor for ScenarioNewWizard.
@ -65,49 +62,61 @@ public class ScenarioNewWizard extends Wizard implements INewWizard {
* Adding the page to the wizard.
*/
@Override
public void addPages() {
page0_ = new ScenarioPage0(selection);
addPage(page0_);
public void addPages()
{
this.page0_ = new ScenarioPage0(this.selection);
addPage(this.page0_);
page1_ = new ScenarioPage1();
//addPage(page1_);
this.page1_ = new ScenarioPage1();
// addPage(page1_);
lastPageHashCode_ = getPages()[getPageCount()-1].hashCode();
this.lastPageHashCode_ = getPages()[getPageCount() - 1].hashCode();
}
/* (non-Javadoc)
/*
* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#canFinish()
*/
@Override
public boolean canFinish() {
public boolean canFinish()
{
IWizardPage page = getContainer().getCurrentPage();
return super.canFinish() && page.hashCode() == lastPageHashCode_ && page.isPageComplete();
return super.canFinish() && page.hashCode() == this.lastPageHashCode_ && page.isPageComplete();
}
/**
* This method is called when 'Finish' button is pressed in
* the wizard. We will create an operation and run it
* using wizard as execution context.
* This method is called when 'Finish' button is pressed in the wizard. We
* will create an operation and run it using wizard as execution context.
*/
@Override
public boolean performFinish() {
final String containerName = page0_.getProjectName();
final String fileName = page0_.getFileName();
public boolean performFinish()
{
final String containerName = this.page0_.getProjectName();
final String fileName = this.page0_.getFileName();
IRunnableWithProgress op = new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
public void run(IProgressMonitor monitor) throws InvocationTargetException
{
try
{
doFinish(containerName, fileName, monitor);
} catch (CoreException e) {
} catch (CoreException e)
{
throw new InvocationTargetException(e);
} finally {
} finally
{
monitor.done();
}
}
};
try {
try
{
getContainer().run(false, false, op);
} catch (InterruptedException e) {
} catch (InterruptedException e)
{
return false;
} catch (InvocationTargetException e) {
} catch (InvocationTargetException e)
{
Throwable realException = e.getTargetException();
MessageDialog.openError(getShell(), "Error", realException.getMessage());
return false;
@ -116,50 +125,56 @@ public class ScenarioNewWizard extends Wizard implements INewWizard {
}
/**
* The worker method. It will find the container, create the
* file if missing or just replace its contents, and open
* the editor on the newly created file.
* The worker method. It will find the container, create the file if missing
* or just replace its contents, and open the editor on the newly created
* file.
*/
private void doFinish(
String containerName,
String fileName,
IProgressMonitor monitor)
throws CoreException {
private void doFinish(String containerName, String fileName, IProgressMonitor monitor) throws CoreException
{
// create a sample file
monitor.beginTask("Creating " + fileName, 2);
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IResource resource = root.findMember(new Path(containerName));
if (!resource.exists() || !(resource instanceof IContainer)) {
if (!resource.exists() || !(resource instanceof IContainer))
{
throwCoreException("Container \"" + containerName + "\" does not exist.");
}
IContainer container = (IContainer) resource;
final IFile file = container.getFile(new Path(fileName));
try {
try
{
InputStream stream = getScenarioStream();
if (stream == null) {
if (stream == null)
{
return;
}
if (file.exists()) {
if (file.exists())
{
file.setContents(stream, true, true, monitor);
} else {
} else
{
file.create(stream, true, monitor);
}
stream.close();
} catch (IOException e) {
} catch (IOException e)
{
e.printStackTrace();
}
monitor.worked(1);
monitor.setTaskName("Opening file for editing...");
getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
IWorkbenchPage page =
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
try {
@Override
public void run()
{
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
try
{
IDE.openEditor(page, file, true);
} catch (PartInitException e) {
} catch (PartInitException e)
{
}
}
});
@ -169,41 +184,42 @@ public class ScenarioNewWizard extends Wizard implements INewWizard {
/**
* Returns the scenario file contents as an InputStream
*/
private InputStream getScenarioStream() {
private InputStream getScenarioStream()
{
ArrayList<ReplaceableParameter> params = new ArrayList<ReplaceableParameter>();
params.add(new ReplaceableParameter("$$scenario_id", page0_.getScenarioId()));
params.add(new ReplaceableParameter("$$next_scenario_id", page0_.getNextScenarioId()));
params.add(new ReplaceableParameter("$$scenario_name", page0_.getScenarioName()));
params.add(new ReplaceableParameter("$$map_data", page0_.getMapData()));
params.add(new ReplaceableParameter("$$turns_number", String.valueOf(page0_.getTurnsNumber())));
params.add(new ReplaceableParameter("$$scenario_id", this.page0_.getScenarioId()));
params.add(new ReplaceableParameter("$$next_scenario_id", this.page0_.getNextScenarioId()));
params.add(new ReplaceableParameter("$$scenario_name", this.page0_.getScenarioName()));
params.add(new ReplaceableParameter("$$map_data", this.page0_.getMapData()));
params.add(new ReplaceableParameter("$$turns_number", String.valueOf(this.page0_.getTurnsNumber())));
String template = TemplateProvider.getProcessedTemplate("scenario", params);
if (template == null)
{
GUIUtils.showMessageBox(WorkspaceUtils.getWorkbenchWindow(),
"Template for \"scenario\" not found.");
GUIUtils.showMessageBox(WorkspaceUtils.getWorkbenchWindow(), "Template for \"scenario\" not found.");
return null;
}
return new ByteArrayInputStream(template.getBytes());
}
private void throwCoreException(String message) throws CoreException {
IStatus status =
new Status(IStatus.ERROR, "Wesnoth_Eclipse_Plugin", IStatus.OK, message, null);
private void throwCoreException(String message) throws CoreException
{
IStatus status = new Status(IStatus.ERROR, "Wesnoth_Eclipse_Plugin", IStatus.OK, message, null);
throw new CoreException(status);
}
/**
* We will accept the selection in the workbench to see if
* we can initialize from it.
* We will accept the selection in the workbench to see if we can initialize
* from it.
* @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
*/
public void init(IWorkbench workbench, IStructuredSelection selection) {
@Override
public void init(IWorkbench workbench, IStructuredSelection selection)
{
this.selection = selection;
}
}

View file

@ -0,0 +1,128 @@
/**
* @author Timotei Dolean
*/
package wesnoth_eclipse_plugin.wizards;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import wesnoth_eclipse_plugin.Logger;
import wesnoth_eclipse_plugin.utils.StringUtils;
public class TemplateProvider
{
private static TemplateProvider instance_;
private final HashMap<String, String> templates_ = new HashMap<String, String>();
public static TemplateProvider getInstance()
{
if (instance_ == null)
{
instance_ = new TemplateProvider();
}
return instance_;
}
public final String templatesFile = "templatesIndex.txt";
private final String pluginFullPath_ = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
/**
* Loads the templates from the file system
*/
public void loadTemplates()
{
try
{
Logger.print("reading templates...");
Logger.print(this.pluginFullPath_ + this.templatesFile);
BufferedReader reader = new BufferedReader(new FileReader(getClass().getProtectionDomain().getCodeSource().getLocation().getPath() + this.templatesFile));
BufferedReader tmpReader;
String line, tmpLine, content;
// read the main "templatesIndex.txt" file
while ((line = reader.readLine()) != null)
{
// comment
if (line.startsWith("#"))
{
continue;
}
// 0 - template name | 1 - template file
String[] tokensStrings = line.split(" ");
if (tokensStrings.length != 2)
{
continue;
}
content = "";
if (new File(this.pluginFullPath_ + tokensStrings[1]).exists())
{
tmpReader = new BufferedReader(new FileReader(this.pluginFullPath_ + tokensStrings[1]));
while ((tmpLine = tmpReader.readLine()) != null)
{
content += tmpLine + '\n';
}
this.templates_.put(tokensStrings[0], content);
// System.out.println(String.format("read %s with content: %s\n",tokensStrings[0],content));
tmpReader.close();
}
}
reader.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
public static String getProcessedTemplate(String templateName, ArrayList<ReplaceableParameter> parameters)
{
String tmpTemplate = TemplateProvider.getInstance().getTemplate(templateName);
if (tmpTemplate == null)
return null;
String result = "";
String[] template = StringUtils.getLines(tmpTemplate);
for (int i = 0; i < template.length; ++i)
{
for (ReplaceableParameter param : parameters)
{
if (template[i].contains(param.paramName))
{
template[i] = template[i].replace(param.paramName, param.paramValue);
if (param.paramValue == null || param.paramValue.isEmpty())
{
// we don't have any value supplied -
// let's comment that line (if it's not already
// commented)
if (!(StringUtils.startsWith(template[i], "#")))
{
template[i] = "#" + template[i];
}
}
}
}
result += template[i] + "\n";
}
return result;
}
public String getTemplate(String name)
{
if (this.templates_.get(name) == null)
return "";
return this.templates_.get(name);
}
}

View file

@ -1,6 +1,6 @@
# specifies the folders or files(and template name used)
# to be created on a new campaign project
# NOT IMPLEMENTED!
# specifies a list of file/directory names to be created on a new campaign project
# if a line doesn't contain a template (e.g. <filename>:<template_name>)
# it will be considered a directory
ai
images
maps
@ -10,3 +10,4 @@ units
utils
_main.cfg:campaign
$$campaign_name.pbl:pbl
build.xml:build_xml

View file

@ -4,4 +4,4 @@ campaign_structure templates/camp_structure.txt
campaign templates/campaign.txt
scenario templates/scenario.txt
pbl templates/pbl.txt
build.xml templates/build.xml
build_xml templates/build.xml