Initial checkin of unified hierarchy of WPILib 2015

This commit is contained in:
Brad Miller
2013-12-15 18:30:16 -05:00
commit 3178911eef
1560 changed files with 410007 additions and 0 deletions

View File

@@ -0,0 +1,126 @@
package edu.wpi.first.wpilib.plugins.java;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import edu.wpi.first.wpilib.plugins.core.WPILibCore;
import edu.wpi.first.wpilib.plugins.core.ant.AntPropertiesParser;
import edu.wpi.first.wpilib.plugins.java.installer.JavaInstaller;
/**
* The activator class controls the plug-in life cycle
*/
public class WPILibJavaPlugin extends AbstractUIPlugin implements IStartup {
// The plug-in ID
public static final String PLUGIN_ID = "WPILib_Java_Robot_Development"; //$NON-NLS-1$
// The shared instance
private static WPILibJavaPlugin plugin;
/**
* The constructor
*/
public WPILibJavaPlugin() {
}
/*
* (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 WPILibJavaPlugin getDefault() {
return plugin;
}
public String getCurrentVersion() {
try {
Properties props = new AntPropertiesParser(WPILibJavaPlugin.class.getResourceAsStream("/resources/configuration.properties")).getProperties();
if (props.getProperty("version").startsWith("$")) {
return "DEVELOPMENT";
} else {
return props.getProperty("version");
}
} catch (CoreException e) {
return "DEVELOPMENT";
}
}
public Properties getProjectProperties(IProject project) {
Properties defaults = WPILibCore.getDefault().getProjectProperties(project);
Properties props;
try {
File file = new File(WPILibCore.getDefault().getWPILibBaseDir()+"/java/"+getCurrentVersion()+"/ant/build.properties");
props = new AntPropertiesParser(new FileInputStream(file)).getProperties(defaults);
} catch (Exception e) {
e.printStackTrace();
props = new Properties(defaults);
}
return props;
}
public void updateProjects() {
// Get the root of the workspace
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
// Get all projects in the workspace
IProject[] projects = root.getProjects();
// Loop over all projects
for (IProject project : projects) {
try {
updateVariables(project);
} catch (CoreException e) {
e.printStackTrace();
}
}
}
public void updateVariables(IProject project) throws CoreException {
Properties props = WPILibJavaPlugin.getDefault().getProjectProperties(project);
try {
JavaCore.setClasspathVariable("wpilib", new Path(props.getProperty("wpilib.jar")), null);
JavaCore.setClasspathVariable("wpilib.sources", new Path(props.getProperty("wpilib.sources")), null);
JavaCore.setClasspathVariable("networktables", new Path(props.getProperty("networktables.jar")), null);
JavaCore.setClasspathVariable("networktables.sources", new Path(props.getProperty("networktables.sources")), null);
} catch (JavaModelException e) {
e.printStackTrace(); // Classpath variables didn't get set
}
}
@Override
public void earlyStartup() {
new JavaInstaller(getCurrentVersion()).installIfNecessary();
}
}

View File

@@ -0,0 +1,47 @@
package edu.wpi.first.wpilib.plugins.java.installer;
import java.io.InputStream;
import java.util.Properties;
import org.eclipse.jface.preference.IPreferenceStore;
import edu.wpi.first.wpilib.plugins.core.WPILibCore;
import edu.wpi.first.wpilib.plugins.core.installer.AbstractInstaller;
import edu.wpi.first.wpilib.plugins.java.WPILibJavaPlugin;
import edu.wpi.first.wpilib.plugins.java.preferences.PreferenceConstants;
/**
* Installs the given version of WPILib into the correct location. Where the
* install directory is usually ~/wpilib/java/version.
*
* @author alex
*/
public class JavaInstaller extends AbstractInstaller {
public JavaInstaller(String version) {
super(version);
}
@Override
protected String getFeatureName() {
return "java";
}
@Override
protected void updateInstalledVersion(String version) {
IPreferenceStore prefs = WPILibJavaPlugin.getDefault().getPreferenceStore();
if (prefs.getBoolean(PreferenceConstants.UPDATE_LIBRARY_VERSION)) {
System.out.println("Forcing library version to "+version);
Properties props = WPILibCore.getDefault().getProjectProperties(null);
props.setProperty("version", version);
WPILibCore.getDefault().saveGlobalProperties(props);
prefs.setValue(PreferenceConstants.LIBRARY_VERSION, version);
}
WPILibJavaPlugin.getDefault().updateProjects();
}
@Override
protected InputStream getInstallResourceStream() {
return JavaInstaller.class.getResourceAsStream("/resources/java.zip");
}
}

View File

@@ -0,0 +1,207 @@
package edu.wpi.first.wpilib.plugins.java.launching;
import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.internal.resources.Resource;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.IStreamListener;
import org.eclipse.debug.core.model.IStreamMonitor;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.debug.ui.ILaunchShortcut;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.launching.IVMConnector;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PlatformUI;
import com.sun.jdi.connect.Connector.Argument;
import edu.wpi.first.wpilib.plugins.core.WPILibCore;
import edu.wpi.first.wpilib.plugins.core.launching.AntLauncher;
/**
* Launch shortcut base functionality, common for deploying to the robot.
* Retrieves the project the operation is being called on, and runs the correct
* ant targets based on polymorphically determined data values
*
* @author Ryan O'Meara
* @author Alex Henning
*/
@SuppressWarnings("restriction")
public class DeployLaunchShortcut implements ILaunchShortcut {
//Class constants - used to delineate types for launch shortcuts
public static final String DEPLOY_TYPE = "edu.wpi.first.wpilib.plugins.core.deploy";
private static final String ANT_SERVER_THREAD_NAME = "Ant Build Server Connection";
// NOTE: This string must be changed if the port is changed.
private static final String DEBUG_START_TEXT = "Listening for transport dt_socket at address: 8348";
private static ILaunch lastDeploy = null;
/**
* Returns the launch type of the shortcut that was used, one of the constants
* defined in BaseLaunchShortcut
* @return Launch shortcut type
*/
public String getLaunchType() {return DEPLOY_TYPE;}
@Override
public void launch(ISelection selection, String mode) {
//Extract resource from selection
StructuredSelection sel = (StructuredSelection)selection;
IProject activeProject = null;
//NOTE: This caused issues earlier, as the sel return was treated as a workspace, instead of a project
//When it is a valid FIRST project, the selection is always a JavaProject
if(sel.getFirstElement() instanceof IJavaProject){
activeProject = ((IJavaProject)sel.getFirstElement()).getProject();
}else if(sel.getFirstElement() instanceof IJavaElement){
activeProject = ((IJavaElement)sel.getFirstElement()).getJavaProject().getProject();
}else{
return;
}
//Run config using project found in extracted resource, with indicated mode
runConfig(activeProject, mode);
}
@Override
public void launch(IEditorPart editor, String mode) {
//Extract resource from editor
if(editor != null){
IFileEditorInput input = (IFileEditorInput)editor.getEditorInput();
IFile file = input.getFile();
IProject activeProject = file.getProject();
//If editor existed, run config using extracted resource in indicated mode
runConfig(activeProject, mode);
}else{
System.err.println("editor was null");
}
}
/**
* Runs the ant script using the correct target for the indicated mode (deploy to cRIO or just compile)
* @param activeProj The project that the script will be run on/from
* @param mode The mode it will be run in (ILaunchManager.RUN_MODE or ILaunchManager.DEBUG_MODE)
*/
public void runConfig(IProject activeProj, String mode){
String targets = "deploy";
if(mode.equals(ILaunchManager.RUN_MODE)){
if(getLaunchType().equals(DEPLOY_TYPE)){
targets = "deploy";
}
} else if ((mode.equals(ILaunchManager.DEBUG_MODE))&&(getLaunchType().equals(DEPLOY_TYPE))) {
targets = "debug-deploy";
try{
PlatformUI.getWorkbench().showPerspective(IDebugUIConstants.ID_DEBUG_PERSPECTIVE,
PlatformUI.getWorkbench().getActiveWorkbenchWindow());
}catch(Exception e){}
}
if((lastDeploy != null)&&(!lastDeploy.isTerminated())){
System.out.println("Last deploy running");
//Find the server connection thread and kill it
Vector<ThreadGroup> threadGroups = new Vector<ThreadGroup>();
ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
while (root.getParent() != null) {root = root.getParent();}
threadGroups.add(root);
ThreadGroup threadGroup = threadGroups.remove(0);
int numThreads = threadGroup.activeCount();
Thread[] threads = new Thread[numThreads*100];
numThreads = threadGroup.enumerate(threads, true);
for(Thread current: threads){
if(current != null){
if(current.getName().equals(ANT_SERVER_THREAD_NAME)){
try{
//Manually end thread and then try terminating launch
Method stopMethod = current.getClass().getMethod("stop");
stopMethod.invoke(current);
lastDeploy.terminate();
break;
}catch(Exception e){e.printStackTrace();}
}
}
}
System.out.println("Waiting");
try{wait(1000);}catch(Exception e){}
}
System.out.println("Running ant file: " + activeProj.getLocation().toOSString() + File.separator + "build.xml");
System.out.println("Targets: " + targets + ", Mode: " + mode);
lastDeploy = AntLauncher.runAntFile(new File (activeProj.getLocation().toOSString() + File.separator + "build.xml"), targets, null, mode);
if((mode.equals(ILaunchManager.DEBUG_MODE))&&(getLaunchType().equals(DEPLOY_TYPE))) {
ILaunchConfigurationWorkingCopy config;
try {
config = getRemoteDebugConfig(activeProj);
startDebugConfig(config, lastDeploy);
} catch (CoreException e) {
System.err.println("Debug attach failed.");
e.printStackTrace();
}
}
try {
activeProj.refreshLocal(Resource.DEPTH_INFINITE, null);
} catch (Exception e) {}
}
private ILaunchConfigurationWorkingCopy getRemoteDebugConfig(IProject activeProj) throws CoreException {
ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType type = manager.getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_REMOTE_JAVA_APPLICATION);
ILaunchConfigurationWorkingCopy config = type.newInstance(null, "Debug "+activeProj.getName());
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, activeProj.getName());
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_ALLOW_TERMINATE, true);
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_CONNECTOR, IJavaLaunchConfigurationConstants.ID_SOCKET_ATTACH_VM_CONNECTOR);
IVMConnector connector = JavaRuntime.getVMConnector(IJavaLaunchConfigurationConstants.ID_SOCKET_ATTACH_VM_CONNECTOR);
Map<String, Argument> def = connector.getDefaultArguments();
Map<String, String> argMap = new HashMap<String, String>(def.size());
argMap.put("hostname", WPILibCore.getDefault().getTargetIP(activeProj));
argMap.put("port", "8348");
System.out.println(argMap);
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CONNECT_MAP, argMap);
return config;
}
private void startDebugConfig(final ILaunchConfigurationWorkingCopy config, ILaunch deploy) throws CoreException {
IStreamListener listener = new IStreamListener() {
@Override
public void streamAppended(String text, IStreamMonitor monitor) {
if (text.contains(DEBUG_START_TEXT)) {
try {
config.launch(ILaunchManager.DEBUG_MODE, null);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
monitor.removeListener(this);
}
}
};
deploy.getProcesses()[0].getStreamsProxy().getOutputStreamMonitor().addListener(listener);
}
}

View File

@@ -0,0 +1,96 @@
package edu.wpi.first.wpilib.plugins.java.preferences;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.IWorkbench;
import edu.wpi.first.wpilib.plugins.core.WPILibCore;
import edu.wpi.first.wpilib.plugins.core.preferences.ComboFieldEditor;
import edu.wpi.first.wpilib.plugins.java.WPILibJavaPlugin;
/**
* This class represents a preference page that
* is contributed to the Preferences dialog. By
* subclassing <samp>FieldEditorPreferencePage</samp>, we
* can use the field support built into JFace that allows
* us to create a page that is small and knows how to
* save, restore and apply itself.
* <p>
* This page is used to modify preferences only. They
* are stored in the preference store that belongs to
* the main plug-in class. That way, preferences can
* be accessed directly via the preference store.
*/
public class JavaPreferencePage
extends FieldEditorPreferencePage
implements IWorkbenchPreferencePage {
ComboFieldEditor wpiLibVersionEditor;
BooleanFieldEditor autoUpdateEditor;
public JavaPreferencePage() {
super(GRID);
setPreferenceStore(WPILibJavaPlugin.getDefault().getPreferenceStore());
setDescription("Change workspace level settings for Java.");
}
/**
* Creates the field editors. Field editors are abstractions of
* the common GUI blocks needed to manipulate various types
* of preferences. Each field editor knows how to save and
* restore itself.
*/
public void createFieldEditors() {
wpiLibVersionEditor = new ComboFieldEditor(PreferenceConstants.LIBRARY_VERSION,
"&Library Version:", getFieldEditorParent(), getInstalledVersions());
addField(wpiLibVersionEditor);
autoUpdateEditor = new BooleanFieldEditor(PreferenceConstants.UPDATE_LIBRARY_VERSION,
"&Auto Update Library Version", getFieldEditorParent());
addField(autoUpdateEditor);
}
private List<String> getInstalledVersions() {
File[] dirs = new File(WPILibCore.getDefault().getWPILibBaseDir()+File.separator+"java")
.listFiles(new FileFilter() {
@Override public boolean accept(File f) {
return f.isDirectory();
}
});
List<String> versions = new ArrayList<String>();
for (File dir : dirs) {
versions.add(dir.getName());
}
Collections.sort(versions);
return versions;
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
public void init(IWorkbench workbench) {
System.out.println("Preferences initialized.");
Properties props = WPILibCore.getDefault().getProjectProperties(null);
getPreferenceStore().setValue(PreferenceConstants.LIBRARY_VERSION,
props.getProperty("version", WPILibJavaPlugin.getDefault().getCurrentVersion()));
}
@Override public void performApply() {
performOk();
}
@Override public boolean performOk() {
Properties props = WPILibCore.getDefault().getProjectProperties(null);
props.setProperty("version", wpiLibVersionEditor.getChoice());
WPILibCore.getDefault().saveGlobalProperties(props);
WPILibJavaPlugin.getDefault().updateProjects();
return super.performOk();
}
}

View File

@@ -0,0 +1,9 @@
package edu.wpi.first.wpilib.plugins.java.preferences;
/**
* Constant definitions for plug-in preferences
*/
public class PreferenceConstants {
public static final String LIBRARY_VERSION = "libraryVersionPreference";
public static final String UPDATE_LIBRARY_VERSION = "udpateLibraryVersionPreference";
}

View File

@@ -0,0 +1,26 @@
package edu.wpi.first.wpilib.plugins.java.preferences;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import edu.wpi.first.wpilib.plugins.core.WPILibCore;
import edu.wpi.first.wpilib.plugins.java.WPILibJavaPlugin;
/**
* Class used to initialize default preference values.
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
*/
public void initializeDefaultPreferences() {
IPreferenceStore store = WPILibJavaPlugin.getDefault().getPreferenceStore();
store.setDefault(PreferenceConstants.LIBRARY_VERSION,
WPILibCore.getDefault().getProjectProperties(null)
.getProperty("version", WPILibJavaPlugin.getDefault().getCurrentVersion()));
store.setDefault(PreferenceConstants.UPDATE_LIBRARY_VERSION, true);
}
}

View File

@@ -0,0 +1,54 @@
package edu.wpi.first.wpilib.plugins.java.wizards.examples;
import java.util.List;
import java.util.Map;
import edu.wpi.first.wpilib.plugins.core.wizards.IExampleProject;
import edu.wpi.first.wpilib.plugins.java.wizards.newproject.JavaProjectType;
public class ExampleJavaProject extends JavaProjectType implements IExampleProject {
private String name, description;
private List<String> tags;
private List<String> packages;
private List<ExportFile> files;
public ExampleJavaProject(String name, String description, List<String> tags,
List<String> packages, List<ExportFile> files) {
this.name = name;
this.description = description;
this.tags = tags;
this.packages = packages;
this.files = files;
}
public String getName() {
return name;
}
public String getContent() {
return "<h1>"+name+"</h1><p>"+description+"</p>";
}
public List<String> getTags() {
return tags;
}
@Override
public String[] getFolders(String packageName) {
String packageDir = packageName.replace(".", "/");
for (int i = 0; i < packages.size(); i++) {
packages.set(i, packages.get(i).replaceAll("\\$package-dir", packageDir));
}
return packages.toArray(new String[0]);
}
@Override
public Map<String, String> getFiles(String packageName) {
String packageDir = packageName.replace(".", "/");
Map<String, String> files = super.getFiles(packageName);
for (ExportFile file : this.files) {
files.put(file.destination.replaceAll("\\$package-dir", packageDir), file.source);
}
return files;
}
}

View File

@@ -0,0 +1,65 @@
package edu.wpi.first.wpilib.plugins.java.wizards.examples;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.wizard.IWizardPage;
import edu.wpi.first.wpilib.plugins.core.WPILibCore;
import edu.wpi.first.wpilib.plugins.core.wizards.ExampleWizard;
import edu.wpi.first.wpilib.plugins.core.wizards.IExampleProject;
import edu.wpi.first.wpilib.plugins.core.wizards.IExampleProject.ExportFile;
import edu.wpi.first.wpilib.plugins.core.wizards.NewProjectMainPage;
import edu.wpi.first.wpilib.plugins.core.wizards.ProjectCreationUtils;
import edu.wpi.first.wpilib.plugins.java.WPILibJavaPlugin;
import edu.wpi.first.wpilib.plugins.java.wizards.newproject.WPIRobotJavaProjectCreator;
public class ExampleJavaWizard extends ExampleWizard {
private NewProjectMainPage detailsPage;
/**
* Constructor for SampleNewWizard.
*/
public ExampleJavaWizard() {
super();
setNeedsProgressMonitor(true);
}
@Override
protected void doFinish(IExampleProject ex, String teamNumber) throws CoreException {
Properties props = WPILibCore.getDefault().getProjectProperties(null);
props.setProperty("team-number", teamNumber);
WPILibCore.getDefault().saveGlobalProperties(props);
final String projectName = detailsPage.getProjectName();
final String packageName = detailsPage.getPackage();
ProjectCreationUtils.createProject(new WPIRobotJavaProjectCreator(projectName, packageName, ex));
}
@Override
protected IWizardPage getDetailsPage() {
if (detailsPage != null) return detailsPage;
detailsPage = new NewProjectMainPage(selection, getTeamNumberPage());
detailsPage.setTitle("Create Example Robot Java Project");
detailsPage.setDescription("This wizard creates a new example project based on your selection.");
return detailsPage;
}
@Override
public IExampleProject makeExampleProject(String name, String description,
List<String> tags, List<String> folders, List<ExportFile> files) {
return new ExampleJavaProject(name, description, tags, folders, files);
}
@Override
public URL getResourceURL() {
return WPILibJavaPlugin.getDefault().getBundle().getEntry("/resources/templates/examples");
}
@Override
public String getXMLFile() {
return "examples.xml";
}
}

View File

@@ -0,0 +1,9 @@
package edu.wpi.first.wpilib.plugins.java.wizards.file_template;
public class CommandGroupWizard extends FileTemplateWizard {
public CommandGroupWizard() {
super("CommandGroup", "command-based/CommandGroup.java", "commands");
}
}

View File

@@ -0,0 +1,9 @@
package edu.wpi.first.wpilib.plugins.java.wizards.file_template;
public class CommandWizard extends FileTemplateWizard {
public CommandWizard() {
super("Command", "command-based/Command.java", "commands");
}
}

View File

@@ -0,0 +1,127 @@
package edu.wpi.first.wpilib.plugins.java.wizards.file_template;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
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.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWizard;
import edu.wpi.first.wpilib.plugins.core.wizards.ProjectCreationUtils;
import edu.wpi.first.wpilib.plugins.java.WPILibJavaPlugin;
public class FileTemplateWizard extends Wizard implements INewWizard {
private String type, source, ending;
private FileTemplateWizardMainPage page;
private ISelection selection;
private IProject project;
/**
* Constructor for SampleNewWizard.
*/
public FileTemplateWizard(String type, String source, String ending) {
super();
setNeedsProgressMonitor(true);
this.type = type;
this.source = source;
this.ending = ending;
}
/**
* Adding the page to the wizard.
*/
public void addPages() {
page = new FileTemplateWizardMainPage(type, project, ending, selection);
addPage(page);
}
/**
* 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() {
final IProject project = page.getProject();
final String className = page.getClassName();
final String packageName = page.getPackage();
System.out.println("Class: "+className+" Package: "+packageName);
IRunnableWithProgress op = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
doFinish(project, className, packageName, 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(IProject project, String className, String packageName, IProgressMonitor monitor) throws CoreException {
Map<String, String> map = new HashMap<String, String>();
map.put("$classname", className);
map.put("$package", packageName);
String filepath = "src/"+packageName.replace(".", "/")+"/"+className+".java";
try {
URL url = new URL(WPILibJavaPlugin.getDefault().getBundle().getEntry("/resources/templates/"), source);
ProjectCreationUtils.createTemplateFile(project, filepath, url, map);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 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;
System.out.println(selection);
Object element = ((StructuredSelection) selection).getFirstElement();
if (element != null) System.out.println(element.getClass());
if (element instanceof IResource) {
project = ((IResource) element).getProject();
} else if (element instanceof IPackageFragment) {
project = ((IPackageFragment) element).getJavaProject().getProject();
} else if (element instanceof IPackageFragmentRoot) {
project = ((IPackageFragmentRoot) element).getJavaProject().getProject();
} else if (element instanceof ICompilationUnit) {
project = ((ICompilationUnit) element).getJavaProject().getProject();
} else System.out.println("Element not instance of IResource");
}
}

View File

@@ -0,0 +1,203 @@
package edu.wpi.first.wpilib.plugins.java.wizards.file_template;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.dialogs.IDialogPage;
import org.eclipse.jface.viewers.ISelection;
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 edu.wpi.first.wpilib.plugins.core.nature.FRCProjectNature;
import edu.wpi.first.wpilib.plugins.core.wizards.IProjectFilter;
import edu.wpi.first.wpilib.plugins.core.wizards.ProjectComboField;
/**
* 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 (mpe).
*/
public class FileTemplateWizardMainPage extends WizardPage {
private IProject project;
private String ending;
private ProjectComboField projectsCombo;
private Text classNameText;
private Text packageText;
/**
* Constructor for SampleNewWizardPage.
*
* @param pageName
*/
public FileTemplateWizardMainPage(String type, IProject project, String ending, ISelection selection) {
super("wizardPage");
setTitle("Create New "+type);
setDescription("This wizard creates a new "+type.toLowerCase()+" from a template.");
this.project = project;
this.ending = ending;
}
/**
* @see IDialogPage#createControl(Composite)
*/
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout();
container.setLayout(layout);
layout.numColumns = 2;
layout.verticalSpacing = 9;
Label label = new Label(container, SWT.NULL);
label.setText("Pro&ject:");
projectsCombo = new ProjectComboField(container, SWT.BORDER | SWT.SINGLE,
new IProjectFilter() {
@Override public boolean accept(IProject project) {
try {
return project.hasNature(FRCProjectNature.FRC_PROJECT_NATURE)
&& project.hasNature(JavaCore.NATURE_ID);
} catch (CoreException e) {
e.printStackTrace();
return false;
}
}
});
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
projectsCombo.setLayoutData(gd);
projectsCombo.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
dialogChanged();
}
});
label = new Label(container, SWT.NULL);
label.setText("Class &Name:");
classNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
gd = new GridData(GridData.FILL_HORIZONTAL);
classNameText.setLayoutData(gd);
classNameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
dialogChanged();
}
});
label = new Label(container, SWT.NULL);
label.setText("&Package:");
packageText = new Text(container, SWT.BORDER | SWT.SINGLE);
gd = new GridData(GridData.FILL_HORIZONTAL);
packageText.setLayoutData(gd);
packageText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
dialogChanged();
}
});
initialize();
dialogChanged();
setControl(container);
}
/**
* Tests if the current workbench selection is a suitable container to use.
*/
private void initialize() {
projectsCombo.setProject(project);
packageText.setText(getDefaultPackage());
}
/**
* Ensures that both text fields are set.
*/
private void dialogChanged() {
String className = getClassName();
String packageString = getPackage();
// Update the default package if necessary
if (project == null || !project.equals(projectsCombo.getProject())) {
String oldDefault = getDefaultPackage();
project = projectsCombo.getProject();
if (packageString.equals(oldDefault)) {
packageText.setText(getDefaultPackage());
}
}
if (!projectsCombo.isValid()) {
updateStatus("Must select a project.");
return;
}
if (className.length() == 0) {
updateStatus("Class name must be specified");
return;
}
if (!className.matches("^([a-zA-Z_]{1}[a-zA-Z0-9_]*)$")) {
updateStatus("Must be a valid java class name");
return;
}
if (packageString.length() == 0) {
updateStatus("Package must be specified");
return;
}
if (!packageString.matches("^([a-zA-Z_]{1}[a-zA-Z0-9_]*(\\.[a-zA-Z_]{1}[a-zA-Z0-9_]*)*)$")) {
updateStatus("Must be valid java package");
return;
}
updateStatus(null);
}
private void updateStatus(String message) {
setErrorMessage(message);
setPageComplete(message == null);
}
public IProject getProject() {
return projectsCombo.getProject();
}
public String getClassName() {
return classNameText.getText();
}
public String getPackage() {
return packageText.getText();
}
public String getDefaultPackage() {
System.out.println("Project: "+project);
String defaultPackage = null;
if (project != null) {
try {
IPackageFragmentRoot root = JavaCore.create(project)
.getPackageFragmentRoot(project.getFolder("src"));
String backupPackage = "";
for (IJavaElement child : root.getChildren()) {
if (child.getElementType()==IJavaElement.PACKAGE_FRAGMENT
&& child.getElementName().endsWith("."+ending)) {
defaultPackage = child.getElementName();
}
backupPackage = child.getElementName();
}
if (defaultPackage == null) defaultPackage = backupPackage;
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (defaultPackage != null) return defaultPackage;
else return "";
}
}

View File

@@ -0,0 +1,9 @@
package edu.wpi.first.wpilib.plugins.java.wizards.file_template;
public class PIDSubsystemWizard extends FileTemplateWizard {
public PIDSubsystemWizard() {
super("PIDSubsystem", "command-based/PIDSubsystem.java", "subsystems");
}
}

View File

@@ -0,0 +1,9 @@
package edu.wpi.first.wpilib.plugins.java.wizards.file_template;
public class SubsystemWizard extends FileTemplateWizard {
public SubsystemWizard() {
super("Subsystem", "command-based/Subsystem.java", "subsystems");
}
}

View File

@@ -0,0 +1,9 @@
package edu.wpi.first.wpilib.plugins.java.wizards.file_template;
public class TriggerWizard extends FileTemplateWizard {
public TriggerWizard() {
super("Trigger", "command-based/Trigger.java", "triggers");
}
}

View File

@@ -0,0 +1,67 @@
package edu.wpi.first.wpilib.plugins.java.wizards.newproject;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import edu.wpi.first.wpilib.plugins.core.wizards.ProjectType;
import edu.wpi.first.wpilib.plugins.java.WPILibJavaPlugin;
public class JavaProjectType implements ProjectType {
static ProjectType SIMPLE = new JavaProjectType() {
@Override public Map<String, String> getFiles(String packageName) {
Map<String, String> files = super.getFiles(packageName);
files.put("src/"+packageName.replace(".", "/")+"/Robot.java", "simple/Robot.java");
return files;
}
};
static ProjectType ITERATIVE = new JavaProjectType() {
@Override public Map<String, String> getFiles(String packageName) {
Map<String, String> files = super.getFiles(packageName);
files.put("src/"+packageName.replace(".", "/")+"/Robot.java", "iterative/Robot.java");
return files;
}
};
static ProjectType COMMAND_BASED = new JavaProjectType() {
@Override public String[] getFolders(String packageName) {
String[] paths = {"src/"+packageName.replace(".", "/"),
"src/"+packageName.replace(".", "/")+"/commands",
"src/"+packageName.replace(".", "/")+"/subsystems",
"src/"+packageName.replace(".", "/")+"/triggers"};
return paths;
}
@Override public Map<String, String> getFiles(String packageName) {
Map<String, String> files = super.getFiles(packageName);
files.put("src/"+packageName.replace(".", "/")+"/Robot.java", "command-based/Robot.java");
files.put("src/"+packageName.replace(".", "/")+"/commands/ExampleCommand.java", "command-based/ExampleCommand.java");
files.put("src/"+packageName.replace(".", "/")+"/subsystems/ExampleSubsystem.java", "command-based/ExampleSubsystem.java");
return files;
}
};
@SuppressWarnings("serial")
static Map<String, ProjectType> TYPES = new HashMap<String, ProjectType>() {{
put(ProjectType.SIMPLE, SIMPLE);
put(ProjectType.ITERATIVE, ITERATIVE);
put(ProjectType.COMMAND_BASED, COMMAND_BASED);
}};
@Override
public String[] getFolders(String packageName) {
String[] paths = {"src/"+packageName.replace(".", "/")};
return paths;
}
@Override
public Map<String, String> getFiles(String packageName) {
HashMap<String, String> files = new HashMap<String, String>();
files.put("build.xml", "build.xml");
files.put("build.properties", "build.properties");
files.put(".classpath", ".classpath");
return files;
}
@Override
public URL getBaseURL() {
return WPILibJavaPlugin.getDefault().getBundle().getEntry("/resources/templates/");
}
}

View File

@@ -0,0 +1,120 @@
package edu.wpi.first.wpilib.plugins.java.wizards.newproject;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
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.ui.IWorkbenchWizard;
import edu.wpi.first.wpilib.plugins.core.WPILibCore;
import edu.wpi.first.wpilib.plugins.core.wizards.NewProjectMainPage;
import edu.wpi.first.wpilib.plugins.core.wizards.ProjectCreationUtils;
import edu.wpi.first.wpilib.plugins.core.wizards.ProjectType;
import edu.wpi.first.wpilib.plugins.core.wizards.TeamNumberPage;
/**
*
* Example Docs:
* 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
* "mpe". 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 NewJavaWizard extends Wizard implements INewWizard {
private TeamNumberPage teamNumberPage;
private NewProjectMainPage page;
private ISelection selection;
/**
* Constructor for SampleNewWizard.
*/
public NewJavaWizard() {
super();
setNeedsProgressMonitor(true);
}
/**
* Adding the page to the wizard.
*/
public void addPages() {
if (TeamNumberPage.needsTeamNumberPage()) {
teamNumberPage = new TeamNumberPage(selection);
addPage(teamNumberPage);
}
page = new NewProjectMainPage(selection, teamNumberPage);
page.setProjectTypes(JavaProjectType.TYPES);
page.setTitle("Create New Robot Java Project");
page.setDescription("This wizard creates a new Robot Java Project configured to use WPILib for programming FRC robots.");
addPage(page);
}
/**
* 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() {
final String projectName = page.getProjectName();
final String teamNumber = TeamNumberPage.getTeamNumberFromPage(teamNumberPage);
final String packageName = page.getPackage();
final ProjectType projectType = page.getProjectType();
System.out.println("Project: "+projectName+" Package: "+packageName+" Project Type: "+projectType);
IRunnableWithProgress op = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
doFinish(projectName, teamNumber, packageName, projectType, 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(String projectName, String teamNumber, String packageName, ProjectType projectType, IProgressMonitor monitor) throws CoreException {
Properties props = WPILibCore.getDefault().getProjectProperties(null);
props.setProperty("team-number", teamNumber);
WPILibCore.getDefault().saveGlobalProperties(props);
ProjectCreationUtils.createProject(new WPIRobotJavaProjectCreator(projectName, packageName, projectType));
}
/**
* 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,67 @@
package edu.wpi.first.wpilib.plugins.java.wizards.newproject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.JavaCore;
import edu.wpi.first.wpilib.plugins.core.nature.FRCProjectNature;
import edu.wpi.first.wpilib.plugins.core.wizards.IProjectCreator;
import edu.wpi.first.wpilib.plugins.core.wizards.ProjectType;
import edu.wpi.first.wpilib.plugins.java.WPILibJavaPlugin;
public class WPIRobotJavaProjectCreator implements IProjectCreator {
String projectName, packageName;
ProjectType projectType;
public WPIRobotJavaProjectCreator(String projectName, String packageName, ProjectType projectType) {
this.projectName = projectName;
this.packageName = packageName;
this.projectType = projectType;
}
@Override
public String getName() {
return projectName;
}
@Override
public String getPackageName() {
return packageName;
}
@Override
public Map<String, String> getValues() {
Map<String, String> vals = new HashMap<String, String>();
vals.put("$project", projectName);
vals.put("$package", packageName);
return vals;
}
@Override
public List<String> getNatures() {
List<String> natures = new ArrayList<>();
natures.add(JavaCore.NATURE_ID);
natures.add(FRCProjectNature.FRC_PROJECT_NATURE);
return natures;
}
@Override
public ProjectType getProjectType() {
return projectType;
}
@Override
public void initialize(IProject project) {
JavaCore.create(project);
}
@Override
public void finalize(IProject project) throws CoreException {
WPILibJavaPlugin.getDefault().updateVariables(project);
}
}

View File

@@ -0,0 +1,30 @@
# Deployment information
username=admin
password=
deploy.dir=/home/admin
deploy.run.command=./runjavaprogram
deploy.debug.command=./debugjavaprogram
# Libraries to use
wpilib=${user.home}/wpilib/java/${version}
wpilib.lib=${wpilib}/lib
wpilib.jar=${wpilib.lib}/WPILib.jar
wpilib.sources=${wpilib.lib}/WPILib-sources.jar
networktables.jar=${wpilib.lib}/NetworkTables.jar
networktables.sources=${wpilib.lib}/NetworkTables-sources.jar
jna.jar=${wpilib.lib}/jna-4.0.0.jar
jnaerator.jar=${wpilib.lib}/jnaerator-runtime.jar
classpath=${wpilib.jar}:${networktables.jar}:${jna.jar}:${jnaerator.jar}
# Ant support
wpilib.ant.dir=${wpilib}/ant
jsch.jar=${wpilib.ant.dir}/jsch-0.1.50.jar
classloadertask.jar=${wpilib.ant.dir}/ant-classloadertask.jar
# Build information
jar=FRCUserProgram.jar
src.dir=src
build.dir=build
build.jars=${build.dir}/jars
dist.dir=dist
dist.jar=${dist.dir}/${jar}

View File

@@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="athena-project-build" default="deploy">
<!-- Load Tasks -->
<taskdef resource="net/sf/antcontrib/antlib.xml">
<classpath>
<pathelement location="${wpilib.ant.dir}/ant-contrib.jar"/>
</classpath>
</taskdef>
<taskdef resource="net/jtools/classloadertask/antlib.xml" classpath="${classloadertask.jar}"/>
<classloader loader="system" classpath="${jsch.jar}"/>
<target name="clean" description="Clean up all build and distribution artifacts.">
<delete dir="${build.dir}"/>
<delete dir="${dist.dir}"/>
</target>
<!-- Targets -->
<target name="get-target-ip">
<math result="ip.upper" operand1="${team-number}" operation="/" operand2="100" datatype="int"/>
<math result="ip.lower" operand1="${team-number}" operation="%" operand2="100" datatype="int"/>
<property name="target" value="10.${ip.upper}.${ip.lower}.2" />
<echo>Target IP: ${target}</echo>
</target>
<target name="compile" description="Compile the source code.">
<mkdir dir="${build.dir}"/>
<echo>[athena-compile] Compiling ${src.dir} with classpath=${classpath} to ${build.dir}</echo>
<javac srcdir="${src.dir}"
destdir="${build.dir}"
includeAntRuntime="no"
includeJavaRuntime="no"
classpath="${classpath}"
target="1.7"
source="1.7"
debug="true">
</javac>
</target>
<target name="jar" depends="compile">
<echo>[athena-jar] Making jar ${dist.jar}.</echo>
<mkdir dir="${dist.dir}" />
<mkdir dir="${build.jars}" />
<echo>[athena-jar] Copying jars from ${classpath} to ${build.jars}.</echo>
<copy todir="${build.jars}" flatten="true">
<path>
<pathelement path="${classpath}"/>
</path>
</copy>
<jar destfile="${dist.jar}" update="false">
<manifest>
<attribute name="Main-Class" value="edu.wpi.first.wpilibj.RobotBase"/>
<attribute name="Robot-Class" value="${main}"/>
<attribute name="Class-Path" value="."/>
</manifest>
<fileset dir="${build.dir}" includes="**/*.class"/>
<zipgroupfileset dir="${build.jars}">
<include name="**/*.jar" />
</zipgroupfileset>
</jar>
</target>
<target name="deploy" depends="get-target-ip,jar" description="Deploy the jar and start the program running.">
<echo>[athena-deploy] Copying code over.</echo>
<scp file="${dist.jar}" todir="${username}@${target}:${deploy.dir}"
password="${password}" trust="true"/>
<echo>[athena-deploy] Starting program.</echo>
<sshexec host="${target}"
username="${username}"
password="${password}"
trust="true"
command="${deploy.run.command}"/>
</target>
<target name="debug-deploy" depends="get-target-ip,jar" description="Deploy the jar and start the program running in debug mode.">
<echo>[athena-debug-deploy] Copying code over.</echo>
<scp file="${dist.jar}" todir="${username}@${target}:${deploy.dir}"
password="${password}" trust="true"/>
<echo>[athena-debug-deploy] Starting program.</echo>
<sshexec host="${target}"
username="${username}"
password="${password}"
trust="true"
command="${deploy.debug.command}"/>
</target>
</project>