git-svn-id: svn://svn.code.sf.net/p/chibios/svn/trunk@4520 35acf78f-673a-0410-8e92-d51de3d6d3f4

master
gdisirio 2012-08-05 07:50:46 +00:00
parent aee94a40c7
commit ee8a302e4c
7 changed files with 1122 additions and 0 deletions

View File

@ -0,0 +1,88 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
2011,2012 Giovanni Di Sirio.
This file is part of ChibiOS/RT.
ChibiOS/RT is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS/RT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package config_wizard;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.chibios.tools.eclipse.config"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
* )
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
* )
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given plug-in
* relative path
*
* @param path
* the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
}

View File

@ -0,0 +1,54 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
2011,2012 Giovanni Di Sirio.
This file is part of ChibiOS/RT.
ChibiOS/RT is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS/RT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.chibios.tools.eclipse.config.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.jface.dialogs.MessageDialog;
/**
* Our sample handler extends AbstractHandler, an IHandler base class.
* @see org.eclipse.core.commands.IHandler
* @see org.eclipse.core.commands.AbstractHandler
*/
public class CheckDescription extends AbstractHandler {
/**
* The constructor.
*/
public CheckDescription() {
}
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"ChibiOS-RT_Configuration_Support",
"Hello, Eclipse world");
return null;
}
}

View File

@ -0,0 +1,141 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
2011,2012 Giovanni Di Sirio.
This file is part of ChibiOS/RT.
ChibiOS/RT is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS/RT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.chibios.tools.eclipse.config.handlers;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import org.chibios.tools.eclipse.config.utils.TemplateEngine;
import org.chibios.tools.eclipse.config.utils.TemplateException;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.osgi.framework.Bundle;
import config_wizard.Activator;
/**
* Our sample handler extends AbstractHandler, an IHandler base class.
*
* @see org.eclipse.core.commands.IHandler
* @see org.eclipse.core.commands.AbstractHandler
*/
public class GenerateFiles extends AbstractHandler {
/**
* The constructor.
*/
public GenerateFiles() {
}
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil
.getActiveWorkbenchWindowChecked(event);
ISelection selection = window.getSelectionService().getSelection();
if (selection instanceof IStructuredSelection) {
/* Retrieves the full path of the configuration file. */
IPath cfgfilepath = ((IFile) ((IStructuredSelection) selection)
.getFirstElement()).getLocation();
/* Determines the base path as the parent of the configuration file.*/
IPath basepath = cfgfilepath.removeLastSegments(1);
/* Reads the configuration file into a Properties object. */
Properties cfgfile = new Properties();
try {
cfgfile.load(new FileReader(cfgfilepath.toFile()));
} catch (IOException e) {
MessageDialog.openInformation(window.getShell(), "I/O Error",
e.getMessage());
return null;
}
/* Retrieves source property. */
String source = cfgfile.getProperty("source");
if (source == null) {
MessageDialog.openInformation(window.getShell(), "Properties Error",
"Property \"source\" not found in configuration file.");
return null;
}
/* Retrieves xmlfile property. */
String xmlfile = cfgfile.getProperty("xmlfile");
if (xmlfile == null) {
MessageDialog.openInformation(window.getShell(), "Properties Error",
"Property \"xmlfile\" not found in configuration file.");
return null;
}
/* Retrieves output property. */
String output = cfgfile.getProperty("output");
if (output == null) {
MessageDialog.openInformation(window.getShell(), "Properties Error",
"Property \"output\" not found in configuration file.");
return null;
}
/* Calculating derived paths. */
IPath sourcepath = new Path(source);
IPath libpath = new Path("resources/gencfg/lib");
try {
Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
sourcepath = new Path(FileLocator.toFileURL(
FileLocator.find(bundle, sourcepath, null)).getFile());
libpath = new Path(FileLocator.toFileURL(
FileLocator.find(bundle, libpath, null)).getFile());
} catch (IOException e) {
MessageDialog.openInformation(window.getShell(), "Path Error",
e.getMessage());
return null;
}
/* Templates execution. */
try {
TemplateEngine.process(basepath.addTrailingSeparator().append(xmlfile)
.toFile(), libpath.toFile(), sourcepath.toFile(),
basepath.toFile(), new File(output));
} catch (TemplateException e) {
MessageDialog.openInformation(window.getShell(), "Processing Error",
e.getMessage());
return null;
}
}
return null;
}
}

View File

@ -0,0 +1,213 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
2011,2012 Giovanni Di Sirio.
This file is part of ChibiOS/RT.
ChibiOS/RT is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS/RT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.chibios.tools.eclipse.config.utils;
import java.io.IOException;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.IConsoleView;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import fmpp.Engine;
import fmpp.ProcessingException;
import fmpp.ProgressListener;
import fmpp.setting.SettingException;
import fmpp.setting.Settings;
import freemarker.ext.dom.NodeModel;
import freemarker.template.TemplateNodeModel;
/**
* FMPP wrapper class.
*/
public class TemplateEngine {
private static final String CONSOLE_NAME = "ChibiOS/RT Configuration Tool";
private static Settings settings;
private static MessageConsoleStream out;
/**
* Runs the templates engine.
*
* @param xmldata
* absolute path to XML data file
* @param libdir
* absolute path to libraries directory
* @param sourcedir
* absolute path to templates directory
* @param basedir
* absolute path to project directory
* @param outputdir
* output directory relative to basedir
*
* @throws SettingException
* @throws ProcessingException
*/
public static void process(java.io.File xmldata, java.io.File libdir,
java.io.File sourcedir, java.io.File basedir,
java.io.File outputdir) throws TemplateException {
/* Finds or creates a named console. */
MessageConsole console = findConsole(CONSOLE_NAME);
activateConsole(console);
console.clearConsole();
out = console.newMessageStream();
/*
* Instantiates the FMPP Settings engine and associates a listener for
* events to be logged.
*/
try {
settings = new Settings(basedir);
} catch (SettingException e) {
e.printStackTrace();
return;
}
settings.addProgressListener(new ProgressListener() {
public void notifyProgressEvent(Engine engine, int event,
java.io.File src, int pMode,
java.lang.Throwable error,
java.lang.Object param) {
if (pMode == Engine.PMODE_IGNORE)
return;
switch (event) {
case EVENT_BEGIN_PROCESSING_SESSION:
out.println("Starting session");
break;
case EVENT_END_PROCESSING_SESSION:
out.println("Finished");
break;
case EVENT_BEGIN_FILE_PROCESSING:
out.println("Processing " + src.getName());
break;
case EVENT_END_FILE_PROCESSING:
break;
case EVENT_IGNORING_DIR:
out.println("Ignoring directory " + src.getName());
break;
case EVENT_SOURCE_NOT_MODIFIED:
out.println("Skipping " + src.getName());
break;
case EVENT_WARNING:
out.println("Warning:" + (String) param);
break;
}
}
});
/* Loading data model. */
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(false);
DocumentBuilder db;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new TemplateException(e.getMessage());
}
Document dom1;
try {
dom1 = db.parse(xmldata);
} catch (SAXException e) {
throw new TemplateException(e.getMessage());
} catch (IOException e) {
throw new TemplateException(e.getMessage());
}
NodeModel.removeComments(dom1);
NodeModel.mergeAdjacentText(dom1);
TemplateNodeModel doc1 = NodeModel.wrap(dom1);
HashMap<String, TemplateNodeModel> xmls = new HashMap<String, TemplateNodeModel>();
xmls.put("doc1", doc1);
/* Setting libraries path. */
HashMap<String, String> libs = new HashMap<String, String>();
libs.put("lib", libdir.toString());
/* Other settings. */
try {
settings.add("freemarkerLinks", libs);
settings.add("data", xmls);
settings.add("sourceRoot", sourcedir.toString());
settings.add("outputRoot", outputdir.toString());
settings.add("ignoreCvsFiles", true);
settings.add("ignoreSvnFiles", true);
} catch (SettingException e) {
throw new TemplateException(e.getMessage());
}
/* Processor execution. */
try {
settings.execute();
} catch (SettingException e) {
throw new TemplateException(e.getMessage());
} catch (ProcessingException e) {
throw new TemplateException(e.getMessage());
}
}
private static MessageConsole findConsole(String name) {
ConsolePlugin plugin = ConsolePlugin.getDefault();
IConsoleManager conMan = plugin.getConsoleManager();
IConsole[] existing = conMan.getConsoles();
for (int i = 0; i < existing.length; i++)
if (name.equals(existing[i].getName()))
return (MessageConsole) existing[i];
/* No console found, so create a new one. */
MessageConsole myConsole = new MessageConsole(name, null);
conMan.addConsoles(new IConsole[] { myConsole });
return myConsole;
}
private static void activateConsole(MessageConsole console) {
IWorkbench wb = PlatformUI.getWorkbench();
IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
IWorkbenchPage page = win.getActivePage();
IConsoleView view;
try {
view = (IConsoleView) page.showView(IConsoleConstants.ID_CONSOLE_VIEW);
} catch (PartInitException e) {
e.printStackTrace();
return;
}
view.display(console);
}
}

View File

@ -0,0 +1,30 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
2011,2012 Giovanni Di Sirio.
This file is part of ChibiOS/RT.
ChibiOS/RT is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS/RT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.chibios.tools.eclipse.config.utils;
public class TemplateException extends Exception {
private static final long serialVersionUID = -3317410595937500925L;
public TemplateException(String msg) {
super(msg);
}
}

View File

@ -0,0 +1,225 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
2011,2012 Giovanni Di Sirio.
This file is part of ChibiOS/RT.
ChibiOS/RT is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS/RT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.chibios.tools.eclipse.config.wizards;
import java.lang.reflect.InvocationTargetException;
import java.io.*;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.operation.*;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.*;
import org.eclipse.ui.ide.IDE;
import org.osgi.framework.Bundle;
import config_wizard.Activator;
/**
* 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 "chcfg". 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 ConfigurationNewWizard extends Wizard implements INewWizard {
private ConfigurationNewWizardPage page;
private ISelection selection;
private String containerName;
private String projectFileName;
private String dataFileName;
private String templatesPath;
private String outputDirName;
private String defaultDataFile;
/**
* Constructor for ConfigurationNewWizard.
*/
public ConfigurationNewWizard() {
super();
setNeedsProgressMonitor(true);
}
/**
* Adding the page to the wizard.
*/
public void addPages() {
page = new ConfigurationNewWizardPage(selection);
addPage(page);
}
/**
* Checks if the wizard page allows to finish.
*/
public boolean canFinish() {
return page.canFinish();
}
/**
* 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.
*/
public boolean performFinish() {
containerName = page.getContainerName();
projectFileName = page.getProjectFileName();
dataFileName = page.getDataFileName();
templatesPath = page.getTemplatesPath();
outputDirName = page.getOutputDirName();
defaultDataFile = page.getDefaultDataFile();
IRunnableWithProgress op = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor)
throws InvocationTargetException {
try {
doFinish(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
};
try {
getContainer().run(true, false, op);
} catch (InterruptedException e) {
return false;
} catch (InvocationTargetException e) {
Throwable realException = e.getTargetException();
MessageDialog.openError(getShell(), "Error", realException.getMessage());
return false;
}
return true;
}
/**
* 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(IProgressMonitor monitor) throws CoreException {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IResource resource = root.findMember(new Path(containerName));
if (!resource.exists() || !(resource instanceof IContainer)) {
throwCoreException("Container \"" + containerName + "\" does not exist.");
}
IContainer container = (IContainer)resource;
monitor.beginTask("Creating " + projectFileName, 4);
/* Step #1, creates the project file.*/
final IFile projectFile = container.getFile(new Path(projectFileName));
try {
InputStream stream = openProjectContentStream(templatesPath,
dataFileName,
outputDirName);
if (projectFile.exists()) {
projectFile.setContents(stream, true, true, monitor);
} else {
projectFile.create(stream, true, monitor);
}
stream.close();
} catch (IOException e) {
}
monitor.worked(1);
/* Step #2, creates the XML data file.*/
final IFile dataFile = container.getFile(new Path(dataFileName));
Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
IPath path = new Path(defaultDataFile);
String s;
try {
s = FileLocator.toFileURL(FileLocator.find(bundle, path, null)).getFile();
InputStream stream = new FileInputStream(s);
if (dataFile.exists()) {
dataFile.setContents(stream, true, true, monitor);
} else {
dataFile.create(stream, true, monitor);
}
stream.close();
} catch (IOException e) {
}
monitor.worked(1);
/* Step #2, opens the XML data file.*/
monitor.setTaskName("Opening XML data file for editing...");
getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
try {
IDE.openEditor(page, projectFile, true);
} catch (PartInitException e) {
}
}
});
monitor.worked(1);
/* Step #4, refreshing local resources.*/
container.refreshLocal(IResource.DEPTH_INFINITE, monitor);
monitor.worked(1);
}
/**
* We will initialize file contents with a sample text.
*/
private InputStream openProjectContentStream(String templatesPath,
String dataFileName,
String outputDirName) {
String contents = "# Automatically generated configuration project file.\n\n" +
"# Templates path in the configuration plugin resources, do not modify.\n" +
"source=" + templatesPath + "\n\n" +
"# XML configuration data file path relative to this configuration file.\n" +
"xmlfile=" + dataFileName + "\n\n" +
"# Output directory path relative to directory containing this configuration\n" +
"# file.\n" +
"output=" + outputDirName + "\n";
return new ByteArrayInputStream(contents.getBytes());
}
private void throwCoreException(String message) throws CoreException {
IStatus status = new Status(IStatus.ERROR,
"org.chibios.tools.eclipse.config", IStatus.OK,
message, null);
throw new CoreException(status);
}
/**
* 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) {
this.selection = selection;
}
}

View File

@ -0,0 +1,371 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
2011,2012 Giovanni Di Sirio.
This file is part of ChibiOS/RT.
ChibiOS/RT is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS/RT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.chibios.tools.eclipse.config.wizards;
import java.io.IOException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Combo;
import org.osgi.framework.Bundle;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import config_wizard.Activator;
/**
* The "New" wizard page allows setting the container for the new file as well
* as the file name. The page will only accept file name without the extension
* OR with the extension that matches the expected one (chcfg).
*/
public class ConfigurationNewWizardPage extends WizardPage {
private ISelection selection;
private IContainer resourceContainer;
private Document processorsDocument;
private String currentTemplatesPath;
private String currentDefaultDataFile;
private Composite container;
private Combo configurationTemplatesCombo;
private Text confProjectFilenameText;
private Text confDataFilenameText;
private Text confOutputDirectoryText;
/**
* Constructor for SampleNewWizardPage.
*
* @param pageName
*/
public ConfigurationNewWizardPage(ISelection selection) {
super("wizardPage");
setTitle("ChibiOS/RT Configuration Project File");
setDescription("This wizard creates a ChibiOS/RT configuration resource. Configuration resources allow to generate project resources starting from high level descriptions written in XML.");
this.selection = selection;
}
/**
* @see IDialogPage#createControl(Composite)
*/
public void createControl(Composite parent) {
container = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout();
container.setLayout(layout);
layout.numColumns = 2;
layout.verticalSpacing = 9;
Label lbl1 = new Label(container, SWT.NULL);
lbl1.setText("Configuration template:");
configurationTemplatesCombo = new Combo(container, SWT.READ_ONLY);
configurationTemplatesCombo.setLayoutData(new GridData(SWT.FILL,
SWT.CENTER, true,
false, 1, 1));
Label lbl2 = new Label(container, SWT.NULL);
lbl2.setText("Configuration project filename:");
confProjectFilenameText = new Text(container, SWT.BORDER | SWT.SINGLE);
confProjectFilenameText.setText("config.chcfg");
confProjectFilenameText
.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
confProjectFilenameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
confProjectFilenameUpdated();
}
});
Label lbl3 = new Label(container, SWT.NONE);
lbl3.setText("Configuration data filename:");
confDataFilenameText = new Text(container, SWT.BORDER);
confDataFilenameText.setText("config.chxml");
confDataFilenameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
false, 1, 1));
confDataFilenameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
confDataFilenameUpdated();
}
});
Label lbl4 = new Label(container, SWT.NONE);
lbl4.setText("Configuration output directory:");
confOutputDirectoryText = new Text(container, SWT.BORDER);
confOutputDirectoryText.setText(".");
confOutputDirectoryText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
true, false, 1, 1));
/* Note, it must stay after the creation of the text fields. */
configurationTemplatesCombo.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
Element processor = getSelectedTemplate();
String basefilename = processor.getChildText("basefilename");
confProjectFilenameText.setText(basefilename.concat(".chcfg"));
confDataFilenameText.setText(basefilename.concat(".chxml"));
currentTemplatesPath = processor.getChildText("path");
currentDefaultDataFile = processor.getChildText("default");
}
});
confOutputDirectoryText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
confOutputDirectoryUpdated();
}
});
populateWizardPanel();
initialize();
setControl(container);
}
public String getContainerName() {
return resourceContainer.getFullPath().toString();
}
public String getProjectFileName() {
return confProjectFilenameText.getText();
}
public String getDataFileName() {
return confDataFilenameText.getText();
}
public String getOutputDirName() {
return confOutputDirectoryText.getText();
}
public String getTemplatesPath() {
return currentTemplatesPath;
}
public String getDefaultDataFile() {
return currentDefaultDataFile;
}
public boolean canFinish() {
return container.getEnabled();
}
/**
* Tests if the current workbench selection is a suitable container to use.
*/
private void initialize() {
if (selection != null && selection.isEmpty() == false
&& selection instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) selection;
if (ssel.size() > 1)
return;
Object obj = ssel.getFirstElement();
if (obj instanceof IResource) {
if (obj instanceof IContainer)
resourceContainer = (IContainer) obj;
else
resourceContainer = ((IResource) obj).getParent();
}
}
else {
MessageDialog.openError(getShell(),
"Error", "Container for the resource not selected.");
container.setEnabled(false);
updateStatus("Container for the resource not selected.");
}
}
/**
* Fills the wizard configuration panel from XML data.
*
* @param configurationTemplateCombo
* the combo box to be populated
*/
private void populateWizardPanel() {
String fpath;
/* Retrieving the resource path of the processors.xml file. */
try {
Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
IPath path = new Path("resources/gencfg/processors/processors.xml");
fpath = FileLocator.toFileURL(FileLocator.find(bundle, path, null))
.getFile();
} catch (IOException e) {
e.printStackTrace();
return;
}
/* DOM tree creation. */
SAXBuilder builder = new SAXBuilder();
try {
processorsDocument = builder.build(fpath);
} catch (JDOMException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
/*
* Parsing the content of the processors.xml file in order to populate the
* panel objects.
*/
Element root = processorsDocument.getRootElement();
for (Element processor : root.getChildren("processor")) {
String name = processor.getChildText("name");
configurationTemplatesCombo.add(name);
}
configurationTemplatesCombo.select(0);
}
/**
* Checks the content of the confProjectFilenameText field.
*/
private void confProjectFilenameUpdated() {
String fileName = getProjectFileName();
if (fileName.length() == 0) {
updateStatus("File name must be specified");
return;
}
if (fileName.replace('\\', '/').indexOf('/', 1) > 0) {
updateStatus("File name must be valid");
return;
}
int dotLoc = fileName.lastIndexOf('.');
if (dotLoc != -1) {
String ext = fileName.substring(dotLoc + 1);
if (ext.equalsIgnoreCase("chcfg") == false) {
updateStatus("Configuration project filename extension must be \"chcfg\"");
return;
}
}
updateStatus(null);
}
/**
* Checks the content of the confProjectFilenameText field.
*/
private void confDataFilenameUpdated() {
String fileName = getDataFileName();
if (fileName.length() == 0) {
updateStatus("File name must be specified");
return;
}
if (fileName.replace('\\', '/').indexOf('/', 1) > 0) {
updateStatus("File name must be valid");
return;
}
int dotLoc = fileName.lastIndexOf('.');
if (dotLoc != -1) {
String ext = fileName.substring(dotLoc + 1);
if (ext.equalsIgnoreCase("chxml") == false) {
updateStatus("Configuration project filename extension must be \"chxml\"");
return;
}
}
updateStatus(null);
}
/**
* Checks the content of the confOutputDirectoryText field.
*/
private void confOutputDirectoryUpdated() {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IPath outputPath = resourceContainer.getFullPath().addTrailingSeparator()
.append(getOutputDirName());
IResource outputContainer = root.findMember(outputPath);
if (outputContainer == null) {
updateStatus("The directory must exists");
return;
}
if (!(outputContainer instanceof IContainer)) {
updateStatus("A directory must be specified");
return;
}
updateStatus(null);
}
/**
* Returns the XML Element associated to the current selection in the combo
* box.
*
* @return An Element Object.
*/
private Element getSelectedTemplate() {
for (Element processor : processorsDocument.getRootElement()
.getChildren("processor")) {
String name = processor.getChildText("name");
String item = configurationTemplatesCombo
.getItem(configurationTemplatesCombo.getSelectionIndex());
if (name.compareTo(item) == 0) {
return processor;
}
}
return null;
}
/**
* Updates the status text in the Wizard page.
*
* @param message
* the message to be shown
*/
private void updateStatus(String message) {
setErrorMessage(message);
setPageComplete(message == null);
}
}